blob: 54c805fc79844a38ffde5bc17a780f55f09de25f [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 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700890 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
891 * should add all focusable Views regardless if they are focusable in touch mode.
892 */
893 public static final int FOCUSABLES_ALL = 0x00000000;
894
895 /**
896 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
897 * should add only Views focusable in touch mode.
898 */
899 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
900
901 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 * Use with {@link #focusSearch}. Move focus to the previous selectable
903 * item.
904 */
905 public static final int FOCUS_BACKWARD = 0x00000001;
906
907 /**
908 * Use with {@link #focusSearch}. Move focus to the next selectable
909 * item.
910 */
911 public static final int FOCUS_FORWARD = 0x00000002;
912
913 /**
914 * Use with {@link #focusSearch}. Move focus to the left.
915 */
916 public static final int FOCUS_LEFT = 0x00000011;
917
918 /**
919 * Use with {@link #focusSearch}. Move focus up.
920 */
921 public static final int FOCUS_UP = 0x00000021;
922
923 /**
924 * Use with {@link #focusSearch}. Move focus to the right.
925 */
926 public static final int FOCUS_RIGHT = 0x00000042;
927
928 /**
929 * Use with {@link #focusSearch}. Move focus down.
930 */
931 public static final int FOCUS_DOWN = 0x00000082;
932
933 /**
934 * Base View state sets
935 */
936 // Singles
937 /**
938 * Indicates the view has no states set. States are used with
939 * {@link android.graphics.drawable.Drawable} to change the drawing of the
940 * view depending on its state.
941 *
942 * @see android.graphics.drawable.Drawable
943 * @see #getDrawableState()
944 */
945 protected static final int[] EMPTY_STATE_SET = {};
946 /**
947 * Indicates the view is enabled. States are used with
948 * {@link android.graphics.drawable.Drawable} to change the drawing of the
949 * view depending on its state.
950 *
951 * @see android.graphics.drawable.Drawable
952 * @see #getDrawableState()
953 */
954 protected static final int[] ENABLED_STATE_SET = {R.attr.state_enabled};
955 /**
956 * Indicates the view is focused. States are used with
957 * {@link android.graphics.drawable.Drawable} to change the drawing of the
958 * view depending on its state.
959 *
960 * @see android.graphics.drawable.Drawable
961 * @see #getDrawableState()
962 */
963 protected static final int[] FOCUSED_STATE_SET = {R.attr.state_focused};
964 /**
965 * Indicates the view is selected. States are used with
966 * {@link android.graphics.drawable.Drawable} to change the drawing of the
967 * view depending on its state.
968 *
969 * @see android.graphics.drawable.Drawable
970 * @see #getDrawableState()
971 */
972 protected static final int[] SELECTED_STATE_SET = {R.attr.state_selected};
973 /**
974 * Indicates the view is pressed. States are used with
975 * {@link android.graphics.drawable.Drawable} to change the drawing of the
976 * view depending on its state.
977 *
978 * @see android.graphics.drawable.Drawable
979 * @see #getDrawableState()
980 * @hide
981 */
982 protected static final int[] PRESSED_STATE_SET = {R.attr.state_pressed};
983 /**
984 * Indicates the view's window has focus. States are used with
985 * {@link android.graphics.drawable.Drawable} to change the drawing of the
986 * view depending on its state.
987 *
988 * @see android.graphics.drawable.Drawable
989 * @see #getDrawableState()
990 */
991 protected static final int[] WINDOW_FOCUSED_STATE_SET =
992 {R.attr.state_window_focused};
993 // Doubles
994 /**
995 * Indicates the view is enabled and has the focus.
996 *
997 * @see #ENABLED_STATE_SET
998 * @see #FOCUSED_STATE_SET
999 */
1000 protected static final int[] ENABLED_FOCUSED_STATE_SET =
1001 stateSetUnion(ENABLED_STATE_SET, FOCUSED_STATE_SET);
1002 /**
1003 * Indicates the view is enabled and selected.
1004 *
1005 * @see #ENABLED_STATE_SET
1006 * @see #SELECTED_STATE_SET
1007 */
1008 protected static final int[] ENABLED_SELECTED_STATE_SET =
1009 stateSetUnion(ENABLED_STATE_SET, SELECTED_STATE_SET);
1010 /**
1011 * Indicates the view is enabled and that its window has focus.
1012 *
1013 * @see #ENABLED_STATE_SET
1014 * @see #WINDOW_FOCUSED_STATE_SET
1015 */
1016 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET =
1017 stateSetUnion(ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1018 /**
1019 * Indicates the view is focused and selected.
1020 *
1021 * @see #FOCUSED_STATE_SET
1022 * @see #SELECTED_STATE_SET
1023 */
1024 protected static final int[] FOCUSED_SELECTED_STATE_SET =
1025 stateSetUnion(FOCUSED_STATE_SET, SELECTED_STATE_SET);
1026 /**
1027 * Indicates the view has the focus and that its window has the focus.
1028 *
1029 * @see #FOCUSED_STATE_SET
1030 * @see #WINDOW_FOCUSED_STATE_SET
1031 */
1032 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET =
1033 stateSetUnion(FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1034 /**
1035 * Indicates the view is selected and that its window has the focus.
1036 *
1037 * @see #SELECTED_STATE_SET
1038 * @see #WINDOW_FOCUSED_STATE_SET
1039 */
1040 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET =
1041 stateSetUnion(SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1042 // Triples
1043 /**
1044 * Indicates the view is enabled, focused and selected.
1045 *
1046 * @see #ENABLED_STATE_SET
1047 * @see #FOCUSED_STATE_SET
1048 * @see #SELECTED_STATE_SET
1049 */
1050 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET =
1051 stateSetUnion(ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1052 /**
1053 * Indicates the view is enabled, focused and its window has the focus.
1054 *
1055 * @see #ENABLED_STATE_SET
1056 * @see #FOCUSED_STATE_SET
1057 * @see #WINDOW_FOCUSED_STATE_SET
1058 */
1059 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1060 stateSetUnion(ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1061 /**
1062 * Indicates the view is enabled, selected and its window has the focus.
1063 *
1064 * @see #ENABLED_STATE_SET
1065 * @see #SELECTED_STATE_SET
1066 * @see #WINDOW_FOCUSED_STATE_SET
1067 */
1068 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1069 stateSetUnion(ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1070 /**
1071 * Indicates the view is focused, selected and its window has the focus.
1072 *
1073 * @see #FOCUSED_STATE_SET
1074 * @see #SELECTED_STATE_SET
1075 * @see #WINDOW_FOCUSED_STATE_SET
1076 */
1077 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1078 stateSetUnion(FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1079 /**
1080 * Indicates the view is enabled, focused, selected and its window
1081 * has the focus.
1082 *
1083 * @see #ENABLED_STATE_SET
1084 * @see #FOCUSED_STATE_SET
1085 * @see #SELECTED_STATE_SET
1086 * @see #WINDOW_FOCUSED_STATE_SET
1087 */
1088 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1089 stateSetUnion(ENABLED_FOCUSED_SELECTED_STATE_SET,
1090 WINDOW_FOCUSED_STATE_SET);
1091
1092 /**
1093 * Indicates the view is pressed and its window has the focus.
1094 *
1095 * @see #PRESSED_STATE_SET
1096 * @see #WINDOW_FOCUSED_STATE_SET
1097 */
1098 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET =
1099 stateSetUnion(PRESSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1100
1101 /**
1102 * Indicates the view is pressed and selected.
1103 *
1104 * @see #PRESSED_STATE_SET
1105 * @see #SELECTED_STATE_SET
1106 */
1107 protected static final int[] PRESSED_SELECTED_STATE_SET =
1108 stateSetUnion(PRESSED_STATE_SET, SELECTED_STATE_SET);
1109
1110 /**
1111 * Indicates the view is pressed, selected and its window has the focus.
1112 *
1113 * @see #PRESSED_STATE_SET
1114 * @see #SELECTED_STATE_SET
1115 * @see #WINDOW_FOCUSED_STATE_SET
1116 */
1117 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1118 stateSetUnion(PRESSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1119
1120 /**
1121 * Indicates the view is pressed and focused.
1122 *
1123 * @see #PRESSED_STATE_SET
1124 * @see #FOCUSED_STATE_SET
1125 */
1126 protected static final int[] PRESSED_FOCUSED_STATE_SET =
1127 stateSetUnion(PRESSED_STATE_SET, FOCUSED_STATE_SET);
1128
1129 /**
1130 * Indicates the view is pressed, focused and its window has the focus.
1131 *
1132 * @see #PRESSED_STATE_SET
1133 * @see #FOCUSED_STATE_SET
1134 * @see #WINDOW_FOCUSED_STATE_SET
1135 */
1136 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1137 stateSetUnion(PRESSED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1138
1139 /**
1140 * Indicates the view is pressed, focused and selected.
1141 *
1142 * @see #PRESSED_STATE_SET
1143 * @see #SELECTED_STATE_SET
1144 * @see #FOCUSED_STATE_SET
1145 */
1146 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET =
1147 stateSetUnion(PRESSED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1148
1149 /**
1150 * Indicates the view is pressed, focused, selected and its window has the focus.
1151 *
1152 * @see #PRESSED_STATE_SET
1153 * @see #FOCUSED_STATE_SET
1154 * @see #SELECTED_STATE_SET
1155 * @see #WINDOW_FOCUSED_STATE_SET
1156 */
1157 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1158 stateSetUnion(PRESSED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1159
1160 /**
1161 * Indicates the view is pressed and enabled.
1162 *
1163 * @see #PRESSED_STATE_SET
1164 * @see #ENABLED_STATE_SET
1165 */
1166 protected static final int[] PRESSED_ENABLED_STATE_SET =
1167 stateSetUnion(PRESSED_STATE_SET, ENABLED_STATE_SET);
1168
1169 /**
1170 * Indicates the view is pressed, enabled and its window has the focus.
1171 *
1172 * @see #PRESSED_STATE_SET
1173 * @see #ENABLED_STATE_SET
1174 * @see #WINDOW_FOCUSED_STATE_SET
1175 */
1176 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET =
1177 stateSetUnion(PRESSED_ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1178
1179 /**
1180 * Indicates the view is pressed, enabled and selected.
1181 *
1182 * @see #PRESSED_STATE_SET
1183 * @see #ENABLED_STATE_SET
1184 * @see #SELECTED_STATE_SET
1185 */
1186 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET =
1187 stateSetUnion(PRESSED_ENABLED_STATE_SET, SELECTED_STATE_SET);
1188
1189 /**
1190 * Indicates the view is pressed, enabled, selected and its window has the
1191 * focus.
1192 *
1193 * @see #PRESSED_STATE_SET
1194 * @see #ENABLED_STATE_SET
1195 * @see #SELECTED_STATE_SET
1196 * @see #WINDOW_FOCUSED_STATE_SET
1197 */
1198 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1199 stateSetUnion(PRESSED_ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1200
1201 /**
1202 * Indicates the view is pressed, enabled and focused.
1203 *
1204 * @see #PRESSED_STATE_SET
1205 * @see #ENABLED_STATE_SET
1206 * @see #FOCUSED_STATE_SET
1207 */
1208 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET =
1209 stateSetUnion(PRESSED_ENABLED_STATE_SET, FOCUSED_STATE_SET);
1210
1211 /**
1212 * Indicates the view is pressed, enabled, focused and its window has the
1213 * focus.
1214 *
1215 * @see #PRESSED_STATE_SET
1216 * @see #ENABLED_STATE_SET
1217 * @see #FOCUSED_STATE_SET
1218 * @see #WINDOW_FOCUSED_STATE_SET
1219 */
1220 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1221 stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1222
1223 /**
1224 * Indicates the view is pressed, enabled, focused and selected.
1225 *
1226 * @see #PRESSED_STATE_SET
1227 * @see #ENABLED_STATE_SET
1228 * @see #SELECTED_STATE_SET
1229 * @see #FOCUSED_STATE_SET
1230 */
1231 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET =
1232 stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1233
1234 /**
1235 * Indicates the view is pressed, enabled, focused, selected and its window
1236 * has the focus.
1237 *
1238 * @see #PRESSED_STATE_SET
1239 * @see #ENABLED_STATE_SET
1240 * @see #SELECTED_STATE_SET
1241 * @see #FOCUSED_STATE_SET
1242 * @see #WINDOW_FOCUSED_STATE_SET
1243 */
1244 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1245 stateSetUnion(PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1246
1247 /**
1248 * The order here is very important to {@link #getDrawableState()}
1249 */
1250 private static final int[][] VIEW_STATE_SETS = {
1251 EMPTY_STATE_SET, // 0 0 0 0 0
1252 WINDOW_FOCUSED_STATE_SET, // 0 0 0 0 1
1253 SELECTED_STATE_SET, // 0 0 0 1 0
1254 SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 0 1 1
1255 FOCUSED_STATE_SET, // 0 0 1 0 0
1256 FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 0 1
1257 FOCUSED_SELECTED_STATE_SET, // 0 0 1 1 0
1258 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 1 1
1259 ENABLED_STATE_SET, // 0 1 0 0 0
1260 ENABLED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 0 1
1261 ENABLED_SELECTED_STATE_SET, // 0 1 0 1 0
1262 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 1 1
1263 ENABLED_FOCUSED_STATE_SET, // 0 1 1 0 0
1264 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 0 1
1265 ENABLED_FOCUSED_SELECTED_STATE_SET, // 0 1 1 1 0
1266 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 1 1
1267 PRESSED_STATE_SET, // 1 0 0 0 0
1268 PRESSED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 0 1
1269 PRESSED_SELECTED_STATE_SET, // 1 0 0 1 0
1270 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 1 1
1271 PRESSED_FOCUSED_STATE_SET, // 1 0 1 0 0
1272 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 0 1
1273 PRESSED_FOCUSED_SELECTED_STATE_SET, // 1 0 1 1 0
1274 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 1 1
1275 PRESSED_ENABLED_STATE_SET, // 1 1 0 0 0
1276 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 0 1
1277 PRESSED_ENABLED_SELECTED_STATE_SET, // 1 1 0 1 0
1278 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 1 1
1279 PRESSED_ENABLED_FOCUSED_STATE_SET, // 1 1 1 0 0
1280 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 0 1
1281 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, // 1 1 1 1 0
1282 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 1 1
1283 };
1284
1285 /**
1286 * Used by views that contain lists of items. This state indicates that
1287 * the view is showing the last item.
1288 * @hide
1289 */
1290 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1291 /**
1292 * Used by views that contain lists of items. This state indicates that
1293 * the view is showing the first item.
1294 * @hide
1295 */
1296 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1297 /**
1298 * Used by views that contain lists of items. This state indicates that
1299 * the view is showing the middle item.
1300 * @hide
1301 */
1302 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1303 /**
1304 * Used by views that contain lists of items. This state indicates that
1305 * the view is showing only one item.
1306 * @hide
1307 */
1308 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1309 /**
1310 * Used by views that contain lists of items. This state indicates that
1311 * the view is pressed and showing the last item.
1312 * @hide
1313 */
1314 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1315 /**
1316 * Used by views that contain lists of items. This state indicates that
1317 * the view is pressed and showing the first item.
1318 * @hide
1319 */
1320 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1321 /**
1322 * Used by views that contain lists of items. This state indicates that
1323 * the view is pressed and showing the middle item.
1324 * @hide
1325 */
1326 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1327 /**
1328 * Used by views that contain lists of items. This state indicates that
1329 * the view is pressed and showing only one item.
1330 * @hide
1331 */
1332 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1333
1334 /**
1335 * Temporary Rect currently for use in setBackground(). This will probably
1336 * be extended in the future to hold our own class with more than just
1337 * a Rect. :)
1338 */
1339 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001340
1341 /**
1342 * Map used to store views' tags.
1343 */
1344 private static WeakHashMap<View, SparseArray<Object>> sTags;
1345
1346 /**
1347 * Lock used to access sTags.
1348 */
1349 private static final Object sTagsLock = new Object();
1350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 /**
1352 * The animation currently associated with this view.
1353 * @hide
1354 */
1355 protected Animation mCurrentAnimation = null;
1356
1357 /**
1358 * Width as measured during measure pass.
1359 * {@hide}
1360 */
1361 @ViewDebug.ExportedProperty
1362 protected int mMeasuredWidth;
1363
1364 /**
1365 * Height as measured during measure pass.
1366 * {@hide}
1367 */
1368 @ViewDebug.ExportedProperty
1369 protected int mMeasuredHeight;
1370
1371 /**
1372 * The view's identifier.
1373 * {@hide}
1374 *
1375 * @see #setId(int)
1376 * @see #getId()
1377 */
1378 @ViewDebug.ExportedProperty(resolveId = true)
1379 int mID = NO_ID;
1380
1381 /**
1382 * The view's tag.
1383 * {@hide}
1384 *
1385 * @see #setTag(Object)
1386 * @see #getTag()
1387 */
1388 protected Object mTag;
1389
1390 // for mPrivateFlags:
1391 /** {@hide} */
1392 static final int WANTS_FOCUS = 0x00000001;
1393 /** {@hide} */
1394 static final int FOCUSED = 0x00000002;
1395 /** {@hide} */
1396 static final int SELECTED = 0x00000004;
1397 /** {@hide} */
1398 static final int IS_ROOT_NAMESPACE = 0x00000008;
1399 /** {@hide} */
1400 static final int HAS_BOUNDS = 0x00000010;
1401 /** {@hide} */
1402 static final int DRAWN = 0x00000020;
1403 /**
1404 * When this flag is set, this view is running an animation on behalf of its
1405 * children and should therefore not cancel invalidate requests, even if they
1406 * lie outside of this view's bounds.
1407 *
1408 * {@hide}
1409 */
1410 static final int DRAW_ANIMATION = 0x00000040;
1411 /** {@hide} */
1412 static final int SKIP_DRAW = 0x00000080;
1413 /** {@hide} */
1414 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1415 /** {@hide} */
1416 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1417 /** {@hide} */
1418 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1419 /** {@hide} */
1420 static final int MEASURED_DIMENSION_SET = 0x00000800;
1421 /** {@hide} */
1422 static final int FORCE_LAYOUT = 0x00001000;
1423
1424 private static final int LAYOUT_REQUIRED = 0x00002000;
1425
1426 private static final int PRESSED = 0x00004000;
1427
1428 /** {@hide} */
1429 static final int DRAWING_CACHE_VALID = 0x00008000;
1430 /**
1431 * Flag used to indicate that this view should be drawn once more (and only once
1432 * more) after its animation has completed.
1433 * {@hide}
1434 */
1435 static final int ANIMATION_STARTED = 0x00010000;
1436
1437 private static final int SAVE_STATE_CALLED = 0x00020000;
1438
1439 /**
1440 * Indicates that the View returned true when onSetAlpha() was called and that
1441 * the alpha must be restored.
1442 * {@hide}
1443 */
1444 static final int ALPHA_SET = 0x00040000;
1445
1446 /**
1447 * Set by {@link #setScrollContainer(boolean)}.
1448 */
1449 static final int SCROLL_CONTAINER = 0x00080000;
1450
1451 /**
1452 * Set by {@link #setScrollContainer(boolean)}.
1453 */
1454 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1455
1456 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001457 * View flag indicating whether this view was invalidated (fully or partially.)
1458 *
1459 * @hide
1460 */
1461 static final int DIRTY = 0x00200000;
1462
1463 /**
1464 * View flag indicating whether this view was invalidated by an opaque
1465 * invalidate request.
1466 *
1467 * @hide
1468 */
1469 static final int DIRTY_OPAQUE = 0x00400000;
1470
1471 /**
1472 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1473 *
1474 * @hide
1475 */
1476 static final int DIRTY_MASK = 0x00600000;
1477
1478 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001479 * Indicates whether the background is opaque.
1480 *
1481 * @hide
1482 */
1483 static final int OPAQUE_BACKGROUND = 0x00800000;
1484
1485 /**
1486 * Indicates whether the scrollbars are opaque.
1487 *
1488 * @hide
1489 */
1490 static final int OPAQUE_SCROLLBARS = 0x01000000;
1491
1492 /**
1493 * Indicates whether the view is opaque.
1494 *
1495 * @hide
1496 */
1497 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001498
1499 /**
1500 * Indicates a prepressed state;
1501 * the short time between ACTION_DOWN and recognizing
1502 * a 'real' press. Prepressed is used to recognize quick taps
1503 * even when they are shorter than ViewConfiguration.getTapTimeout().
1504 *
1505 * @hide
1506 */
1507 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001508
1509 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001510 * Indicates whether the view is temporarily detached.
1511 *
1512 * @hide
1513 */
1514 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1515
1516 /**
Adam Powellc9fbaab2010-02-16 17:16:19 -08001517 * Always allow a user to overscroll this view, provided it is a
1518 * view that can scroll.
Adam Powell51c5a0c2010-03-05 10:50:38 -08001519 *
1520 * @see #getOverscrollMode()
1521 * @see #setOverscrollMode(int)
Adam Powellc9fbaab2010-02-16 17:16:19 -08001522 */
Adam Powell51c5a0c2010-03-05 10:50:38 -08001523 public static final int OVERSCROLL_ALWAYS = 0;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001524
1525 /**
1526 * Allow a user to overscroll this view only if the content is large
1527 * enough to meaningfully scroll, provided it is a view that can scroll.
Adam Powell51c5a0c2010-03-05 10:50:38 -08001528 *
1529 * @see #getOverscrollMode()
1530 * @see #setOverscrollMode(int)
Adam Powellc9fbaab2010-02-16 17:16:19 -08001531 */
Adam Powell51c5a0c2010-03-05 10:50:38 -08001532 public static final int OVERSCROLL_IF_CONTENT_SCROLLS = 1;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001533
1534 /**
1535 * Never allow a user to overscroll this view.
Adam Powell51c5a0c2010-03-05 10:50:38 -08001536 *
1537 * @see #getOverscrollMode()
1538 * @see #setOverscrollMode(int)
Adam Powellc9fbaab2010-02-16 17:16:19 -08001539 */
Adam Powell51c5a0c2010-03-05 10:50:38 -08001540 public static final int OVERSCROLL_NEVER = 2;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001541
1542 /**
1543 * Controls the overscroll mode for this view.
1544 * See {@link #overscrollBy(int, int, int, int, int, int, int, int)},
1545 * {@link #OVERSCROLL_ALWAYS}, {@link #OVERSCROLL_IF_CONTENT_SCROLLS},
1546 * and {@link #OVERSCROLL_NEVER}.
1547 */
1548 private int mOverscrollMode = OVERSCROLL_ALWAYS;
Romain Guy8f1344f52009-05-15 16:03:59 -07001549
1550 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 * The parent this view is attached to.
1552 * {@hide}
1553 *
1554 * @see #getParent()
1555 */
1556 protected ViewParent mParent;
1557
1558 /**
1559 * {@hide}
1560 */
1561 AttachInfo mAttachInfo;
1562
1563 /**
1564 * {@hide}
1565 */
Romain Guy809a7f62009-05-14 15:44:42 -07001566 @ViewDebug.ExportedProperty(flagMapping = {
1567 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1568 name = "FORCE_LAYOUT"),
1569 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1570 name = "LAYOUT_REQUIRED"),
1571 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001572 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001573 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1574 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1575 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1576 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1577 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 int mPrivateFlags;
1579
1580 /**
1581 * Count of how many windows this view has been attached to.
1582 */
1583 int mWindowAttachCount;
1584
1585 /**
1586 * The layout parameters associated with this view and used by the parent
1587 * {@link android.view.ViewGroup} to determine how this view should be
1588 * laid out.
1589 * {@hide}
1590 */
1591 protected ViewGroup.LayoutParams mLayoutParams;
1592
1593 /**
1594 * The view flags hold various views states.
1595 * {@hide}
1596 */
1597 @ViewDebug.ExportedProperty
1598 int mViewFlags;
1599
1600 /**
1601 * The distance in pixels from the left edge of this view's parent
1602 * to the left edge of this view.
1603 * {@hide}
1604 */
1605 @ViewDebug.ExportedProperty
1606 protected int mLeft;
1607 /**
1608 * The distance in pixels from the left edge of this view's parent
1609 * to the right edge of this view.
1610 * {@hide}
1611 */
1612 @ViewDebug.ExportedProperty
1613 protected int mRight;
1614 /**
1615 * The distance in pixels from the top edge of this view's parent
1616 * to the top edge of this view.
1617 * {@hide}
1618 */
1619 @ViewDebug.ExportedProperty
1620 protected int mTop;
1621 /**
1622 * The distance in pixels from the top edge of this view's parent
1623 * to the bottom edge of this view.
1624 * {@hide}
1625 */
1626 @ViewDebug.ExportedProperty
1627 protected int mBottom;
1628
1629 /**
1630 * The offset, in pixels, by which the content of this view is scrolled
1631 * horizontally.
1632 * {@hide}
1633 */
1634 @ViewDebug.ExportedProperty
1635 protected int mScrollX;
1636 /**
1637 * The offset, in pixels, by which the content of this view is scrolled
1638 * vertically.
1639 * {@hide}
1640 */
1641 @ViewDebug.ExportedProperty
1642 protected int mScrollY;
1643
1644 /**
1645 * The left padding in pixels, that is the distance in pixels between the
1646 * left edge of this view and the left edge of its content.
1647 * {@hide}
1648 */
1649 @ViewDebug.ExportedProperty
1650 protected int mPaddingLeft;
1651 /**
1652 * The right padding in pixels, that is the distance in pixels between the
1653 * right edge of this view and the right edge of its content.
1654 * {@hide}
1655 */
1656 @ViewDebug.ExportedProperty
1657 protected int mPaddingRight;
1658 /**
1659 * The top padding in pixels, that is the distance in pixels between the
1660 * top edge of this view and the top edge of its content.
1661 * {@hide}
1662 */
1663 @ViewDebug.ExportedProperty
1664 protected int mPaddingTop;
1665 /**
1666 * The bottom padding in pixels, that is the distance in pixels between the
1667 * bottom edge of this view and the bottom edge of its content.
1668 * {@hide}
1669 */
1670 @ViewDebug.ExportedProperty
1671 protected int mPaddingBottom;
1672
1673 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001674 * Briefly describes the view and is primarily used for accessibility support.
1675 */
1676 private CharSequence mContentDescription;
1677
1678 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 * Cache the paddingRight set by the user to append to the scrollbar's size.
1680 */
1681 @ViewDebug.ExportedProperty
1682 int mUserPaddingRight;
1683
1684 /**
1685 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1686 */
1687 @ViewDebug.ExportedProperty
1688 int mUserPaddingBottom;
1689
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001690 /**
1691 * @hide
1692 */
1693 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1694 /**
1695 * @hide
1696 */
1697 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698
1699 private Resources mResources = null;
1700
1701 private Drawable mBGDrawable;
1702
1703 private int mBackgroundResource;
1704 private boolean mBackgroundSizeChanged;
1705
1706 /**
1707 * Listener used to dispatch focus change events.
1708 * This field should be made private, so it is hidden from the SDK.
1709 * {@hide}
1710 */
1711 protected OnFocusChangeListener mOnFocusChangeListener;
1712
1713 /**
1714 * Listener used to dispatch click events.
1715 * This field should be made private, so it is hidden from the SDK.
1716 * {@hide}
1717 */
1718 protected OnClickListener mOnClickListener;
1719
1720 /**
1721 * Listener used to dispatch long click events.
1722 * This field should be made private, so it is hidden from the SDK.
1723 * {@hide}
1724 */
1725 protected OnLongClickListener mOnLongClickListener;
1726
1727 /**
1728 * Listener used to build the context menu.
1729 * This field should be made private, so it is hidden from the SDK.
1730 * {@hide}
1731 */
1732 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
1733
1734 private OnKeyListener mOnKeyListener;
1735
1736 private OnTouchListener mOnTouchListener;
1737
1738 /**
1739 * The application environment this view lives in.
1740 * This field should be made private, so it is hidden from the SDK.
1741 * {@hide}
1742 */
1743 protected Context mContext;
1744
1745 private ScrollabilityCache mScrollCache;
1746
1747 private int[] mDrawableState = null;
1748
1749 private SoftReference<Bitmap> mDrawingCache;
Romain Guyfbd8f692009-06-26 14:51:58 -07001750 private SoftReference<Bitmap> mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751
1752 /**
1753 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
1754 * the user may specify which view to go to next.
1755 */
1756 private int mNextFocusLeftId = View.NO_ID;
1757
1758 /**
1759 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
1760 * the user may specify which view to go to next.
1761 */
1762 private int mNextFocusRightId = View.NO_ID;
1763
1764 /**
1765 * When this view has focus and the next focus is {@link #FOCUS_UP},
1766 * the user may specify which view to go to next.
1767 */
1768 private int mNextFocusUpId = View.NO_ID;
1769
1770 /**
1771 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
1772 * the user may specify which view to go to next.
1773 */
1774 private int mNextFocusDownId = View.NO_ID;
1775
1776 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08001777 private CheckForTap mPendingCheckForTap = null;
1778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 private UnsetPressedState mUnsetPressedState;
1780
1781 /**
1782 * Whether the long press's action has been invoked. The tap's action is invoked on the
1783 * up event while a long press is invoked as soon as the long press duration is reached, so
1784 * a long press could be performed before the tap is checked, in which case the tap's action
1785 * should not be invoked.
1786 */
1787 private boolean mHasPerformedLongPress;
1788
1789 /**
1790 * The minimum height of the view. We'll try our best to have the height
1791 * of this view to at least this amount.
1792 */
1793 @ViewDebug.ExportedProperty
1794 private int mMinHeight;
1795
1796 /**
1797 * The minimum width of the view. We'll try our best to have the width
1798 * of this view to at least this amount.
1799 */
1800 @ViewDebug.ExportedProperty
1801 private int mMinWidth;
1802
1803 /**
1804 * The delegate to handle touch events that are physically in this view
1805 * but should be handled by another view.
1806 */
1807 private TouchDelegate mTouchDelegate = null;
1808
1809 /**
1810 * Solid color to use as a background when creating the drawing cache. Enables
1811 * the cache to use 16 bit bitmaps instead of 32 bit.
1812 */
1813 private int mDrawingCacheBackgroundColor = 0;
1814
1815 /**
1816 * Special tree observer used when mAttachInfo is null.
1817 */
1818 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08001819
1820 /**
1821 * Cache the touch slop from the context that created the view.
1822 */
1823 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824
1825 // Used for debug only
1826 static long sInstanceCount = 0;
1827
1828 /**
1829 * Simple constructor to use when creating a view from code.
1830 *
1831 * @param context The Context the view is running in, through which it can
1832 * access the current theme, resources, etc.
1833 */
1834 public View(Context context) {
1835 mContext = context;
1836 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07001837 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Carl Shapiro82fe5642010-02-24 00:14:23 -08001838 // Used for debug only
1839 //++sInstanceCount;
Adam Powelle14579b2009-12-16 18:39:52 -08001840 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 }
1842
1843 /**
1844 * Constructor that is called when inflating a view from XML. This is called
1845 * when a view is being constructed from an XML file, supplying attributes
1846 * that were specified in the XML file. This version uses a default style of
1847 * 0, so the only attribute values applied are those in the Context's Theme
1848 * and the given AttributeSet.
1849 *
1850 * <p>
1851 * The method onFinishInflate() will be called after all children have been
1852 * added.
1853 *
1854 * @param context The Context the view is running in, through which it can
1855 * access the current theme, resources, etc.
1856 * @param attrs The attributes of the XML tag that is inflating the view.
1857 * @see #View(Context, AttributeSet, int)
1858 */
1859 public View(Context context, AttributeSet attrs) {
1860 this(context, attrs, 0);
1861 }
1862
1863 /**
1864 * Perform inflation from XML and apply a class-specific base style. This
1865 * constructor of View allows subclasses to use their own base style when
1866 * they are inflating. For example, a Button class's constructor would call
1867 * this version of the super class constructor and supply
1868 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
1869 * the theme's button style to modify all of the base view attributes (in
1870 * particular its background) as well as the Button class's attributes.
1871 *
1872 * @param context The Context the view is running in, through which it can
1873 * access the current theme, resources, etc.
1874 * @param attrs The attributes of the XML tag that is inflating the view.
1875 * @param defStyle The default style to apply to this view. If 0, no style
1876 * will be applied (beyond what is included in the theme). This may
1877 * either be an attribute resource, whose value will be retrieved
1878 * from the current theme, or an explicit style resource.
1879 * @see #View(Context, AttributeSet)
1880 */
1881 public View(Context context, AttributeSet attrs, int defStyle) {
1882 this(context);
1883
1884 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
1885 defStyle, 0);
1886
1887 Drawable background = null;
1888
1889 int leftPadding = -1;
1890 int topPadding = -1;
1891 int rightPadding = -1;
1892 int bottomPadding = -1;
1893
1894 int padding = -1;
1895
1896 int viewFlagValues = 0;
1897 int viewFlagMasks = 0;
1898
1899 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 int x = 0;
1902 int y = 0;
1903
1904 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
1905
1906 final int N = a.getIndexCount();
1907 for (int i = 0; i < N; i++) {
1908 int attr = a.getIndex(i);
1909 switch (attr) {
1910 case com.android.internal.R.styleable.View_background:
1911 background = a.getDrawable(attr);
1912 break;
1913 case com.android.internal.R.styleable.View_padding:
1914 padding = a.getDimensionPixelSize(attr, -1);
1915 break;
1916 case com.android.internal.R.styleable.View_paddingLeft:
1917 leftPadding = a.getDimensionPixelSize(attr, -1);
1918 break;
1919 case com.android.internal.R.styleable.View_paddingTop:
1920 topPadding = a.getDimensionPixelSize(attr, -1);
1921 break;
1922 case com.android.internal.R.styleable.View_paddingRight:
1923 rightPadding = a.getDimensionPixelSize(attr, -1);
1924 break;
1925 case com.android.internal.R.styleable.View_paddingBottom:
1926 bottomPadding = a.getDimensionPixelSize(attr, -1);
1927 break;
1928 case com.android.internal.R.styleable.View_scrollX:
1929 x = a.getDimensionPixelOffset(attr, 0);
1930 break;
1931 case com.android.internal.R.styleable.View_scrollY:
1932 y = a.getDimensionPixelOffset(attr, 0);
1933 break;
1934 case com.android.internal.R.styleable.View_id:
1935 mID = a.getResourceId(attr, NO_ID);
1936 break;
1937 case com.android.internal.R.styleable.View_tag:
1938 mTag = a.getText(attr);
1939 break;
1940 case com.android.internal.R.styleable.View_fitsSystemWindows:
1941 if (a.getBoolean(attr, false)) {
1942 viewFlagValues |= FITS_SYSTEM_WINDOWS;
1943 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
1944 }
1945 break;
1946 case com.android.internal.R.styleable.View_focusable:
1947 if (a.getBoolean(attr, false)) {
1948 viewFlagValues |= FOCUSABLE;
1949 viewFlagMasks |= FOCUSABLE_MASK;
1950 }
1951 break;
1952 case com.android.internal.R.styleable.View_focusableInTouchMode:
1953 if (a.getBoolean(attr, false)) {
1954 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
1955 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
1956 }
1957 break;
1958 case com.android.internal.R.styleable.View_clickable:
1959 if (a.getBoolean(attr, false)) {
1960 viewFlagValues |= CLICKABLE;
1961 viewFlagMasks |= CLICKABLE;
1962 }
1963 break;
1964 case com.android.internal.R.styleable.View_longClickable:
1965 if (a.getBoolean(attr, false)) {
1966 viewFlagValues |= LONG_CLICKABLE;
1967 viewFlagMasks |= LONG_CLICKABLE;
1968 }
1969 break;
1970 case com.android.internal.R.styleable.View_saveEnabled:
1971 if (!a.getBoolean(attr, true)) {
1972 viewFlagValues |= SAVE_DISABLED;
1973 viewFlagMasks |= SAVE_DISABLED_MASK;
1974 }
1975 break;
1976 case com.android.internal.R.styleable.View_duplicateParentState:
1977 if (a.getBoolean(attr, false)) {
1978 viewFlagValues |= DUPLICATE_PARENT_STATE;
1979 viewFlagMasks |= DUPLICATE_PARENT_STATE;
1980 }
1981 break;
1982 case com.android.internal.R.styleable.View_visibility:
1983 final int visibility = a.getInt(attr, 0);
1984 if (visibility != 0) {
1985 viewFlagValues |= VISIBILITY_FLAGS[visibility];
1986 viewFlagMasks |= VISIBILITY_MASK;
1987 }
1988 break;
1989 case com.android.internal.R.styleable.View_drawingCacheQuality:
1990 final int cacheQuality = a.getInt(attr, 0);
1991 if (cacheQuality != 0) {
1992 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
1993 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
1994 }
1995 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07001996 case com.android.internal.R.styleable.View_contentDescription:
1997 mContentDescription = a.getString(attr);
1998 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2000 if (!a.getBoolean(attr, true)) {
2001 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2002 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2003 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002004 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2006 if (!a.getBoolean(attr, true)) {
2007 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2008 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2009 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002010 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 case R.styleable.View_scrollbars:
2012 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2013 if (scrollbars != SCROLLBARS_NONE) {
2014 viewFlagValues |= scrollbars;
2015 viewFlagMasks |= SCROLLBARS_MASK;
2016 initializeScrollbars(a);
2017 }
2018 break;
2019 case R.styleable.View_fadingEdge:
2020 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2021 if (fadingEdge != FADING_EDGE_NONE) {
2022 viewFlagValues |= fadingEdge;
2023 viewFlagMasks |= FADING_EDGE_MASK;
2024 initializeFadingEdge(a);
2025 }
2026 break;
2027 case R.styleable.View_scrollbarStyle:
2028 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2029 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2030 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2031 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2032 }
2033 break;
2034 case R.styleable.View_isScrollContainer:
2035 setScrollContainer = true;
2036 if (a.getBoolean(attr, false)) {
2037 setScrollContainer(true);
2038 }
2039 break;
2040 case com.android.internal.R.styleable.View_keepScreenOn:
2041 if (a.getBoolean(attr, false)) {
2042 viewFlagValues |= KEEP_SCREEN_ON;
2043 viewFlagMasks |= KEEP_SCREEN_ON;
2044 }
2045 break;
2046 case R.styleable.View_nextFocusLeft:
2047 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2048 break;
2049 case R.styleable.View_nextFocusRight:
2050 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2051 break;
2052 case R.styleable.View_nextFocusUp:
2053 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2054 break;
2055 case R.styleable.View_nextFocusDown:
2056 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2057 break;
2058 case R.styleable.View_minWidth:
2059 mMinWidth = a.getDimensionPixelSize(attr, 0);
2060 break;
2061 case R.styleable.View_minHeight:
2062 mMinHeight = a.getDimensionPixelSize(attr, 0);
2063 break;
Romain Guy9a817362009-05-01 10:57:14 -07002064 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002065 if (context.isRestricted()) {
2066 throw new IllegalStateException("The android:onClick attribute cannot "
2067 + "be used within a restricted context");
2068 }
2069
Romain Guy9a817362009-05-01 10:57:14 -07002070 final String handlerName = a.getString(attr);
2071 if (handlerName != null) {
2072 setOnClickListener(new OnClickListener() {
2073 private Method mHandler;
2074
2075 public void onClick(View v) {
2076 if (mHandler == null) {
2077 try {
2078 mHandler = getContext().getClass().getMethod(handlerName,
2079 View.class);
2080 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002081 int id = getId();
2082 String idText = id == NO_ID ? "" : " with id '"
2083 + getContext().getResources().getResourceEntryName(
2084 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002085 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002086 handlerName + "(View) in the activity "
2087 + getContext().getClass() + " for onClick handler"
2088 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002089 }
2090 }
2091
2092 try {
2093 mHandler.invoke(getContext(), View.this);
2094 } catch (IllegalAccessException e) {
2095 throw new IllegalStateException("Could not execute non "
2096 + "public method of the activity", e);
2097 } catch (InvocationTargetException e) {
2098 throw new IllegalStateException("Could not execute "
2099 + "method of the activity", e);
2100 }
2101 }
2102 });
2103 }
2104 break;
Adam Powellc9fbaab2010-02-16 17:16:19 -08002105 case R.styleable.View_overscrollMode:
2106 mOverscrollMode = a.getInt(attr, OVERSCROLL_ALWAYS);
2107 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 }
2109 }
2110
2111 if (background != null) {
2112 setBackgroundDrawable(background);
2113 }
2114
2115 if (padding >= 0) {
2116 leftPadding = padding;
2117 topPadding = padding;
2118 rightPadding = padding;
2119 bottomPadding = padding;
2120 }
2121
2122 // If the user specified the padding (either with android:padding or
2123 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2124 // use the default padding or the padding from the background drawable
2125 // (stored at this point in mPadding*)
2126 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2127 topPadding >= 0 ? topPadding : mPaddingTop,
2128 rightPadding >= 0 ? rightPadding : mPaddingRight,
2129 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2130
2131 if (viewFlagMasks != 0) {
2132 setFlags(viewFlagValues, viewFlagMasks);
2133 }
2134
2135 // Needs to be called after mViewFlags is set
2136 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2137 recomputePadding();
2138 }
2139
2140 if (x != 0 || y != 0) {
2141 scrollTo(x, y);
2142 }
2143
2144 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2145 setScrollContainer(true);
2146 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002147
2148 computeOpaqueFlags();
2149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 a.recycle();
2151 }
2152
2153 /**
2154 * Non-public constructor for use in testing
2155 */
2156 View() {
2157 }
2158
Carl Shapiro82fe5642010-02-24 00:14:23 -08002159 // Used for debug only
2160 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 @Override
2162 protected void finalize() throws Throwable {
2163 super.finalize();
2164 --sInstanceCount;
2165 }
Carl Shapiro82fe5642010-02-24 00:14:23 -08002166 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167
2168 /**
2169 * <p>
2170 * Initializes the fading edges from a given set of styled attributes. This
2171 * method should be called by subclasses that need fading edges and when an
2172 * instance of these subclasses is created programmatically rather than
2173 * being inflated from XML. This method is automatically called when the XML
2174 * is inflated.
2175 * </p>
2176 *
2177 * @param a the styled attributes set to initialize the fading edges from
2178 */
2179 protected void initializeFadingEdge(TypedArray a) {
2180 initScrollCache();
2181
2182 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2183 R.styleable.View_fadingEdgeLength,
2184 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2185 }
2186
2187 /**
2188 * Returns the size of the vertical faded edges used to indicate that more
2189 * content in this view is visible.
2190 *
2191 * @return The size in pixels of the vertical faded edge or 0 if vertical
2192 * faded edges are not enabled for this view.
2193 * @attr ref android.R.styleable#View_fadingEdgeLength
2194 */
2195 public int getVerticalFadingEdgeLength() {
2196 if (isVerticalFadingEdgeEnabled()) {
2197 ScrollabilityCache cache = mScrollCache;
2198 if (cache != null) {
2199 return cache.fadingEdgeLength;
2200 }
2201 }
2202 return 0;
2203 }
2204
2205 /**
2206 * Set the size of the faded edge used to indicate that more content in this
2207 * view is available. Will not change whether the fading edge is enabled; use
2208 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2209 * to enable the fading edge for the vertical or horizontal fading edges.
2210 *
2211 * @param length The size in pixels of the faded edge used to indicate that more
2212 * content in this view is visible.
2213 */
2214 public void setFadingEdgeLength(int length) {
2215 initScrollCache();
2216 mScrollCache.fadingEdgeLength = length;
2217 }
2218
2219 /**
2220 * Returns the size of the horizontal faded edges used to indicate that more
2221 * content in this view is visible.
2222 *
2223 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2224 * faded edges are not enabled for this view.
2225 * @attr ref android.R.styleable#View_fadingEdgeLength
2226 */
2227 public int getHorizontalFadingEdgeLength() {
2228 if (isHorizontalFadingEdgeEnabled()) {
2229 ScrollabilityCache cache = mScrollCache;
2230 if (cache != null) {
2231 return cache.fadingEdgeLength;
2232 }
2233 }
2234 return 0;
2235 }
2236
2237 /**
2238 * Returns the width of the vertical scrollbar.
2239 *
2240 * @return The width in pixels of the vertical scrollbar or 0 if there
2241 * is no vertical scrollbar.
2242 */
2243 public int getVerticalScrollbarWidth() {
2244 ScrollabilityCache cache = mScrollCache;
2245 if (cache != null) {
2246 ScrollBarDrawable scrollBar = cache.scrollBar;
2247 if (scrollBar != null) {
2248 int size = scrollBar.getSize(true);
2249 if (size <= 0) {
2250 size = cache.scrollBarSize;
2251 }
2252 return size;
2253 }
2254 return 0;
2255 }
2256 return 0;
2257 }
2258
2259 /**
2260 * Returns the height of the horizontal scrollbar.
2261 *
2262 * @return The height in pixels of the horizontal scrollbar or 0 if
2263 * there is no horizontal scrollbar.
2264 */
2265 protected int getHorizontalScrollbarHeight() {
2266 ScrollabilityCache cache = mScrollCache;
2267 if (cache != null) {
2268 ScrollBarDrawable scrollBar = cache.scrollBar;
2269 if (scrollBar != null) {
2270 int size = scrollBar.getSize(false);
2271 if (size <= 0) {
2272 size = cache.scrollBarSize;
2273 }
2274 return size;
2275 }
2276 return 0;
2277 }
2278 return 0;
2279 }
2280
2281 /**
2282 * <p>
2283 * Initializes the scrollbars from a given set of styled attributes. This
2284 * method should be called by subclasses that need scrollbars and when an
2285 * instance of these subclasses is created programmatically rather than
2286 * being inflated from XML. This method is automatically called when the XML
2287 * is inflated.
2288 * </p>
2289 *
2290 * @param a the styled attributes set to initialize the scrollbars from
2291 */
2292 protected void initializeScrollbars(TypedArray a) {
2293 initScrollCache();
2294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002296
2297 if (scrollabilityCache.scrollBar == null) {
2298 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2299 }
2300
Romain Guy8bda2482010-03-02 11:42:11 -08002301 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302
Mike Cleronf116bf82009-09-27 19:14:12 -07002303 if (!fadeScrollbars) {
2304 scrollabilityCache.state = ScrollabilityCache.ON;
2305 }
2306 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2307
2308
2309 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2310 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2311 .getScrollBarFadeDuration());
2312 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2313 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2314 ViewConfiguration.getScrollDefaultDelay());
2315
2316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2318 com.android.internal.R.styleable.View_scrollbarSize,
2319 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2320
2321 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2322 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2323
2324 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2325 if (thumb != null) {
2326 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2327 }
2328
2329 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2330 false);
2331 if (alwaysDraw) {
2332 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2333 }
2334
2335 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2336 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2337
2338 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2339 if (thumb != null) {
2340 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2341 }
2342
2343 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2344 false);
2345 if (alwaysDraw) {
2346 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2347 }
2348
2349 // Re-apply user/background padding so that scrollbar(s) get added
2350 recomputePadding();
2351 }
2352
2353 /**
2354 * <p>
2355 * Initalizes the scrollability cache if necessary.
2356 * </p>
2357 */
2358 private void initScrollCache() {
2359 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002360 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 }
2362 }
2363
2364 /**
2365 * Register a callback to be invoked when focus of this view changed.
2366 *
2367 * @param l The callback that will run.
2368 */
2369 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2370 mOnFocusChangeListener = l;
2371 }
2372
2373 /**
2374 * Returns the focus-change callback registered for this view.
2375 *
2376 * @return The callback, or null if one is not registered.
2377 */
2378 public OnFocusChangeListener getOnFocusChangeListener() {
2379 return mOnFocusChangeListener;
2380 }
2381
2382 /**
2383 * Register a callback to be invoked when this view is clicked. If this view is not
2384 * clickable, it becomes clickable.
2385 *
2386 * @param l The callback that will run
2387 *
2388 * @see #setClickable(boolean)
2389 */
2390 public void setOnClickListener(OnClickListener l) {
2391 if (!isClickable()) {
2392 setClickable(true);
2393 }
2394 mOnClickListener = l;
2395 }
2396
2397 /**
2398 * Register a callback to be invoked when this view is clicked and held. If this view is not
2399 * long clickable, it becomes long clickable.
2400 *
2401 * @param l The callback that will run
2402 *
2403 * @see #setLongClickable(boolean)
2404 */
2405 public void setOnLongClickListener(OnLongClickListener l) {
2406 if (!isLongClickable()) {
2407 setLongClickable(true);
2408 }
2409 mOnLongClickListener = l;
2410 }
2411
2412 /**
2413 * Register a callback to be invoked when the context menu for this view is
2414 * being built. If this view is not long clickable, it becomes long clickable.
2415 *
2416 * @param l The callback that will run
2417 *
2418 */
2419 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2420 if (!isLongClickable()) {
2421 setLongClickable(true);
2422 }
2423 mOnCreateContextMenuListener = l;
2424 }
2425
2426 /**
2427 * Call this view's OnClickListener, if it is defined.
2428 *
2429 * @return True there was an assigned OnClickListener that was called, false
2430 * otherwise is returned.
2431 */
2432 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002433 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 if (mOnClickListener != null) {
2436 playSoundEffect(SoundEffectConstants.CLICK);
2437 mOnClickListener.onClick(this);
2438 return true;
2439 }
2440
2441 return false;
2442 }
2443
2444 /**
2445 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu
2446 * if the OnLongClickListener did not consume the event.
2447 *
2448 * @return True there was an assigned OnLongClickListener that was called, false
2449 * otherwise is returned.
2450 */
2451 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002452 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 boolean handled = false;
2455 if (mOnLongClickListener != null) {
2456 handled = mOnLongClickListener.onLongClick(View.this);
2457 }
2458 if (!handled) {
2459 handled = showContextMenu();
2460 }
2461 if (handled) {
2462 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2463 }
2464 return handled;
2465 }
2466
2467 /**
2468 * Bring up the context menu for this view.
2469 *
2470 * @return Whether a context menu was displayed.
2471 */
2472 public boolean showContextMenu() {
2473 return getParent().showContextMenuForChild(this);
2474 }
2475
2476 /**
2477 * Register a callback to be invoked when a key is pressed in this view.
2478 * @param l the key listener to attach to this view
2479 */
2480 public void setOnKeyListener(OnKeyListener l) {
2481 mOnKeyListener = l;
2482 }
2483
2484 /**
2485 * Register a callback to be invoked when a touch event is sent to this view.
2486 * @param l the touch listener to attach to this view
2487 */
2488 public void setOnTouchListener(OnTouchListener l) {
2489 mOnTouchListener = l;
2490 }
2491
2492 /**
2493 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2494 *
2495 * Note: this does not check whether this {@link View} should get focus, it just
2496 * gives it focus no matter what. It should only be called internally by framework
2497 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2498 *
2499 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2500 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2501 * focus moved when requestFocus() is called. It may not always
2502 * apply, in which case use the default View.FOCUS_DOWN.
2503 * @param previouslyFocusedRect The rectangle of the view that had focus
2504 * prior in this View's coordinate system.
2505 */
2506 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2507 if (DBG) {
2508 System.out.println(this + " requestFocus()");
2509 }
2510
2511 if ((mPrivateFlags & FOCUSED) == 0) {
2512 mPrivateFlags |= FOCUSED;
2513
2514 if (mParent != null) {
2515 mParent.requestChildFocus(this, this);
2516 }
2517
2518 onFocusChanged(true, direction, previouslyFocusedRect);
2519 refreshDrawableState();
2520 }
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 * @param rectangle The rectangle.
2532 * @return Whether any parent scrolled.
2533 */
2534 public boolean requestRectangleOnScreen(Rect rectangle) {
2535 return requestRectangleOnScreen(rectangle, false);
2536 }
2537
2538 /**
2539 * Request that a rectangle of this view be visible on the screen,
2540 * scrolling if necessary just enough.
2541 *
2542 * <p>A View should call this if it maintains some notion of which part
2543 * of its content is interesting. For example, a text editing view
2544 * should call this when its cursor moves.
2545 *
2546 * <p>When <code>immediate</code> is set to true, scrolling will not be
2547 * animated.
2548 *
2549 * @param rectangle The rectangle.
2550 * @param immediate True to forbid animated scrolling, false otherwise
2551 * @return Whether any parent scrolled.
2552 */
2553 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
2554 View child = this;
2555 ViewParent parent = mParent;
2556 boolean scrolled = false;
2557 while (parent != null) {
2558 scrolled |= parent.requestChildRectangleOnScreen(child,
2559 rectangle, immediate);
2560
2561 // offset rect so next call has the rectangle in the
2562 // coordinate system of its direct child.
2563 rectangle.offset(child.getLeft(), child.getTop());
2564 rectangle.offset(-child.getScrollX(), -child.getScrollY());
2565
2566 if (!(parent instanceof View)) {
2567 break;
2568 }
Romain Guy8506ab42009-06-11 17:35:47 -07002569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 child = (View) parent;
2571 parent = child.getParent();
2572 }
2573 return scrolled;
2574 }
2575
2576 /**
2577 * Called when this view wants to give up focus. This will cause
2578 * {@link #onFocusChanged} to be called.
2579 */
2580 public void clearFocus() {
2581 if (DBG) {
2582 System.out.println(this + " clearFocus()");
2583 }
2584
2585 if ((mPrivateFlags & FOCUSED) != 0) {
2586 mPrivateFlags &= ~FOCUSED;
2587
2588 if (mParent != null) {
2589 mParent.clearChildFocus(this);
2590 }
2591
2592 onFocusChanged(false, 0, null);
2593 refreshDrawableState();
2594 }
2595 }
2596
2597 /**
2598 * Called to clear the focus of a view that is about to be removed.
2599 * Doesn't call clearChildFocus, which prevents this view from taking
2600 * focus again before it has been removed from the parent
2601 */
2602 void clearFocusForRemoval() {
2603 if ((mPrivateFlags & FOCUSED) != 0) {
2604 mPrivateFlags &= ~FOCUSED;
2605
2606 onFocusChanged(false, 0, null);
2607 refreshDrawableState();
2608 }
2609 }
2610
2611 /**
2612 * Called internally by the view system when a new view is getting focus.
2613 * This is what clears the old focus.
2614 */
2615 void unFocus() {
2616 if (DBG) {
2617 System.out.println(this + " unFocus()");
2618 }
2619
2620 if ((mPrivateFlags & FOCUSED) != 0) {
2621 mPrivateFlags &= ~FOCUSED;
2622
2623 onFocusChanged(false, 0, null);
2624 refreshDrawableState();
2625 }
2626 }
2627
2628 /**
2629 * Returns true if this view has focus iteself, or is the ancestor of the
2630 * view that has focus.
2631 *
2632 * @return True if this view has or contains focus, false otherwise.
2633 */
2634 @ViewDebug.ExportedProperty
2635 public boolean hasFocus() {
2636 return (mPrivateFlags & FOCUSED) != 0;
2637 }
2638
2639 /**
2640 * Returns true if this view is focusable or if it contains a reachable View
2641 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
2642 * is a View whose parents do not block descendants focus.
2643 *
2644 * Only {@link #VISIBLE} views are considered focusable.
2645 *
2646 * @return True if the view is focusable or if the view contains a focusable
2647 * View, false otherwise.
2648 *
2649 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
2650 */
2651 public boolean hasFocusable() {
2652 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
2653 }
2654
2655 /**
2656 * Called by the view system when the focus state of this view changes.
2657 * When the focus change event is caused by directional navigation, direction
2658 * and previouslyFocusedRect provide insight into where the focus is coming from.
2659 * When overriding, be sure to call up through to the super class so that
2660 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07002661 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 * @param gainFocus True if the View has focus; false otherwise.
2663 * @param direction The direction focus has moved when requestFocus()
2664 * is called to give this view focus. Values are
Romain Guyea4823c2009-12-08 15:03:39 -08002665 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT} or
2666 * {@link #FOCUS_RIGHT}. It may not always apply, in which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 * case use the default.
2668 * @param previouslyFocusedRect The rectangle, in this view's coordinate
2669 * system, of the previously focused view. If applicable, this will be
2670 * passed in as finer grained information about where the focus is coming
2671 * from (in addition to direction). Will be <code>null</code> otherwise.
2672 */
2673 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07002674 if (gainFocus) {
2675 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2676 }
2677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 InputMethodManager imm = InputMethodManager.peekInstance();
2679 if (!gainFocus) {
2680 if (isPressed()) {
2681 setPressed(false);
2682 }
2683 if (imm != null && mAttachInfo != null
2684 && mAttachInfo.mHasWindowFocus) {
2685 imm.focusOut(this);
2686 }
Romain Guya2431d02009-04-30 16:30:00 -07002687 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 } else if (imm != null && mAttachInfo != null
2689 && mAttachInfo.mHasWindowFocus) {
2690 imm.focusIn(this);
2691 }
Romain Guy8506ab42009-06-11 17:35:47 -07002692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 invalidate();
2694 if (mOnFocusChangeListener != null) {
2695 mOnFocusChangeListener.onFocusChange(this, gainFocus);
2696 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002697
2698 if (mAttachInfo != null) {
2699 mAttachInfo.mKeyDispatchState.reset(this);
2700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 }
2702
2703 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002704 * {@inheritDoc}
2705 */
2706 public void sendAccessibilityEvent(int eventType) {
2707 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2708 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
2709 }
2710 }
2711
2712 /**
2713 * {@inheritDoc}
2714 */
2715 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
2716 event.setClassName(getClass().getName());
2717 event.setPackageName(getContext().getPackageName());
2718 event.setEnabled(isEnabled());
2719 event.setContentDescription(mContentDescription);
2720
2721 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
2722 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
2723 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
2724 event.setItemCount(focusablesTempList.size());
2725 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
2726 focusablesTempList.clear();
2727 }
2728
2729 dispatchPopulateAccessibilityEvent(event);
2730
2731 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
2732 }
2733
2734 /**
2735 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
2736 * to be populated.
2737 *
2738 * @param event The event.
2739 *
2740 * @return True if the event population was completed.
2741 */
2742 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2743 return false;
2744 }
2745
2746 /**
2747 * Gets 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 * @return The content descriptiopn.
2754 *
2755 * @attr ref android.R.styleable#View_contentDescription
2756 */
2757 public CharSequence getContentDescription() {
2758 return mContentDescription;
2759 }
2760
2761 /**
2762 * Sets the {@link View} description. It briefly describes the view and is
2763 * primarily used for accessibility support. Set this property to enable
2764 * better accessibility support for your application. This is especially
2765 * true for views that do not have textual representation (For example,
2766 * ImageButton).
2767 *
2768 * @param contentDescription The content description.
2769 *
2770 * @attr ref android.R.styleable#View_contentDescription
2771 */
2772 public void setContentDescription(CharSequence contentDescription) {
2773 mContentDescription = contentDescription;
2774 }
2775
2776 /**
Romain Guya2431d02009-04-30 16:30:00 -07002777 * Invoked whenever this view loses focus, either by losing window focus or by losing
2778 * focus within its window. This method can be used to clear any state tied to the
2779 * focus. For instance, if a button is held pressed with the trackball and the window
2780 * loses focus, this method can be used to cancel the press.
2781 *
2782 * Subclasses of View overriding this method should always call super.onFocusLost().
2783 *
2784 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07002785 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07002786 *
2787 * @hide pending API council approval
2788 */
2789 protected void onFocusLost() {
2790 resetPressedState();
2791 }
2792
2793 private void resetPressedState() {
2794 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
2795 return;
2796 }
2797
2798 if (isPressed()) {
2799 setPressed(false);
2800
2801 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05002802 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07002803 }
2804 }
2805 }
2806
2807 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 * Returns true if this view has focus
2809 *
2810 * @return True if this view has focus, false otherwise.
2811 */
2812 @ViewDebug.ExportedProperty
2813 public boolean isFocused() {
2814 return (mPrivateFlags & FOCUSED) != 0;
2815 }
2816
2817 /**
2818 * Find the view in the hierarchy rooted at this view that currently has
2819 * focus.
2820 *
2821 * @return The view that currently has focus, or null if no focused view can
2822 * be found.
2823 */
2824 public View findFocus() {
2825 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
2826 }
2827
2828 /**
2829 * Change whether this view is one of the set of scrollable containers in
2830 * its window. This will be used to determine whether the window can
2831 * resize or must pan when a soft input area is open -- scrollable
2832 * containers allow the window to use resize mode since the container
2833 * will appropriately shrink.
2834 */
2835 public void setScrollContainer(boolean isScrollContainer) {
2836 if (isScrollContainer) {
2837 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
2838 mAttachInfo.mScrollContainers.add(this);
2839 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
2840 }
2841 mPrivateFlags |= SCROLL_CONTAINER;
2842 } else {
2843 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
2844 mAttachInfo.mScrollContainers.remove(this);
2845 }
2846 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
2847 }
2848 }
2849
2850 /**
2851 * Returns the quality of the drawing cache.
2852 *
2853 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
2854 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
2855 *
2856 * @see #setDrawingCacheQuality(int)
2857 * @see #setDrawingCacheEnabled(boolean)
2858 * @see #isDrawingCacheEnabled()
2859 *
2860 * @attr ref android.R.styleable#View_drawingCacheQuality
2861 */
2862 public int getDrawingCacheQuality() {
2863 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
2864 }
2865
2866 /**
2867 * Set the drawing cache quality of this view. This value is used only when the
2868 * drawing cache is enabled
2869 *
2870 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
2871 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
2872 *
2873 * @see #getDrawingCacheQuality()
2874 * @see #setDrawingCacheEnabled(boolean)
2875 * @see #isDrawingCacheEnabled()
2876 *
2877 * @attr ref android.R.styleable#View_drawingCacheQuality
2878 */
2879 public void setDrawingCacheQuality(int quality) {
2880 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
2881 }
2882
2883 /**
2884 * Returns whether the screen should remain on, corresponding to the current
2885 * value of {@link #KEEP_SCREEN_ON}.
2886 *
2887 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
2888 *
2889 * @see #setKeepScreenOn(boolean)
2890 *
2891 * @attr ref android.R.styleable#View_keepScreenOn
2892 */
2893 public boolean getKeepScreenOn() {
2894 return (mViewFlags & KEEP_SCREEN_ON) != 0;
2895 }
2896
2897 /**
2898 * Controls whether the screen should remain on, modifying the
2899 * value of {@link #KEEP_SCREEN_ON}.
2900 *
2901 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
2902 *
2903 * @see #getKeepScreenOn()
2904 *
2905 * @attr ref android.R.styleable#View_keepScreenOn
2906 */
2907 public void setKeepScreenOn(boolean keepScreenOn) {
2908 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
2909 }
2910
2911 /**
2912 * @return The user specified next focus ID.
2913 *
2914 * @attr ref android.R.styleable#View_nextFocusLeft
2915 */
2916 public int getNextFocusLeftId() {
2917 return mNextFocusLeftId;
2918 }
2919
2920 /**
2921 * Set the id of the view to use for the next focus
2922 *
2923 * @param nextFocusLeftId
2924 *
2925 * @attr ref android.R.styleable#View_nextFocusLeft
2926 */
2927 public void setNextFocusLeftId(int nextFocusLeftId) {
2928 mNextFocusLeftId = nextFocusLeftId;
2929 }
2930
2931 /**
2932 * @return The user specified next focus ID.
2933 *
2934 * @attr ref android.R.styleable#View_nextFocusRight
2935 */
2936 public int getNextFocusRightId() {
2937 return mNextFocusRightId;
2938 }
2939
2940 /**
2941 * Set the id of the view to use for the next focus
2942 *
2943 * @param nextFocusRightId
2944 *
2945 * @attr ref android.R.styleable#View_nextFocusRight
2946 */
2947 public void setNextFocusRightId(int nextFocusRightId) {
2948 mNextFocusRightId = nextFocusRightId;
2949 }
2950
2951 /**
2952 * @return The user specified next focus ID.
2953 *
2954 * @attr ref android.R.styleable#View_nextFocusUp
2955 */
2956 public int getNextFocusUpId() {
2957 return mNextFocusUpId;
2958 }
2959
2960 /**
2961 * Set the id of the view to use for the next focus
2962 *
2963 * @param nextFocusUpId
2964 *
2965 * @attr ref android.R.styleable#View_nextFocusUp
2966 */
2967 public void setNextFocusUpId(int nextFocusUpId) {
2968 mNextFocusUpId = nextFocusUpId;
2969 }
2970
2971 /**
2972 * @return The user specified next focus ID.
2973 *
2974 * @attr ref android.R.styleable#View_nextFocusDown
2975 */
2976 public int getNextFocusDownId() {
2977 return mNextFocusDownId;
2978 }
2979
2980 /**
2981 * Set the id of the view to use for the next focus
2982 *
2983 * @param nextFocusDownId
2984 *
2985 * @attr ref android.R.styleable#View_nextFocusDown
2986 */
2987 public void setNextFocusDownId(int nextFocusDownId) {
2988 mNextFocusDownId = nextFocusDownId;
2989 }
2990
2991 /**
2992 * Returns the visibility of this view and all of its ancestors
2993 *
2994 * @return True if this view and all of its ancestors are {@link #VISIBLE}
2995 */
2996 public boolean isShown() {
2997 View current = this;
2998 //noinspection ConstantConditions
2999 do {
3000 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3001 return false;
3002 }
3003 ViewParent parent = current.mParent;
3004 if (parent == null) {
3005 return false; // We are not attached to the view root
3006 }
3007 if (!(parent instanceof View)) {
3008 return true;
3009 }
3010 current = (View) parent;
3011 } while (current != null);
3012
3013 return false;
3014 }
3015
3016 /**
3017 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3018 * is set
3019 *
3020 * @param insets Insets for system windows
3021 *
3022 * @return True if this view applied the insets, false otherwise
3023 */
3024 protected boolean fitSystemWindows(Rect insets) {
3025 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3026 mPaddingLeft = insets.left;
3027 mPaddingTop = insets.top;
3028 mPaddingRight = insets.right;
3029 mPaddingBottom = insets.bottom;
3030 requestLayout();
3031 return true;
3032 }
3033 return false;
3034 }
3035
3036 /**
3037 * Returns the visibility status for this view.
3038 *
3039 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3040 * @attr ref android.R.styleable#View_visibility
3041 */
3042 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003043 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3044 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3045 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 })
3047 public int getVisibility() {
3048 return mViewFlags & VISIBILITY_MASK;
3049 }
3050
3051 /**
3052 * Set the enabled state of this view.
3053 *
3054 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3055 * @attr ref android.R.styleable#View_visibility
3056 */
3057 @RemotableViewMethod
3058 public void setVisibility(int visibility) {
3059 setFlags(visibility, VISIBILITY_MASK);
3060 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3061 }
3062
3063 /**
3064 * Returns the enabled status for this view. The interpretation of the
3065 * enabled state varies by subclass.
3066 *
3067 * @return True if this view is enabled, false otherwise.
3068 */
3069 @ViewDebug.ExportedProperty
3070 public boolean isEnabled() {
3071 return (mViewFlags & ENABLED_MASK) == ENABLED;
3072 }
3073
3074 /**
3075 * Set the enabled state of this view. The interpretation of the enabled
3076 * state varies by subclass.
3077 *
3078 * @param enabled True if this view is enabled, false otherwise.
3079 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003080 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003082 if (enabled == isEnabled()) return;
3083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3085
3086 /*
3087 * The View most likely has to change its appearance, so refresh
3088 * the drawable state.
3089 */
3090 refreshDrawableState();
3091
3092 // Invalidate too, since the default behavior for views is to be
3093 // be drawn at 50% alpha rather than to change the drawable.
3094 invalidate();
3095 }
3096
3097 /**
3098 * Set whether this view can receive the focus.
3099 *
3100 * Setting this to false will also ensure that this view is not focusable
3101 * in touch mode.
3102 *
3103 * @param focusable If true, this view can receive the focus.
3104 *
3105 * @see #setFocusableInTouchMode(boolean)
3106 * @attr ref android.R.styleable#View_focusable
3107 */
3108 public void setFocusable(boolean focusable) {
3109 if (!focusable) {
3110 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3111 }
3112 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3113 }
3114
3115 /**
3116 * Set whether this view can receive focus while in touch mode.
3117 *
3118 * Setting this to true will also ensure that this view is focusable.
3119 *
3120 * @param focusableInTouchMode If true, this view can receive the focus while
3121 * in touch mode.
3122 *
3123 * @see #setFocusable(boolean)
3124 * @attr ref android.R.styleable#View_focusableInTouchMode
3125 */
3126 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3127 // Focusable in touch mode should always be set before the focusable flag
3128 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3129 // which, in touch mode, will not successfully request focus on this view
3130 // because the focusable in touch mode flag is not set
3131 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3132 if (focusableInTouchMode) {
3133 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3134 }
3135 }
3136
3137 /**
3138 * Set whether this view should have sound effects enabled for events such as
3139 * clicking and touching.
3140 *
3141 * <p>You may wish to disable sound effects for a view if you already play sounds,
3142 * for instance, a dial key that plays dtmf tones.
3143 *
3144 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3145 * @see #isSoundEffectsEnabled()
3146 * @see #playSoundEffect(int)
3147 * @attr ref android.R.styleable#View_soundEffectsEnabled
3148 */
3149 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3150 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3151 }
3152
3153 /**
3154 * @return whether this view should have sound effects enabled for events such as
3155 * clicking and touching.
3156 *
3157 * @see #setSoundEffectsEnabled(boolean)
3158 * @see #playSoundEffect(int)
3159 * @attr ref android.R.styleable#View_soundEffectsEnabled
3160 */
3161 @ViewDebug.ExportedProperty
3162 public boolean isSoundEffectsEnabled() {
3163 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3164 }
3165
3166 /**
3167 * Set whether this view should have haptic feedback for events such as
3168 * long presses.
3169 *
3170 * <p>You may wish to disable haptic feedback if your view already controls
3171 * its own haptic feedback.
3172 *
3173 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3174 * @see #isHapticFeedbackEnabled()
3175 * @see #performHapticFeedback(int)
3176 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3177 */
3178 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3179 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3180 }
3181
3182 /**
3183 * @return whether this view should have haptic feedback enabled for events
3184 * long presses.
3185 *
3186 * @see #setHapticFeedbackEnabled(boolean)
3187 * @see #performHapticFeedback(int)
3188 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3189 */
3190 @ViewDebug.ExportedProperty
3191 public boolean isHapticFeedbackEnabled() {
3192 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3193 }
3194
3195 /**
3196 * If this view doesn't do any drawing on its own, set this flag to
3197 * allow further optimizations. By default, this flag is not set on
3198 * View, but could be set on some View subclasses such as ViewGroup.
3199 *
3200 * Typically, if you override {@link #onDraw} you should clear this flag.
3201 *
3202 * @param willNotDraw whether or not this View draw on its own
3203 */
3204 public void setWillNotDraw(boolean willNotDraw) {
3205 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3206 }
3207
3208 /**
3209 * Returns whether or not this View draws on its own.
3210 *
3211 * @return true if this view has nothing to draw, false otherwise
3212 */
3213 @ViewDebug.ExportedProperty
3214 public boolean willNotDraw() {
3215 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3216 }
3217
3218 /**
3219 * When a View's drawing cache is enabled, drawing is redirected to an
3220 * offscreen bitmap. Some views, like an ImageView, must be able to
3221 * bypass this mechanism if they already draw a single bitmap, to avoid
3222 * unnecessary usage of the memory.
3223 *
3224 * @param willNotCacheDrawing true if this view does not cache its
3225 * drawing, false otherwise
3226 */
3227 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3228 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3229 }
3230
3231 /**
3232 * Returns whether or not this View can cache its drawing or not.
3233 *
3234 * @return true if this view does not cache its drawing, false otherwise
3235 */
3236 @ViewDebug.ExportedProperty
3237 public boolean willNotCacheDrawing() {
3238 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3239 }
3240
3241 /**
3242 * Indicates whether this view reacts to click events or not.
3243 *
3244 * @return true if the view is clickable, false otherwise
3245 *
3246 * @see #setClickable(boolean)
3247 * @attr ref android.R.styleable#View_clickable
3248 */
3249 @ViewDebug.ExportedProperty
3250 public boolean isClickable() {
3251 return (mViewFlags & CLICKABLE) == CLICKABLE;
3252 }
3253
3254 /**
3255 * Enables or disables click events for this view. When a view
3256 * is clickable it will change its state to "pressed" on every click.
3257 * Subclasses should set the view clickable to visually react to
3258 * user's clicks.
3259 *
3260 * @param clickable true to make the view clickable, false otherwise
3261 *
3262 * @see #isClickable()
3263 * @attr ref android.R.styleable#View_clickable
3264 */
3265 public void setClickable(boolean clickable) {
3266 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3267 }
3268
3269 /**
3270 * Indicates whether this view reacts to long click events or not.
3271 *
3272 * @return true if the view is long clickable, false otherwise
3273 *
3274 * @see #setLongClickable(boolean)
3275 * @attr ref android.R.styleable#View_longClickable
3276 */
3277 public boolean isLongClickable() {
3278 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3279 }
3280
3281 /**
3282 * Enables or disables long click events for this view. When a view is long
3283 * clickable it reacts to the user holding down the button for a longer
3284 * duration than a tap. This event can either launch the listener or a
3285 * context menu.
3286 *
3287 * @param longClickable true to make the view long clickable, false otherwise
3288 * @see #isLongClickable()
3289 * @attr ref android.R.styleable#View_longClickable
3290 */
3291 public void setLongClickable(boolean longClickable) {
3292 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3293 }
3294
3295 /**
3296 * Sets the pressed that for this view.
3297 *
3298 * @see #isClickable()
3299 * @see #setClickable(boolean)
3300 *
3301 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3302 * the View's internal state from a previously set "pressed" state.
3303 */
3304 public void setPressed(boolean pressed) {
3305 if (pressed) {
3306 mPrivateFlags |= PRESSED;
3307 } else {
3308 mPrivateFlags &= ~PRESSED;
3309 }
3310 refreshDrawableState();
3311 dispatchSetPressed(pressed);
3312 }
3313
3314 /**
3315 * Dispatch setPressed to all of this View's children.
3316 *
3317 * @see #setPressed(boolean)
3318 *
3319 * @param pressed The new pressed state
3320 */
3321 protected void dispatchSetPressed(boolean pressed) {
3322 }
3323
3324 /**
3325 * Indicates whether the view is currently in pressed state. Unless
3326 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3327 * the pressed state.
3328 *
3329 * @see #setPressed
3330 * @see #isClickable()
3331 * @see #setClickable(boolean)
3332 *
3333 * @return true if the view is currently pressed, false otherwise
3334 */
3335 public boolean isPressed() {
3336 return (mPrivateFlags & PRESSED) == PRESSED;
3337 }
3338
3339 /**
3340 * Indicates whether this view will save its state (that is,
3341 * whether its {@link #onSaveInstanceState} method will be called).
3342 *
3343 * @return Returns true if the view state saving is enabled, else false.
3344 *
3345 * @see #setSaveEnabled(boolean)
3346 * @attr ref android.R.styleable#View_saveEnabled
3347 */
3348 public boolean isSaveEnabled() {
3349 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3350 }
3351
3352 /**
3353 * Controls whether the saving of this view's state is
3354 * enabled (that is, whether its {@link #onSaveInstanceState} method
3355 * will be called). Note that even if freezing is enabled, the
3356 * view still must have an id assigned to it (via {@link #setId setId()})
3357 * for its state to be saved. This flag can only disable the
3358 * saving of this view; any child views may still have their state saved.
3359 *
3360 * @param enabled Set to false to <em>disable</em> state saving, or true
3361 * (the default) to allow it.
3362 *
3363 * @see #isSaveEnabled()
3364 * @see #setId(int)
3365 * @see #onSaveInstanceState()
3366 * @attr ref android.R.styleable#View_saveEnabled
3367 */
3368 public void setSaveEnabled(boolean enabled) {
3369 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3370 }
3371
3372
3373 /**
3374 * Returns whether this View is able to take focus.
3375 *
3376 * @return True if this view can take focus, or false otherwise.
3377 * @attr ref android.R.styleable#View_focusable
3378 */
3379 @ViewDebug.ExportedProperty
3380 public final boolean isFocusable() {
3381 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3382 }
3383
3384 /**
3385 * When a view is focusable, it may not want to take focus when in touch mode.
3386 * For example, a button would like focus when the user is navigating via a D-pad
3387 * so that the user can click on it, but once the user starts touching the screen,
3388 * the button shouldn't take focus
3389 * @return Whether the view is focusable in touch mode.
3390 * @attr ref android.R.styleable#View_focusableInTouchMode
3391 */
3392 @ViewDebug.ExportedProperty
3393 public final boolean isFocusableInTouchMode() {
3394 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3395 }
3396
3397 /**
3398 * Find the nearest view in the specified direction that can take focus.
3399 * This does not actually give focus to that view.
3400 *
3401 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3402 *
3403 * @return The nearest focusable in the specified direction, or null if none
3404 * can be found.
3405 */
3406 public View focusSearch(int direction) {
3407 if (mParent != null) {
3408 return mParent.focusSearch(this, direction);
3409 } else {
3410 return null;
3411 }
3412 }
3413
3414 /**
3415 * This method is the last chance for the focused view and its ancestors to
3416 * respond to an arrow key. This is called when the focused view did not
3417 * consume the key internally, nor could the view system find a new view in
3418 * the requested direction to give focus to.
3419 *
3420 * @param focused The currently focused view.
3421 * @param direction The direction focus wants to move. One of FOCUS_UP,
3422 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3423 * @return True if the this view consumed this unhandled move.
3424 */
3425 public boolean dispatchUnhandledMove(View focused, int direction) {
3426 return false;
3427 }
3428
3429 /**
3430 * If a user manually specified the next view id for a particular direction,
3431 * use the root to look up the view. Once a view is found, it is cached
3432 * for future lookups.
3433 * @param root The root view of the hierarchy containing this view.
3434 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3435 * @return The user specified next view, or null if there is none.
3436 */
3437 View findUserSetNextFocus(View root, int direction) {
3438 switch (direction) {
3439 case FOCUS_LEFT:
3440 if (mNextFocusLeftId == View.NO_ID) return null;
3441 return findViewShouldExist(root, mNextFocusLeftId);
3442 case FOCUS_RIGHT:
3443 if (mNextFocusRightId == View.NO_ID) return null;
3444 return findViewShouldExist(root, mNextFocusRightId);
3445 case FOCUS_UP:
3446 if (mNextFocusUpId == View.NO_ID) return null;
3447 return findViewShouldExist(root, mNextFocusUpId);
3448 case FOCUS_DOWN:
3449 if (mNextFocusDownId == View.NO_ID) return null;
3450 return findViewShouldExist(root, mNextFocusDownId);
3451 }
3452 return null;
3453 }
3454
3455 private static View findViewShouldExist(View root, int childViewId) {
3456 View result = root.findViewById(childViewId);
3457 if (result == null) {
3458 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3459 + "by user for id " + childViewId);
3460 }
3461 return result;
3462 }
3463
3464 /**
3465 * Find and return all focusable views that are descendants of this view,
3466 * possibly including this view if it is focusable itself.
3467 *
3468 * @param direction The direction of the focus
3469 * @return A list of focusable views
3470 */
3471 public ArrayList<View> getFocusables(int direction) {
3472 ArrayList<View> result = new ArrayList<View>(24);
3473 addFocusables(result, direction);
3474 return result;
3475 }
3476
3477 /**
3478 * Add any focusable views that are descendants of this view (possibly
3479 * including this view if it is focusable itself) to views. If we are in touch mode,
3480 * only add views that are also focusable in touch mode.
3481 *
3482 * @param views Focusable views found so far
3483 * @param direction The direction of the focus
3484 */
3485 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003486 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488
svetoslavganov75986cf2009-05-14 22:28:01 -07003489 /**
3490 * Adds any focusable views that are descendants of this view (possibly
3491 * including this view if it is focusable itself) to views. This method
3492 * adds all focusable views regardless if we are in touch mode or
3493 * only views focusable in touch mode if we are in touch mode depending on
3494 * the focusable mode paramater.
3495 *
3496 * @param views Focusable views found so far or null if all we are interested is
3497 * the number of focusables.
3498 * @param direction The direction of the focus.
3499 * @param focusableMode The type of focusables to be added.
3500 *
3501 * @see #FOCUSABLES_ALL
3502 * @see #FOCUSABLES_TOUCH_MODE
3503 */
3504 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3505 if (!isFocusable()) {
3506 return;
3507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003508
svetoslavganov75986cf2009-05-14 22:28:01 -07003509 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3510 isInTouchMode() && !isFocusableInTouchMode()) {
3511 return;
3512 }
3513
3514 if (views != null) {
3515 views.add(this);
3516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 }
3518
3519 /**
3520 * Find and return all touchable views that are descendants of this view,
3521 * possibly including this view if it is touchable itself.
3522 *
3523 * @return A list of touchable views
3524 */
3525 public ArrayList<View> getTouchables() {
3526 ArrayList<View> result = new ArrayList<View>();
3527 addTouchables(result);
3528 return result;
3529 }
3530
3531 /**
3532 * Add any touchable views that are descendants of this view (possibly
3533 * including this view if it is touchable itself) to views.
3534 *
3535 * @param views Touchable views found so far
3536 */
3537 public void addTouchables(ArrayList<View> views) {
3538 final int viewFlags = mViewFlags;
3539
3540 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
3541 && (viewFlags & ENABLED_MASK) == ENABLED) {
3542 views.add(this);
3543 }
3544 }
3545
3546 /**
3547 * Call this to try to give focus to a specific view or to one of its
3548 * descendants.
3549 *
3550 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3551 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3552 * while the device is in touch mode.
3553 *
3554 * See also {@link #focusSearch}, which is what you call to say that you
3555 * have focus, and you want your parent to look for the next one.
3556 *
3557 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
3558 * {@link #FOCUS_DOWN} and <code>null</code>.
3559 *
3560 * @return Whether this view or one of its descendants actually took focus.
3561 */
3562 public final boolean requestFocus() {
3563 return requestFocus(View.FOCUS_DOWN);
3564 }
3565
3566
3567 /**
3568 * Call this to try to give focus to a specific view or to one of its
3569 * descendants and give it a hint about what direction focus is heading.
3570 *
3571 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3572 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3573 * while the device is in touch mode.
3574 *
3575 * See also {@link #focusSearch}, which is what you call to say that you
3576 * have focus, and you want your parent to look for the next one.
3577 *
3578 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
3579 * <code>null</code> set for the previously focused rectangle.
3580 *
3581 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3582 * @return Whether this view or one of its descendants actually took focus.
3583 */
3584 public final boolean requestFocus(int direction) {
3585 return requestFocus(direction, null);
3586 }
3587
3588 /**
3589 * Call this to try to give focus to a specific view or to one of its descendants
3590 * and give it hints about the direction and a specific rectangle that the focus
3591 * is coming from. The rectangle can help give larger views a finer grained hint
3592 * about where focus is coming from, and therefore, where to show selection, or
3593 * forward focus change internally.
3594 *
3595 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3596 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3597 * while the device is in touch mode.
3598 *
3599 * A View will not take focus if it is not visible.
3600 *
3601 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
3602 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
3603 *
3604 * See also {@link #focusSearch}, which is what you call to say that you
3605 * have focus, and you want your parent to look for the next one.
3606 *
3607 * You may wish to override this method if your custom {@link View} has an internal
3608 * {@link View} that it wishes to forward the request to.
3609 *
3610 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3611 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
3612 * to give a finer grained hint about where focus is coming from. May be null
3613 * if there is no hint.
3614 * @return Whether this view or one of its descendants actually took focus.
3615 */
3616 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
3617 // need to be focusable
3618 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
3619 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3620 return false;
3621 }
3622
3623 // need to be focusable in touch mode if in touch mode
3624 if (isInTouchMode() &&
3625 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
3626 return false;
3627 }
3628
3629 // need to not have any parents blocking us
3630 if (hasAncestorThatBlocksDescendantFocus()) {
3631 return false;
3632 }
3633
3634 handleFocusGainInternal(direction, previouslyFocusedRect);
3635 return true;
3636 }
3637
3638 /**
3639 * Call this to try to give focus to a specific view or to one of its descendants. This is a
3640 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
3641 * touch mode to request focus when they are touched.
3642 *
3643 * @return Whether this view or one of its descendants actually took focus.
3644 *
3645 * @see #isInTouchMode()
3646 *
3647 */
3648 public final boolean requestFocusFromTouch() {
3649 // Leave touch mode if we need to
3650 if (isInTouchMode()) {
3651 View root = getRootView();
3652 if (root != null) {
3653 ViewRoot viewRoot = (ViewRoot)root.getParent();
3654 if (viewRoot != null) {
3655 viewRoot.ensureTouchMode(false);
3656 }
3657 }
3658 }
3659 return requestFocus(View.FOCUS_DOWN);
3660 }
3661
3662 /**
3663 * @return Whether any ancestor of this view blocks descendant focus.
3664 */
3665 private boolean hasAncestorThatBlocksDescendantFocus() {
3666 ViewParent ancestor = mParent;
3667 while (ancestor instanceof ViewGroup) {
3668 final ViewGroup vgAncestor = (ViewGroup) ancestor;
3669 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
3670 return true;
3671 } else {
3672 ancestor = vgAncestor.getParent();
3673 }
3674 }
3675 return false;
3676 }
3677
3678 /**
Romain Guya440b002010-02-24 15:57:54 -08003679 * @hide
3680 */
3681 public void dispatchStartTemporaryDetach() {
3682 onStartTemporaryDetach();
3683 }
3684
3685 /**
3686 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
3688 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08003689 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003690 */
3691 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08003692 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08003693 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08003694 }
3695
3696 /**
3697 * @hide
3698 */
3699 public void dispatchFinishTemporaryDetach() {
3700 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 }
Romain Guy8506ab42009-06-11 17:35:47 -07003702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 /**
3704 * Called after {@link #onStartTemporaryDetach} when the container is done
3705 * changing the view.
3706 */
3707 public void onFinishTemporaryDetach() {
3708 }
Romain Guy8506ab42009-06-11 17:35:47 -07003709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 /**
3711 * capture information of this view for later analysis: developement only
3712 * check dynamic switch to make sure we only dump view
3713 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
3714 */
3715 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003716 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 return;
3718 }
3719 ViewDebug.dumpCapturedView(subTag, v);
3720 }
3721
3722 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003723 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
3724 * for this view's window. Returns null if the view is not currently attached
3725 * to the window. Normally you will not need to use this directly, but
3726 * just use the standard high-level event callbacks like {@link #onKeyDown}.
3727 */
3728 public KeyEvent.DispatcherState getKeyDispatcherState() {
3729 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
3730 }
3731
3732 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 * Dispatch a key event before it is processed by any input method
3734 * associated with the view hierarchy. This can be used to intercept
3735 * key events in special situations before the IME consumes them; a
3736 * typical example would be handling the BACK key to update the application's
3737 * UI instead of allowing the IME to see it and close itself.
3738 *
3739 * @param event The key event to be dispatched.
3740 * @return True if the event was handled, false otherwise.
3741 */
3742 public boolean dispatchKeyEventPreIme(KeyEvent event) {
3743 return onKeyPreIme(event.getKeyCode(), event);
3744 }
3745
3746 /**
3747 * Dispatch a key event to the next view on the focus path. This path runs
3748 * from the top of the view tree down to the currently focused view. If this
3749 * view has focus, it will dispatch to itself. Otherwise it will dispatch
3750 * the next node down the focus path. This method also fires any key
3751 * listeners.
3752 *
3753 * @param event The key event to be dispatched.
3754 * @return True if the event was handled, false otherwise.
3755 */
3756 public boolean dispatchKeyEvent(KeyEvent event) {
3757 // If any attached key listener a first crack at the event.
3758 //noinspection SimplifiableIfStatement
3759
3760 if (android.util.Config.LOGV) {
3761 captureViewInfo("captureViewKeyEvent", this);
3762 }
3763
3764 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
3765 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
3766 return true;
3767 }
3768
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003769 return event.dispatch(this, mAttachInfo != null
3770 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 }
3772
3773 /**
3774 * Dispatches a key shortcut event.
3775 *
3776 * @param event The key event to be dispatched.
3777 * @return True if the event was handled by the view, false otherwise.
3778 */
3779 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3780 return onKeyShortcut(event.getKeyCode(), event);
3781 }
3782
3783 /**
3784 * Pass the touch screen motion event down to the target view, or this
3785 * view if it is the target.
3786 *
3787 * @param event The motion event to be dispatched.
3788 * @return True if the event was handled by the view, false otherwise.
3789 */
3790 public boolean dispatchTouchEvent(MotionEvent event) {
3791 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
3792 mOnTouchListener.onTouch(this, event)) {
3793 return true;
3794 }
3795 return onTouchEvent(event);
3796 }
3797
3798 /**
3799 * Pass a trackball motion event down to the focused view.
3800 *
3801 * @param event The motion event to be dispatched.
3802 * @return True if the event was handled by the view, false otherwise.
3803 */
3804 public boolean dispatchTrackballEvent(MotionEvent event) {
3805 //Log.i("view", "view=" + this + ", " + event.toString());
3806 return onTrackballEvent(event);
3807 }
3808
3809 /**
3810 * Called when the window containing this view gains or loses window focus.
3811 * ViewGroups should override to route to their children.
3812 *
3813 * @param hasFocus True if the window containing this view now has focus,
3814 * false otherwise.
3815 */
3816 public void dispatchWindowFocusChanged(boolean hasFocus) {
3817 onWindowFocusChanged(hasFocus);
3818 }
3819
3820 /**
3821 * Called when the window containing this view gains or loses focus. Note
3822 * that this is separate from view focus: to receive key events, both
3823 * your view and its window must have focus. If a window is displayed
3824 * on top of yours that takes input focus, then your own window will lose
3825 * focus but the view focus will remain unchanged.
3826 *
3827 * @param hasWindowFocus True if the window containing this view now has
3828 * focus, false otherwise.
3829 */
3830 public void onWindowFocusChanged(boolean hasWindowFocus) {
3831 InputMethodManager imm = InputMethodManager.peekInstance();
3832 if (!hasWindowFocus) {
3833 if (isPressed()) {
3834 setPressed(false);
3835 }
3836 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
3837 imm.focusOut(this);
3838 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05003839 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003840 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003841 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
3842 imm.focusIn(this);
3843 }
3844 refreshDrawableState();
3845 }
3846
3847 /**
3848 * Returns true if this view is in a window that currently has window focus.
3849 * Note that this is not the same as the view itself having focus.
3850 *
3851 * @return True if this view is in a window that currently has window focus.
3852 */
3853 public boolean hasWindowFocus() {
3854 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
3855 }
3856
3857 /**
Adam Powell326d8082009-12-09 15:10:07 -08003858 * Dispatch a view visibility change down the view hierarchy.
3859 * ViewGroups should override to route to their children.
3860 * @param changedView The view whose visibility changed. Could be 'this' or
3861 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08003862 * @param visibility The new visibility of changedView: {@link #VISIBLE},
3863 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08003864 */
3865 protected void dispatchVisibilityChanged(View changedView, int visibility) {
3866 onVisibilityChanged(changedView, visibility);
3867 }
3868
3869 /**
3870 * Called when the visibility of the view or an ancestor of the view is changed.
3871 * @param changedView The view whose visibility changed. Could be 'this' or
3872 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08003873 * @param visibility The new visibility of changedView: {@link #VISIBLE},
3874 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08003875 */
3876 protected void onVisibilityChanged(View changedView, int visibility) {
3877 }
3878
3879 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08003880 * Dispatch a hint about whether this view is displayed. For instance, when
3881 * a View moves out of the screen, it might receives a display hint indicating
3882 * the view is not displayed. Applications should not <em>rely</em> on this hint
3883 * as there is no guarantee that they will receive one.
3884 *
3885 * @param hint A hint about whether or not this view is displayed:
3886 * {@link #VISIBLE} or {@link #INVISIBLE}.
3887 */
3888 public void dispatchDisplayHint(int hint) {
3889 onDisplayHint(hint);
3890 }
3891
3892 /**
3893 * Gives this view a hint about whether is displayed or not. For instance, when
3894 * a View moves out of the screen, it might receives a display hint indicating
3895 * the view is not displayed. Applications should not <em>rely</em> on this hint
3896 * as there is no guarantee that they will receive one.
3897 *
3898 * @param hint A hint about whether or not this view is displayed:
3899 * {@link #VISIBLE} or {@link #INVISIBLE}.
3900 */
3901 protected void onDisplayHint(int hint) {
3902 }
3903
3904 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 * Dispatch a window visibility change down the view hierarchy.
3906 * ViewGroups should override to route to their children.
3907 *
3908 * @param visibility The new visibility of the window.
3909 *
3910 * @see #onWindowVisibilityChanged
3911 */
3912 public void dispatchWindowVisibilityChanged(int visibility) {
3913 onWindowVisibilityChanged(visibility);
3914 }
3915
3916 /**
3917 * Called when the window containing has change its visibility
3918 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
3919 * that this tells you whether or not your window is being made visible
3920 * to the window manager; this does <em>not</em> tell you whether or not
3921 * your window is obscured by other windows on the screen, even if it
3922 * is itself visible.
3923 *
3924 * @param visibility The new visibility of the window.
3925 */
3926 protected void onWindowVisibilityChanged(int visibility) {
3927 }
3928
3929 /**
3930 * Returns the current visibility of the window this view is attached to
3931 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
3932 *
3933 * @return Returns the current visibility of the view's window.
3934 */
3935 public int getWindowVisibility() {
3936 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
3937 }
3938
3939 /**
3940 * Retrieve the overall visible display size in which the window this view is
3941 * attached to has been positioned in. This takes into account screen
3942 * decorations above the window, for both cases where the window itself
3943 * is being position inside of them or the window is being placed under
3944 * then and covered insets are used for the window to position its content
3945 * inside. In effect, this tells you the available area where content can
3946 * be placed and remain visible to users.
3947 *
3948 * <p>This function requires an IPC back to the window manager to retrieve
3949 * the requested information, so should not be used in performance critical
3950 * code like drawing.
3951 *
3952 * @param outRect Filled in with the visible display frame. If the view
3953 * is not attached to a window, this is simply the raw display size.
3954 */
3955 public void getWindowVisibleDisplayFrame(Rect outRect) {
3956 if (mAttachInfo != null) {
3957 try {
3958 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
3959 } catch (RemoteException e) {
3960 return;
3961 }
3962 // XXX This is really broken, and probably all needs to be done
3963 // in the window manager, and we need to know more about whether
3964 // we want the area behind or in front of the IME.
3965 final Rect insets = mAttachInfo.mVisibleInsets;
3966 outRect.left += insets.left;
3967 outRect.top += insets.top;
3968 outRect.right -= insets.right;
3969 outRect.bottom -= insets.bottom;
3970 return;
3971 }
3972 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
3973 outRect.set(0, 0, d.getWidth(), d.getHeight());
3974 }
3975
3976 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003977 * Dispatch a notification about a resource configuration change down
3978 * the view hierarchy.
3979 * ViewGroups should override to route to their children.
3980 *
3981 * @param newConfig The new resource configuration.
3982 *
3983 * @see #onConfigurationChanged
3984 */
3985 public void dispatchConfigurationChanged(Configuration newConfig) {
3986 onConfigurationChanged(newConfig);
3987 }
3988
3989 /**
3990 * Called when the current configuration of the resources being used
3991 * by the application have changed. You can use this to decide when
3992 * to reload resources that can changed based on orientation and other
3993 * configuration characterstics. You only need to use this if you are
3994 * not relying on the normal {@link android.app.Activity} mechanism of
3995 * recreating the activity instance upon a configuration change.
3996 *
3997 * @param newConfig The new resource configuration.
3998 */
3999 protected void onConfigurationChanged(Configuration newConfig) {
4000 }
4001
4002 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 * Private function to aggregate all per-view attributes in to the view
4004 * root.
4005 */
4006 void dispatchCollectViewAttributes(int visibility) {
4007 performCollectViewAttributes(visibility);
4008 }
4009
4010 void performCollectViewAttributes(int visibility) {
4011 //noinspection PointlessBitwiseExpression
4012 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4013 == (VISIBLE | KEEP_SCREEN_ON)) {
4014 mAttachInfo.mKeepScreenOn = true;
4015 }
4016 }
4017
4018 void needGlobalAttributesUpdate(boolean force) {
4019 AttachInfo ai = mAttachInfo;
4020 if (ai != null) {
4021 if (ai.mKeepScreenOn || force) {
4022 ai.mRecomputeGlobalAttributes = true;
4023 }
4024 }
4025 }
4026
4027 /**
4028 * Returns whether the device is currently in touch mode. Touch mode is entered
4029 * once the user begins interacting with the device by touch, and affects various
4030 * things like whether focus is always visible to the user.
4031 *
4032 * @return Whether the device is in touch mode.
4033 */
4034 @ViewDebug.ExportedProperty
4035 public boolean isInTouchMode() {
4036 if (mAttachInfo != null) {
4037 return mAttachInfo.mInTouchMode;
4038 } else {
4039 return ViewRoot.isInTouchMode();
4040 }
4041 }
4042
4043 /**
4044 * Returns the context the view is running in, through which it can
4045 * access the current theme, resources, etc.
4046 *
4047 * @return The view's Context.
4048 */
4049 @ViewDebug.CapturedViewProperty
4050 public final Context getContext() {
4051 return mContext;
4052 }
4053
4054 /**
4055 * Handle a key event before it is processed by any input method
4056 * associated with the view hierarchy. This can be used to intercept
4057 * key events in special situations before the IME consumes them; a
4058 * typical example would be handling the BACK key to update the application's
4059 * UI instead of allowing the IME to see it and close itself.
4060 *
4061 * @param keyCode The value in event.getKeyCode().
4062 * @param event Description of the key event.
4063 * @return If you handled the event, return true. If you want to allow the
4064 * event to be handled by the next receiver, return false.
4065 */
4066 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4067 return false;
4068 }
4069
4070 /**
4071 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4072 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4073 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4074 * is released, if the view is enabled and clickable.
4075 *
4076 * @param keyCode A key code that represents the button pressed, from
4077 * {@link android.view.KeyEvent}.
4078 * @param event The KeyEvent object that defines the button action.
4079 */
4080 public boolean onKeyDown(int keyCode, KeyEvent event) {
4081 boolean result = false;
4082
4083 switch (keyCode) {
4084 case KeyEvent.KEYCODE_DPAD_CENTER:
4085 case KeyEvent.KEYCODE_ENTER: {
4086 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4087 return true;
4088 }
4089 // Long clickable items don't necessarily have to be clickable
4090 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4091 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4092 (event.getRepeatCount() == 0)) {
4093 setPressed(true);
4094 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004095 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 }
4097 return true;
4098 }
4099 break;
4100 }
4101 }
4102 return result;
4103 }
4104
4105 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004106 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4107 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4108 * the event).
4109 */
4110 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4111 return false;
4112 }
4113
4114 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4116 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4117 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4118 * {@link KeyEvent#KEYCODE_ENTER} is released.
4119 *
4120 * @param keyCode A key code that represents the button pressed, from
4121 * {@link android.view.KeyEvent}.
4122 * @param event The KeyEvent object that defines the button action.
4123 */
4124 public boolean onKeyUp(int keyCode, KeyEvent event) {
4125 boolean result = false;
4126
4127 switch (keyCode) {
4128 case KeyEvent.KEYCODE_DPAD_CENTER:
4129 case KeyEvent.KEYCODE_ENTER: {
4130 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4131 return true;
4132 }
4133 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4134 setPressed(false);
4135
4136 if (!mHasPerformedLongPress) {
4137 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004138 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139
4140 result = performClick();
4141 }
4142 }
4143 break;
4144 }
4145 }
4146 return result;
4147 }
4148
4149 /**
4150 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4151 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4152 * the event).
4153 *
4154 * @param keyCode A key code that represents the button pressed, from
4155 * {@link android.view.KeyEvent}.
4156 * @param repeatCount The number of times the action was made.
4157 * @param event The KeyEvent object that defines the button action.
4158 */
4159 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4160 return false;
4161 }
4162
4163 /**
4164 * Called when an unhandled key shortcut event occurs.
4165 *
4166 * @param keyCode The value in event.getKeyCode().
4167 * @param event Description of the key event.
4168 * @return If you handled the event, return true. If you want to allow the
4169 * event to be handled by the next receiver, return false.
4170 */
4171 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4172 return false;
4173 }
4174
4175 /**
4176 * Check whether the called view is a text editor, in which case it
4177 * would make sense to automatically display a soft input window for
4178 * it. Subclasses should override this if they implement
4179 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004180 * a call on that method would return a non-null InputConnection, and
4181 * they are really a first-class editor that the user would normally
4182 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004183 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004184 * <p>The default implementation always returns false. This does
4185 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4186 * will not be called or the user can not otherwise perform edits on your
4187 * view; it is just a hint to the system that this is not the primary
4188 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004189 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 * @return Returns true if this view is a text editor, else false.
4191 */
4192 public boolean onCheckIsTextEditor() {
4193 return false;
4194 }
Romain Guy8506ab42009-06-11 17:35:47 -07004195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 /**
4197 * Create a new InputConnection for an InputMethod to interact
4198 * with the view. The default implementation returns null, since it doesn't
4199 * support input methods. You can override this to implement such support.
4200 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004201 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 * <p>When implementing this, you probably also want to implement
4203 * {@link #onCheckIsTextEditor()} to indicate you will return a
4204 * non-null InputConnection.
4205 *
4206 * @param outAttrs Fill in with attribute information about the connection.
4207 */
4208 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4209 return null;
4210 }
4211
4212 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004213 * Called by the {@link android.view.inputmethod.InputMethodManager}
4214 * when a view who is not the current
4215 * input connection target is trying to make a call on the manager. The
4216 * default implementation returns false; you can override this to return
4217 * true for certain views if you are performing InputConnection proxying
4218 * to them.
4219 * @param view The View that is making the InputMethodManager call.
4220 * @return Return true to allow the call, false to reject.
4221 */
4222 public boolean checkInputConnectionProxy(View view) {
4223 return false;
4224 }
Romain Guy8506ab42009-06-11 17:35:47 -07004225
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004226 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004227 * Show the context menu for this view. It is not safe to hold on to the
4228 * menu after returning from this method.
4229 *
4230 * @param menu The context menu to populate
4231 */
4232 public void createContextMenu(ContextMenu menu) {
4233 ContextMenuInfo menuInfo = getContextMenuInfo();
4234
4235 // Sets the current menu info so all items added to menu will have
4236 // my extra info set.
4237 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4238
4239 onCreateContextMenu(menu);
4240 if (mOnCreateContextMenuListener != null) {
4241 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4242 }
4243
4244 // Clear the extra information so subsequent items that aren't mine don't
4245 // have my extra info.
4246 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4247
4248 if (mParent != null) {
4249 mParent.createContextMenu(menu);
4250 }
4251 }
4252
4253 /**
4254 * Views should implement this if they have extra information to associate
4255 * with the context menu. The return result is supplied as a parameter to
4256 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4257 * callback.
4258 *
4259 * @return Extra information about the item for which the context menu
4260 * should be shown. This information will vary across different
4261 * subclasses of View.
4262 */
4263 protected ContextMenuInfo getContextMenuInfo() {
4264 return null;
4265 }
4266
4267 /**
4268 * Views should implement this if the view itself is going to add items to
4269 * the context menu.
4270 *
4271 * @param menu the context menu to populate
4272 */
4273 protected void onCreateContextMenu(ContextMenu menu) {
4274 }
4275
4276 /**
4277 * Implement this method to handle trackball motion events. The
4278 * <em>relative</em> movement of the trackball since the last event
4279 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4280 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4281 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4282 * they will often be fractional values, representing the more fine-grained
4283 * movement information available from a trackball).
4284 *
4285 * @param event The motion event.
4286 * @return True if the event was handled, false otherwise.
4287 */
4288 public boolean onTrackballEvent(MotionEvent event) {
4289 return false;
4290 }
4291
4292 /**
4293 * Implement this method to handle touch screen motion events.
4294 *
4295 * @param event The motion event.
4296 * @return True if the event was handled, false otherwise.
4297 */
4298 public boolean onTouchEvent(MotionEvent event) {
4299 final int viewFlags = mViewFlags;
4300
4301 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4302 // A disabled view that is clickable still consumes the touch
4303 // events, it just doesn't respond to them.
4304 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4305 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4306 }
4307
4308 if (mTouchDelegate != null) {
4309 if (mTouchDelegate.onTouchEvent(event)) {
4310 return true;
4311 }
4312 }
4313
4314 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4315 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4316 switch (event.getAction()) {
4317 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004318 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4319 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320 // take focus if we don't have it already and we should in
4321 // touch mode.
4322 boolean focusTaken = false;
4323 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4324 focusTaken = requestFocus();
4325 }
4326
4327 if (!mHasPerformedLongPress) {
4328 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004329 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330
4331 // Only perform take click actions if we were in the pressed state
4332 if (!focusTaken) {
4333 performClick();
4334 }
4335 }
4336
4337 if (mUnsetPressedState == null) {
4338 mUnsetPressedState = new UnsetPressedState();
4339 }
4340
Adam Powelle14579b2009-12-16 18:39:52 -08004341 if (prepressed) {
4342 mPrivateFlags |= PRESSED;
4343 refreshDrawableState();
4344 postDelayed(mUnsetPressedState,
4345 ViewConfiguration.getPressedStateDuration());
4346 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 // If the post failed, unpress right now
4348 mUnsetPressedState.run();
4349 }
Adam Powelle14579b2009-12-16 18:39:52 -08004350 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004351 }
4352 break;
4353
4354 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004355 if (mPendingCheckForTap == null) {
4356 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 }
Adam Powelle14579b2009-12-16 18:39:52 -08004358 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004359 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004360 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 break;
4362
4363 case MotionEvent.ACTION_CANCEL:
4364 mPrivateFlags &= ~PRESSED;
4365 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004366 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 break;
4368
4369 case MotionEvent.ACTION_MOVE:
4370 final int x = (int) event.getX();
4371 final int y = (int) event.getY();
4372
4373 // Be lenient about moving outside of buttons
Adam Powelle14579b2009-12-16 18:39:52 -08004374 int slop = mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004375 if ((x < 0 - slop) || (x >= getWidth() + slop) ||
4376 (y < 0 - slop) || (y >= getHeight() + slop)) {
4377 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004378 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004380 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004381 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382
4383 // Need to switch from pressed to not pressed
4384 mPrivateFlags &= ~PRESSED;
4385 refreshDrawableState();
4386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 }
4388 break;
4389 }
4390 return true;
4391 }
4392
4393 return false;
4394 }
4395
4396 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004397 * Remove the longpress detection timer.
4398 */
4399 private void removeLongPressCallback() {
4400 if (mPendingCheckForLongPress != null) {
4401 removeCallbacks(mPendingCheckForLongPress);
4402 }
4403 }
Adam Powelle14579b2009-12-16 18:39:52 -08004404
4405 /**
Romain Guya440b002010-02-24 15:57:54 -08004406 * Remove the prepress detection timer.
4407 */
4408 private void removeUnsetPressCallback() {
4409 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4410 setPressed(false);
4411 removeCallbacks(mUnsetPressedState);
4412 }
4413 }
4414
4415 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004416 * Remove the tap detection timer.
4417 */
4418 private void removeTapCallback() {
4419 if (mPendingCheckForTap != null) {
4420 mPrivateFlags &= ~PREPRESSED;
4421 removeCallbacks(mPendingCheckForTap);
4422 }
4423 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004424
4425 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004426 * Cancels a pending long press. Your subclass can use this if you
4427 * want the context menu to come up if the user presses and holds
4428 * at the same place, but you don't want it to come up if they press
4429 * and then move around enough to cause scrolling.
4430 */
4431 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004432 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004433
4434 /*
4435 * The prepressed state handled by the tap callback is a display
4436 * construct, but the tap callback will post a long press callback
4437 * less its own timeout. Remove it here.
4438 */
4439 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440 }
4441
4442 /**
4443 * Sets the TouchDelegate for this View.
4444 */
4445 public void setTouchDelegate(TouchDelegate delegate) {
4446 mTouchDelegate = delegate;
4447 }
4448
4449 /**
4450 * Gets the TouchDelegate for this View.
4451 */
4452 public TouchDelegate getTouchDelegate() {
4453 return mTouchDelegate;
4454 }
4455
4456 /**
4457 * Set flags controlling behavior of this view.
4458 *
4459 * @param flags Constant indicating the value which should be set
4460 * @param mask Constant indicating the bit range that should be changed
4461 */
4462 void setFlags(int flags, int mask) {
4463 int old = mViewFlags;
4464 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4465
4466 int changed = mViewFlags ^ old;
4467 if (changed == 0) {
4468 return;
4469 }
4470 int privateFlags = mPrivateFlags;
4471
4472 /* Check if the FOCUSABLE bit has changed */
4473 if (((changed & FOCUSABLE_MASK) != 0) &&
4474 ((privateFlags & HAS_BOUNDS) !=0)) {
4475 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4476 && ((privateFlags & FOCUSED) != 0)) {
4477 /* Give up focus if we are no longer focusable */
4478 clearFocus();
4479 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4480 && ((privateFlags & FOCUSED) == 0)) {
4481 /*
4482 * Tell the view system that we are now available to take focus
4483 * if no one else already has it.
4484 */
4485 if (mParent != null) mParent.focusableViewAvailable(this);
4486 }
4487 }
4488
4489 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4490 if ((changed & VISIBILITY_MASK) != 0) {
4491 /*
4492 * If this view is becoming visible, set the DRAWN flag so that
4493 * the next invalidate() will not be skipped.
4494 */
4495 mPrivateFlags |= DRAWN;
4496
4497 needGlobalAttributesUpdate(true);
4498
4499 // a view becoming visible is worth notifying the parent
4500 // about in case nothing has focus. even if this specific view
4501 // isn't focusable, it may contain something that is, so let
4502 // the root view try to give this focus if nothing else does.
4503 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4504 mParent.focusableViewAvailable(this);
4505 }
4506 }
4507 }
4508
4509 /* Check if the GONE bit has changed */
4510 if ((changed & GONE) != 0) {
4511 needGlobalAttributesUpdate(false);
4512 requestLayout();
4513 invalidate();
4514
Romain Guyecd80ee2009-12-03 17:13:02 -08004515 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
4516 if (hasFocus()) clearFocus();
4517 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004518 }
4519 if (mAttachInfo != null) {
4520 mAttachInfo.mViewVisibilityChanged = true;
4521 }
4522 }
4523
4524 /* Check if the VISIBLE bit has changed */
4525 if ((changed & INVISIBLE) != 0) {
4526 needGlobalAttributesUpdate(false);
4527 invalidate();
4528
4529 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4530 // root view becoming invisible shouldn't clear focus
4531 if (getRootView() != this) {
4532 clearFocus();
4533 }
4534 }
4535 if (mAttachInfo != null) {
4536 mAttachInfo.mViewVisibilityChanged = true;
4537 }
4538 }
4539
Adam Powell326d8082009-12-09 15:10:07 -08004540 if ((changed & VISIBILITY_MASK) != 0) {
4541 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
4542 }
4543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4545 destroyDrawingCache();
4546 }
4547
4548 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4549 destroyDrawingCache();
4550 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4551 }
4552
4553 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4554 destroyDrawingCache();
4555 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4556 }
4557
4558 if ((changed & DRAW_MASK) != 0) {
4559 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4560 if (mBGDrawable != null) {
4561 mPrivateFlags &= ~SKIP_DRAW;
4562 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4563 } else {
4564 mPrivateFlags |= SKIP_DRAW;
4565 }
4566 } else {
4567 mPrivateFlags &= ~SKIP_DRAW;
4568 }
4569 requestLayout();
4570 invalidate();
4571 }
4572
4573 if ((changed & KEEP_SCREEN_ON) != 0) {
4574 if (mParent != null) {
4575 mParent.recomputeViewAttributes(this);
4576 }
4577 }
4578 }
4579
4580 /**
4581 * Change the view's z order in the tree, so it's on top of other sibling
4582 * views
4583 */
4584 public void bringToFront() {
4585 if (mParent != null) {
4586 mParent.bringChildToFront(this);
4587 }
4588 }
4589
4590 /**
4591 * This is called in response to an internal scroll in this view (i.e., the
4592 * view scrolled its own contents). This is typically as a result of
4593 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4594 * called.
4595 *
4596 * @param l Current horizontal scroll origin.
4597 * @param t Current vertical scroll origin.
4598 * @param oldl Previous horizontal scroll origin.
4599 * @param oldt Previous vertical scroll origin.
4600 */
4601 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4602 mBackgroundSizeChanged = true;
4603
4604 final AttachInfo ai = mAttachInfo;
4605 if (ai != null) {
4606 ai.mViewScrollChanged = true;
4607 }
4608 }
4609
4610 /**
4611 * This is called during layout when the size of this view has changed. If
4612 * you were just added to the view hierarchy, you're called with the old
4613 * values of 0.
4614 *
4615 * @param w Current width of this view.
4616 * @param h Current height of this view.
4617 * @param oldw Old width of this view.
4618 * @param oldh Old height of this view.
4619 */
4620 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
4621 }
4622
4623 /**
4624 * Called by draw to draw the child views. This may be overridden
4625 * by derived classes to gain control just before its children are drawn
4626 * (but after its own view has been drawn).
4627 * @param canvas the canvas on which to draw the view
4628 */
4629 protected void dispatchDraw(Canvas canvas) {
4630 }
4631
4632 /**
4633 * Gets the parent of this view. Note that the parent is a
4634 * ViewParent and not necessarily a View.
4635 *
4636 * @return Parent of this view.
4637 */
4638 public final ViewParent getParent() {
4639 return mParent;
4640 }
4641
4642 /**
4643 * Return the scrolled left position of this view. This is the left edge of
4644 * the displayed part of your view. You do not need to draw any pixels
4645 * farther left, since those are outside of the frame of your view on
4646 * screen.
4647 *
4648 * @return The left edge of the displayed part of your view, in pixels.
4649 */
4650 public final int getScrollX() {
4651 return mScrollX;
4652 }
4653
4654 /**
4655 * Return the scrolled top position of this view. This is the top edge of
4656 * the displayed part of your view. You do not need to draw any pixels above
4657 * it, since those are outside of the frame of your view on screen.
4658 *
4659 * @return The top edge of the displayed part of your view, in pixels.
4660 */
4661 public final int getScrollY() {
4662 return mScrollY;
4663 }
4664
4665 /**
4666 * Return the width of the your view.
4667 *
4668 * @return The width of your view, in pixels.
4669 */
4670 @ViewDebug.ExportedProperty
4671 public final int getWidth() {
4672 return mRight - mLeft;
4673 }
4674
4675 /**
4676 * Return the height of your view.
4677 *
4678 * @return The height of your view, in pixels.
4679 */
4680 @ViewDebug.ExportedProperty
4681 public final int getHeight() {
4682 return mBottom - mTop;
4683 }
4684
4685 /**
4686 * Return the visible drawing bounds of your view. Fills in the output
4687 * rectangle with the values from getScrollX(), getScrollY(),
4688 * getWidth(), and getHeight().
4689 *
4690 * @param outRect The (scrolled) drawing bounds of the view.
4691 */
4692 public void getDrawingRect(Rect outRect) {
4693 outRect.left = mScrollX;
4694 outRect.top = mScrollY;
4695 outRect.right = mScrollX + (mRight - mLeft);
4696 outRect.bottom = mScrollY + (mBottom - mTop);
4697 }
4698
4699 /**
4700 * The width of this view as measured in the most recent call to measure().
4701 * This should be used during measurement and layout calculations only. Use
4702 * {@link #getWidth()} to see how wide a view is after layout.
4703 *
4704 * @return The measured width of this view.
4705 */
4706 public final int getMeasuredWidth() {
4707 return mMeasuredWidth;
4708 }
4709
4710 /**
4711 * The height of this view as measured in the most recent call to measure().
4712 * This should be used during measurement and layout calculations only. Use
4713 * {@link #getHeight()} to see how tall a view is after layout.
4714 *
4715 * @return The measured height of this view.
4716 */
4717 public final int getMeasuredHeight() {
4718 return mMeasuredHeight;
4719 }
4720
4721 /**
4722 * Top position of this view relative to its parent.
4723 *
4724 * @return The top of this view, in pixels.
4725 */
4726 @ViewDebug.CapturedViewProperty
4727 public final int getTop() {
4728 return mTop;
4729 }
4730
4731 /**
4732 * Bottom position of this view relative to its parent.
4733 *
4734 * @return The bottom of this view, in pixels.
4735 */
4736 @ViewDebug.CapturedViewProperty
4737 public final int getBottom() {
4738 return mBottom;
4739 }
4740
4741 /**
4742 * Left position of this view relative to its parent.
4743 *
4744 * @return The left edge of this view, in pixels.
4745 */
4746 @ViewDebug.CapturedViewProperty
4747 public final int getLeft() {
4748 return mLeft;
4749 }
4750
4751 /**
4752 * Right position of this view relative to its parent.
4753 *
4754 * @return The right edge of this view, in pixels.
4755 */
4756 @ViewDebug.CapturedViewProperty
4757 public final int getRight() {
4758 return mRight;
4759 }
4760
4761 /**
4762 * Hit rectangle in parent's coordinates
4763 *
4764 * @param outRect The hit rectangle of the view.
4765 */
4766 public void getHitRect(Rect outRect) {
4767 outRect.set(mLeft, mTop, mRight, mBottom);
4768 }
4769
4770 /**
4771 * When a view has focus and the user navigates away from it, the next view is searched for
4772 * starting from the rectangle filled in by this method.
4773 *
4774 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
4775 * view maintains some idea of internal selection, such as a cursor, or a selected row
4776 * or column, you should override this method and fill in a more specific rectangle.
4777 *
4778 * @param r The rectangle to fill in, in this view's coordinates.
4779 */
4780 public void getFocusedRect(Rect r) {
4781 getDrawingRect(r);
4782 }
4783
4784 /**
4785 * If some part of this view is not clipped by any of its parents, then
4786 * return that area in r in global (root) coordinates. To convert r to local
4787 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
4788 * -globalOffset.y)) If the view is completely clipped or translated out,
4789 * return false.
4790 *
4791 * @param r If true is returned, r holds the global coordinates of the
4792 * visible portion of this view.
4793 * @param globalOffset If true is returned, globalOffset holds the dx,dy
4794 * between this view and its root. globalOffet may be null.
4795 * @return true if r is non-empty (i.e. part of the view is visible at the
4796 * root level.
4797 */
4798 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
4799 int width = mRight - mLeft;
4800 int height = mBottom - mTop;
4801 if (width > 0 && height > 0) {
4802 r.set(0, 0, width, height);
4803 if (globalOffset != null) {
4804 globalOffset.set(-mScrollX, -mScrollY);
4805 }
4806 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
4807 }
4808 return false;
4809 }
4810
4811 public final boolean getGlobalVisibleRect(Rect r) {
4812 return getGlobalVisibleRect(r, null);
4813 }
4814
4815 public final boolean getLocalVisibleRect(Rect r) {
4816 Point offset = new Point();
4817 if (getGlobalVisibleRect(r, offset)) {
4818 r.offset(-offset.x, -offset.y); // make r local
4819 return true;
4820 }
4821 return false;
4822 }
4823
4824 /**
4825 * Offset this view's vertical location by the specified number of pixels.
4826 *
4827 * @param offset the number of pixels to offset the view by
4828 */
4829 public void offsetTopAndBottom(int offset) {
4830 mTop += offset;
4831 mBottom += offset;
4832 }
4833
4834 /**
4835 * Offset this view's horizontal location by the specified amount of pixels.
4836 *
4837 * @param offset the numer of pixels to offset the view by
4838 */
4839 public void offsetLeftAndRight(int offset) {
4840 mLeft += offset;
4841 mRight += offset;
4842 }
4843
4844 /**
4845 * Get the LayoutParams associated with this view. All views should have
4846 * layout parameters. These supply parameters to the <i>parent</i> of this
4847 * view specifying how it should be arranged. There are many subclasses of
4848 * ViewGroup.LayoutParams, and these correspond to the different subclasses
4849 * of ViewGroup that are responsible for arranging their children.
4850 * @return The LayoutParams associated with this view
4851 */
4852 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
4853 public ViewGroup.LayoutParams getLayoutParams() {
4854 return mLayoutParams;
4855 }
4856
4857 /**
4858 * Set the layout parameters associated with this view. These supply
4859 * parameters to the <i>parent</i> of this view specifying how it should be
4860 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
4861 * correspond to the different subclasses of ViewGroup that are responsible
4862 * for arranging their children.
4863 *
4864 * @param params the layout parameters for this view
4865 */
4866 public void setLayoutParams(ViewGroup.LayoutParams params) {
4867 if (params == null) {
4868 throw new NullPointerException("params == null");
4869 }
4870 mLayoutParams = params;
4871 requestLayout();
4872 }
4873
4874 /**
4875 * Set the scrolled position of your view. This will cause a call to
4876 * {@link #onScrollChanged(int, int, int, int)} and the view will be
4877 * invalidated.
4878 * @param x the x position to scroll to
4879 * @param y the y position to scroll to
4880 */
4881 public void scrollTo(int x, int y) {
4882 if (mScrollX != x || mScrollY != y) {
4883 int oldX = mScrollX;
4884 int oldY = mScrollY;
4885 mScrollX = x;
4886 mScrollY = y;
4887 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07004888 if (!awakenScrollBars()) {
4889 invalidate();
4890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 }
4892 }
4893
4894 /**
4895 * Move the scrolled position of your view. This will cause a call to
4896 * {@link #onScrollChanged(int, int, int, int)} and the view will be
4897 * invalidated.
4898 * @param x the amount of pixels to scroll by horizontally
4899 * @param y the amount of pixels to scroll by vertically
4900 */
4901 public void scrollBy(int x, int y) {
4902 scrollTo(mScrollX + x, mScrollY + y);
4903 }
4904
4905 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07004906 * <p>Trigger the scrollbars to draw. When invoked this method starts an
4907 * animation to fade the scrollbars out after a default delay. If a subclass
4908 * provides animated scrolling, the start delay should equal the duration
4909 * of the scrolling animation.</p>
4910 *
4911 * <p>The animation starts only if at least one of the scrollbars is
4912 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
4913 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
4914 * this method returns true, and false otherwise. If the animation is
4915 * started, this method calls {@link #invalidate()}; in that case the
4916 * caller should not call {@link #invalidate()}.</p>
4917 *
4918 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07004919 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07004920 *
4921 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
4922 * and {@link #scrollTo(int, int)}.</p>
4923 *
4924 * @return true if the animation is played, false otherwise
4925 *
4926 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07004927 * @see #scrollBy(int, int)
4928 * @see #scrollTo(int, int)
4929 * @see #isHorizontalScrollBarEnabled()
4930 * @see #isVerticalScrollBarEnabled()
4931 * @see #setHorizontalScrollBarEnabled(boolean)
4932 * @see #setVerticalScrollBarEnabled(boolean)
4933 */
4934 protected boolean awakenScrollBars() {
4935 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07004936 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07004937 }
4938
4939 /**
4940 * <p>
4941 * Trigger the scrollbars to draw. When invoked this method starts an
4942 * animation to fade the scrollbars out after a fixed delay. If a subclass
4943 * provides animated scrolling, the start delay should equal the duration of
4944 * the scrolling animation.
4945 * </p>
4946 *
4947 * <p>
4948 * The animation starts only if at least one of the scrollbars is enabled,
4949 * as specified by {@link #isHorizontalScrollBarEnabled()} and
4950 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
4951 * this method returns true, and false otherwise. If the animation is
4952 * started, this method calls {@link #invalidate()}; in that case the caller
4953 * should not call {@link #invalidate()}.
4954 * </p>
4955 *
4956 * <p>
4957 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07004958 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07004959 * </p>
4960 *
4961 * @param startDelay the delay, in milliseconds, after which the animation
4962 * should start; when the delay is 0, the animation starts
4963 * immediately
4964 * @return true if the animation is played, false otherwise
4965 *
Mike Cleronf116bf82009-09-27 19:14:12 -07004966 * @see #scrollBy(int, int)
4967 * @see #scrollTo(int, int)
4968 * @see #isHorizontalScrollBarEnabled()
4969 * @see #isVerticalScrollBarEnabled()
4970 * @see #setHorizontalScrollBarEnabled(boolean)
4971 * @see #setVerticalScrollBarEnabled(boolean)
4972 */
4973 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07004974 return awakenScrollBars(startDelay, true);
4975 }
4976
4977 /**
4978 * <p>
4979 * Trigger the scrollbars to draw. When invoked this method starts an
4980 * animation to fade the scrollbars out after a fixed delay. If a subclass
4981 * provides animated scrolling, the start delay should equal the duration of
4982 * the scrolling animation.
4983 * </p>
4984 *
4985 * <p>
4986 * The animation starts only if at least one of the scrollbars is enabled,
4987 * as specified by {@link #isHorizontalScrollBarEnabled()} and
4988 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
4989 * this method returns true, and false otherwise. If the animation is
4990 * started, this method calls {@link #invalidate()} if the invalidate parameter
4991 * is set to true; in that case the caller
4992 * should not call {@link #invalidate()}.
4993 * </p>
4994 *
4995 * <p>
4996 * This method should be invoked everytime a subclass directly updates the
4997 * scroll parameters.
4998 * </p>
4999 *
5000 * @param startDelay the delay, in milliseconds, after which the animation
5001 * should start; when the delay is 0, the animation starts
5002 * immediately
5003 *
5004 * @param invalidate Wheter this method should call invalidate
5005 *
5006 * @return true if the animation is played, false otherwise
5007 *
5008 * @see #scrollBy(int, int)
5009 * @see #scrollTo(int, int)
5010 * @see #isHorizontalScrollBarEnabled()
5011 * @see #isVerticalScrollBarEnabled()
5012 * @see #setHorizontalScrollBarEnabled(boolean)
5013 * @see #setVerticalScrollBarEnabled(boolean)
5014 */
5015 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07005016 final ScrollabilityCache scrollCache = mScrollCache;
5017
5018 if (scrollCache == null || !scrollCache.fadeScrollBars) {
5019 return false;
5020 }
5021
5022 if (scrollCache.scrollBar == null) {
5023 scrollCache.scrollBar = new ScrollBarDrawable();
5024 }
5025
5026 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
5027
Mike Cleron290947b2009-09-29 18:34:32 -07005028 if (invalidate) {
5029 // Invalidate to show the scrollbars
5030 invalidate();
5031 }
Mike Cleronf116bf82009-09-27 19:14:12 -07005032
5033 if (scrollCache.state == ScrollabilityCache.OFF) {
5034 // FIXME: this is copied from WindowManagerService.
5035 // We should get this value from the system when it
5036 // is possible to do so.
5037 final int KEY_REPEAT_FIRST_DELAY = 750;
5038 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
5039 }
5040
5041 // Tell mScrollCache when we should start fading. This may
5042 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07005043 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07005044 scrollCache.fadeStartTime = fadeStartTime;
5045 scrollCache.state = ScrollabilityCache.ON;
5046
5047 // Schedule our fader to run, unscheduling any old ones first
5048 if (mAttachInfo != null) {
5049 mAttachInfo.mHandler.removeCallbacks(scrollCache);
5050 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
5051 }
5052
5053 return true;
5054 }
5055
5056 return false;
5057 }
5058
5059 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005060 * Mark the the area defined by dirty as needing to be drawn. If the view is
5061 * visible, {@link #onDraw} will be called at some point in the future.
5062 * This must be called from a UI thread. To call from a non-UI thread, call
5063 * {@link #postInvalidate()}.
5064 *
5065 * WARNING: This method is destructive to dirty.
5066 * @param dirty the rectangle representing the bounds of the dirty region
5067 */
5068 public void invalidate(Rect dirty) {
5069 if (ViewDebug.TRACE_HIERARCHY) {
5070 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5071 }
5072
5073 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5074 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5075 final ViewParent p = mParent;
5076 final AttachInfo ai = mAttachInfo;
5077 if (p != null && ai != null) {
5078 final int scrollX = mScrollX;
5079 final int scrollY = mScrollY;
5080 final Rect r = ai.mTmpInvalRect;
5081 r.set(dirty.left - scrollX, dirty.top - scrollY,
5082 dirty.right - scrollX, dirty.bottom - scrollY);
5083 mParent.invalidateChild(this, r);
5084 }
5085 }
5086 }
5087
5088 /**
5089 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
5090 * The coordinates of the dirty rect are relative to the view.
5091 * If the view is visible, {@link #onDraw} will be called at some point
5092 * in the future. This must be called from a UI thread. To call
5093 * from a non-UI thread, call {@link #postInvalidate()}.
5094 * @param l the left position of the dirty region
5095 * @param t the top position of the dirty region
5096 * @param r the right position of the dirty region
5097 * @param b the bottom position of the dirty region
5098 */
5099 public void invalidate(int l, int t, int r, int b) {
5100 if (ViewDebug.TRACE_HIERARCHY) {
5101 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5102 }
5103
5104 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5105 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5106 final ViewParent p = mParent;
5107 final AttachInfo ai = mAttachInfo;
5108 if (p != null && ai != null && l < r && t < b) {
5109 final int scrollX = mScrollX;
5110 final int scrollY = mScrollY;
5111 final Rect tmpr = ai.mTmpInvalRect;
5112 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
5113 p.invalidateChild(this, tmpr);
5114 }
5115 }
5116 }
5117
5118 /**
5119 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
5120 * be called at some point in the future. This must be called from a
5121 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
5122 */
5123 public void invalidate() {
5124 if (ViewDebug.TRACE_HIERARCHY) {
5125 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5126 }
5127
5128 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5129 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
5130 final ViewParent p = mParent;
5131 final AttachInfo ai = mAttachInfo;
5132 if (p != null && ai != null) {
5133 final Rect r = ai.mTmpInvalRect;
5134 r.set(0, 0, mRight - mLeft, mBottom - mTop);
5135 // Don't call invalidate -- we don't want to internally scroll
5136 // our own bounds
5137 p.invalidateChild(this, r);
5138 }
5139 }
5140 }
5141
5142 /**
Romain Guy24443ea2009-05-11 11:56:30 -07005143 * Indicates whether this View is opaque. An opaque View guarantees that it will
5144 * draw all the pixels overlapping its bounds using a fully opaque color.
5145 *
5146 * Subclasses of View should override this method whenever possible to indicate
5147 * whether an instance is opaque. Opaque Views are treated in a special way by
5148 * the View hierarchy, possibly allowing it to perform optimizations during
5149 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07005150 *
Romain Guy24443ea2009-05-11 11:56:30 -07005151 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07005152 */
Romain Guy83b21072009-05-12 10:54:51 -07005153 @ViewDebug.ExportedProperty
Romain Guy24443ea2009-05-11 11:56:30 -07005154 public boolean isOpaque() {
Romain Guy8f1344f52009-05-15 16:03:59 -07005155 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
5156 }
5157
5158 private void computeOpaqueFlags() {
5159 // Opaque if:
5160 // - Has a background
5161 // - Background is opaque
5162 // - Doesn't have scrollbars or scrollbars are inside overlay
5163
5164 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
5165 mPrivateFlags |= OPAQUE_BACKGROUND;
5166 } else {
5167 mPrivateFlags &= ~OPAQUE_BACKGROUND;
5168 }
5169
5170 final int flags = mViewFlags;
5171 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
5172 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
5173 mPrivateFlags |= OPAQUE_SCROLLBARS;
5174 } else {
5175 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
5176 }
5177 }
5178
5179 /**
5180 * @hide
5181 */
5182 protected boolean hasOpaqueScrollbars() {
5183 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07005184 }
5185
5186 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005187 * @return A handler associated with the thread running the View. This
5188 * handler can be used to pump events in the UI events queue.
5189 */
5190 public Handler getHandler() {
5191 if (mAttachInfo != null) {
5192 return mAttachInfo.mHandler;
5193 }
5194 return null;
5195 }
5196
5197 /**
5198 * Causes the Runnable to be added to the message queue.
5199 * The runnable will be run on the user interface thread.
5200 *
5201 * @param action The Runnable that will be executed.
5202 *
5203 * @return Returns true if the Runnable was successfully placed in to the
5204 * message queue. Returns false on failure, usually because the
5205 * looper processing the message queue is exiting.
5206 */
5207 public boolean post(Runnable action) {
5208 Handler handler;
5209 if (mAttachInfo != null) {
5210 handler = mAttachInfo.mHandler;
5211 } else {
5212 // Assume that post will succeed later
5213 ViewRoot.getRunQueue().post(action);
5214 return true;
5215 }
5216
5217 return handler.post(action);
5218 }
5219
5220 /**
5221 * Causes the Runnable to be added to the message queue, to be run
5222 * after the specified amount of time elapses.
5223 * The runnable will be run on the user interface thread.
5224 *
5225 * @param action The Runnable that will be executed.
5226 * @param delayMillis The delay (in milliseconds) until the Runnable
5227 * will be executed.
5228 *
5229 * @return true if the Runnable was successfully placed in to the
5230 * message queue. Returns false on failure, usually because the
5231 * looper processing the message queue is exiting. Note that a
5232 * result of true does not mean the Runnable will be processed --
5233 * if the looper is quit before the delivery time of the message
5234 * occurs then the message will be dropped.
5235 */
5236 public boolean postDelayed(Runnable action, long delayMillis) {
5237 Handler handler;
5238 if (mAttachInfo != null) {
5239 handler = mAttachInfo.mHandler;
5240 } else {
5241 // Assume that post will succeed later
5242 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
5243 return true;
5244 }
5245
5246 return handler.postDelayed(action, delayMillis);
5247 }
5248
5249 /**
5250 * Removes the specified Runnable from the message queue.
5251 *
5252 * @param action The Runnable to remove from the message handling queue
5253 *
5254 * @return true if this view could ask the Handler to remove the Runnable,
5255 * false otherwise. When the returned value is true, the Runnable
5256 * may or may not have been actually removed from the message queue
5257 * (for instance, if the Runnable was not in the queue already.)
5258 */
5259 public boolean removeCallbacks(Runnable action) {
5260 Handler handler;
5261 if (mAttachInfo != null) {
5262 handler = mAttachInfo.mHandler;
5263 } else {
5264 // Assume that post will succeed later
5265 ViewRoot.getRunQueue().removeCallbacks(action);
5266 return true;
5267 }
5268
5269 handler.removeCallbacks(action);
5270 return true;
5271 }
5272
5273 /**
5274 * Cause an invalidate to happen on a subsequent cycle through the event loop.
5275 * Use this to invalidate the View from a non-UI thread.
5276 *
5277 * @see #invalidate()
5278 */
5279 public void postInvalidate() {
5280 postInvalidateDelayed(0);
5281 }
5282
5283 /**
5284 * Cause an invalidate of the specified area to happen on a subsequent cycle
5285 * through the event loop. Use this to invalidate the View from a non-UI thread.
5286 *
5287 * @param left The left coordinate of the rectangle to invalidate.
5288 * @param top The top coordinate of the rectangle to invalidate.
5289 * @param right The right coordinate of the rectangle to invalidate.
5290 * @param bottom The bottom coordinate of the rectangle to invalidate.
5291 *
5292 * @see #invalidate(int, int, int, int)
5293 * @see #invalidate(Rect)
5294 */
5295 public void postInvalidate(int left, int top, int right, int bottom) {
5296 postInvalidateDelayed(0, left, top, right, bottom);
5297 }
5298
5299 /**
5300 * Cause an invalidate to happen on a subsequent cycle through the event
5301 * loop. Waits for the specified amount of time.
5302 *
5303 * @param delayMilliseconds the duration in milliseconds to delay the
5304 * invalidation by
5305 */
5306 public void postInvalidateDelayed(long delayMilliseconds) {
5307 // We try only with the AttachInfo because there's no point in invalidating
5308 // if we are not attached to our window
5309 if (mAttachInfo != null) {
5310 Message msg = Message.obtain();
5311 msg.what = AttachInfo.INVALIDATE_MSG;
5312 msg.obj = this;
5313 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
5314 }
5315 }
5316
5317 /**
5318 * Cause an invalidate of the specified area to happen on a subsequent cycle
5319 * through the event loop. Waits for the specified amount of time.
5320 *
5321 * @param delayMilliseconds the duration in milliseconds to delay the
5322 * invalidation by
5323 * @param left The left coordinate of the rectangle to invalidate.
5324 * @param top The top coordinate of the rectangle to invalidate.
5325 * @param right The right coordinate of the rectangle to invalidate.
5326 * @param bottom The bottom coordinate of the rectangle to invalidate.
5327 */
5328 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
5329 int right, int bottom) {
5330
5331 // We try only with the AttachInfo because there's no point in invalidating
5332 // if we are not attached to our window
5333 if (mAttachInfo != null) {
5334 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
5335 info.target = this;
5336 info.left = left;
5337 info.top = top;
5338 info.right = right;
5339 info.bottom = bottom;
5340
5341 final Message msg = Message.obtain();
5342 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
5343 msg.obj = info;
5344 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
5345 }
5346 }
5347
5348 /**
5349 * Called by a parent to request that a child update its values for mScrollX
5350 * and mScrollY if necessary. This will typically be done if the child is
5351 * animating a scroll using a {@link android.widget.Scroller Scroller}
5352 * object.
5353 */
5354 public void computeScroll() {
5355 }
5356
5357 /**
5358 * <p>Indicate whether the horizontal edges are faded when the view is
5359 * scrolled horizontally.</p>
5360 *
5361 * @return true if the horizontal edges should are faded on scroll, false
5362 * otherwise
5363 *
5364 * @see #setHorizontalFadingEdgeEnabled(boolean)
5365 * @attr ref android.R.styleable#View_fadingEdge
5366 */
5367 public boolean isHorizontalFadingEdgeEnabled() {
5368 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
5369 }
5370
5371 /**
5372 * <p>Define whether the horizontal edges should be faded when this view
5373 * is scrolled horizontally.</p>
5374 *
5375 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
5376 * be faded when the view is scrolled
5377 * horizontally
5378 *
5379 * @see #isHorizontalFadingEdgeEnabled()
5380 * @attr ref android.R.styleable#View_fadingEdge
5381 */
5382 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
5383 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
5384 if (horizontalFadingEdgeEnabled) {
5385 initScrollCache();
5386 }
5387
5388 mViewFlags ^= FADING_EDGE_HORIZONTAL;
5389 }
5390 }
5391
5392 /**
5393 * <p>Indicate whether the vertical edges are faded when the view is
5394 * scrolled horizontally.</p>
5395 *
5396 * @return true if the vertical edges should are faded on scroll, false
5397 * otherwise
5398 *
5399 * @see #setVerticalFadingEdgeEnabled(boolean)
5400 * @attr ref android.R.styleable#View_fadingEdge
5401 */
5402 public boolean isVerticalFadingEdgeEnabled() {
5403 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
5404 }
5405
5406 /**
5407 * <p>Define whether the vertical edges should be faded when this view
5408 * is scrolled vertically.</p>
5409 *
5410 * @param verticalFadingEdgeEnabled true if the vertical edges should
5411 * be faded when the view is scrolled
5412 * vertically
5413 *
5414 * @see #isVerticalFadingEdgeEnabled()
5415 * @attr ref android.R.styleable#View_fadingEdge
5416 */
5417 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
5418 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
5419 if (verticalFadingEdgeEnabled) {
5420 initScrollCache();
5421 }
5422
5423 mViewFlags ^= FADING_EDGE_VERTICAL;
5424 }
5425 }
5426
5427 /**
5428 * Returns the strength, or intensity, of the top faded edge. The strength is
5429 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5430 * returns 0.0 or 1.0 but no value in between.
5431 *
5432 * Subclasses should override this method to provide a smoother fade transition
5433 * when scrolling occurs.
5434 *
5435 * @return the intensity of the top fade as a float between 0.0f and 1.0f
5436 */
5437 protected float getTopFadingEdgeStrength() {
5438 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
5439 }
5440
5441 /**
5442 * Returns the strength, or intensity, of the bottom faded edge. The strength is
5443 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5444 * returns 0.0 or 1.0 but no value in between.
5445 *
5446 * Subclasses should override this method to provide a smoother fade transition
5447 * when scrolling occurs.
5448 *
5449 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
5450 */
5451 protected float getBottomFadingEdgeStrength() {
5452 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
5453 computeVerticalScrollRange() ? 1.0f : 0.0f;
5454 }
5455
5456 /**
5457 * Returns the strength, or intensity, of the left faded edge. The strength is
5458 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5459 * returns 0.0 or 1.0 but no value in between.
5460 *
5461 * Subclasses should override this method to provide a smoother fade transition
5462 * when scrolling occurs.
5463 *
5464 * @return the intensity of the left fade as a float between 0.0f and 1.0f
5465 */
5466 protected float getLeftFadingEdgeStrength() {
5467 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
5468 }
5469
5470 /**
5471 * Returns the strength, or intensity, of the right faded edge. The strength is
5472 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5473 * returns 0.0 or 1.0 but no value in between.
5474 *
5475 * Subclasses should override this method to provide a smoother fade transition
5476 * when scrolling occurs.
5477 *
5478 * @return the intensity of the right fade as a float between 0.0f and 1.0f
5479 */
5480 protected float getRightFadingEdgeStrength() {
5481 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
5482 computeHorizontalScrollRange() ? 1.0f : 0.0f;
5483 }
5484
5485 /**
5486 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
5487 * scrollbar is not drawn by default.</p>
5488 *
5489 * @return true if the horizontal scrollbar should be painted, false
5490 * otherwise
5491 *
5492 * @see #setHorizontalScrollBarEnabled(boolean)
5493 */
5494 public boolean isHorizontalScrollBarEnabled() {
5495 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
5496 }
5497
5498 /**
5499 * <p>Define whether the horizontal scrollbar should be drawn or not. The
5500 * scrollbar is not drawn by default.</p>
5501 *
5502 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
5503 * be painted
5504 *
5505 * @see #isHorizontalScrollBarEnabled()
5506 */
5507 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
5508 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
5509 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07005510 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005511 recomputePadding();
5512 }
5513 }
5514
5515 /**
5516 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
5517 * scrollbar is not drawn by default.</p>
5518 *
5519 * @return true if the vertical scrollbar should be painted, false
5520 * otherwise
5521 *
5522 * @see #setVerticalScrollBarEnabled(boolean)
5523 */
5524 public boolean isVerticalScrollBarEnabled() {
5525 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
5526 }
5527
5528 /**
5529 * <p>Define whether the vertical scrollbar should be drawn or not. The
5530 * scrollbar is not drawn by default.</p>
5531 *
5532 * @param verticalScrollBarEnabled true if the vertical scrollbar should
5533 * be painted
5534 *
5535 * @see #isVerticalScrollBarEnabled()
5536 */
5537 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
5538 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
5539 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07005540 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 recomputePadding();
5542 }
5543 }
5544
5545 private void recomputePadding() {
5546 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
5547 }
Mike Cleronfe81d382009-09-28 14:22:16 -07005548
5549 /**
5550 * Define whether scrollbars will fade when the view is not scrolling.
5551 *
5552 * @param fadeScrollbars wheter to enable fading
5553 *
5554 */
5555 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
5556 initScrollCache();
5557 final ScrollabilityCache scrollabilityCache = mScrollCache;
5558 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07005559 if (fadeScrollbars) {
5560 scrollabilityCache.state = ScrollabilityCache.OFF;
5561 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07005562 scrollabilityCache.state = ScrollabilityCache.ON;
5563 }
5564 }
5565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07005567 *
5568 * Returns true if scrollbars will fade when this view is not scrolling
5569 *
5570 * @return true if scrollbar fading is enabled
5571 */
5572 public boolean isScrollbarFadingEnabled() {
5573 return mScrollCache != null && mScrollCache.fadeScrollBars;
5574 }
5575
5576 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
5578 * inset. When inset, they add to the padding of the view. And the scrollbars
5579 * can be drawn inside the padding area or on the edge of the view. For example,
5580 * if a view has a background drawable and you want to draw the scrollbars
5581 * inside the padding specified by the drawable, you can use
5582 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
5583 * appear at the edge of the view, ignoring the padding, then you can use
5584 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
5585 * @param style the style of the scrollbars. Should be one of
5586 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
5587 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
5588 * @see #SCROLLBARS_INSIDE_OVERLAY
5589 * @see #SCROLLBARS_INSIDE_INSET
5590 * @see #SCROLLBARS_OUTSIDE_OVERLAY
5591 * @see #SCROLLBARS_OUTSIDE_INSET
5592 */
5593 public void setScrollBarStyle(int style) {
5594 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
5595 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07005596 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597 recomputePadding();
5598 }
5599 }
5600
5601 /**
5602 * <p>Returns the current scrollbar style.</p>
5603 * @return the current scrollbar style
5604 * @see #SCROLLBARS_INSIDE_OVERLAY
5605 * @see #SCROLLBARS_INSIDE_INSET
5606 * @see #SCROLLBARS_OUTSIDE_OVERLAY
5607 * @see #SCROLLBARS_OUTSIDE_INSET
5608 */
5609 public int getScrollBarStyle() {
5610 return mViewFlags & SCROLLBARS_STYLE_MASK;
5611 }
5612
5613 /**
5614 * <p>Compute the horizontal range that the horizontal scrollbar
5615 * represents.</p>
5616 *
5617 * <p>The range is expressed in arbitrary units that must be the same as the
5618 * units used by {@link #computeHorizontalScrollExtent()} and
5619 * {@link #computeHorizontalScrollOffset()}.</p>
5620 *
5621 * <p>The default range is the drawing width of this view.</p>
5622 *
5623 * @return the total horizontal range represented by the horizontal
5624 * scrollbar
5625 *
5626 * @see #computeHorizontalScrollExtent()
5627 * @see #computeHorizontalScrollOffset()
5628 * @see android.widget.ScrollBarDrawable
5629 */
5630 protected int computeHorizontalScrollRange() {
5631 return getWidth();
5632 }
5633
5634 /**
5635 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
5636 * within the horizontal range. This value is used to compute the position
5637 * of the thumb within the scrollbar's track.</p>
5638 *
5639 * <p>The range is expressed in arbitrary units that must be the same as the
5640 * units used by {@link #computeHorizontalScrollRange()} and
5641 * {@link #computeHorizontalScrollExtent()}.</p>
5642 *
5643 * <p>The default offset is the scroll offset of this view.</p>
5644 *
5645 * @return the horizontal offset of the scrollbar's thumb
5646 *
5647 * @see #computeHorizontalScrollRange()
5648 * @see #computeHorizontalScrollExtent()
5649 * @see android.widget.ScrollBarDrawable
5650 */
5651 protected int computeHorizontalScrollOffset() {
5652 return mScrollX;
5653 }
5654
5655 /**
5656 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
5657 * within the horizontal range. This value is used to compute the length
5658 * of the thumb within the scrollbar's track.</p>
5659 *
5660 * <p>The range is expressed in arbitrary units that must be the same as the
5661 * units used by {@link #computeHorizontalScrollRange()} and
5662 * {@link #computeHorizontalScrollOffset()}.</p>
5663 *
5664 * <p>The default extent is the drawing width of this view.</p>
5665 *
5666 * @return the horizontal extent of the scrollbar's thumb
5667 *
5668 * @see #computeHorizontalScrollRange()
5669 * @see #computeHorizontalScrollOffset()
5670 * @see android.widget.ScrollBarDrawable
5671 */
5672 protected int computeHorizontalScrollExtent() {
5673 return getWidth();
5674 }
5675
5676 /**
5677 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
5678 *
5679 * <p>The range is expressed in arbitrary units that must be the same as the
5680 * units used by {@link #computeVerticalScrollExtent()} and
5681 * {@link #computeVerticalScrollOffset()}.</p>
5682 *
5683 * @return the total vertical range represented by the vertical scrollbar
5684 *
5685 * <p>The default range is the drawing height of this view.</p>
5686 *
5687 * @see #computeVerticalScrollExtent()
5688 * @see #computeVerticalScrollOffset()
5689 * @see android.widget.ScrollBarDrawable
5690 */
5691 protected int computeVerticalScrollRange() {
5692 return getHeight();
5693 }
5694
5695 /**
5696 * <p>Compute the vertical offset of the vertical scrollbar's thumb
5697 * within the horizontal range. This value is used to compute the position
5698 * of the thumb within the scrollbar's track.</p>
5699 *
5700 * <p>The range is expressed in arbitrary units that must be the same as the
5701 * units used by {@link #computeVerticalScrollRange()} and
5702 * {@link #computeVerticalScrollExtent()}.</p>
5703 *
5704 * <p>The default offset is the scroll offset of this view.</p>
5705 *
5706 * @return the vertical offset of the scrollbar's thumb
5707 *
5708 * @see #computeVerticalScrollRange()
5709 * @see #computeVerticalScrollExtent()
5710 * @see android.widget.ScrollBarDrawable
5711 */
5712 protected int computeVerticalScrollOffset() {
5713 return mScrollY;
5714 }
5715
5716 /**
5717 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
5718 * within the vertical range. This value is used to compute the length
5719 * of the thumb within the scrollbar's track.</p>
5720 *
5721 * <p>The range is expressed in arbitrary units that must be the same as the
5722 * units used by {@link #computeHorizontalScrollRange()} and
5723 * {@link #computeVerticalScrollOffset()}.</p>
5724 *
5725 * <p>The default extent is the drawing height of this view.</p>
5726 *
5727 * @return the vertical extent of the scrollbar's thumb
5728 *
5729 * @see #computeVerticalScrollRange()
5730 * @see #computeVerticalScrollOffset()
5731 * @see android.widget.ScrollBarDrawable
5732 */
5733 protected int computeVerticalScrollExtent() {
5734 return getHeight();
5735 }
5736
5737 /**
5738 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
5739 * scrollbars are painted only if they have been awakened first.</p>
5740 *
5741 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07005742 *
5743 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08005745 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005746 // scrollbars are drawn only when the animation is running
5747 final ScrollabilityCache cache = mScrollCache;
5748 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07005749
5750 int state = cache.state;
5751
5752 if (state == ScrollabilityCache.OFF) {
5753 return;
5754 }
5755
5756 boolean invalidate = false;
5757
5758 if (state == ScrollabilityCache.FADING) {
5759 // We're fading -- get our fade interpolation
5760 if (cache.interpolatorValues == null) {
5761 cache.interpolatorValues = new float[1];
5762 }
5763
5764 float[] values = cache.interpolatorValues;
5765
5766 // Stops the animation if we're done
5767 if (cache.scrollBarInterpolator.timeToValues(values) ==
5768 Interpolator.Result.FREEZE_END) {
5769 cache.state = ScrollabilityCache.OFF;
5770 } else {
5771 cache.scrollBar.setAlpha(Math.round(values[0]));
5772 }
5773
5774 // This will make the scroll bars inval themselves after
5775 // drawing. We only want this when we're fading so that
5776 // we prevent excessive redraws
5777 invalidate = true;
5778 } else {
5779 // We're just on -- but we may have been fading before so
5780 // reset alpha
5781 cache.scrollBar.setAlpha(255);
5782 }
5783
5784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 final int viewFlags = mViewFlags;
5786
5787 final boolean drawHorizontalScrollBar =
5788 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
5789 final boolean drawVerticalScrollBar =
5790 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
5791 && !isVerticalScrollBarHidden();
5792
5793 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
5794 final int width = mRight - mLeft;
5795 final int height = mBottom - mTop;
5796
5797 final ScrollBarDrawable scrollBar = cache.scrollBar;
5798 int size = scrollBar.getSize(false);
5799 if (size <= 0) {
5800 size = cache.scrollBarSize;
5801 }
5802
Mike Reede8853fc2009-09-04 14:01:48 -04005803 final int scrollX = mScrollX;
5804 final int scrollY = mScrollY;
5805 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
5806
Mike Cleronf116bf82009-09-27 19:14:12 -07005807 int left, top, right, bottom;
5808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07005810 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04005811 computeHorizontalScrollOffset(),
5812 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04005813 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07005814 getVerticalScrollbarWidth() : 0;
5815 top = scrollY + height - size - (mUserPaddingBottom & inside);
5816 left = scrollX + (mPaddingLeft & inside);
5817 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
5818 bottom = top + size;
5819 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
5820 if (invalidate) {
5821 invalidate(left, top, right, bottom);
5822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823 }
5824
5825 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04005826 scrollBar.setParameters(computeVerticalScrollRange(),
5827 computeVerticalScrollOffset(),
5828 computeVerticalScrollExtent(), true);
5829 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07005830 left = scrollX + width - size - (mUserPaddingRight & inside);
5831 top = scrollY + (mPaddingTop & inside);
5832 right = left + size;
5833 bottom = scrollY + height - (mUserPaddingBottom & inside);
5834 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
5835 if (invalidate) {
5836 invalidate(left, top, right, bottom);
5837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005838 }
5839 }
5840 }
5841 }
Romain Guy8506ab42009-06-11 17:35:47 -07005842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 /**
Romain Guy8506ab42009-06-11 17:35:47 -07005844 * 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 -08005845 * FastScroller is visible.
5846 * @return whether to temporarily hide the vertical scrollbar
5847 * @hide
5848 */
5849 protected boolean isVerticalScrollBarHidden() {
5850 return false;
5851 }
5852
5853 /**
5854 * <p>Draw the horizontal scrollbar if
5855 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
5856 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 * @param canvas the canvas on which to draw the scrollbar
5858 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005859 *
5860 * @see #isHorizontalScrollBarEnabled()
5861 * @see #computeHorizontalScrollRange()
5862 * @see #computeHorizontalScrollExtent()
5863 * @see #computeHorizontalScrollOffset()
5864 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07005865 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005866 */
Mike Reede8853fc2009-09-04 14:01:48 -04005867 protected void onDrawHorizontalScrollBar(Canvas canvas,
5868 Drawable scrollBar,
5869 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005870 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005871 scrollBar.draw(canvas);
5872 }
Mike Reede8853fc2009-09-04 14:01:48 -04005873
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005874 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
5876 * returns true.</p>
5877 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005878 * @param canvas the canvas on which to draw the scrollbar
5879 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 *
5881 * @see #isVerticalScrollBarEnabled()
5882 * @see #computeVerticalScrollRange()
5883 * @see #computeVerticalScrollExtent()
5884 * @see #computeVerticalScrollOffset()
5885 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04005886 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 */
Mike Reede8853fc2009-09-04 14:01:48 -04005888 protected void onDrawVerticalScrollBar(Canvas canvas,
5889 Drawable scrollBar,
5890 int l, int t, int r, int b) {
5891 scrollBar.setBounds(l, t, r, b);
5892 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 }
5894
5895 /**
5896 * Implement this to do your drawing.
5897 *
5898 * @param canvas the canvas on which the background will be drawn
5899 */
5900 protected void onDraw(Canvas canvas) {
5901 }
5902
5903 /*
5904 * Caller is responsible for calling requestLayout if necessary.
5905 * (This allows addViewInLayout to not request a new layout.)
5906 */
5907 void assignParent(ViewParent parent) {
5908 if (mParent == null) {
5909 mParent = parent;
5910 } else if (parent == null) {
5911 mParent = null;
5912 } else {
5913 throw new RuntimeException("view " + this + " being added, but"
5914 + " it already has a parent");
5915 }
5916 }
5917
5918 /**
5919 * This is called when the view is attached to a window. At this point it
5920 * has a Surface and will start drawing. Note that this function is
5921 * guaranteed to be called before {@link #onDraw}, however it may be called
5922 * any time before the first onDraw -- including before or after
5923 * {@link #onMeasure}.
5924 *
5925 * @see #onDetachedFromWindow()
5926 */
5927 protected void onAttachedToWindow() {
5928 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
5929 mParent.requestTransparentRegion(this);
5930 }
5931 }
5932
5933 /**
5934 * This is called when the view is detached from a window. At this point it
5935 * no longer has a surface for drawing.
5936 *
5937 * @see #onAttachedToWindow()
5938 */
5939 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08005940 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08005941 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05005942 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 destroyDrawingCache();
5944 }
5945
5946 /**
5947 * @return The number of times this view has been attached to a window
5948 */
5949 protected int getWindowAttachCount() {
5950 return mWindowAttachCount;
5951 }
5952
5953 /**
5954 * Retrieve a unique token identifying the window this view is attached to.
5955 * @return Return the window's token for use in
5956 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
5957 */
5958 public IBinder getWindowToken() {
5959 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
5960 }
5961
5962 /**
5963 * Retrieve a unique token identifying the top-level "real" window of
5964 * the window that this view is attached to. That is, this is like
5965 * {@link #getWindowToken}, except if the window this view in is a panel
5966 * window (attached to another containing window), then the token of
5967 * the containing window is returned instead.
5968 *
5969 * @return Returns the associated window token, either
5970 * {@link #getWindowToken()} or the containing window's token.
5971 */
5972 public IBinder getApplicationWindowToken() {
5973 AttachInfo ai = mAttachInfo;
5974 if (ai != null) {
5975 IBinder appWindowToken = ai.mPanelParentWindowToken;
5976 if (appWindowToken == null) {
5977 appWindowToken = ai.mWindowToken;
5978 }
5979 return appWindowToken;
5980 }
5981 return null;
5982 }
5983
5984 /**
5985 * Retrieve private session object this view hierarchy is using to
5986 * communicate with the window manager.
5987 * @return the session object to communicate with the window manager
5988 */
5989 /*package*/ IWindowSession getWindowSession() {
5990 return mAttachInfo != null ? mAttachInfo.mSession : null;
5991 }
5992
5993 /**
5994 * @param info the {@link android.view.View.AttachInfo} to associated with
5995 * this view
5996 */
5997 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
5998 //System.out.println("Attached! " + this);
5999 mAttachInfo = info;
6000 mWindowAttachCount++;
6001 if (mFloatingTreeObserver != null) {
6002 info.mTreeObserver.merge(mFloatingTreeObserver);
6003 mFloatingTreeObserver = null;
6004 }
6005 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
6006 mAttachInfo.mScrollContainers.add(this);
6007 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
6008 }
6009 performCollectViewAttributes(visibility);
6010 onAttachedToWindow();
6011 int vis = info.mWindowVisibility;
6012 if (vis != GONE) {
6013 onWindowVisibilityChanged(vis);
6014 }
6015 }
6016
6017 void dispatchDetachedFromWindow() {
6018 //System.out.println("Detached! " + this);
6019 AttachInfo info = mAttachInfo;
6020 if (info != null) {
6021 int vis = info.mWindowVisibility;
6022 if (vis != GONE) {
6023 onWindowVisibilityChanged(GONE);
6024 }
6025 }
6026
6027 onDetachedFromWindow();
6028 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
6029 mAttachInfo.mScrollContainers.remove(this);
6030 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
6031 }
6032 mAttachInfo = null;
6033 }
6034
6035 /**
6036 * Store this view hierarchy's frozen state into the given container.
6037 *
6038 * @param container The SparseArray in which to save the view's state.
6039 *
6040 * @see #restoreHierarchyState
6041 * @see #dispatchSaveInstanceState
6042 * @see #onSaveInstanceState
6043 */
6044 public void saveHierarchyState(SparseArray<Parcelable> container) {
6045 dispatchSaveInstanceState(container);
6046 }
6047
6048 /**
6049 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
6050 * May be overridden to modify how freezing happens to a view's children; for example, some
6051 * views may want to not store state for their children.
6052 *
6053 * @param container The SparseArray in which to save the view's state.
6054 *
6055 * @see #dispatchRestoreInstanceState
6056 * @see #saveHierarchyState
6057 * @see #onSaveInstanceState
6058 */
6059 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
6060 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
6061 mPrivateFlags &= ~SAVE_STATE_CALLED;
6062 Parcelable state = onSaveInstanceState();
6063 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
6064 throw new IllegalStateException(
6065 "Derived class did not call super.onSaveInstanceState()");
6066 }
6067 if (state != null) {
6068 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
6069 // + ": " + state);
6070 container.put(mID, state);
6071 }
6072 }
6073 }
6074
6075 /**
6076 * Hook allowing a view to generate a representation of its internal state
6077 * that can later be used to create a new instance with that same state.
6078 * This state should only contain information that is not persistent or can
6079 * not be reconstructed later. For example, you will never store your
6080 * current position on screen because that will be computed again when a
6081 * new instance of the view is placed in its view hierarchy.
6082 * <p>
6083 * Some examples of things you may store here: the current cursor position
6084 * in a text view (but usually not the text itself since that is stored in a
6085 * content provider or other persistent storage), the currently selected
6086 * item in a list view.
6087 *
6088 * @return Returns a Parcelable object containing the view's current dynamic
6089 * state, or null if there is nothing interesting to save. The
6090 * default implementation returns null.
6091 * @see #onRestoreInstanceState
6092 * @see #saveHierarchyState
6093 * @see #dispatchSaveInstanceState
6094 * @see #setSaveEnabled(boolean)
6095 */
6096 protected Parcelable onSaveInstanceState() {
6097 mPrivateFlags |= SAVE_STATE_CALLED;
6098 return BaseSavedState.EMPTY_STATE;
6099 }
6100
6101 /**
6102 * Restore this view hierarchy's frozen state from the given container.
6103 *
6104 * @param container The SparseArray which holds previously frozen states.
6105 *
6106 * @see #saveHierarchyState
6107 * @see #dispatchRestoreInstanceState
6108 * @see #onRestoreInstanceState
6109 */
6110 public void restoreHierarchyState(SparseArray<Parcelable> container) {
6111 dispatchRestoreInstanceState(container);
6112 }
6113
6114 /**
6115 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
6116 * children. May be overridden to modify how restoreing happens to a view's children; for
6117 * example, some views may want to not store state for their children.
6118 *
6119 * @param container The SparseArray which holds previously saved state.
6120 *
6121 * @see #dispatchSaveInstanceState
6122 * @see #restoreHierarchyState
6123 * @see #onRestoreInstanceState
6124 */
6125 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
6126 if (mID != NO_ID) {
6127 Parcelable state = container.get(mID);
6128 if (state != null) {
6129 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
6130 // + ": " + state);
6131 mPrivateFlags &= ~SAVE_STATE_CALLED;
6132 onRestoreInstanceState(state);
6133 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
6134 throw new IllegalStateException(
6135 "Derived class did not call super.onRestoreInstanceState()");
6136 }
6137 }
6138 }
6139 }
6140
6141 /**
6142 * Hook allowing a view to re-apply a representation of its internal state that had previously
6143 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
6144 * null state.
6145 *
6146 * @param state The frozen state that had previously been returned by
6147 * {@link #onSaveInstanceState}.
6148 *
6149 * @see #onSaveInstanceState
6150 * @see #restoreHierarchyState
6151 * @see #dispatchRestoreInstanceState
6152 */
6153 protected void onRestoreInstanceState(Parcelable state) {
6154 mPrivateFlags |= SAVE_STATE_CALLED;
6155 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08006156 throw new IllegalArgumentException("Wrong state class, expecting View State but "
6157 + "received " + state.getClass().toString() + " instead. This usually happens "
6158 + "when two views of different type have the same id in the same hierarchy. "
6159 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
6160 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 }
6162 }
6163
6164 /**
6165 * <p>Return the time at which the drawing of the view hierarchy started.</p>
6166 *
6167 * @return the drawing start time in milliseconds
6168 */
6169 public long getDrawingTime() {
6170 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
6171 }
6172
6173 /**
6174 * <p>Enables or disables the duplication of the parent's state into this view. When
6175 * duplication is enabled, this view gets its drawable state from its parent rather
6176 * than from its own internal properties.</p>
6177 *
6178 * <p>Note: in the current implementation, setting this property to true after the
6179 * view was added to a ViewGroup might have no effect at all. This property should
6180 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
6181 *
6182 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
6183 * property is enabled, an exception will be thrown.</p>
6184 *
6185 * @param enabled True to enable duplication of the parent's drawable state, false
6186 * to disable it.
6187 *
6188 * @see #getDrawableState()
6189 * @see #isDuplicateParentStateEnabled()
6190 */
6191 public void setDuplicateParentStateEnabled(boolean enabled) {
6192 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
6193 }
6194
6195 /**
6196 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
6197 *
6198 * @return True if this view's drawable state is duplicated from the parent,
6199 * false otherwise
6200 *
6201 * @see #getDrawableState()
6202 * @see #setDuplicateParentStateEnabled(boolean)
6203 */
6204 public boolean isDuplicateParentStateEnabled() {
6205 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
6206 }
6207
6208 /**
6209 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
6210 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
6211 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
6212 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
6213 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
6214 * null.</p>
6215 *
6216 * @param enabled true to enable the drawing cache, false otherwise
6217 *
6218 * @see #isDrawingCacheEnabled()
6219 * @see #getDrawingCache()
6220 * @see #buildDrawingCache()
6221 */
6222 public void setDrawingCacheEnabled(boolean enabled) {
6223 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
6224 }
6225
6226 /**
6227 * <p>Indicates whether the drawing cache is enabled for this view.</p>
6228 *
6229 * @return true if the drawing cache is enabled
6230 *
6231 * @see #setDrawingCacheEnabled(boolean)
6232 * @see #getDrawingCache()
6233 */
6234 @ViewDebug.ExportedProperty
6235 public boolean isDrawingCacheEnabled() {
6236 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
6237 }
6238
6239 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07006240 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
6241 *
6242 * @return A non-scaled bitmap representing this view or null if cache is disabled.
6243 *
6244 * @see #getDrawingCache(boolean)
6245 */
6246 public Bitmap getDrawingCache() {
6247 return getDrawingCache(false);
6248 }
6249
6250 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
6252 * is null when caching is disabled. If caching is enabled and the cache is not ready,
6253 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
6254 * draw from the cache when the cache is enabled. To benefit from the cache, you must
6255 * request the drawing cache by calling this method and draw it on screen if the
6256 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07006257 *
6258 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
6259 * this method will create a bitmap of the same size as this view. Because this bitmap
6260 * will be drawn scaled by the parent ViewGroup, the result on screen might show
6261 * scaling artifacts. To avoid such artifacts, you should call this method by setting
6262 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
6263 * size than the view. This implies that your application must be able to handle this
6264 * size.</p>
6265 *
6266 * @param autoScale Indicates whether the generated bitmap should be scaled based on
6267 * the current density of the screen when the application is in compatibility
6268 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 *
Romain Guyfbd8f692009-06-26 14:51:58 -07006270 * @return A bitmap representing this view or null if cache is disabled.
6271 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 * @see #setDrawingCacheEnabled(boolean)
6273 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07006274 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 * @see #destroyDrawingCache()
6276 */
Romain Guyfbd8f692009-06-26 14:51:58 -07006277 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
6279 return null;
6280 }
6281 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07006282 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 }
Romain Guyfbd8f692009-06-26 14:51:58 -07006284 return autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) :
6285 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 }
6287
6288 /**
6289 * <p>Frees the resources used by the drawing cache. If you call
6290 * {@link #buildDrawingCache()} manually without calling
6291 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
6292 * should cleanup the cache with this method afterwards.</p>
6293 *
6294 * @see #setDrawingCacheEnabled(boolean)
6295 * @see #buildDrawingCache()
6296 * @see #getDrawingCache()
6297 */
6298 public void destroyDrawingCache() {
6299 if (mDrawingCache != null) {
6300 final Bitmap bitmap = mDrawingCache.get();
6301 if (bitmap != null) bitmap.recycle();
6302 mDrawingCache = null;
6303 }
Romain Guyfbd8f692009-06-26 14:51:58 -07006304 if (mUnscaledDrawingCache != null) {
6305 final Bitmap bitmap = mUnscaledDrawingCache.get();
6306 if (bitmap != null) bitmap.recycle();
6307 mUnscaledDrawingCache = null;
6308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 }
6310
6311 /**
6312 * Setting a solid background color for the drawing cache's bitmaps will improve
6313 * perfromance and memory usage. Note, though that this should only be used if this
6314 * view will always be drawn on top of a solid color.
6315 *
6316 * @param color The background color to use for the drawing cache's bitmap
6317 *
6318 * @see #setDrawingCacheEnabled(boolean)
6319 * @see #buildDrawingCache()
6320 * @see #getDrawingCache()
6321 */
6322 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08006323 if (color != mDrawingCacheBackgroundColor) {
6324 mDrawingCacheBackgroundColor = color;
6325 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 }
6328
6329 /**
6330 * @see #setDrawingCacheBackgroundColor(int)
6331 *
6332 * @return The background color to used for the drawing cache's bitmap
6333 */
6334 public int getDrawingCacheBackgroundColor() {
6335 return mDrawingCacheBackgroundColor;
6336 }
6337
6338 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07006339 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
6340 *
6341 * @see #buildDrawingCache(boolean)
6342 */
6343 public void buildDrawingCache() {
6344 buildDrawingCache(false);
6345 }
6346
6347 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
6349 *
6350 * <p>If you call {@link #buildDrawingCache()} manually without calling
6351 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
6352 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07006353 *
6354 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
6355 * this method will create a bitmap of the same size as this view. Because this bitmap
6356 * will be drawn scaled by the parent ViewGroup, the result on screen might show
6357 * scaling artifacts. To avoid such artifacts, you should call this method by setting
6358 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
6359 * size than the view. This implies that your application must be able to handle this
6360 * size.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006361 *
6362 * @see #getDrawingCache()
6363 * @see #destroyDrawingCache()
6364 */
Romain Guyfbd8f692009-06-26 14:51:58 -07006365 public void buildDrawingCache(boolean autoScale) {
6366 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
6367 (mDrawingCache == null || mDrawingCache.get() == null) :
6368 (mUnscaledDrawingCache == null || mUnscaledDrawingCache.get() == null))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369
6370 if (ViewDebug.TRACE_HIERARCHY) {
6371 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
6372 }
Romain Guy13922e02009-05-12 17:56:14 -07006373 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 EventLog.writeEvent(60002, hashCode());
6375 }
6376
Romain Guy8506ab42009-06-11 17:35:47 -07006377 int width = mRight - mLeft;
6378 int height = mBottom - mTop;
6379
6380 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07006381 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07006382
Romain Guye1123222009-06-29 14:24:56 -07006383 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07006384 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
6385 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07006386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387
6388 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07006389 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Romain Guya62e4702009-10-08 10:48:54 -07006390 final boolean translucentWindow = attachInfo != null && attachInfo.mTranslucentWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391
6392 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07006393 // Projected bitmap size in bytes
6394 (width * height * (opaque && !translucentWindow ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
6396 destroyDrawingCache();
6397 return;
6398 }
6399
6400 boolean clear = true;
Romain Guyfbd8f692009-06-26 14:51:58 -07006401 Bitmap bitmap = autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) :
6402 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403
6404 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 Bitmap.Config quality;
6406 if (!opaque) {
6407 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
6408 case DRAWING_CACHE_QUALITY_AUTO:
6409 quality = Bitmap.Config.ARGB_8888;
6410 break;
6411 case DRAWING_CACHE_QUALITY_LOW:
6412 quality = Bitmap.Config.ARGB_4444;
6413 break;
6414 case DRAWING_CACHE_QUALITY_HIGH:
6415 quality = Bitmap.Config.ARGB_8888;
6416 break;
6417 default:
6418 quality = Bitmap.Config.ARGB_8888;
6419 break;
6420 }
6421 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07006422 // Optimization for translucent windows
6423 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
6424 quality = translucentWindow ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 }
6426
6427 // Try to cleanup memory
6428 if (bitmap != null) bitmap.recycle();
6429
6430 try {
6431 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07006432 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07006433 if (autoScale) {
6434 mDrawingCache = new SoftReference<Bitmap>(bitmap);
6435 } else {
6436 mUnscaledDrawingCache = new SoftReference<Bitmap>(bitmap);
6437 }
Romain Guy35b38ce2009-10-07 13:38:55 -07006438 if (opaque && translucentWindow) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 } catch (OutOfMemoryError e) {
6440 // If there is not enough memory to create the bitmap cache, just
6441 // ignore the issue as bitmap caches are not required to draw the
6442 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07006443 if (autoScale) {
6444 mDrawingCache = null;
6445 } else {
6446 mUnscaledDrawingCache = null;
6447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 return;
6449 }
6450
6451 clear = drawingCacheBackgroundColor != 0;
6452 }
6453
6454 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 if (attachInfo != null) {
6456 canvas = attachInfo.mCanvas;
6457 if (canvas == null) {
6458 canvas = new Canvas();
6459 }
6460 canvas.setBitmap(bitmap);
6461 // Temporarily clobber the cached Canvas in case one of our children
6462 // is also using a drawing cache. Without this, the children would
6463 // steal the canvas by attaching their own bitmap to it and bad, bad
6464 // thing would happen (invisible views, corrupted drawings, etc.)
6465 attachInfo.mCanvas = null;
6466 } else {
6467 // This case should hopefully never or seldom happen
6468 canvas = new Canvas(bitmap);
6469 }
6470
6471 if (clear) {
6472 bitmap.eraseColor(drawingCacheBackgroundColor);
6473 }
6474
6475 computeScroll();
6476 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07006477
Romain Guye1123222009-06-29 14:24:56 -07006478 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07006479 final float scale = attachInfo.mApplicationScale;
6480 canvas.scale(scale, scale);
6481 }
6482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 canvas.translate(-mScrollX, -mScrollY);
6484
Romain Guy5bcdff42009-05-14 21:27:18 -07006485 mPrivateFlags |= DRAWN;
Romain Guyecd80ee2009-12-03 17:13:02 -08006486 mPrivateFlags |= DRAWING_CACHE_VALID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487
6488 // Fast path for layouts with no backgrounds
6489 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
6490 if (ViewDebug.TRACE_HIERARCHY) {
6491 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
6492 }
Romain Guy5bcdff42009-05-14 21:27:18 -07006493 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 dispatchDraw(canvas);
6495 } else {
6496 draw(canvas);
6497 }
6498
6499 canvas.restoreToCount(restoreCount);
6500
6501 if (attachInfo != null) {
6502 // Restore the cached Canvas for our siblings
6503 attachInfo.mCanvas = canvas;
6504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 }
6506 }
6507
6508 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006509 * Create a snapshot of the view into a bitmap. We should probably make
6510 * some form of this public, but should think about the API.
6511 */
Romain Guy223ff5c2010-03-02 17:07:47 -08006512 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006513 int width = mRight - mLeft;
6514 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006515
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006516 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07006517 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006518 width = (int) ((width * scale) + 0.5f);
6519 height = (int) ((height * scale) + 0.5f);
6520
Romain Guy8c11e312009-09-14 15:15:30 -07006521 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006522 if (bitmap == null) {
6523 throw new OutOfMemoryError();
6524 }
6525
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006526 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
6527
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006528 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006529 if (attachInfo != null) {
6530 canvas = attachInfo.mCanvas;
6531 if (canvas == null) {
6532 canvas = new Canvas();
6533 }
6534 canvas.setBitmap(bitmap);
6535 // Temporarily clobber the cached Canvas in case one of our children
6536 // is also using a drawing cache. Without this, the children would
6537 // steal the canvas by attaching their own bitmap to it and bad, bad
6538 // things would happen (invisible views, corrupted drawings, etc.)
6539 attachInfo.mCanvas = null;
6540 } else {
6541 // This case should hopefully never or seldom happen
6542 canvas = new Canvas(bitmap);
6543 }
6544
Romain Guy5bcdff42009-05-14 21:27:18 -07006545 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006546 bitmap.eraseColor(backgroundColor);
6547 }
6548
6549 computeScroll();
6550 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006551 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006552 canvas.translate(-mScrollX, -mScrollY);
6553
Romain Guy5bcdff42009-05-14 21:27:18 -07006554 // Temporarily remove the dirty mask
6555 int flags = mPrivateFlags;
6556 mPrivateFlags &= ~DIRTY_MASK;
6557
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006558 // Fast path for layouts with no backgrounds
6559 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
6560 dispatchDraw(canvas);
6561 } else {
6562 draw(canvas);
6563 }
6564
Romain Guy5bcdff42009-05-14 21:27:18 -07006565 mPrivateFlags = flags;
6566
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006567 canvas.restoreToCount(restoreCount);
6568
6569 if (attachInfo != null) {
6570 // Restore the cached Canvas for our siblings
6571 attachInfo.mCanvas = canvas;
6572 }
Romain Guy8506ab42009-06-11 17:35:47 -07006573
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006574 return bitmap;
6575 }
6576
6577 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 * Indicates whether this View is currently in edit mode. A View is usually
6579 * in edit mode when displayed within a developer tool. For instance, if
6580 * this View is being drawn by a visual user interface builder, this method
6581 * should return true.
6582 *
6583 * Subclasses should check the return value of this method to provide
6584 * different behaviors if their normal behavior might interfere with the
6585 * host environment. For instance: the class spawns a thread in its
6586 * constructor, the drawing code relies on device-specific features, etc.
6587 *
6588 * This method is usually checked in the drawing code of custom widgets.
6589 *
6590 * @return True if this View is in edit mode, false otherwise.
6591 */
6592 public boolean isInEditMode() {
6593 return false;
6594 }
6595
6596 /**
6597 * If the View draws content inside its padding and enables fading edges,
6598 * it needs to support padding offsets. Padding offsets are added to the
6599 * fading edges to extend the length of the fade so that it covers pixels
6600 * drawn inside the padding.
6601 *
6602 * Subclasses of this class should override this method if they need
6603 * to draw content inside the padding.
6604 *
6605 * @return True if padding offset must be applied, false otherwise.
6606 *
6607 * @see #getLeftPaddingOffset()
6608 * @see #getRightPaddingOffset()
6609 * @see #getTopPaddingOffset()
6610 * @see #getBottomPaddingOffset()
6611 *
6612 * @since CURRENT
6613 */
6614 protected boolean isPaddingOffsetRequired() {
6615 return false;
6616 }
6617
6618 /**
6619 * Amount by which to extend the left fading region. Called only when
6620 * {@link #isPaddingOffsetRequired()} returns true.
6621 *
6622 * @return The left padding offset in pixels.
6623 *
6624 * @see #isPaddingOffsetRequired()
6625 *
6626 * @since CURRENT
6627 */
6628 protected int getLeftPaddingOffset() {
6629 return 0;
6630 }
6631
6632 /**
6633 * Amount by which to extend the right fading region. Called only when
6634 * {@link #isPaddingOffsetRequired()} returns true.
6635 *
6636 * @return The right padding offset in pixels.
6637 *
6638 * @see #isPaddingOffsetRequired()
6639 *
6640 * @since CURRENT
6641 */
6642 protected int getRightPaddingOffset() {
6643 return 0;
6644 }
6645
6646 /**
6647 * Amount by which to extend the top fading region. Called only when
6648 * {@link #isPaddingOffsetRequired()} returns true.
6649 *
6650 * @return The top padding offset in pixels.
6651 *
6652 * @see #isPaddingOffsetRequired()
6653 *
6654 * @since CURRENT
6655 */
6656 protected int getTopPaddingOffset() {
6657 return 0;
6658 }
6659
6660 /**
6661 * Amount by which to extend the bottom fading region. Called only when
6662 * {@link #isPaddingOffsetRequired()} returns true.
6663 *
6664 * @return The bottom padding offset in pixels.
6665 *
6666 * @see #isPaddingOffsetRequired()
6667 *
6668 * @since CURRENT
6669 */
6670 protected int getBottomPaddingOffset() {
6671 return 0;
6672 }
6673
6674 /**
6675 * Manually render this view (and all of its children) to the given Canvas.
6676 * The view must have already done a full layout before this function is
6677 * called. When implementing a view, do not override this method; instead,
6678 * you should implement {@link #onDraw}.
6679 *
6680 * @param canvas The Canvas to which the View is rendered.
6681 */
6682 public void draw(Canvas canvas) {
6683 if (ViewDebug.TRACE_HIERARCHY) {
6684 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
6685 }
6686
Romain Guy5bcdff42009-05-14 21:27:18 -07006687 final int privateFlags = mPrivateFlags;
6688 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
6689 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
6690 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07006691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 /*
6693 * Draw traversal performs several drawing steps which must be executed
6694 * in the appropriate order:
6695 *
6696 * 1. Draw the background
6697 * 2. If necessary, save the canvas' layers to prepare for fading
6698 * 3. Draw view's content
6699 * 4. Draw children
6700 * 5. If necessary, draw the fading edges and restore layers
6701 * 6. Draw decorations (scrollbars for instance)
6702 */
6703
6704 // Step 1, draw the background, if needed
6705 int saveCount;
6706
Romain Guy24443ea2009-05-11 11:56:30 -07006707 if (!dirtyOpaque) {
6708 final Drawable background = mBGDrawable;
6709 if (background != null) {
6710 final int scrollX = mScrollX;
6711 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712
Romain Guy24443ea2009-05-11 11:56:30 -07006713 if (mBackgroundSizeChanged) {
6714 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
6715 mBackgroundSizeChanged = false;
6716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717
Romain Guy24443ea2009-05-11 11:56:30 -07006718 if ((scrollX | scrollY) == 0) {
6719 background.draw(canvas);
6720 } else {
6721 canvas.translate(scrollX, scrollY);
6722 background.draw(canvas);
6723 canvas.translate(-scrollX, -scrollY);
6724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006725 }
6726 }
6727
6728 // skip step 2 & 5 if possible (common case)
6729 final int viewFlags = mViewFlags;
6730 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
6731 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
6732 if (!verticalEdges && !horizontalEdges) {
6733 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07006734 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735
6736 // Step 4, draw the children
6737 dispatchDraw(canvas);
6738
6739 // Step 6, draw decorations (scrollbars)
6740 onDrawScrollBars(canvas);
6741
6742 // we're done...
6743 return;
6744 }
6745
6746 /*
6747 * Here we do the full fledged routine...
6748 * (this is an uncommon case where speed matters less,
6749 * this is why we repeat some of the tests that have been
6750 * done above)
6751 */
6752
6753 boolean drawTop = false;
6754 boolean drawBottom = false;
6755 boolean drawLeft = false;
6756 boolean drawRight = false;
6757
6758 float topFadeStrength = 0.0f;
6759 float bottomFadeStrength = 0.0f;
6760 float leftFadeStrength = 0.0f;
6761 float rightFadeStrength = 0.0f;
6762
6763 // Step 2, save the canvas' layers
6764 int paddingLeft = mPaddingLeft;
6765 int paddingTop = mPaddingTop;
6766
6767 final boolean offsetRequired = isPaddingOffsetRequired();
6768 if (offsetRequired) {
6769 paddingLeft += getLeftPaddingOffset();
6770 paddingTop += getTopPaddingOffset();
6771 }
6772
6773 int left = mScrollX + paddingLeft;
6774 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
6775 int top = mScrollY + paddingTop;
6776 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
6777
6778 if (offsetRequired) {
6779 right += getRightPaddingOffset();
6780 bottom += getBottomPaddingOffset();
6781 }
6782
6783 final ScrollabilityCache scrollabilityCache = mScrollCache;
6784 int length = scrollabilityCache.fadingEdgeLength;
6785
6786 // clip the fade length if top and bottom fades overlap
6787 // overlapping fades produce odd-looking artifacts
6788 if (verticalEdges && (top + length > bottom - length)) {
6789 length = (bottom - top) / 2;
6790 }
6791
6792 // also clip horizontal fades if necessary
6793 if (horizontalEdges && (left + length > right - length)) {
6794 length = (right - left) / 2;
6795 }
6796
6797 if (verticalEdges) {
6798 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
6799 drawTop = topFadeStrength >= 0.0f;
6800 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
6801 drawBottom = bottomFadeStrength >= 0.0f;
6802 }
6803
6804 if (horizontalEdges) {
6805 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
6806 drawLeft = leftFadeStrength >= 0.0f;
6807 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
6808 drawRight = rightFadeStrength >= 0.0f;
6809 }
6810
6811 saveCount = canvas.getSaveCount();
6812
6813 int solidColor = getSolidColor();
6814 if (solidColor == 0) {
6815 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
6816
6817 if (drawTop) {
6818 canvas.saveLayer(left, top, right, top + length, null, flags);
6819 }
6820
6821 if (drawBottom) {
6822 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
6823 }
6824
6825 if (drawLeft) {
6826 canvas.saveLayer(left, top, left + length, bottom, null, flags);
6827 }
6828
6829 if (drawRight) {
6830 canvas.saveLayer(right - length, top, right, bottom, null, flags);
6831 }
6832 } else {
6833 scrollabilityCache.setFadeColor(solidColor);
6834 }
6835
6836 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07006837 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838
6839 // Step 4, draw the children
6840 dispatchDraw(canvas);
6841
6842 // Step 5, draw the fade effect and restore layers
6843 final Paint p = scrollabilityCache.paint;
6844 final Matrix matrix = scrollabilityCache.matrix;
6845 final Shader fade = scrollabilityCache.shader;
6846 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
6847
6848 if (drawTop) {
6849 matrix.setScale(1, fadeHeight * topFadeStrength);
6850 matrix.postTranslate(left, top);
6851 fade.setLocalMatrix(matrix);
6852 canvas.drawRect(left, top, right, top + length, p);
6853 }
6854
6855 if (drawBottom) {
6856 matrix.setScale(1, fadeHeight * bottomFadeStrength);
6857 matrix.postRotate(180);
6858 matrix.postTranslate(left, bottom);
6859 fade.setLocalMatrix(matrix);
6860 canvas.drawRect(left, bottom - length, right, bottom, p);
6861 }
6862
6863 if (drawLeft) {
6864 matrix.setScale(1, fadeHeight * leftFadeStrength);
6865 matrix.postRotate(-90);
6866 matrix.postTranslate(left, top);
6867 fade.setLocalMatrix(matrix);
6868 canvas.drawRect(left, top, left + length, bottom, p);
6869 }
6870
6871 if (drawRight) {
6872 matrix.setScale(1, fadeHeight * rightFadeStrength);
6873 matrix.postRotate(90);
6874 matrix.postTranslate(right, top);
6875 fade.setLocalMatrix(matrix);
6876 canvas.drawRect(right - length, top, right, bottom, p);
6877 }
6878
6879 canvas.restoreToCount(saveCount);
6880
6881 // Step 6, draw decorations (scrollbars)
6882 onDrawScrollBars(canvas);
6883 }
6884
6885 /**
6886 * Override this if your view is known to always be drawn on top of a solid color background,
6887 * and needs to draw fading edges. Returning a non-zero color enables the view system to
6888 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
6889 * should be set to 0xFF.
6890 *
6891 * @see #setVerticalFadingEdgeEnabled
6892 * @see #setHorizontalFadingEdgeEnabled
6893 *
6894 * @return The known solid color background for this view, or 0 if the color may vary
6895 */
6896 public int getSolidColor() {
6897 return 0;
6898 }
6899
6900 /**
6901 * Build a human readable string representation of the specified view flags.
6902 *
6903 * @param flags the view flags to convert to a string
6904 * @return a String representing the supplied flags
6905 */
6906 private static String printFlags(int flags) {
6907 String output = "";
6908 int numFlags = 0;
6909 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
6910 output += "TAKES_FOCUS";
6911 numFlags++;
6912 }
6913
6914 switch (flags & VISIBILITY_MASK) {
6915 case INVISIBLE:
6916 if (numFlags > 0) {
6917 output += " ";
6918 }
6919 output += "INVISIBLE";
6920 // USELESS HERE numFlags++;
6921 break;
6922 case GONE:
6923 if (numFlags > 0) {
6924 output += " ";
6925 }
6926 output += "GONE";
6927 // USELESS HERE numFlags++;
6928 break;
6929 default:
6930 break;
6931 }
6932 return output;
6933 }
6934
6935 /**
6936 * Build a human readable string representation of the specified private
6937 * view flags.
6938 *
6939 * @param privateFlags the private view flags to convert to a string
6940 * @return a String representing the supplied flags
6941 */
6942 private static String printPrivateFlags(int privateFlags) {
6943 String output = "";
6944 int numFlags = 0;
6945
6946 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
6947 output += "WANTS_FOCUS";
6948 numFlags++;
6949 }
6950
6951 if ((privateFlags & FOCUSED) == FOCUSED) {
6952 if (numFlags > 0) {
6953 output += " ";
6954 }
6955 output += "FOCUSED";
6956 numFlags++;
6957 }
6958
6959 if ((privateFlags & SELECTED) == SELECTED) {
6960 if (numFlags > 0) {
6961 output += " ";
6962 }
6963 output += "SELECTED";
6964 numFlags++;
6965 }
6966
6967 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
6968 if (numFlags > 0) {
6969 output += " ";
6970 }
6971 output += "IS_ROOT_NAMESPACE";
6972 numFlags++;
6973 }
6974
6975 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
6976 if (numFlags > 0) {
6977 output += " ";
6978 }
6979 output += "HAS_BOUNDS";
6980 numFlags++;
6981 }
6982
6983 if ((privateFlags & DRAWN) == DRAWN) {
6984 if (numFlags > 0) {
6985 output += " ";
6986 }
6987 output += "DRAWN";
6988 // USELESS HERE numFlags++;
6989 }
6990 return output;
6991 }
6992
6993 /**
6994 * <p>Indicates whether or not this view's layout will be requested during
6995 * the next hierarchy layout pass.</p>
6996 *
6997 * @return true if the layout will be forced during next layout pass
6998 */
6999 public boolean isLayoutRequested() {
7000 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
7001 }
7002
7003 /**
7004 * Assign a size and position to a view and all of its
7005 * descendants
7006 *
7007 * <p>This is the second phase of the layout mechanism.
7008 * (The first is measuring). In this phase, each parent calls
7009 * layout on all of its children to position them.
7010 * This is typically done using the child measurements
7011 * that were stored in the measure pass().
7012 *
7013 * Derived classes with children should override
7014 * onLayout. In that method, they should
7015 * call layout on each of their their children.
7016 *
7017 * @param l Left position, relative to parent
7018 * @param t Top position, relative to parent
7019 * @param r Right position, relative to parent
7020 * @param b Bottom position, relative to parent
7021 */
7022 public final void layout(int l, int t, int r, int b) {
7023 boolean changed = setFrame(l, t, r, b);
7024 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
7025 if (ViewDebug.TRACE_HIERARCHY) {
7026 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
7027 }
7028
7029 onLayout(changed, l, t, r, b);
7030 mPrivateFlags &= ~LAYOUT_REQUIRED;
7031 }
7032 mPrivateFlags &= ~FORCE_LAYOUT;
7033 }
7034
7035 /**
7036 * Called from layout when this view should
7037 * assign a size and position to each of its children.
7038 *
7039 * Derived classes with children should override
7040 * this method and call layout on each of
7041 * their their children.
7042 * @param changed This is a new size or position for this view
7043 * @param left Left position, relative to parent
7044 * @param top Top position, relative to parent
7045 * @param right Right position, relative to parent
7046 * @param bottom Bottom position, relative to parent
7047 */
7048 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
7049 }
7050
7051 /**
7052 * Assign a size and position to this view.
7053 *
7054 * This is called from layout.
7055 *
7056 * @param left Left position, relative to parent
7057 * @param top Top position, relative to parent
7058 * @param right Right position, relative to parent
7059 * @param bottom Bottom position, relative to parent
7060 * @return true if the new size and position are different than the
7061 * previous ones
7062 * {@hide}
7063 */
7064 protected boolean setFrame(int left, int top, int right, int bottom) {
7065 boolean changed = false;
7066
7067 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07007068 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007069 + right + "," + bottom + ")");
7070 }
7071
7072 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
7073 changed = true;
7074
7075 // Remember our drawn bit
7076 int drawn = mPrivateFlags & DRAWN;
7077
7078 // Invalidate our old position
7079 invalidate();
7080
7081
7082 int oldWidth = mRight - mLeft;
7083 int oldHeight = mBottom - mTop;
7084
7085 mLeft = left;
7086 mTop = top;
7087 mRight = right;
7088 mBottom = bottom;
7089
7090 mPrivateFlags |= HAS_BOUNDS;
7091
7092 int newWidth = right - left;
7093 int newHeight = bottom - top;
7094
7095 if (newWidth != oldWidth || newHeight != oldHeight) {
7096 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
7097 }
7098
7099 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
7100 // If we are visible, force the DRAWN bit to on so that
7101 // this invalidate will go through (at least to our parent).
7102 // This is because someone may have invalidated this view
7103 // before this call to setFrame came in, therby clearing
7104 // the DRAWN bit.
7105 mPrivateFlags |= DRAWN;
7106 invalidate();
7107 }
7108
7109 // Reset drawn bit to original value (invalidate turns it off)
7110 mPrivateFlags |= drawn;
7111
7112 mBackgroundSizeChanged = true;
7113 }
7114 return changed;
7115 }
7116
7117 /**
7118 * Finalize inflating a view from XML. This is called as the last phase
7119 * of inflation, after all child views have been added.
7120 *
7121 * <p>Even if the subclass overrides onFinishInflate, they should always be
7122 * sure to call the super method, so that we get called.
7123 */
7124 protected void onFinishInflate() {
7125 }
7126
7127 /**
7128 * Returns the resources associated with this view.
7129 *
7130 * @return Resources object.
7131 */
7132 public Resources getResources() {
7133 return mResources;
7134 }
7135
7136 /**
7137 * Invalidates the specified Drawable.
7138 *
7139 * @param drawable the drawable to invalidate
7140 */
7141 public void invalidateDrawable(Drawable drawable) {
7142 if (verifyDrawable(drawable)) {
7143 final Rect dirty = drawable.getBounds();
7144 final int scrollX = mScrollX;
7145 final int scrollY = mScrollY;
7146
7147 invalidate(dirty.left + scrollX, dirty.top + scrollY,
7148 dirty.right + scrollX, dirty.bottom + scrollY);
7149 }
7150 }
7151
7152 /**
7153 * Schedules an action on a drawable to occur at a specified time.
7154 *
7155 * @param who the recipient of the action
7156 * @param what the action to run on the drawable
7157 * @param when the time at which the action must occur. Uses the
7158 * {@link SystemClock#uptimeMillis} timebase.
7159 */
7160 public void scheduleDrawable(Drawable who, Runnable what, long when) {
7161 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
7162 mAttachInfo.mHandler.postAtTime(what, who, when);
7163 }
7164 }
7165
7166 /**
7167 * Cancels a scheduled action on a drawable.
7168 *
7169 * @param who the recipient of the action
7170 * @param what the action to cancel
7171 */
7172 public void unscheduleDrawable(Drawable who, Runnable what) {
7173 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
7174 mAttachInfo.mHandler.removeCallbacks(what, who);
7175 }
7176 }
7177
7178 /**
7179 * Unschedule any events associated with the given Drawable. This can be
7180 * used when selecting a new Drawable into a view, so that the previous
7181 * one is completely unscheduled.
7182 *
7183 * @param who The Drawable to unschedule.
7184 *
7185 * @see #drawableStateChanged
7186 */
7187 public void unscheduleDrawable(Drawable who) {
7188 if (mAttachInfo != null) {
7189 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
7190 }
7191 }
7192
7193 /**
7194 * If your view subclass is displaying its own Drawable objects, it should
7195 * override this function and return true for any Drawable it is
7196 * displaying. This allows animations for those drawables to be
7197 * scheduled.
7198 *
7199 * <p>Be sure to call through to the super class when overriding this
7200 * function.
7201 *
7202 * @param who The Drawable to verify. Return true if it is one you are
7203 * displaying, else return the result of calling through to the
7204 * super class.
7205 *
7206 * @return boolean If true than the Drawable is being displayed in the
7207 * view; else false and it is not allowed to animate.
7208 *
7209 * @see #unscheduleDrawable
7210 * @see #drawableStateChanged
7211 */
7212 protected boolean verifyDrawable(Drawable who) {
7213 return who == mBGDrawable;
7214 }
7215
7216 /**
7217 * This function is called whenever the state of the view changes in such
7218 * a way that it impacts the state of drawables being shown.
7219 *
7220 * <p>Be sure to call through to the superclass when overriding this
7221 * function.
7222 *
7223 * @see Drawable#setState
7224 */
7225 protected void drawableStateChanged() {
7226 Drawable d = mBGDrawable;
7227 if (d != null && d.isStateful()) {
7228 d.setState(getDrawableState());
7229 }
7230 }
7231
7232 /**
7233 * Call this to force a view to update its drawable state. This will cause
7234 * drawableStateChanged to be called on this view. Views that are interested
7235 * in the new state should call getDrawableState.
7236 *
7237 * @see #drawableStateChanged
7238 * @see #getDrawableState
7239 */
7240 public void refreshDrawableState() {
7241 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
7242 drawableStateChanged();
7243
7244 ViewParent parent = mParent;
7245 if (parent != null) {
7246 parent.childDrawableStateChanged(this);
7247 }
7248 }
7249
7250 /**
7251 * Return an array of resource IDs of the drawable states representing the
7252 * current state of the view.
7253 *
7254 * @return The current drawable state
7255 *
7256 * @see Drawable#setState
7257 * @see #drawableStateChanged
7258 * @see #onCreateDrawableState
7259 */
7260 public final int[] getDrawableState() {
7261 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
7262 return mDrawableState;
7263 } else {
7264 mDrawableState = onCreateDrawableState(0);
7265 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
7266 return mDrawableState;
7267 }
7268 }
7269
7270 /**
7271 * Generate the new {@link android.graphics.drawable.Drawable} state for
7272 * this view. This is called by the view
7273 * system when the cached Drawable state is determined to be invalid. To
7274 * retrieve the current state, you should use {@link #getDrawableState}.
7275 *
7276 * @param extraSpace if non-zero, this is the number of extra entries you
7277 * would like in the returned array in which you can place your own
7278 * states.
7279 *
7280 * @return Returns an array holding the current {@link Drawable} state of
7281 * the view.
7282 *
7283 * @see #mergeDrawableStates
7284 */
7285 protected int[] onCreateDrawableState(int extraSpace) {
7286 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
7287 mParent instanceof View) {
7288 return ((View) mParent).onCreateDrawableState(extraSpace);
7289 }
7290
7291 int[] drawableState;
7292
7293 int privateFlags = mPrivateFlags;
7294
7295 int viewStateIndex = (((privateFlags & PRESSED) != 0) ? 1 : 0);
7296
7297 viewStateIndex = (viewStateIndex << 1)
7298 + (((mViewFlags & ENABLED_MASK) == ENABLED) ? 1 : 0);
7299
7300 viewStateIndex = (viewStateIndex << 1) + (isFocused() ? 1 : 0);
7301
7302 viewStateIndex = (viewStateIndex << 1)
7303 + (((privateFlags & SELECTED) != 0) ? 1 : 0);
7304
7305 final boolean hasWindowFocus = hasWindowFocus();
7306 viewStateIndex = (viewStateIndex << 1) + (hasWindowFocus ? 1 : 0);
7307
7308 drawableState = VIEW_STATE_SETS[viewStateIndex];
7309
7310 //noinspection ConstantIfStatement
7311 if (false) {
7312 Log.i("View", "drawableStateIndex=" + viewStateIndex);
7313 Log.i("View", toString()
7314 + " pressed=" + ((privateFlags & PRESSED) != 0)
7315 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
7316 + " fo=" + hasFocus()
7317 + " sl=" + ((privateFlags & SELECTED) != 0)
7318 + " wf=" + hasWindowFocus
7319 + ": " + Arrays.toString(drawableState));
7320 }
7321
7322 if (extraSpace == 0) {
7323 return drawableState;
7324 }
7325
7326 final int[] fullState;
7327 if (drawableState != null) {
7328 fullState = new int[drawableState.length + extraSpace];
7329 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
7330 } else {
7331 fullState = new int[extraSpace];
7332 }
7333
7334 return fullState;
7335 }
7336
7337 /**
7338 * Merge your own state values in <var>additionalState</var> into the base
7339 * state values <var>baseState</var> that were returned by
7340 * {@link #onCreateDrawableState}.
7341 *
7342 * @param baseState The base state values returned by
7343 * {@link #onCreateDrawableState}, which will be modified to also hold your
7344 * own additional state values.
7345 *
7346 * @param additionalState The additional state values you would like
7347 * added to <var>baseState</var>; this array is not modified.
7348 *
7349 * @return As a convenience, the <var>baseState</var> array you originally
7350 * passed into the function is returned.
7351 *
7352 * @see #onCreateDrawableState
7353 */
7354 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
7355 final int N = baseState.length;
7356 int i = N - 1;
7357 while (i >= 0 && baseState[i] == 0) {
7358 i--;
7359 }
7360 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
7361 return baseState;
7362 }
7363
7364 /**
7365 * Sets the background color for this view.
7366 * @param color the color of the background
7367 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00007368 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007369 public void setBackgroundColor(int color) {
7370 setBackgroundDrawable(new ColorDrawable(color));
7371 }
7372
7373 /**
7374 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07007375 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007376 * @param resid The identifier of the resource.
7377 * @attr ref android.R.styleable#View_background
7378 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00007379 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007380 public void setBackgroundResource(int resid) {
7381 if (resid != 0 && resid == mBackgroundResource) {
7382 return;
7383 }
7384
7385 Drawable d= null;
7386 if (resid != 0) {
7387 d = mResources.getDrawable(resid);
7388 }
7389 setBackgroundDrawable(d);
7390
7391 mBackgroundResource = resid;
7392 }
7393
7394 /**
7395 * Set the background to a given Drawable, or remove the background. If the
7396 * background has padding, this View's padding is set to the background's
7397 * padding. However, when a background is removed, this View's padding isn't
7398 * touched. If setting the padding is desired, please use
7399 * {@link #setPadding(int, int, int, int)}.
7400 *
7401 * @param d The Drawable to use as the background, or null to remove the
7402 * background
7403 */
7404 public void setBackgroundDrawable(Drawable d) {
7405 boolean requestLayout = false;
7406
7407 mBackgroundResource = 0;
7408
7409 /*
7410 * Regardless of whether we're setting a new background or not, we want
7411 * to clear the previous drawable.
7412 */
7413 if (mBGDrawable != null) {
7414 mBGDrawable.setCallback(null);
7415 unscheduleDrawable(mBGDrawable);
7416 }
7417
7418 if (d != null) {
7419 Rect padding = sThreadLocal.get();
7420 if (padding == null) {
7421 padding = new Rect();
7422 sThreadLocal.set(padding);
7423 }
7424 if (d.getPadding(padding)) {
7425 setPadding(padding.left, padding.top, padding.right, padding.bottom);
7426 }
7427
7428 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
7429 // if it has a different minimum size, we should layout again
7430 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
7431 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
7432 requestLayout = true;
7433 }
7434
7435 d.setCallback(this);
7436 if (d.isStateful()) {
7437 d.setState(getDrawableState());
7438 }
7439 d.setVisible(getVisibility() == VISIBLE, false);
7440 mBGDrawable = d;
7441
7442 if ((mPrivateFlags & SKIP_DRAW) != 0) {
7443 mPrivateFlags &= ~SKIP_DRAW;
7444 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
7445 requestLayout = true;
7446 }
7447 } else {
7448 /* Remove the background */
7449 mBGDrawable = null;
7450
7451 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
7452 /*
7453 * This view ONLY drew the background before and we're removing
7454 * the background, so now it won't draw anything
7455 * (hence we SKIP_DRAW)
7456 */
7457 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
7458 mPrivateFlags |= SKIP_DRAW;
7459 }
7460
7461 /*
7462 * When the background is set, we try to apply its padding to this
7463 * View. When the background is removed, we don't touch this View's
7464 * padding. This is noted in the Javadocs. Hence, we don't need to
7465 * requestLayout(), the invalidate() below is sufficient.
7466 */
7467
7468 // The old background's minimum size could have affected this
7469 // View's layout, so let's requestLayout
7470 requestLayout = true;
7471 }
7472
Romain Guy8f1344f52009-05-15 16:03:59 -07007473 computeOpaqueFlags();
7474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007475 if (requestLayout) {
7476 requestLayout();
7477 }
7478
7479 mBackgroundSizeChanged = true;
7480 invalidate();
7481 }
7482
7483 /**
7484 * Gets the background drawable
7485 * @return The drawable used as the background for this view, if any.
7486 */
7487 public Drawable getBackground() {
7488 return mBGDrawable;
7489 }
7490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007491 /**
7492 * Sets the padding. The view may add on the space required to display
7493 * the scrollbars, depending on the style and visibility of the scrollbars.
7494 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
7495 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
7496 * from the values set in this call.
7497 *
7498 * @attr ref android.R.styleable#View_padding
7499 * @attr ref android.R.styleable#View_paddingBottom
7500 * @attr ref android.R.styleable#View_paddingLeft
7501 * @attr ref android.R.styleable#View_paddingRight
7502 * @attr ref android.R.styleable#View_paddingTop
7503 * @param left the left padding in pixels
7504 * @param top the top padding in pixels
7505 * @param right the right padding in pixels
7506 * @param bottom the bottom padding in pixels
7507 */
7508 public void setPadding(int left, int top, int right, int bottom) {
7509 boolean changed = false;
7510
7511 mUserPaddingRight = right;
7512 mUserPaddingBottom = bottom;
7513
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007514 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07007515
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007516 // Common case is there are no scroll bars.
7517 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
7518 // TODO: Deal with RTL languages to adjust left padding instead of right.
7519 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
7520 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
7521 ? 0 : getVerticalScrollbarWidth();
7522 }
7523 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
7524 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
7525 ? 0 : getHorizontalScrollbarHeight();
7526 }
7527 }
Romain Guy8506ab42009-06-11 17:35:47 -07007528
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007529 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007530 changed = true;
7531 mPaddingLeft = left;
7532 }
7533 if (mPaddingTop != top) {
7534 changed = true;
7535 mPaddingTop = top;
7536 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007537 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007539 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007540 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007541 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007543 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007544 }
7545
7546 if (changed) {
7547 requestLayout();
7548 }
7549 }
7550
7551 /**
7552 * Returns the top padding of this view.
7553 *
7554 * @return the top padding in pixels
7555 */
7556 public int getPaddingTop() {
7557 return mPaddingTop;
7558 }
7559
7560 /**
7561 * Returns the bottom padding of this view. If there are inset and enabled
7562 * scrollbars, this value may include the space required to display the
7563 * scrollbars as well.
7564 *
7565 * @return the bottom padding in pixels
7566 */
7567 public int getPaddingBottom() {
7568 return mPaddingBottom;
7569 }
7570
7571 /**
7572 * Returns the left padding of this view. If there are inset and enabled
7573 * scrollbars, this value may include the space required to display the
7574 * scrollbars as well.
7575 *
7576 * @return the left padding in pixels
7577 */
7578 public int getPaddingLeft() {
7579 return mPaddingLeft;
7580 }
7581
7582 /**
7583 * Returns the right padding of this view. If there are inset and enabled
7584 * scrollbars, this value may include the space required to display the
7585 * scrollbars as well.
7586 *
7587 * @return the right padding in pixels
7588 */
7589 public int getPaddingRight() {
7590 return mPaddingRight;
7591 }
7592
7593 /**
7594 * Changes the selection state of this view. A view can be selected or not.
7595 * Note that selection is not the same as focus. Views are typically
7596 * selected in the context of an AdapterView like ListView or GridView;
7597 * the selected view is the view that is highlighted.
7598 *
7599 * @param selected true if the view must be selected, false otherwise
7600 */
7601 public void setSelected(boolean selected) {
7602 if (((mPrivateFlags & SELECTED) != 0) != selected) {
7603 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07007604 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007605 invalidate();
7606 refreshDrawableState();
7607 dispatchSetSelected(selected);
7608 }
7609 }
7610
7611 /**
7612 * Dispatch setSelected to all of this View's children.
7613 *
7614 * @see #setSelected(boolean)
7615 *
7616 * @param selected The new selected state
7617 */
7618 protected void dispatchSetSelected(boolean selected) {
7619 }
7620
7621 /**
7622 * Indicates the selection state of this view.
7623 *
7624 * @return true if the view is selected, false otherwise
7625 */
7626 @ViewDebug.ExportedProperty
7627 public boolean isSelected() {
7628 return (mPrivateFlags & SELECTED) != 0;
7629 }
7630
7631 /**
7632 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
7633 * observer can be used to get notifications when global events, like
7634 * layout, happen.
7635 *
7636 * The returned ViewTreeObserver observer is not guaranteed to remain
7637 * valid for the lifetime of this View. If the caller of this method keeps
7638 * a long-lived reference to ViewTreeObserver, it should always check for
7639 * the return value of {@link ViewTreeObserver#isAlive()}.
7640 *
7641 * @return The ViewTreeObserver for this view's hierarchy.
7642 */
7643 public ViewTreeObserver getViewTreeObserver() {
7644 if (mAttachInfo != null) {
7645 return mAttachInfo.mTreeObserver;
7646 }
7647 if (mFloatingTreeObserver == null) {
7648 mFloatingTreeObserver = new ViewTreeObserver();
7649 }
7650 return mFloatingTreeObserver;
7651 }
7652
7653 /**
7654 * <p>Finds the topmost view in the current view hierarchy.</p>
7655 *
7656 * @return the topmost view containing this view
7657 */
7658 public View getRootView() {
7659 if (mAttachInfo != null) {
7660 final View v = mAttachInfo.mRootView;
7661 if (v != null) {
7662 return v;
7663 }
7664 }
Romain Guy8506ab42009-06-11 17:35:47 -07007665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666 View parent = this;
7667
7668 while (parent.mParent != null && parent.mParent instanceof View) {
7669 parent = (View) parent.mParent;
7670 }
7671
7672 return parent;
7673 }
7674
7675 /**
7676 * <p>Computes the coordinates of this view on the screen. The argument
7677 * must be an array of two integers. After the method returns, the array
7678 * contains the x and y location in that order.</p>
7679 *
7680 * @param location an array of two integers in which to hold the coordinates
7681 */
7682 public void getLocationOnScreen(int[] location) {
7683 getLocationInWindow(location);
7684
7685 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07007686 if (info != null) {
7687 location[0] += info.mWindowLeft;
7688 location[1] += info.mWindowTop;
7689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 }
7691
7692 /**
7693 * <p>Computes the coordinates of this view in its window. The argument
7694 * must be an array of two integers. After the method returns, the array
7695 * contains the x and y location in that order.</p>
7696 *
7697 * @param location an array of two integers in which to hold the coordinates
7698 */
7699 public void getLocationInWindow(int[] location) {
7700 if (location == null || location.length < 2) {
7701 throw new IllegalArgumentException("location must be an array of "
7702 + "two integers");
7703 }
7704
7705 location[0] = mLeft;
7706 location[1] = mTop;
7707
7708 ViewParent viewParent = mParent;
7709 while (viewParent instanceof View) {
7710 final View view = (View)viewParent;
7711 location[0] += view.mLeft - view.mScrollX;
7712 location[1] += view.mTop - view.mScrollY;
7713 viewParent = view.mParent;
7714 }
Romain Guy8506ab42009-06-11 17:35:47 -07007715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 if (viewParent instanceof ViewRoot) {
7717 // *cough*
7718 final ViewRoot vr = (ViewRoot)viewParent;
7719 location[1] -= vr.mCurScrollY;
7720 }
7721 }
7722
7723 /**
7724 * {@hide}
7725 * @param id the id of the view to be found
7726 * @return the view of the specified id, null if cannot be found
7727 */
7728 protected View findViewTraversal(int id) {
7729 if (id == mID) {
7730 return this;
7731 }
7732 return null;
7733 }
7734
7735 /**
7736 * {@hide}
7737 * @param tag the tag of the view to be found
7738 * @return the view of specified tag, null if cannot be found
7739 */
7740 protected View findViewWithTagTraversal(Object tag) {
7741 if (tag != null && tag.equals(mTag)) {
7742 return this;
7743 }
7744 return null;
7745 }
7746
7747 /**
7748 * Look for a child view with the given id. If this view has the given
7749 * id, return this view.
7750 *
7751 * @param id The id to search for.
7752 * @return The view that has the given id in the hierarchy or null
7753 */
7754 public final View findViewById(int id) {
7755 if (id < 0) {
7756 return null;
7757 }
7758 return findViewTraversal(id);
7759 }
7760
7761 /**
7762 * Look for a child view with the given tag. If this view has the given
7763 * tag, return this view.
7764 *
7765 * @param tag The tag to search for, using "tag.equals(getTag())".
7766 * @return The View that has the given tag in the hierarchy or null
7767 */
7768 public final View findViewWithTag(Object tag) {
7769 if (tag == null) {
7770 return null;
7771 }
7772 return findViewWithTagTraversal(tag);
7773 }
7774
7775 /**
7776 * Sets the identifier for this view. The identifier does not have to be
7777 * unique in this view's hierarchy. The identifier should be a positive
7778 * number.
7779 *
7780 * @see #NO_ID
7781 * @see #getId
7782 * @see #findViewById
7783 *
7784 * @param id a number used to identify the view
7785 *
7786 * @attr ref android.R.styleable#View_id
7787 */
7788 public void setId(int id) {
7789 mID = id;
7790 }
7791
7792 /**
7793 * {@hide}
7794 *
7795 * @param isRoot true if the view belongs to the root namespace, false
7796 * otherwise
7797 */
7798 public void setIsRootNamespace(boolean isRoot) {
7799 if (isRoot) {
7800 mPrivateFlags |= IS_ROOT_NAMESPACE;
7801 } else {
7802 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
7803 }
7804 }
7805
7806 /**
7807 * {@hide}
7808 *
7809 * @return true if the view belongs to the root namespace, false otherwise
7810 */
7811 public boolean isRootNamespace() {
7812 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
7813 }
7814
7815 /**
7816 * Returns this view's identifier.
7817 *
7818 * @return a positive integer used to identify the view or {@link #NO_ID}
7819 * if the view has no ID
7820 *
7821 * @see #setId
7822 * @see #findViewById
7823 * @attr ref android.R.styleable#View_id
7824 */
7825 @ViewDebug.CapturedViewProperty
7826 public int getId() {
7827 return mID;
7828 }
7829
7830 /**
7831 * Returns this view's tag.
7832 *
7833 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07007834 *
7835 * @see #setTag(Object)
7836 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007837 */
7838 @ViewDebug.ExportedProperty
7839 public Object getTag() {
7840 return mTag;
7841 }
7842
7843 /**
7844 * Sets the tag associated with this view. A tag can be used to mark
7845 * a view in its hierarchy and does not have to be unique within the
7846 * hierarchy. Tags can also be used to store data within a view without
7847 * resorting to another data structure.
7848 *
7849 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07007850 *
7851 * @see #getTag()
7852 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007853 */
7854 public void setTag(final Object tag) {
7855 mTag = tag;
7856 }
7857
7858 /**
Romain Guyd90a3312009-05-06 14:54:28 -07007859 * Returns the tag associated with this view and the specified key.
7860 *
7861 * @param key The key identifying the tag
7862 *
7863 * @return the Object stored in this view as a tag
7864 *
7865 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07007866 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07007867 */
7868 public Object getTag(int key) {
7869 SparseArray<Object> tags = null;
7870 synchronized (sTagsLock) {
7871 if (sTags != null) {
7872 tags = sTags.get(this);
7873 }
7874 }
7875
7876 if (tags != null) return tags.get(key);
7877 return null;
7878 }
7879
7880 /**
7881 * Sets a tag associated with this view and a key. A tag can be used
7882 * to mark a view in its hierarchy and does not have to be unique within
7883 * the hierarchy. Tags can also be used to store data within a view
7884 * without resorting to another data structure.
7885 *
7886 * The specified key should be an id declared in the resources of the
7887 * application to ensure it is unique. Keys identified as belonging to
7888 * the Android framework or not associated with any package will cause
7889 * an {@link IllegalArgumentException} to be thrown.
7890 *
7891 * @param key The key identifying the tag
7892 * @param tag An Object to tag the view with
7893 *
7894 * @throws IllegalArgumentException If they specified key is not valid
7895 *
7896 * @see #setTag(Object)
7897 * @see #getTag(int)
7898 */
7899 public void setTag(int key, final Object tag) {
7900 // If the package id is 0x00 or 0x01, it's either an undefined package
7901 // or a framework id
7902 if ((key >>> 24) < 2) {
7903 throw new IllegalArgumentException("The key must be an application-specific "
7904 + "resource id.");
7905 }
7906
7907 setTagInternal(this, key, tag);
7908 }
7909
7910 /**
7911 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
7912 * framework id.
7913 *
7914 * @hide
7915 */
7916 public void setTagInternal(int key, Object tag) {
7917 if ((key >>> 24) != 0x1) {
7918 throw new IllegalArgumentException("The key must be a framework-specific "
7919 + "resource id.");
7920 }
7921
Romain Guy8506ab42009-06-11 17:35:47 -07007922 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07007923 }
7924
7925 private static void setTagInternal(View view, int key, Object tag) {
7926 SparseArray<Object> tags = null;
7927 synchronized (sTagsLock) {
7928 if (sTags == null) {
7929 sTags = new WeakHashMap<View, SparseArray<Object>>();
7930 } else {
7931 tags = sTags.get(view);
7932 }
7933 }
7934
7935 if (tags == null) {
7936 tags = new SparseArray<Object>(2);
7937 synchronized (sTagsLock) {
7938 sTags.put(view, tags);
7939 }
7940 }
7941
7942 tags.put(key, tag);
7943 }
7944
7945 /**
Romain Guy13922e02009-05-12 17:56:14 -07007946 * @param consistency The type of consistency. See ViewDebug for more information.
7947 *
7948 * @hide
7949 */
7950 protected boolean dispatchConsistencyCheck(int consistency) {
7951 return onConsistencyCheck(consistency);
7952 }
7953
7954 /**
7955 * Method that subclasses should implement to check their consistency. The type of
7956 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07007957 *
Romain Guy13922e02009-05-12 17:56:14 -07007958 * @param consistency The type of consistency. See ViewDebug for more information.
7959 *
7960 * @throws IllegalStateException if the view is in an inconsistent state.
7961 *
7962 * @hide
7963 */
7964 protected boolean onConsistencyCheck(int consistency) {
7965 boolean result = true;
7966
7967 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
7968 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
7969
7970 if (checkLayout) {
7971 if (getParent() == null) {
7972 result = false;
7973 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
7974 "View " + this + " does not have a parent.");
7975 }
7976
7977 if (mAttachInfo == null) {
7978 result = false;
7979 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
7980 "View " + this + " is not attached to a window.");
7981 }
7982 }
7983
7984 if (checkDrawing) {
7985 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
7986 // from their draw() method
7987
7988 if ((mPrivateFlags & DRAWN) != DRAWN &&
7989 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
7990 result = false;
7991 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
7992 "View " + this + " was invalidated but its drawing cache is valid.");
7993 }
7994 }
7995
7996 return result;
7997 }
7998
7999 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 * Prints information about this view in the log output, with the tag
8001 * {@link #VIEW_LOG_TAG}.
8002 *
8003 * @hide
8004 */
8005 public void debug() {
8006 debug(0);
8007 }
8008
8009 /**
8010 * Prints information about this view in the log output, with the tag
8011 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
8012 * indentation defined by the <code>depth</code>.
8013 *
8014 * @param depth the indentation level
8015 *
8016 * @hide
8017 */
8018 protected void debug(int depth) {
8019 String output = debugIndent(depth - 1);
8020
8021 output += "+ " + this;
8022 int id = getId();
8023 if (id != -1) {
8024 output += " (id=" + id + ")";
8025 }
8026 Object tag = getTag();
8027 if (tag != null) {
8028 output += " (tag=" + tag + ")";
8029 }
8030 Log.d(VIEW_LOG_TAG, output);
8031
8032 if ((mPrivateFlags & FOCUSED) != 0) {
8033 output = debugIndent(depth) + " FOCUSED";
8034 Log.d(VIEW_LOG_TAG, output);
8035 }
8036
8037 output = debugIndent(depth);
8038 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
8039 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
8040 + "} ";
8041 Log.d(VIEW_LOG_TAG, output);
8042
8043 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
8044 || mPaddingBottom != 0) {
8045 output = debugIndent(depth);
8046 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
8047 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
8048 Log.d(VIEW_LOG_TAG, output);
8049 }
8050
8051 output = debugIndent(depth);
8052 output += "mMeasureWidth=" + mMeasuredWidth +
8053 " mMeasureHeight=" + mMeasuredHeight;
8054 Log.d(VIEW_LOG_TAG, output);
8055
8056 output = debugIndent(depth);
8057 if (mLayoutParams == null) {
8058 output += "BAD! no layout params";
8059 } else {
8060 output = mLayoutParams.debug(output);
8061 }
8062 Log.d(VIEW_LOG_TAG, output);
8063
8064 output = debugIndent(depth);
8065 output += "flags={";
8066 output += View.printFlags(mViewFlags);
8067 output += "}";
8068 Log.d(VIEW_LOG_TAG, output);
8069
8070 output = debugIndent(depth);
8071 output += "privateFlags={";
8072 output += View.printPrivateFlags(mPrivateFlags);
8073 output += "}";
8074 Log.d(VIEW_LOG_TAG, output);
8075 }
8076
8077 /**
8078 * Creates an string of whitespaces used for indentation.
8079 *
8080 * @param depth the indentation level
8081 * @return a String containing (depth * 2 + 3) * 2 white spaces
8082 *
8083 * @hide
8084 */
8085 protected static String debugIndent(int depth) {
8086 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
8087 for (int i = 0; i < (depth * 2) + 3; i++) {
8088 spaces.append(' ').append(' ');
8089 }
8090 return spaces.toString();
8091 }
8092
8093 /**
8094 * <p>Return the offset of the widget's text baseline from the widget's top
8095 * boundary. If this widget does not support baseline alignment, this
8096 * method returns -1. </p>
8097 *
8098 * @return the offset of the baseline within the widget's bounds or -1
8099 * if baseline alignment is not supported
8100 */
8101 @ViewDebug.ExportedProperty
8102 public int getBaseline() {
8103 return -1;
8104 }
8105
8106 /**
8107 * Call this when something has changed which has invalidated the
8108 * layout of this view. This will schedule a layout pass of the view
8109 * tree.
8110 */
8111 public void requestLayout() {
8112 if (ViewDebug.TRACE_HIERARCHY) {
8113 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
8114 }
8115
8116 mPrivateFlags |= FORCE_LAYOUT;
8117
8118 if (mParent != null && !mParent.isLayoutRequested()) {
8119 mParent.requestLayout();
8120 }
8121 }
8122
8123 /**
8124 * Forces this view to be laid out during the next layout pass.
8125 * This method does not call requestLayout() or forceLayout()
8126 * on the parent.
8127 */
8128 public void forceLayout() {
8129 mPrivateFlags |= FORCE_LAYOUT;
8130 }
8131
8132 /**
8133 * <p>
8134 * This is called to find out how big a view should be. The parent
8135 * supplies constraint information in the width and height parameters.
8136 * </p>
8137 *
8138 * <p>
8139 * The actual mesurement work of a view is performed in
8140 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
8141 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
8142 * </p>
8143 *
8144 *
8145 * @param widthMeasureSpec Horizontal space requirements as imposed by the
8146 * parent
8147 * @param heightMeasureSpec Vertical space requirements as imposed by the
8148 * parent
8149 *
8150 * @see #onMeasure(int, int)
8151 */
8152 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
8153 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
8154 widthMeasureSpec != mOldWidthMeasureSpec ||
8155 heightMeasureSpec != mOldHeightMeasureSpec) {
8156
8157 // first clears the measured dimension flag
8158 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
8159
8160 if (ViewDebug.TRACE_HIERARCHY) {
8161 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
8162 }
8163
8164 // measure ourselves, this should set the measured dimension flag back
8165 onMeasure(widthMeasureSpec, heightMeasureSpec);
8166
8167 // flag not set, setMeasuredDimension() was not invoked, we raise
8168 // an exception to warn the developer
8169 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
8170 throw new IllegalStateException("onMeasure() did not set the"
8171 + " measured dimension by calling"
8172 + " setMeasuredDimension()");
8173 }
8174
8175 mPrivateFlags |= LAYOUT_REQUIRED;
8176 }
8177
8178 mOldWidthMeasureSpec = widthMeasureSpec;
8179 mOldHeightMeasureSpec = heightMeasureSpec;
8180 }
8181
8182 /**
8183 * <p>
8184 * Measure the view and its content to determine the measured width and the
8185 * measured height. This method is invoked by {@link #measure(int, int)} and
8186 * should be overriden by subclasses to provide accurate and efficient
8187 * measurement of their contents.
8188 * </p>
8189 *
8190 * <p>
8191 * <strong>CONTRACT:</strong> When overriding this method, you
8192 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
8193 * measured width and height of this view. Failure to do so will trigger an
8194 * <code>IllegalStateException</code>, thrown by
8195 * {@link #measure(int, int)}. Calling the superclass'
8196 * {@link #onMeasure(int, int)} is a valid use.
8197 * </p>
8198 *
8199 * <p>
8200 * The base class implementation of measure defaults to the background size,
8201 * unless a larger size is allowed by the MeasureSpec. Subclasses should
8202 * override {@link #onMeasure(int, int)} to provide better measurements of
8203 * their content.
8204 * </p>
8205 *
8206 * <p>
8207 * If this method is overridden, it is the subclass's responsibility to make
8208 * sure the measured height and width are at least the view's minimum height
8209 * and width ({@link #getSuggestedMinimumHeight()} and
8210 * {@link #getSuggestedMinimumWidth()}).
8211 * </p>
8212 *
8213 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
8214 * The requirements are encoded with
8215 * {@link android.view.View.MeasureSpec}.
8216 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
8217 * The requirements are encoded with
8218 * {@link android.view.View.MeasureSpec}.
8219 *
8220 * @see #getMeasuredWidth()
8221 * @see #getMeasuredHeight()
8222 * @see #setMeasuredDimension(int, int)
8223 * @see #getSuggestedMinimumHeight()
8224 * @see #getSuggestedMinimumWidth()
8225 * @see android.view.View.MeasureSpec#getMode(int)
8226 * @see android.view.View.MeasureSpec#getSize(int)
8227 */
8228 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
8229 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
8230 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
8231 }
8232
8233 /**
8234 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
8235 * measured width and measured height. Failing to do so will trigger an
8236 * exception at measurement time.</p>
8237 *
8238 * @param measuredWidth the measured width of this view
8239 * @param measuredHeight the measured height of this view
8240 */
8241 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
8242 mMeasuredWidth = measuredWidth;
8243 mMeasuredHeight = measuredHeight;
8244
8245 mPrivateFlags |= MEASURED_DIMENSION_SET;
8246 }
8247
8248 /**
8249 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
8250 * Will take the desired size, unless a different size is imposed by the constraints.
8251 *
8252 * @param size How big the view wants to be
8253 * @param measureSpec Constraints imposed by the parent
8254 * @return The size this view should be.
8255 */
8256 public static int resolveSize(int size, int measureSpec) {
8257 int result = size;
8258 int specMode = MeasureSpec.getMode(measureSpec);
8259 int specSize = MeasureSpec.getSize(measureSpec);
8260 switch (specMode) {
8261 case MeasureSpec.UNSPECIFIED:
8262 result = size;
8263 break;
8264 case MeasureSpec.AT_MOST:
8265 result = Math.min(size, specSize);
8266 break;
8267 case MeasureSpec.EXACTLY:
8268 result = specSize;
8269 break;
8270 }
8271 return result;
8272 }
8273
8274 /**
8275 * Utility to return a default size. Uses the supplied size if the
8276 * MeasureSpec imposed no contraints. Will get larger if allowed
8277 * by the MeasureSpec.
8278 *
8279 * @param size Default size for this view
8280 * @param measureSpec Constraints imposed by the parent
8281 * @return The size this view should be.
8282 */
8283 public static int getDefaultSize(int size, int measureSpec) {
8284 int result = size;
8285 int specMode = MeasureSpec.getMode(measureSpec);
8286 int specSize = MeasureSpec.getSize(measureSpec);
8287
8288 switch (specMode) {
8289 case MeasureSpec.UNSPECIFIED:
8290 result = size;
8291 break;
8292 case MeasureSpec.AT_MOST:
8293 case MeasureSpec.EXACTLY:
8294 result = specSize;
8295 break;
8296 }
8297 return result;
8298 }
8299
8300 /**
8301 * Returns the suggested minimum height that the view should use. This
8302 * returns the maximum of the view's minimum height
8303 * and the background's minimum height
8304 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
8305 * <p>
8306 * When being used in {@link #onMeasure(int, int)}, the caller should still
8307 * ensure the returned height is within the requirements of the parent.
8308 *
8309 * @return The suggested minimum height of the view.
8310 */
8311 protected int getSuggestedMinimumHeight() {
8312 int suggestedMinHeight = mMinHeight;
8313
8314 if (mBGDrawable != null) {
8315 final int bgMinHeight = mBGDrawable.getMinimumHeight();
8316 if (suggestedMinHeight < bgMinHeight) {
8317 suggestedMinHeight = bgMinHeight;
8318 }
8319 }
8320
8321 return suggestedMinHeight;
8322 }
8323
8324 /**
8325 * Returns the suggested minimum width that the view should use. This
8326 * returns the maximum of the view's minimum width)
8327 * and the background's minimum width
8328 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
8329 * <p>
8330 * When being used in {@link #onMeasure(int, int)}, the caller should still
8331 * ensure the returned width is within the requirements of the parent.
8332 *
8333 * @return The suggested minimum width of the view.
8334 */
8335 protected int getSuggestedMinimumWidth() {
8336 int suggestedMinWidth = mMinWidth;
8337
8338 if (mBGDrawable != null) {
8339 final int bgMinWidth = mBGDrawable.getMinimumWidth();
8340 if (suggestedMinWidth < bgMinWidth) {
8341 suggestedMinWidth = bgMinWidth;
8342 }
8343 }
8344
8345 return suggestedMinWidth;
8346 }
8347
8348 /**
8349 * Sets the minimum height of the view. It is not guaranteed the view will
8350 * be able to achieve this minimum height (for example, if its parent layout
8351 * constrains it with less available height).
8352 *
8353 * @param minHeight The minimum height the view will try to be.
8354 */
8355 public void setMinimumHeight(int minHeight) {
8356 mMinHeight = minHeight;
8357 }
8358
8359 /**
8360 * Sets the minimum width of the view. It is not guaranteed the view will
8361 * be able to achieve this minimum width (for example, if its parent layout
8362 * constrains it with less available width).
8363 *
8364 * @param minWidth The minimum width the view will try to be.
8365 */
8366 public void setMinimumWidth(int minWidth) {
8367 mMinWidth = minWidth;
8368 }
8369
8370 /**
8371 * Get the animation currently associated with this view.
8372 *
8373 * @return The animation that is currently playing or
8374 * scheduled to play for this view.
8375 */
8376 public Animation getAnimation() {
8377 return mCurrentAnimation;
8378 }
8379
8380 /**
8381 * Start the specified animation now.
8382 *
8383 * @param animation the animation to start now
8384 */
8385 public void startAnimation(Animation animation) {
8386 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
8387 setAnimation(animation);
8388 invalidate();
8389 }
8390
8391 /**
8392 * Cancels any animations for this view.
8393 */
8394 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08008395 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08008396 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08008397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008398 mCurrentAnimation = null;
8399 }
8400
8401 /**
8402 * Sets the next animation to play for this view.
8403 * If you want the animation to play immediately, use
8404 * startAnimation. This method provides allows fine-grained
8405 * control over the start time and invalidation, but you
8406 * must make sure that 1) the animation has a start time set, and
8407 * 2) the view will be invalidated when the animation is supposed to
8408 * start.
8409 *
8410 * @param animation The next animation, or null.
8411 */
8412 public void setAnimation(Animation animation) {
8413 mCurrentAnimation = animation;
8414 if (animation != null) {
8415 animation.reset();
8416 }
8417 }
8418
8419 /**
8420 * Invoked by a parent ViewGroup to notify the start of the animation
8421 * currently associated with this view. If you override this method,
8422 * always call super.onAnimationStart();
8423 *
8424 * @see #setAnimation(android.view.animation.Animation)
8425 * @see #getAnimation()
8426 */
8427 protected void onAnimationStart() {
8428 mPrivateFlags |= ANIMATION_STARTED;
8429 }
8430
8431 /**
8432 * Invoked by a parent ViewGroup to notify the end of the animation
8433 * currently associated with this view. If you override this method,
8434 * always call super.onAnimationEnd();
8435 *
8436 * @see #setAnimation(android.view.animation.Animation)
8437 * @see #getAnimation()
8438 */
8439 protected void onAnimationEnd() {
8440 mPrivateFlags &= ~ANIMATION_STARTED;
8441 }
8442
8443 /**
8444 * Invoked if there is a Transform that involves alpha. Subclass that can
8445 * draw themselves with the specified alpha should return true, and then
8446 * respect that alpha when their onDraw() is called. If this returns false
8447 * then the view may be redirected to draw into an offscreen buffer to
8448 * fulfill the request, which will look fine, but may be slower than if the
8449 * subclass handles it internally. The default implementation returns false.
8450 *
8451 * @param alpha The alpha (0..255) to apply to the view's drawing
8452 * @return true if the view can draw with the specified alpha.
8453 */
8454 protected boolean onSetAlpha(int alpha) {
8455 return false;
8456 }
8457
8458 /**
8459 * This is used by the RootView to perform an optimization when
8460 * the view hierarchy contains one or several SurfaceView.
8461 * SurfaceView is always considered transparent, but its children are not,
8462 * therefore all View objects remove themselves from the global transparent
8463 * region (passed as a parameter to this function).
8464 *
8465 * @param region The transparent region for this ViewRoot (window).
8466 *
8467 * @return Returns true if the effective visibility of the view at this
8468 * point is opaque, regardless of the transparent region; returns false
8469 * if it is possible for underlying windows to be seen behind the view.
8470 *
8471 * {@hide}
8472 */
8473 public boolean gatherTransparentRegion(Region region) {
8474 final AttachInfo attachInfo = mAttachInfo;
8475 if (region != null && attachInfo != null) {
8476 final int pflags = mPrivateFlags;
8477 if ((pflags & SKIP_DRAW) == 0) {
8478 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
8479 // remove it from the transparent region.
8480 final int[] location = attachInfo.mTransparentLocation;
8481 getLocationInWindow(location);
8482 region.op(location[0], location[1], location[0] + mRight - mLeft,
8483 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
8484 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
8485 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
8486 // exists, so we remove the background drawable's non-transparent
8487 // parts from this transparent region.
8488 applyDrawableToTransparentRegion(mBGDrawable, region);
8489 }
8490 }
8491 return true;
8492 }
8493
8494 /**
8495 * Play a sound effect for this view.
8496 *
8497 * <p>The framework will play sound effects for some built in actions, such as
8498 * clicking, but you may wish to play these effects in your widget,
8499 * for instance, for internal navigation.
8500 *
8501 * <p>The sound effect will only be played if sound effects are enabled by the user, and
8502 * {@link #isSoundEffectsEnabled()} is true.
8503 *
8504 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
8505 */
8506 public void playSoundEffect(int soundConstant) {
8507 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
8508 return;
8509 }
8510 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
8511 }
8512
8513 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008514 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07008515 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008516 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 *
8518 * <p>The framework will provide haptic feedback for some built in actions,
8519 * such as long presses, but you may wish to provide feedback for your
8520 * own widget.
8521 *
8522 * <p>The feedback will only be performed if
8523 * {@link #isHapticFeedbackEnabled()} is true.
8524 *
8525 * @param feedbackConstant One of the constants defined in
8526 * {@link HapticFeedbackConstants}
8527 */
8528 public boolean performHapticFeedback(int feedbackConstant) {
8529 return performHapticFeedback(feedbackConstant, 0);
8530 }
8531
8532 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008533 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07008534 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008535 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008536 *
8537 * @param feedbackConstant One of the constants defined in
8538 * {@link HapticFeedbackConstants}
8539 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
8540 */
8541 public boolean performHapticFeedback(int feedbackConstant, int flags) {
8542 if (mAttachInfo == null) {
8543 return false;
8544 }
8545 if ((flags&HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
8546 && !isHapticFeedbackEnabled()) {
8547 return false;
8548 }
8549 return mAttachInfo.mRootCallbacks.performHapticFeedback(
8550 feedbackConstant,
8551 (flags&HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
8552 }
8553
8554 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -07008555 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
8556 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -07008557 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -07008558 */
8559 public void onCloseSystemDialogs(String reason) {
8560 }
8561
8562 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 * Given a Drawable whose bounds have been set to draw into this view,
8564 * update a Region being computed for {@link #gatherTransparentRegion} so
8565 * that any non-transparent parts of the Drawable are removed from the
8566 * given transparent region.
8567 *
8568 * @param dr The Drawable whose transparency is to be applied to the region.
8569 * @param region A Region holding the current transparency information,
8570 * where any parts of the region that are set are considered to be
8571 * transparent. On return, this region will be modified to have the
8572 * transparency information reduced by the corresponding parts of the
8573 * Drawable that are not transparent.
8574 * {@hide}
8575 */
8576 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
8577 if (DBG) {
8578 Log.i("View", "Getting transparent region for: " + this);
8579 }
8580 final Region r = dr.getTransparentRegion();
8581 final Rect db = dr.getBounds();
8582 final AttachInfo attachInfo = mAttachInfo;
8583 if (r != null && attachInfo != null) {
8584 final int w = getRight()-getLeft();
8585 final int h = getBottom()-getTop();
8586 if (db.left > 0) {
8587 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
8588 r.op(0, 0, db.left, h, Region.Op.UNION);
8589 }
8590 if (db.right < w) {
8591 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
8592 r.op(db.right, 0, w, h, Region.Op.UNION);
8593 }
8594 if (db.top > 0) {
8595 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
8596 r.op(0, 0, w, db.top, Region.Op.UNION);
8597 }
8598 if (db.bottom < h) {
8599 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
8600 r.op(0, db.bottom, w, h, Region.Op.UNION);
8601 }
8602 final int[] location = attachInfo.mTransparentLocation;
8603 getLocationInWindow(location);
8604 r.translate(location[0], location[1]);
8605 region.op(r, Region.Op.INTERSECT);
8606 } else {
8607 region.op(db, Region.Op.DIFFERENCE);
8608 }
8609 }
8610
Adam Powelle14579b2009-12-16 18:39:52 -08008611 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 mHasPerformedLongPress = false;
8613
8614 if (mPendingCheckForLongPress == null) {
8615 mPendingCheckForLongPress = new CheckForLongPress();
8616 }
8617 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -08008618 postDelayed(mPendingCheckForLongPress,
8619 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008620 }
8621
8622 private static int[] stateSetUnion(final int[] stateSet1,
8623 final int[] stateSet2) {
8624 final int stateSet1Length = stateSet1.length;
8625 final int stateSet2Length = stateSet2.length;
8626 final int[] newSet = new int[stateSet1Length + stateSet2Length];
8627 int k = 0;
8628 int i = 0;
8629 int j = 0;
8630 // This is a merge of the two input state sets and assumes that the
8631 // input sets are sorted by the order imposed by ViewDrawableStates.
8632 for (int viewState : R.styleable.ViewDrawableStates) {
8633 if (i < stateSet1Length && stateSet1[i] == viewState) {
8634 newSet[k++] = viewState;
8635 i++;
8636 } else if (j < stateSet2Length && stateSet2[j] == viewState) {
8637 newSet[k++] = viewState;
8638 j++;
8639 }
8640 if (k > 1) {
8641 assert(newSet[k - 1] > newSet[k - 2]);
8642 }
8643 }
8644 return newSet;
8645 }
8646
8647 /**
8648 * Inflate a view from an XML resource. This convenience method wraps the {@link
8649 * LayoutInflater} class, which provides a full range of options for view inflation.
8650 *
8651 * @param context The Context object for your activity or application.
8652 * @param resource The resource ID to inflate
8653 * @param root A view group that will be the parent. Used to properly inflate the
8654 * layout_* parameters.
8655 * @see LayoutInflater
8656 */
8657 public static View inflate(Context context, int resource, ViewGroup root) {
8658 LayoutInflater factory = LayoutInflater.from(context);
8659 return factory.inflate(resource, root);
8660 }
Adam Powell0b8bb422010-02-08 14:30:45 -08008661
8662 /**
8663 * Scroll the view with standard behavior for scrolling beyond the normal
8664 * content boundaries. Views that call this method should override
Adam Powell4886d402010-02-12 11:32:47 -08008665 * {@link #onOverscrolled(int, int, boolean, boolean)} to respond to the
8666 * results of an overscroll operation.
Adam Powell0b8bb422010-02-08 14:30:45 -08008667 *
8668 * Views can use this method to handle any touch or fling-based scrolling.
8669 *
8670 * @param deltaX Change in X in pixels
8671 * @param deltaY Change in Y in pixels
8672 * @param scrollX Current X scroll value in pixels before applying deltaX
8673 * @param scrollY Current Y scroll value in pixels before applying deltaY
8674 * @param scrollRangeX Maximum content scroll range along the X axis
8675 * @param scrollRangeY Maximum content scroll range along the Y axis
8676 * @param maxOverscrollX Number of pixels to overscroll by in either direction
8677 * along the X axis.
8678 * @param maxOverscrollY Number of pixels to overscroll by in either direction
8679 * along the Y axis.
8680 * @return true if scrolling was clamped to an overscroll boundary along either
8681 * axis, false otherwise.
8682 */
8683 protected boolean overscrollBy(int deltaX, int deltaY,
8684 int scrollX, int scrollY,
8685 int scrollRangeX, int scrollRangeY,
8686 int maxOverscrollX, int maxOverscrollY) {
Adam Powellc9fbaab2010-02-16 17:16:19 -08008687 final int overscrollMode = mOverscrollMode;
8688 final boolean canScrollHorizontal =
8689 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
8690 final boolean canScrollVertical =
8691 computeVerticalScrollRange() > computeVerticalScrollExtent();
8692 final boolean overscrollHorizontal = overscrollMode == OVERSCROLL_ALWAYS ||
8693 (overscrollMode == OVERSCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
8694 final boolean overscrollVertical = overscrollMode == OVERSCROLL_ALWAYS ||
8695 (overscrollMode == OVERSCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
Adam Powell0b8bb422010-02-08 14:30:45 -08008696
Adam Powellc9fbaab2010-02-16 17:16:19 -08008697 int newScrollX = scrollX + deltaX;
8698 if (overscrollHorizontal) {
8699 // Scale the scroll amount if we're in the dropoff zone
8700 final int dropoffX = maxOverscrollX / 2;
8701 final int dropoffLeft = -dropoffX;
8702 final int dropoffRight = dropoffX + scrollRangeX;
8703 if ((scrollX < dropoffLeft && deltaX < 0) ||
8704 (scrollX > dropoffRight && deltaX > 0)) {
8705 newScrollX = scrollX + deltaX / 2;
8706 } else {
8707 if (newScrollX > dropoffRight && deltaX > 0) {
8708 int extra = newScrollX - dropoffRight;
8709 newScrollX = dropoffRight + extra / 2;
8710 } else if (newScrollX < dropoffLeft && deltaX < 0) {
8711 int extra = newScrollX - dropoffLeft;
8712 newScrollX = dropoffLeft + extra / 2;
8713 }
Adam Powell0b8bb422010-02-08 14:30:45 -08008714 }
Adam Powellc9fbaab2010-02-16 17:16:19 -08008715 } else {
8716 maxOverscrollX = 0;
Adam Powell0b8bb422010-02-08 14:30:45 -08008717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718
Adam Powellc9fbaab2010-02-16 17:16:19 -08008719 int newScrollY = scrollY + deltaY;
8720 if (overscrollVertical) {
8721 final int dropoffY = maxOverscrollY / 2;
8722 final int dropoffTop = -dropoffY;
8723 final int dropoffBottom = dropoffY + scrollRangeY;
8724 if ((scrollY < dropoffTop && deltaY < 0) ||
8725 (scrollY > dropoffBottom && deltaY > 0)) {
8726 newScrollY = scrollY + deltaY / 2;
8727 } else {
8728 if (newScrollY > dropoffBottom && deltaY > 0) {
8729 int extra = newScrollY - dropoffBottom;
8730 newScrollY = dropoffBottom + extra / 2;
8731 } else if (newScrollY < dropoffTop && deltaY < 0) {
8732 int extra = newScrollY - dropoffTop;
8733 newScrollY = dropoffTop + extra / 2;
8734 }
8735 }
8736 } else {
8737 maxOverscrollY = 0;
8738 }
8739
Adam Powell0b8bb422010-02-08 14:30:45 -08008740 // Clamp values if at the limits and record
8741 final int left = -maxOverscrollX;
8742 final int right = maxOverscrollX + scrollRangeX;
8743 final int top = -maxOverscrollY;
8744 final int bottom = maxOverscrollY + scrollRangeY;
8745
8746 boolean clampedX = false;
8747 if (newScrollX > right) {
8748 newScrollX = right;
8749 clampedX = true;
8750 } else if (newScrollX < left) {
8751 newScrollX = left;
8752 clampedX = true;
8753 }
8754
8755 boolean clampedY = false;
8756 if (newScrollY > bottom) {
8757 newScrollY = bottom;
8758 clampedY = true;
8759 } else if (newScrollY < top) {
8760 newScrollY = top;
8761 clampedY = true;
8762 }
8763
8764 // Bump the device with some haptic feedback if we're at the edge
8765 // and didn't start there.
Adam Powellc9fbaab2010-02-16 17:16:19 -08008766 if ((overscrollHorizontal && clampedX && scrollX != left && scrollX != right) ||
8767 (overscrollVertical && clampedY && scrollY != top && scrollY != bottom)) {
Adam Powell0b8bb422010-02-08 14:30:45 -08008768 performHapticFeedback(HapticFeedbackConstants.SCROLL_BARRIER);
8769 }
8770
8771 onOverscrolled(newScrollX, newScrollY, clampedX, clampedY);
8772
8773 return clampedX || clampedY;
8774 }
8775
8776 /**
8777 * Called by {@link #overscrollBy(int, int, int, int, int, int, int, int)} to
8778 * respond to the results of an overscroll operation.
8779 *
8780 * @param scrollX New X scroll value in pixels
8781 * @param scrollY New Y scroll value in pixels
8782 * @param clampedX True if scrollX was clamped to an overscroll boundary
8783 * @param clampedY True if scrollY was clamped to an overscroll boundary
8784 */
8785 protected void onOverscrolled(int scrollX, int scrollY,
8786 boolean clampedX, boolean clampedY) {
8787 // Intentionally empty.
8788 }
Adam Powell51c5a0c2010-03-05 10:50:38 -08008789
8790 /**
8791 * Returns the overscroll mode for this view. The result will be
8792 * one of {@link #OVERSCROLL_ALWAYS} (default), {@link #OVERSCROLL_IF_CONTENT_SCROLLS}
8793 * (allow overscrolling only if the view content is larger than the container),
8794 * or {@link #OVERSCROLL_NEVER}.
8795 *
8796 * @return This view's overscroll mode.
8797 */
8798 public int getOverscrollMode() {
8799 return mOverscrollMode;
8800 }
8801
8802 /**
8803 * Set the overscroll mode for this view. Valid overscroll modes are
8804 * {@link #OVERSCROLL_ALWAYS} (default), {@link #OVERSCROLL_IF_CONTENT_SCROLLS}
8805 * (allow overscrolling only if the view content is larger than the container),
8806 * or {@link #OVERSCROLL_NEVER}.
8807 *
8808 * Setting the overscroll mode of a view will have an effect only if the
8809 * view is capable of scrolling.
8810 *
8811 * @param overscrollMode The new overscroll mode for this view.
8812 */
8813 public void setOverscrollMode(int overscrollMode) {
8814 if (overscrollMode != OVERSCROLL_ALWAYS &&
8815 overscrollMode != OVERSCROLL_IF_CONTENT_SCROLLS &&
8816 overscrollMode != OVERSCROLL_NEVER) {
8817 throw new IllegalArgumentException("Invalid overscroll mode " + overscrollMode);
8818 }
8819 mOverscrollMode = overscrollMode;
8820 }
Romain Guya440b002010-02-24 15:57:54 -08008821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008822 /**
8823 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
8824 * Each MeasureSpec represents a requirement for either the width or the height.
8825 * A MeasureSpec is comprised of a size and a mode. There are three possible
8826 * modes:
8827 * <dl>
8828 * <dt>UNSPECIFIED</dt>
8829 * <dd>
8830 * The parent has not imposed any constraint on the child. It can be whatever size
8831 * it wants.
8832 * </dd>
8833 *
8834 * <dt>EXACTLY</dt>
8835 * <dd>
8836 * The parent has determined an exact size for the child. The child is going to be
8837 * given those bounds regardless of how big it wants to be.
8838 * </dd>
8839 *
8840 * <dt>AT_MOST</dt>
8841 * <dd>
8842 * The child can be as large as it wants up to the specified size.
8843 * </dd>
8844 * </dl>
8845 *
8846 * MeasureSpecs are implemented as ints to reduce object allocation. This class
8847 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
8848 */
8849 public static class MeasureSpec {
8850 private static final int MODE_SHIFT = 30;
8851 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
8852
8853 /**
8854 * Measure specification mode: The parent has not imposed any constraint
8855 * on the child. It can be whatever size it wants.
8856 */
8857 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
8858
8859 /**
8860 * Measure specification mode: The parent has determined an exact size
8861 * for the child. The child is going to be given those bounds regardless
8862 * of how big it wants to be.
8863 */
8864 public static final int EXACTLY = 1 << MODE_SHIFT;
8865
8866 /**
8867 * Measure specification mode: The child can be as large as it wants up
8868 * to the specified size.
8869 */
8870 public static final int AT_MOST = 2 << MODE_SHIFT;
8871
8872 /**
8873 * Creates a measure specification based on the supplied size and mode.
8874 *
8875 * The mode must always be one of the following:
8876 * <ul>
8877 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
8878 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
8879 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
8880 * </ul>
8881 *
8882 * @param size the size of the measure specification
8883 * @param mode the mode of the measure specification
8884 * @return the measure specification based on size and mode
8885 */
8886 public static int makeMeasureSpec(int size, int mode) {
8887 return size + mode;
8888 }
8889
8890 /**
8891 * Extracts the mode from the supplied measure specification.
8892 *
8893 * @param measureSpec the measure specification to extract the mode from
8894 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
8895 * {@link android.view.View.MeasureSpec#AT_MOST} or
8896 * {@link android.view.View.MeasureSpec#EXACTLY}
8897 */
8898 public static int getMode(int measureSpec) {
8899 return (measureSpec & MODE_MASK);
8900 }
8901
8902 /**
8903 * Extracts the size from the supplied measure specification.
8904 *
8905 * @param measureSpec the measure specification to extract the size from
8906 * @return the size in pixels defined in the supplied measure specification
8907 */
8908 public static int getSize(int measureSpec) {
8909 return (measureSpec & ~MODE_MASK);
8910 }
8911
8912 /**
8913 * Returns a String representation of the specified measure
8914 * specification.
8915 *
8916 * @param measureSpec the measure specification to convert to a String
8917 * @return a String with the following format: "MeasureSpec: MODE SIZE"
8918 */
8919 public static String toString(int measureSpec) {
8920 int mode = getMode(measureSpec);
8921 int size = getSize(measureSpec);
8922
8923 StringBuilder sb = new StringBuilder("MeasureSpec: ");
8924
8925 if (mode == UNSPECIFIED)
8926 sb.append("UNSPECIFIED ");
8927 else if (mode == EXACTLY)
8928 sb.append("EXACTLY ");
8929 else if (mode == AT_MOST)
8930 sb.append("AT_MOST ");
8931 else
8932 sb.append(mode).append(" ");
8933
8934 sb.append(size);
8935 return sb.toString();
8936 }
8937 }
8938
8939 class CheckForLongPress implements Runnable {
8940
8941 private int mOriginalWindowAttachCount;
8942
8943 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -07008944 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 && mOriginalWindowAttachCount == mWindowAttachCount) {
8946 if (performLongClick()) {
8947 mHasPerformedLongPress = true;
8948 }
8949 }
8950 }
8951
8952 public void rememberWindowAttachCount() {
8953 mOriginalWindowAttachCount = mWindowAttachCount;
8954 }
8955 }
Adam Powelle14579b2009-12-16 18:39:52 -08008956
8957 private final class CheckForTap implements Runnable {
8958 public void run() {
8959 mPrivateFlags &= ~PREPRESSED;
8960 mPrivateFlags |= PRESSED;
8961 refreshDrawableState();
8962 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
8963 postCheckForLongClick(ViewConfiguration.getTapTimeout());
8964 }
8965 }
8966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008967
8968 /**
8969 * Interface definition for a callback to be invoked when a key event is
8970 * dispatched to this view. The callback will be invoked before the key
8971 * event is given to the view.
8972 */
8973 public interface OnKeyListener {
8974 /**
8975 * Called when a key is dispatched to a view. This allows listeners to
8976 * get a chance to respond before the target view.
8977 *
8978 * @param v The view the key has been dispatched to.
8979 * @param keyCode The code for the physical key that was pressed
8980 * @param event The KeyEvent object containing full information about
8981 * the event.
8982 * @return True if the listener has consumed the event, false otherwise.
8983 */
8984 boolean onKey(View v, int keyCode, KeyEvent event);
8985 }
8986
8987 /**
8988 * Interface definition for a callback to be invoked when a touch event is
8989 * dispatched to this view. The callback will be invoked before the touch
8990 * event is given to the view.
8991 */
8992 public interface OnTouchListener {
8993 /**
8994 * Called when a touch event is dispatched to a view. This allows listeners to
8995 * get a chance to respond before the target view.
8996 *
8997 * @param v The view the touch event has been dispatched to.
8998 * @param event The MotionEvent object containing full information about
8999 * the event.
9000 * @return True if the listener has consumed the event, false otherwise.
9001 */
9002 boolean onTouch(View v, MotionEvent event);
9003 }
9004
9005 /**
9006 * Interface definition for a callback to be invoked when a view has been clicked and held.
9007 */
9008 public interface OnLongClickListener {
9009 /**
9010 * Called when a view has been clicked and held.
9011 *
9012 * @param v The view that was clicked and held.
9013 *
9014 * return True if the callback consumed the long click, false otherwise
9015 */
9016 boolean onLongClick(View v);
9017 }
9018
9019 /**
9020 * Interface definition for a callback to be invoked when the focus state of
9021 * a view changed.
9022 */
9023 public interface OnFocusChangeListener {
9024 /**
9025 * Called when the focus state of a view has changed.
9026 *
9027 * @param v The view whose state has changed.
9028 * @param hasFocus The new focus state of v.
9029 */
9030 void onFocusChange(View v, boolean hasFocus);
9031 }
9032
9033 /**
9034 * Interface definition for a callback to be invoked when a view is clicked.
9035 */
9036 public interface OnClickListener {
9037 /**
9038 * Called when a view has been clicked.
9039 *
9040 * @param v The view that was clicked.
9041 */
9042 void onClick(View v);
9043 }
9044
9045 /**
9046 * Interface definition for a callback to be invoked when the context menu
9047 * for this view is being built.
9048 */
9049 public interface OnCreateContextMenuListener {
9050 /**
9051 * Called when the context menu for this view is being built. It is not
9052 * safe to hold onto the menu after this method returns.
9053 *
9054 * @param menu The context menu that is being built
9055 * @param v The view for which the context menu is being built
9056 * @param menuInfo Extra information about the item for which the
9057 * context menu should be shown. This information will vary
9058 * depending on the class of v.
9059 */
9060 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
9061 }
9062
9063 private final class UnsetPressedState implements Runnable {
9064 public void run() {
9065 setPressed(false);
9066 }
9067 }
9068
9069 /**
9070 * Base class for derived classes that want to save and restore their own
9071 * state in {@link android.view.View#onSaveInstanceState()}.
9072 */
9073 public static class BaseSavedState extends AbsSavedState {
9074 /**
9075 * Constructor used when reading from a parcel. Reads the state of the superclass.
9076 *
9077 * @param source
9078 */
9079 public BaseSavedState(Parcel source) {
9080 super(source);
9081 }
9082
9083 /**
9084 * Constructor called by derived classes when creating their SavedState objects
9085 *
9086 * @param superState The state of the superclass of this view
9087 */
9088 public BaseSavedState(Parcelable superState) {
9089 super(superState);
9090 }
9091
9092 public static final Parcelable.Creator<BaseSavedState> CREATOR =
9093 new Parcelable.Creator<BaseSavedState>() {
9094 public BaseSavedState createFromParcel(Parcel in) {
9095 return new BaseSavedState(in);
9096 }
9097
9098 public BaseSavedState[] newArray(int size) {
9099 return new BaseSavedState[size];
9100 }
9101 };
9102 }
9103
9104 /**
9105 * A set of information given to a view when it is attached to its parent
9106 * window.
9107 */
9108 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 interface Callbacks {
9110 void playSoundEffect(int effectId);
9111 boolean performHapticFeedback(int effectId, boolean always);
9112 }
9113
9114 /**
9115 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
9116 * to a Handler. This class contains the target (View) to invalidate and
9117 * the coordinates of the dirty rectangle.
9118 *
9119 * For performance purposes, this class also implements a pool of up to
9120 * POOL_LIMIT objects that get reused. This reduces memory allocations
9121 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009122 */
Romain Guyd928d682009-03-31 17:52:16 -07009123 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009124 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -07009125 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
9126 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -07009127 public InvalidateInfo newInstance() {
9128 return new InvalidateInfo();
9129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009130
Romain Guyd928d682009-03-31 17:52:16 -07009131 public void onAcquired(InvalidateInfo element) {
9132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009133
Romain Guyd928d682009-03-31 17:52:16 -07009134 public void onReleased(InvalidateInfo element) {
9135 }
9136 }, POOL_LIMIT)
9137 );
9138
9139 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009140
9141 View target;
9142
9143 int left;
9144 int top;
9145 int right;
9146 int bottom;
9147
Romain Guyd928d682009-03-31 17:52:16 -07009148 public void setNextPoolable(InvalidateInfo element) {
9149 mNext = element;
9150 }
9151
9152 public InvalidateInfo getNextPoolable() {
9153 return mNext;
9154 }
9155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009156 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -07009157 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009158 }
9159
9160 void release() {
Romain Guyd928d682009-03-31 17:52:16 -07009161 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009162 }
9163 }
9164
9165 final IWindowSession mSession;
9166
9167 final IWindow mWindow;
9168
9169 final IBinder mWindowToken;
9170
9171 final Callbacks mRootCallbacks;
9172
9173 /**
9174 * The top view of the hierarchy.
9175 */
9176 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -07009177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009178 IBinder mPanelParentWindowToken;
9179 Surface mSurface;
9180
9181 /**
Romain Guy8506ab42009-06-11 17:35:47 -07009182 * Scale factor used by the compatibility mode
9183 */
9184 float mApplicationScale;
9185
9186 /**
9187 * Indicates whether the application is in compatibility mode
9188 */
9189 boolean mScalingRequired;
9190
9191 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009192 * Left position of this view's window
9193 */
9194 int mWindowLeft;
9195
9196 /**
9197 * Top position of this view's window
9198 */
9199 int mWindowTop;
9200
9201 /**
Romain Guy35b38ce2009-10-07 13:38:55 -07009202 * Indicates whether the window is translucent/transparent
9203 */
9204 boolean mTranslucentWindow;
9205
9206 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009207 * For windows that are full-screen but using insets to layout inside
9208 * of the screen decorations, these are the current insets for the
9209 * content of the window.
9210 */
9211 final Rect mContentInsets = new Rect();
9212
9213 /**
9214 * For windows that are full-screen but using insets to layout inside
9215 * of the screen decorations, these are the current insets for the
9216 * actual visible parts of the window.
9217 */
9218 final Rect mVisibleInsets = new Rect();
9219
9220 /**
9221 * The internal insets given by this window. This value is
9222 * supplied by the client (through
9223 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
9224 * be given to the window manager when changed to be used in laying
9225 * out windows behind it.
9226 */
9227 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
9228 = new ViewTreeObserver.InternalInsetsInfo();
9229
9230 /**
9231 * All views in the window's hierarchy that serve as scroll containers,
9232 * used to determine if the window can be resized or must be panned
9233 * to adjust for a soft input area.
9234 */
9235 final ArrayList<View> mScrollContainers = new ArrayList<View>();
9236
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07009237 final KeyEvent.DispatcherState mKeyDispatchState
9238 = new KeyEvent.DispatcherState();
9239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009240 /**
9241 * Indicates whether the view's window currently has the focus.
9242 */
9243 boolean mHasWindowFocus;
9244
9245 /**
9246 * The current visibility of the window.
9247 */
9248 int mWindowVisibility;
9249
9250 /**
9251 * Indicates the time at which drawing started to occur.
9252 */
9253 long mDrawingTime;
9254
9255 /**
Romain Guy5bcdff42009-05-14 21:27:18 -07009256 * Indicates whether or not ignoring the DIRTY_MASK flags.
9257 */
9258 boolean mIgnoreDirtyState;
9259
9260 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009261 * Indicates whether the view's window is currently in touch mode.
9262 */
9263 boolean mInTouchMode;
9264
9265 /**
9266 * Indicates that ViewRoot should trigger a global layout change
9267 * the next time it performs a traversal
9268 */
9269 boolean mRecomputeGlobalAttributes;
9270
9271 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009272 * Set during a traveral if any views want to keep the screen on.
9273 */
9274 boolean mKeepScreenOn;
9275
9276 /**
9277 * Set if the visibility of any views has changed.
9278 */
9279 boolean mViewVisibilityChanged;
9280
9281 /**
9282 * Set to true if a view has been scrolled.
9283 */
9284 boolean mViewScrollChanged;
9285
9286 /**
9287 * Global to the view hierarchy used as a temporary for dealing with
9288 * x/y points in the transparent region computations.
9289 */
9290 final int[] mTransparentLocation = new int[2];
9291
9292 /**
9293 * Global to the view hierarchy used as a temporary for dealing with
9294 * x/y points in the ViewGroup.invalidateChild implementation.
9295 */
9296 final int[] mInvalidateChildLocation = new int[2];
9297
9298 /**
9299 * The view tree observer used to dispatch global events like
9300 * layout, pre-draw, touch mode change, etc.
9301 */
9302 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
9303
9304 /**
9305 * A Canvas used by the view hierarchy to perform bitmap caching.
9306 */
9307 Canvas mCanvas;
9308
9309 /**
9310 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
9311 * handler can be used to pump events in the UI events queue.
9312 */
9313 final Handler mHandler;
9314
9315 /**
9316 * Identifier for messages requesting the view to be invalidated.
9317 * Such messages should be sent to {@link #mHandler}.
9318 */
9319 static final int INVALIDATE_MSG = 0x1;
9320
9321 /**
9322 * Identifier for messages requesting the view to invalidate a region.
9323 * Such messages should be sent to {@link #mHandler}.
9324 */
9325 static final int INVALIDATE_RECT_MSG = 0x2;
9326
9327 /**
9328 * Temporary for use in computing invalidate rectangles while
9329 * calling up the hierarchy.
9330 */
9331 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -07009332
9333 /**
9334 * Temporary list for use in collecting focusable descendents of a view.
9335 */
9336 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
9337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009338 /**
9339 * Creates a new set of attachment information with the specified
9340 * events handler and thread.
9341 *
9342 * @param handler the events handler the view must use
9343 */
9344 AttachInfo(IWindowSession session, IWindow window,
9345 Handler handler, Callbacks effectPlayer) {
9346 mSession = session;
9347 mWindow = window;
9348 mWindowToken = window.asBinder();
9349 mHandler = handler;
9350 mRootCallbacks = effectPlayer;
9351 }
9352 }
9353
9354 /**
9355 * <p>ScrollabilityCache holds various fields used by a View when scrolling
9356 * is supported. This avoids keeping too many unused fields in most
9357 * instances of View.</p>
9358 */
Mike Cleronf116bf82009-09-27 19:14:12 -07009359 private static class ScrollabilityCache implements Runnable {
9360
9361 /**
9362 * Scrollbars are not visible
9363 */
9364 public static final int OFF = 0;
9365
9366 /**
9367 * Scrollbars are visible
9368 */
9369 public static final int ON = 1;
9370
9371 /**
9372 * Scrollbars are fading away
9373 */
9374 public static final int FADING = 2;
9375
9376 public boolean fadeScrollBars;
9377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009378 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -07009379 public int scrollBarDefaultDelayBeforeFade;
9380 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381
9382 public int scrollBarSize;
9383 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -07009384 public float[] interpolatorValues;
9385 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009386
9387 public final Paint paint;
9388 public final Matrix matrix;
9389 public Shader shader;
9390
Mike Cleronf116bf82009-09-27 19:14:12 -07009391 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
9392
9393 private final float[] mOpaque = {255.0f};
9394 private final float[] mTransparent = {0.0f};
9395
9396 /**
9397 * When fading should start. This time moves into the future every time
9398 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
9399 */
9400 public long fadeStartTime;
9401
9402
9403 /**
9404 * The current state of the scrollbars: ON, OFF, or FADING
9405 */
9406 public int state = OFF;
9407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009408 private int mLastColor;
9409
Mike Cleronf116bf82009-09-27 19:14:12 -07009410 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009411 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
9412 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -07009413 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
9414 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009415
9416 paint = new Paint();
9417 matrix = new Matrix();
9418 // use use a height of 1, and then wack the matrix each time we
9419 // actually use it.
9420 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -07009421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009422 paint.setShader(shader);
9423 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -07009424 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009425 }
Romain Guy8506ab42009-06-11 17:35:47 -07009426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009427 public void setFadeColor(int color) {
9428 if (color != 0 && color != mLastColor) {
9429 mLastColor = color;
9430 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -07009431
Romain Guye55e1a72009-08-27 10:42:26 -07009432 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
9433 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -07009434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009435 paint.setShader(shader);
9436 // Restore the default transfer mode (src_over)
9437 paint.setXfermode(null);
9438 }
9439 }
Mike Cleronf116bf82009-09-27 19:14:12 -07009440
9441 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -07009442 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -07009443 if (now >= fadeStartTime) {
9444
9445 // the animation fades the scrollbars out by changing
9446 // the opacity (alpha) from fully opaque to fully
9447 // transparent
9448 int nextFrame = (int) now;
9449 int framesCount = 0;
9450
9451 Interpolator interpolator = scrollBarInterpolator;
9452
9453 // Start opaque
9454 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
9455
9456 // End transparent
9457 nextFrame += scrollBarFadeDuration;
9458 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
9459
9460 state = FADING;
9461
9462 // Kick off the fade animation
9463 host.invalidate();
9464 }
9465 }
9466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009467 }
9468}