blob: e8bb736da6408b3ad5751e3afcd0acb2def7199d [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;
4359 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 break;
4361
4362 case MotionEvent.ACTION_CANCEL:
4363 mPrivateFlags &= ~PRESSED;
4364 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004365 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004366 break;
4367
4368 case MotionEvent.ACTION_MOVE:
4369 final int x = (int) event.getX();
4370 final int y = (int) event.getY();
4371
4372 // Be lenient about moving outside of buttons
Adam Powelle14579b2009-12-16 18:39:52 -08004373 int slop = mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 if ((x < 0 - slop) || (x >= getWidth() + slop) ||
4375 (y < 0 - slop) || (y >= getHeight() + slop)) {
4376 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004377 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004379 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004380 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004381
4382 // Need to switch from pressed to not pressed
4383 mPrivateFlags &= ~PRESSED;
4384 refreshDrawableState();
4385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 }
4387 break;
4388 }
4389 return true;
4390 }
4391
4392 return false;
4393 }
4394
4395 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004396 * Remove the longpress detection timer.
4397 */
4398 private void removeLongPressCallback() {
4399 if (mPendingCheckForLongPress != null) {
4400 removeCallbacks(mPendingCheckForLongPress);
4401 }
4402 }
Adam Powelle14579b2009-12-16 18:39:52 -08004403
4404 /**
Romain Guya440b002010-02-24 15:57:54 -08004405 * Remove the prepress detection timer.
4406 */
4407 private void removeUnsetPressCallback() {
4408 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4409 setPressed(false);
4410 removeCallbacks(mUnsetPressedState);
4411 }
4412 }
4413
4414 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004415 * Remove the tap detection timer.
4416 */
4417 private void removeTapCallback() {
4418 if (mPendingCheckForTap != null) {
4419 mPrivateFlags &= ~PREPRESSED;
4420 removeCallbacks(mPendingCheckForTap);
4421 }
4422 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004423
4424 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004425 * Cancels a pending long press. Your subclass can use this if you
4426 * want the context menu to come up if the user presses and holds
4427 * at the same place, but you don't want it to come up if they press
4428 * and then move around enough to cause scrolling.
4429 */
4430 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004431 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004432
4433 /*
4434 * The prepressed state handled by the tap callback is a display
4435 * construct, but the tap callback will post a long press callback
4436 * less its own timeout. Remove it here.
4437 */
4438 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004439 }
4440
4441 /**
4442 * Sets the TouchDelegate for this View.
4443 */
4444 public void setTouchDelegate(TouchDelegate delegate) {
4445 mTouchDelegate = delegate;
4446 }
4447
4448 /**
4449 * Gets the TouchDelegate for this View.
4450 */
4451 public TouchDelegate getTouchDelegate() {
4452 return mTouchDelegate;
4453 }
4454
4455 /**
4456 * Set flags controlling behavior of this view.
4457 *
4458 * @param flags Constant indicating the value which should be set
4459 * @param mask Constant indicating the bit range that should be changed
4460 */
4461 void setFlags(int flags, int mask) {
4462 int old = mViewFlags;
4463 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4464
4465 int changed = mViewFlags ^ old;
4466 if (changed == 0) {
4467 return;
4468 }
4469 int privateFlags = mPrivateFlags;
4470
4471 /* Check if the FOCUSABLE bit has changed */
4472 if (((changed & FOCUSABLE_MASK) != 0) &&
4473 ((privateFlags & HAS_BOUNDS) !=0)) {
4474 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4475 && ((privateFlags & FOCUSED) != 0)) {
4476 /* Give up focus if we are no longer focusable */
4477 clearFocus();
4478 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4479 && ((privateFlags & FOCUSED) == 0)) {
4480 /*
4481 * Tell the view system that we are now available to take focus
4482 * if no one else already has it.
4483 */
4484 if (mParent != null) mParent.focusableViewAvailable(this);
4485 }
4486 }
4487
4488 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4489 if ((changed & VISIBILITY_MASK) != 0) {
4490 /*
4491 * If this view is becoming visible, set the DRAWN flag so that
4492 * the next invalidate() will not be skipped.
4493 */
4494 mPrivateFlags |= DRAWN;
4495
4496 needGlobalAttributesUpdate(true);
4497
4498 // a view becoming visible is worth notifying the parent
4499 // about in case nothing has focus. even if this specific view
4500 // isn't focusable, it may contain something that is, so let
4501 // the root view try to give this focus if nothing else does.
4502 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4503 mParent.focusableViewAvailable(this);
4504 }
4505 }
4506 }
4507
4508 /* Check if the GONE bit has changed */
4509 if ((changed & GONE) != 0) {
4510 needGlobalAttributesUpdate(false);
4511 requestLayout();
4512 invalidate();
4513
Romain Guyecd80ee2009-12-03 17:13:02 -08004514 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
4515 if (hasFocus()) clearFocus();
4516 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 }
4518 if (mAttachInfo != null) {
4519 mAttachInfo.mViewVisibilityChanged = true;
4520 }
4521 }
4522
4523 /* Check if the VISIBLE bit has changed */
4524 if ((changed & INVISIBLE) != 0) {
4525 needGlobalAttributesUpdate(false);
4526 invalidate();
4527
4528 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4529 // root view becoming invisible shouldn't clear focus
4530 if (getRootView() != this) {
4531 clearFocus();
4532 }
4533 }
4534 if (mAttachInfo != null) {
4535 mAttachInfo.mViewVisibilityChanged = true;
4536 }
4537 }
4538
Adam Powell326d8082009-12-09 15:10:07 -08004539 if ((changed & VISIBILITY_MASK) != 0) {
4540 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
4541 }
4542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4544 destroyDrawingCache();
4545 }
4546
4547 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4548 destroyDrawingCache();
4549 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4550 }
4551
4552 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4553 destroyDrawingCache();
4554 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4555 }
4556
4557 if ((changed & DRAW_MASK) != 0) {
4558 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4559 if (mBGDrawable != null) {
4560 mPrivateFlags &= ~SKIP_DRAW;
4561 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4562 } else {
4563 mPrivateFlags |= SKIP_DRAW;
4564 }
4565 } else {
4566 mPrivateFlags &= ~SKIP_DRAW;
4567 }
4568 requestLayout();
4569 invalidate();
4570 }
4571
4572 if ((changed & KEEP_SCREEN_ON) != 0) {
4573 if (mParent != null) {
4574 mParent.recomputeViewAttributes(this);
4575 }
4576 }
4577 }
4578
4579 /**
4580 * Change the view's z order in the tree, so it's on top of other sibling
4581 * views
4582 */
4583 public void bringToFront() {
4584 if (mParent != null) {
4585 mParent.bringChildToFront(this);
4586 }
4587 }
4588
4589 /**
4590 * This is called in response to an internal scroll in this view (i.e., the
4591 * view scrolled its own contents). This is typically as a result of
4592 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4593 * called.
4594 *
4595 * @param l Current horizontal scroll origin.
4596 * @param t Current vertical scroll origin.
4597 * @param oldl Previous horizontal scroll origin.
4598 * @param oldt Previous vertical scroll origin.
4599 */
4600 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4601 mBackgroundSizeChanged = true;
4602
4603 final AttachInfo ai = mAttachInfo;
4604 if (ai != null) {
4605 ai.mViewScrollChanged = true;
4606 }
4607 }
4608
4609 /**
4610 * This is called during layout when the size of this view has changed. If
4611 * you were just added to the view hierarchy, you're called with the old
4612 * values of 0.
4613 *
4614 * @param w Current width of this view.
4615 * @param h Current height of this view.
4616 * @param oldw Old width of this view.
4617 * @param oldh Old height of this view.
4618 */
4619 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
4620 }
4621
4622 /**
4623 * Called by draw to draw the child views. This may be overridden
4624 * by derived classes to gain control just before its children are drawn
4625 * (but after its own view has been drawn).
4626 * @param canvas the canvas on which to draw the view
4627 */
4628 protected void dispatchDraw(Canvas canvas) {
4629 }
4630
4631 /**
4632 * Gets the parent of this view. Note that the parent is a
4633 * ViewParent and not necessarily a View.
4634 *
4635 * @return Parent of this view.
4636 */
4637 public final ViewParent getParent() {
4638 return mParent;
4639 }
4640
4641 /**
4642 * Return the scrolled left position of this view. This is the left edge of
4643 * the displayed part of your view. You do not need to draw any pixels
4644 * farther left, since those are outside of the frame of your view on
4645 * screen.
4646 *
4647 * @return The left edge of the displayed part of your view, in pixels.
4648 */
4649 public final int getScrollX() {
4650 return mScrollX;
4651 }
4652
4653 /**
4654 * Return the scrolled top position of this view. This is the top edge of
4655 * the displayed part of your view. You do not need to draw any pixels above
4656 * it, since those are outside of the frame of your view on screen.
4657 *
4658 * @return The top edge of the displayed part of your view, in pixels.
4659 */
4660 public final int getScrollY() {
4661 return mScrollY;
4662 }
4663
4664 /**
4665 * Return the width of the your view.
4666 *
4667 * @return The width of your view, in pixels.
4668 */
4669 @ViewDebug.ExportedProperty
4670 public final int getWidth() {
4671 return mRight - mLeft;
4672 }
4673
4674 /**
4675 * Return the height of your view.
4676 *
4677 * @return The height of your view, in pixels.
4678 */
4679 @ViewDebug.ExportedProperty
4680 public final int getHeight() {
4681 return mBottom - mTop;
4682 }
4683
4684 /**
4685 * Return the visible drawing bounds of your view. Fills in the output
4686 * rectangle with the values from getScrollX(), getScrollY(),
4687 * getWidth(), and getHeight().
4688 *
4689 * @param outRect The (scrolled) drawing bounds of the view.
4690 */
4691 public void getDrawingRect(Rect outRect) {
4692 outRect.left = mScrollX;
4693 outRect.top = mScrollY;
4694 outRect.right = mScrollX + (mRight - mLeft);
4695 outRect.bottom = mScrollY + (mBottom - mTop);
4696 }
4697
4698 /**
4699 * The width of this view as measured in the most recent call to measure().
4700 * This should be used during measurement and layout calculations only. Use
4701 * {@link #getWidth()} to see how wide a view is after layout.
4702 *
4703 * @return The measured width of this view.
4704 */
4705 public final int getMeasuredWidth() {
4706 return mMeasuredWidth;
4707 }
4708
4709 /**
4710 * The height of this view as measured in the most recent call to measure().
4711 * This should be used during measurement and layout calculations only. Use
4712 * {@link #getHeight()} to see how tall a view is after layout.
4713 *
4714 * @return The measured height of this view.
4715 */
4716 public final int getMeasuredHeight() {
4717 return mMeasuredHeight;
4718 }
4719
4720 /**
4721 * Top position of this view relative to its parent.
4722 *
4723 * @return The top of this view, in pixels.
4724 */
4725 @ViewDebug.CapturedViewProperty
4726 public final int getTop() {
4727 return mTop;
4728 }
4729
4730 /**
4731 * Bottom position of this view relative to its parent.
4732 *
4733 * @return The bottom of this view, in pixels.
4734 */
4735 @ViewDebug.CapturedViewProperty
4736 public final int getBottom() {
4737 return mBottom;
4738 }
4739
4740 /**
4741 * Left position of this view relative to its parent.
4742 *
4743 * @return The left edge of this view, in pixels.
4744 */
4745 @ViewDebug.CapturedViewProperty
4746 public final int getLeft() {
4747 return mLeft;
4748 }
4749
4750 /**
4751 * Right position of this view relative to its parent.
4752 *
4753 * @return The right edge of this view, in pixels.
4754 */
4755 @ViewDebug.CapturedViewProperty
4756 public final int getRight() {
4757 return mRight;
4758 }
4759
4760 /**
4761 * Hit rectangle in parent's coordinates
4762 *
4763 * @param outRect The hit rectangle of the view.
4764 */
4765 public void getHitRect(Rect outRect) {
4766 outRect.set(mLeft, mTop, mRight, mBottom);
4767 }
4768
4769 /**
4770 * When a view has focus and the user navigates away from it, the next view is searched for
4771 * starting from the rectangle filled in by this method.
4772 *
4773 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
4774 * view maintains some idea of internal selection, such as a cursor, or a selected row
4775 * or column, you should override this method and fill in a more specific rectangle.
4776 *
4777 * @param r The rectangle to fill in, in this view's coordinates.
4778 */
4779 public void getFocusedRect(Rect r) {
4780 getDrawingRect(r);
4781 }
4782
4783 /**
4784 * If some part of this view is not clipped by any of its parents, then
4785 * return that area in r in global (root) coordinates. To convert r to local
4786 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
4787 * -globalOffset.y)) If the view is completely clipped or translated out,
4788 * return false.
4789 *
4790 * @param r If true is returned, r holds the global coordinates of the
4791 * visible portion of this view.
4792 * @param globalOffset If true is returned, globalOffset holds the dx,dy
4793 * between this view and its root. globalOffet may be null.
4794 * @return true if r is non-empty (i.e. part of the view is visible at the
4795 * root level.
4796 */
4797 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
4798 int width = mRight - mLeft;
4799 int height = mBottom - mTop;
4800 if (width > 0 && height > 0) {
4801 r.set(0, 0, width, height);
4802 if (globalOffset != null) {
4803 globalOffset.set(-mScrollX, -mScrollY);
4804 }
4805 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
4806 }
4807 return false;
4808 }
4809
4810 public final boolean getGlobalVisibleRect(Rect r) {
4811 return getGlobalVisibleRect(r, null);
4812 }
4813
4814 public final boolean getLocalVisibleRect(Rect r) {
4815 Point offset = new Point();
4816 if (getGlobalVisibleRect(r, offset)) {
4817 r.offset(-offset.x, -offset.y); // make r local
4818 return true;
4819 }
4820 return false;
4821 }
4822
4823 /**
4824 * Offset this view's vertical location by the specified number of pixels.
4825 *
4826 * @param offset the number of pixels to offset the view by
4827 */
4828 public void offsetTopAndBottom(int offset) {
4829 mTop += offset;
4830 mBottom += offset;
4831 }
4832
4833 /**
4834 * Offset this view's horizontal location by the specified amount of pixels.
4835 *
4836 * @param offset the numer of pixels to offset the view by
4837 */
4838 public void offsetLeftAndRight(int offset) {
4839 mLeft += offset;
4840 mRight += offset;
4841 }
4842
4843 /**
4844 * Get the LayoutParams associated with this view. All views should have
4845 * layout parameters. These supply parameters to the <i>parent</i> of this
4846 * view specifying how it should be arranged. There are many subclasses of
4847 * ViewGroup.LayoutParams, and these correspond to the different subclasses
4848 * of ViewGroup that are responsible for arranging their children.
4849 * @return The LayoutParams associated with this view
4850 */
4851 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
4852 public ViewGroup.LayoutParams getLayoutParams() {
4853 return mLayoutParams;
4854 }
4855
4856 /**
4857 * Set the layout parameters associated with this view. These supply
4858 * parameters to the <i>parent</i> of this view specifying how it should be
4859 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
4860 * correspond to the different subclasses of ViewGroup that are responsible
4861 * for arranging their children.
4862 *
4863 * @param params the layout parameters for this view
4864 */
4865 public void setLayoutParams(ViewGroup.LayoutParams params) {
4866 if (params == null) {
4867 throw new NullPointerException("params == null");
4868 }
4869 mLayoutParams = params;
4870 requestLayout();
4871 }
4872
4873 /**
4874 * Set the scrolled position of your view. This will cause a call to
4875 * {@link #onScrollChanged(int, int, int, int)} and the view will be
4876 * invalidated.
4877 * @param x the x position to scroll to
4878 * @param y the y position to scroll to
4879 */
4880 public void scrollTo(int x, int y) {
4881 if (mScrollX != x || mScrollY != y) {
4882 int oldX = mScrollX;
4883 int oldY = mScrollY;
4884 mScrollX = x;
4885 mScrollY = y;
4886 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07004887 if (!awakenScrollBars()) {
4888 invalidate();
4889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890 }
4891 }
4892
4893 /**
4894 * Move the scrolled position of your view. This will cause a call to
4895 * {@link #onScrollChanged(int, int, int, int)} and the view will be
4896 * invalidated.
4897 * @param x the amount of pixels to scroll by horizontally
4898 * @param y the amount of pixels to scroll by vertically
4899 */
4900 public void scrollBy(int x, int y) {
4901 scrollTo(mScrollX + x, mScrollY + y);
4902 }
4903
4904 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07004905 * <p>Trigger the scrollbars to draw. When invoked this method starts an
4906 * animation to fade the scrollbars out after a default delay. If a subclass
4907 * provides animated scrolling, the start delay should equal the duration
4908 * of the scrolling animation.</p>
4909 *
4910 * <p>The animation starts only if at least one of the scrollbars is
4911 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
4912 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
4913 * this method returns true, and false otherwise. If the animation is
4914 * started, this method calls {@link #invalidate()}; in that case the
4915 * caller should not call {@link #invalidate()}.</p>
4916 *
4917 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07004918 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07004919 *
4920 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
4921 * and {@link #scrollTo(int, int)}.</p>
4922 *
4923 * @return true if the animation is played, false otherwise
4924 *
4925 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07004926 * @see #scrollBy(int, int)
4927 * @see #scrollTo(int, int)
4928 * @see #isHorizontalScrollBarEnabled()
4929 * @see #isVerticalScrollBarEnabled()
4930 * @see #setHorizontalScrollBarEnabled(boolean)
4931 * @see #setVerticalScrollBarEnabled(boolean)
4932 */
4933 protected boolean awakenScrollBars() {
4934 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07004935 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07004936 }
4937
4938 /**
4939 * <p>
4940 * Trigger the scrollbars to draw. When invoked this method starts an
4941 * animation to fade the scrollbars out after a fixed delay. If a subclass
4942 * provides animated scrolling, the start delay should equal the duration of
4943 * the scrolling animation.
4944 * </p>
4945 *
4946 * <p>
4947 * The animation starts only if at least one of the scrollbars is enabled,
4948 * as specified by {@link #isHorizontalScrollBarEnabled()} and
4949 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
4950 * this method returns true, and false otherwise. If the animation is
4951 * started, this method calls {@link #invalidate()}; in that case the caller
4952 * should not call {@link #invalidate()}.
4953 * </p>
4954 *
4955 * <p>
4956 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07004957 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07004958 * </p>
4959 *
4960 * @param startDelay the delay, in milliseconds, after which the animation
4961 * should start; when the delay is 0, the animation starts
4962 * immediately
4963 * @return true if the animation is played, false otherwise
4964 *
Mike Cleronf116bf82009-09-27 19:14:12 -07004965 * @see #scrollBy(int, int)
4966 * @see #scrollTo(int, int)
4967 * @see #isHorizontalScrollBarEnabled()
4968 * @see #isVerticalScrollBarEnabled()
4969 * @see #setHorizontalScrollBarEnabled(boolean)
4970 * @see #setVerticalScrollBarEnabled(boolean)
4971 */
4972 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07004973 return awakenScrollBars(startDelay, true);
4974 }
4975
4976 /**
4977 * <p>
4978 * Trigger the scrollbars to draw. When invoked this method starts an
4979 * animation to fade the scrollbars out after a fixed delay. If a subclass
4980 * provides animated scrolling, the start delay should equal the duration of
4981 * the scrolling animation.
4982 * </p>
4983 *
4984 * <p>
4985 * The animation starts only if at least one of the scrollbars is enabled,
4986 * as specified by {@link #isHorizontalScrollBarEnabled()} and
4987 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
4988 * this method returns true, and false otherwise. If the animation is
4989 * started, this method calls {@link #invalidate()} if the invalidate parameter
4990 * is set to true; in that case the caller
4991 * should not call {@link #invalidate()}.
4992 * </p>
4993 *
4994 * <p>
4995 * This method should be invoked everytime a subclass directly updates the
4996 * scroll parameters.
4997 * </p>
4998 *
4999 * @param startDelay the delay, in milliseconds, after which the animation
5000 * should start; when the delay is 0, the animation starts
5001 * immediately
5002 *
5003 * @param invalidate Wheter this method should call invalidate
5004 *
5005 * @return true if the animation is played, false otherwise
5006 *
5007 * @see #scrollBy(int, int)
5008 * @see #scrollTo(int, int)
5009 * @see #isHorizontalScrollBarEnabled()
5010 * @see #isVerticalScrollBarEnabled()
5011 * @see #setHorizontalScrollBarEnabled(boolean)
5012 * @see #setVerticalScrollBarEnabled(boolean)
5013 */
5014 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07005015 final ScrollabilityCache scrollCache = mScrollCache;
5016
5017 if (scrollCache == null || !scrollCache.fadeScrollBars) {
5018 return false;
5019 }
5020
5021 if (scrollCache.scrollBar == null) {
5022 scrollCache.scrollBar = new ScrollBarDrawable();
5023 }
5024
5025 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
5026
Mike Cleron290947b2009-09-29 18:34:32 -07005027 if (invalidate) {
5028 // Invalidate to show the scrollbars
5029 invalidate();
5030 }
Mike Cleronf116bf82009-09-27 19:14:12 -07005031
5032 if (scrollCache.state == ScrollabilityCache.OFF) {
5033 // FIXME: this is copied from WindowManagerService.
5034 // We should get this value from the system when it
5035 // is possible to do so.
5036 final int KEY_REPEAT_FIRST_DELAY = 750;
5037 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
5038 }
5039
5040 // Tell mScrollCache when we should start fading. This may
5041 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07005042 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07005043 scrollCache.fadeStartTime = fadeStartTime;
5044 scrollCache.state = ScrollabilityCache.ON;
5045
5046 // Schedule our fader to run, unscheduling any old ones first
5047 if (mAttachInfo != null) {
5048 mAttachInfo.mHandler.removeCallbacks(scrollCache);
5049 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
5050 }
5051
5052 return true;
5053 }
5054
5055 return false;
5056 }
5057
5058 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 * Mark the the area defined by dirty as needing to be drawn. If the view is
5060 * visible, {@link #onDraw} will be called at some point in the future.
5061 * This must be called from a UI thread. To call from a non-UI thread, call
5062 * {@link #postInvalidate()}.
5063 *
5064 * WARNING: This method is destructive to dirty.
5065 * @param dirty the rectangle representing the bounds of the dirty region
5066 */
5067 public void invalidate(Rect dirty) {
5068 if (ViewDebug.TRACE_HIERARCHY) {
5069 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5070 }
5071
5072 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5073 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5074 final ViewParent p = mParent;
5075 final AttachInfo ai = mAttachInfo;
5076 if (p != null && ai != null) {
5077 final int scrollX = mScrollX;
5078 final int scrollY = mScrollY;
5079 final Rect r = ai.mTmpInvalRect;
5080 r.set(dirty.left - scrollX, dirty.top - scrollY,
5081 dirty.right - scrollX, dirty.bottom - scrollY);
5082 mParent.invalidateChild(this, r);
5083 }
5084 }
5085 }
5086
5087 /**
5088 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
5089 * The coordinates of the dirty rect are relative to the view.
5090 * If the view is visible, {@link #onDraw} will be called at some point
5091 * in the future. This must be called from a UI thread. To call
5092 * from a non-UI thread, call {@link #postInvalidate()}.
5093 * @param l the left position of the dirty region
5094 * @param t the top position of the dirty region
5095 * @param r the right position of the dirty region
5096 * @param b the bottom position of the dirty region
5097 */
5098 public void invalidate(int l, int t, int r, int b) {
5099 if (ViewDebug.TRACE_HIERARCHY) {
5100 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5101 }
5102
5103 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5104 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5105 final ViewParent p = mParent;
5106 final AttachInfo ai = mAttachInfo;
5107 if (p != null && ai != null && l < r && t < b) {
5108 final int scrollX = mScrollX;
5109 final int scrollY = mScrollY;
5110 final Rect tmpr = ai.mTmpInvalRect;
5111 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
5112 p.invalidateChild(this, tmpr);
5113 }
5114 }
5115 }
5116
5117 /**
5118 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
5119 * be called at some point in the future. This must be called from a
5120 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
5121 */
5122 public void invalidate() {
5123 if (ViewDebug.TRACE_HIERARCHY) {
5124 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5125 }
5126
5127 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5128 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
5129 final ViewParent p = mParent;
5130 final AttachInfo ai = mAttachInfo;
5131 if (p != null && ai != null) {
5132 final Rect r = ai.mTmpInvalRect;
5133 r.set(0, 0, mRight - mLeft, mBottom - mTop);
5134 // Don't call invalidate -- we don't want to internally scroll
5135 // our own bounds
5136 p.invalidateChild(this, r);
5137 }
5138 }
5139 }
5140
5141 /**
Romain Guy24443ea2009-05-11 11:56:30 -07005142 * Indicates whether this View is opaque. An opaque View guarantees that it will
5143 * draw all the pixels overlapping its bounds using a fully opaque color.
5144 *
5145 * Subclasses of View should override this method whenever possible to indicate
5146 * whether an instance is opaque. Opaque Views are treated in a special way by
5147 * the View hierarchy, possibly allowing it to perform optimizations during
5148 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07005149 *
Romain Guy24443ea2009-05-11 11:56:30 -07005150 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07005151 */
Romain Guy83b21072009-05-12 10:54:51 -07005152 @ViewDebug.ExportedProperty
Romain Guy24443ea2009-05-11 11:56:30 -07005153 public boolean isOpaque() {
Romain Guy8f1344f52009-05-15 16:03:59 -07005154 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
5155 }
5156
5157 private void computeOpaqueFlags() {
5158 // Opaque if:
5159 // - Has a background
5160 // - Background is opaque
5161 // - Doesn't have scrollbars or scrollbars are inside overlay
5162
5163 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
5164 mPrivateFlags |= OPAQUE_BACKGROUND;
5165 } else {
5166 mPrivateFlags &= ~OPAQUE_BACKGROUND;
5167 }
5168
5169 final int flags = mViewFlags;
5170 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
5171 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
5172 mPrivateFlags |= OPAQUE_SCROLLBARS;
5173 } else {
5174 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
5175 }
5176 }
5177
5178 /**
5179 * @hide
5180 */
5181 protected boolean hasOpaqueScrollbars() {
5182 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07005183 }
5184
5185 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 * @return A handler associated with the thread running the View. This
5187 * handler can be used to pump events in the UI events queue.
5188 */
5189 public Handler getHandler() {
5190 if (mAttachInfo != null) {
5191 return mAttachInfo.mHandler;
5192 }
5193 return null;
5194 }
5195
5196 /**
5197 * Causes the Runnable to be added to the message queue.
5198 * The runnable will be run on the user interface thread.
5199 *
5200 * @param action The Runnable that will be executed.
5201 *
5202 * @return Returns true if the Runnable was successfully placed in to the
5203 * message queue. Returns false on failure, usually because the
5204 * looper processing the message queue is exiting.
5205 */
5206 public boolean post(Runnable action) {
5207 Handler handler;
5208 if (mAttachInfo != null) {
5209 handler = mAttachInfo.mHandler;
5210 } else {
5211 // Assume that post will succeed later
5212 ViewRoot.getRunQueue().post(action);
5213 return true;
5214 }
5215
5216 return handler.post(action);
5217 }
5218
5219 /**
5220 * Causes the Runnable to be added to the message queue, to be run
5221 * after the specified amount of time elapses.
5222 * The runnable will be run on the user interface thread.
5223 *
5224 * @param action The Runnable that will be executed.
5225 * @param delayMillis The delay (in milliseconds) until the Runnable
5226 * will be executed.
5227 *
5228 * @return true if the Runnable was successfully placed in to the
5229 * message queue. Returns false on failure, usually because the
5230 * looper processing the message queue is exiting. Note that a
5231 * result of true does not mean the Runnable will be processed --
5232 * if the looper is quit before the delivery time of the message
5233 * occurs then the message will be dropped.
5234 */
5235 public boolean postDelayed(Runnable action, long delayMillis) {
5236 Handler handler;
5237 if (mAttachInfo != null) {
5238 handler = mAttachInfo.mHandler;
5239 } else {
5240 // Assume that post will succeed later
5241 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
5242 return true;
5243 }
5244
5245 return handler.postDelayed(action, delayMillis);
5246 }
5247
5248 /**
5249 * Removes the specified Runnable from the message queue.
5250 *
5251 * @param action The Runnable to remove from the message handling queue
5252 *
5253 * @return true if this view could ask the Handler to remove the Runnable,
5254 * false otherwise. When the returned value is true, the Runnable
5255 * may or may not have been actually removed from the message queue
5256 * (for instance, if the Runnable was not in the queue already.)
5257 */
5258 public boolean removeCallbacks(Runnable action) {
5259 Handler handler;
5260 if (mAttachInfo != null) {
5261 handler = mAttachInfo.mHandler;
5262 } else {
5263 // Assume that post will succeed later
5264 ViewRoot.getRunQueue().removeCallbacks(action);
5265 return true;
5266 }
5267
5268 handler.removeCallbacks(action);
5269 return true;
5270 }
5271
5272 /**
5273 * Cause an invalidate to happen on a subsequent cycle through the event loop.
5274 * Use this to invalidate the View from a non-UI thread.
5275 *
5276 * @see #invalidate()
5277 */
5278 public void postInvalidate() {
5279 postInvalidateDelayed(0);
5280 }
5281
5282 /**
5283 * Cause an invalidate of the specified area to happen on a subsequent cycle
5284 * through the event loop. Use this to invalidate the View from a non-UI thread.
5285 *
5286 * @param left The left coordinate of the rectangle to invalidate.
5287 * @param top The top coordinate of the rectangle to invalidate.
5288 * @param right The right coordinate of the rectangle to invalidate.
5289 * @param bottom The bottom coordinate of the rectangle to invalidate.
5290 *
5291 * @see #invalidate(int, int, int, int)
5292 * @see #invalidate(Rect)
5293 */
5294 public void postInvalidate(int left, int top, int right, int bottom) {
5295 postInvalidateDelayed(0, left, top, right, bottom);
5296 }
5297
5298 /**
5299 * Cause an invalidate to happen on a subsequent cycle through the event
5300 * loop. Waits for the specified amount of time.
5301 *
5302 * @param delayMilliseconds the duration in milliseconds to delay the
5303 * invalidation by
5304 */
5305 public void postInvalidateDelayed(long delayMilliseconds) {
5306 // We try only with the AttachInfo because there's no point in invalidating
5307 // if we are not attached to our window
5308 if (mAttachInfo != null) {
5309 Message msg = Message.obtain();
5310 msg.what = AttachInfo.INVALIDATE_MSG;
5311 msg.obj = this;
5312 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
5313 }
5314 }
5315
5316 /**
5317 * Cause an invalidate of the specified area to happen on a subsequent cycle
5318 * through the event loop. Waits for the specified amount of time.
5319 *
5320 * @param delayMilliseconds the duration in milliseconds to delay the
5321 * invalidation by
5322 * @param left The left coordinate of the rectangle to invalidate.
5323 * @param top The top coordinate of the rectangle to invalidate.
5324 * @param right The right coordinate of the rectangle to invalidate.
5325 * @param bottom The bottom coordinate of the rectangle to invalidate.
5326 */
5327 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
5328 int right, int bottom) {
5329
5330 // We try only with the AttachInfo because there's no point in invalidating
5331 // if we are not attached to our window
5332 if (mAttachInfo != null) {
5333 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
5334 info.target = this;
5335 info.left = left;
5336 info.top = top;
5337 info.right = right;
5338 info.bottom = bottom;
5339
5340 final Message msg = Message.obtain();
5341 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
5342 msg.obj = info;
5343 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
5344 }
5345 }
5346
5347 /**
5348 * Called by a parent to request that a child update its values for mScrollX
5349 * and mScrollY if necessary. This will typically be done if the child is
5350 * animating a scroll using a {@link android.widget.Scroller Scroller}
5351 * object.
5352 */
5353 public void computeScroll() {
5354 }
5355
5356 /**
5357 * <p>Indicate whether the horizontal edges are faded when the view is
5358 * scrolled horizontally.</p>
5359 *
5360 * @return true if the horizontal edges should are faded on scroll, false
5361 * otherwise
5362 *
5363 * @see #setHorizontalFadingEdgeEnabled(boolean)
5364 * @attr ref android.R.styleable#View_fadingEdge
5365 */
5366 public boolean isHorizontalFadingEdgeEnabled() {
5367 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
5368 }
5369
5370 /**
5371 * <p>Define whether the horizontal edges should be faded when this view
5372 * is scrolled horizontally.</p>
5373 *
5374 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
5375 * be faded when the view is scrolled
5376 * horizontally
5377 *
5378 * @see #isHorizontalFadingEdgeEnabled()
5379 * @attr ref android.R.styleable#View_fadingEdge
5380 */
5381 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
5382 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
5383 if (horizontalFadingEdgeEnabled) {
5384 initScrollCache();
5385 }
5386
5387 mViewFlags ^= FADING_EDGE_HORIZONTAL;
5388 }
5389 }
5390
5391 /**
5392 * <p>Indicate whether the vertical edges are faded when the view is
5393 * scrolled horizontally.</p>
5394 *
5395 * @return true if the vertical edges should are faded on scroll, false
5396 * otherwise
5397 *
5398 * @see #setVerticalFadingEdgeEnabled(boolean)
5399 * @attr ref android.R.styleable#View_fadingEdge
5400 */
5401 public boolean isVerticalFadingEdgeEnabled() {
5402 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
5403 }
5404
5405 /**
5406 * <p>Define whether the vertical edges should be faded when this view
5407 * is scrolled vertically.</p>
5408 *
5409 * @param verticalFadingEdgeEnabled true if the vertical edges should
5410 * be faded when the view is scrolled
5411 * vertically
5412 *
5413 * @see #isVerticalFadingEdgeEnabled()
5414 * @attr ref android.R.styleable#View_fadingEdge
5415 */
5416 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
5417 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
5418 if (verticalFadingEdgeEnabled) {
5419 initScrollCache();
5420 }
5421
5422 mViewFlags ^= FADING_EDGE_VERTICAL;
5423 }
5424 }
5425
5426 /**
5427 * Returns the strength, or intensity, of the top faded edge. The strength is
5428 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5429 * returns 0.0 or 1.0 but no value in between.
5430 *
5431 * Subclasses should override this method to provide a smoother fade transition
5432 * when scrolling occurs.
5433 *
5434 * @return the intensity of the top fade as a float between 0.0f and 1.0f
5435 */
5436 protected float getTopFadingEdgeStrength() {
5437 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
5438 }
5439
5440 /**
5441 * Returns the strength, or intensity, of the bottom faded edge. The strength is
5442 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5443 * returns 0.0 or 1.0 but no value in between.
5444 *
5445 * Subclasses should override this method to provide a smoother fade transition
5446 * when scrolling occurs.
5447 *
5448 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
5449 */
5450 protected float getBottomFadingEdgeStrength() {
5451 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
5452 computeVerticalScrollRange() ? 1.0f : 0.0f;
5453 }
5454
5455 /**
5456 * Returns the strength, or intensity, of the left faded edge. The strength is
5457 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5458 * returns 0.0 or 1.0 but no value in between.
5459 *
5460 * Subclasses should override this method to provide a smoother fade transition
5461 * when scrolling occurs.
5462 *
5463 * @return the intensity of the left fade as a float between 0.0f and 1.0f
5464 */
5465 protected float getLeftFadingEdgeStrength() {
5466 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
5467 }
5468
5469 /**
5470 * Returns the strength, or intensity, of the right faded edge. The strength is
5471 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5472 * returns 0.0 or 1.0 but no value in between.
5473 *
5474 * Subclasses should override this method to provide a smoother fade transition
5475 * when scrolling occurs.
5476 *
5477 * @return the intensity of the right fade as a float between 0.0f and 1.0f
5478 */
5479 protected float getRightFadingEdgeStrength() {
5480 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
5481 computeHorizontalScrollRange() ? 1.0f : 0.0f;
5482 }
5483
5484 /**
5485 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
5486 * scrollbar is not drawn by default.</p>
5487 *
5488 * @return true if the horizontal scrollbar should be painted, false
5489 * otherwise
5490 *
5491 * @see #setHorizontalScrollBarEnabled(boolean)
5492 */
5493 public boolean isHorizontalScrollBarEnabled() {
5494 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
5495 }
5496
5497 /**
5498 * <p>Define whether the horizontal scrollbar should be drawn or not. The
5499 * scrollbar is not drawn by default.</p>
5500 *
5501 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
5502 * be painted
5503 *
5504 * @see #isHorizontalScrollBarEnabled()
5505 */
5506 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
5507 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
5508 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07005509 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 recomputePadding();
5511 }
5512 }
5513
5514 /**
5515 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
5516 * scrollbar is not drawn by default.</p>
5517 *
5518 * @return true if the vertical scrollbar should be painted, false
5519 * otherwise
5520 *
5521 * @see #setVerticalScrollBarEnabled(boolean)
5522 */
5523 public boolean isVerticalScrollBarEnabled() {
5524 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
5525 }
5526
5527 /**
5528 * <p>Define whether the vertical scrollbar should be drawn or not. The
5529 * scrollbar is not drawn by default.</p>
5530 *
5531 * @param verticalScrollBarEnabled true if the vertical scrollbar should
5532 * be painted
5533 *
5534 * @see #isVerticalScrollBarEnabled()
5535 */
5536 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
5537 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
5538 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07005539 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 recomputePadding();
5541 }
5542 }
5543
5544 private void recomputePadding() {
5545 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
5546 }
Mike Cleronfe81d382009-09-28 14:22:16 -07005547
5548 /**
5549 * Define whether scrollbars will fade when the view is not scrolling.
5550 *
5551 * @param fadeScrollbars wheter to enable fading
5552 *
5553 */
5554 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
5555 initScrollCache();
5556 final ScrollabilityCache scrollabilityCache = mScrollCache;
5557 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07005558 if (fadeScrollbars) {
5559 scrollabilityCache.state = ScrollabilityCache.OFF;
5560 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07005561 scrollabilityCache.state = ScrollabilityCache.ON;
5562 }
5563 }
5564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07005566 *
5567 * Returns true if scrollbars will fade when this view is not scrolling
5568 *
5569 * @return true if scrollbar fading is enabled
5570 */
5571 public boolean isScrollbarFadingEnabled() {
5572 return mScrollCache != null && mScrollCache.fadeScrollBars;
5573 }
5574
5575 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005576 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
5577 * inset. When inset, they add to the padding of the view. And the scrollbars
5578 * can be drawn inside the padding area or on the edge of the view. For example,
5579 * if a view has a background drawable and you want to draw the scrollbars
5580 * inside the padding specified by the drawable, you can use
5581 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
5582 * appear at the edge of the view, ignoring the padding, then you can use
5583 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
5584 * @param style the style of the scrollbars. Should be one of
5585 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
5586 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
5587 * @see #SCROLLBARS_INSIDE_OVERLAY
5588 * @see #SCROLLBARS_INSIDE_INSET
5589 * @see #SCROLLBARS_OUTSIDE_OVERLAY
5590 * @see #SCROLLBARS_OUTSIDE_INSET
5591 */
5592 public void setScrollBarStyle(int style) {
5593 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
5594 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07005595 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 recomputePadding();
5597 }
5598 }
5599
5600 /**
5601 * <p>Returns the current scrollbar style.</p>
5602 * @return the current scrollbar style
5603 * @see #SCROLLBARS_INSIDE_OVERLAY
5604 * @see #SCROLLBARS_INSIDE_INSET
5605 * @see #SCROLLBARS_OUTSIDE_OVERLAY
5606 * @see #SCROLLBARS_OUTSIDE_INSET
5607 */
5608 public int getScrollBarStyle() {
5609 return mViewFlags & SCROLLBARS_STYLE_MASK;
5610 }
5611
5612 /**
5613 * <p>Compute the horizontal range that the horizontal scrollbar
5614 * represents.</p>
5615 *
5616 * <p>The range is expressed in arbitrary units that must be the same as the
5617 * units used by {@link #computeHorizontalScrollExtent()} and
5618 * {@link #computeHorizontalScrollOffset()}.</p>
5619 *
5620 * <p>The default range is the drawing width of this view.</p>
5621 *
5622 * @return the total horizontal range represented by the horizontal
5623 * scrollbar
5624 *
5625 * @see #computeHorizontalScrollExtent()
5626 * @see #computeHorizontalScrollOffset()
5627 * @see android.widget.ScrollBarDrawable
5628 */
5629 protected int computeHorizontalScrollRange() {
5630 return getWidth();
5631 }
5632
5633 /**
5634 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
5635 * within the horizontal range. This value is used to compute the position
5636 * of the thumb within the scrollbar's track.</p>
5637 *
5638 * <p>The range is expressed in arbitrary units that must be the same as the
5639 * units used by {@link #computeHorizontalScrollRange()} and
5640 * {@link #computeHorizontalScrollExtent()}.</p>
5641 *
5642 * <p>The default offset is the scroll offset of this view.</p>
5643 *
5644 * @return the horizontal offset of the scrollbar's thumb
5645 *
5646 * @see #computeHorizontalScrollRange()
5647 * @see #computeHorizontalScrollExtent()
5648 * @see android.widget.ScrollBarDrawable
5649 */
5650 protected int computeHorizontalScrollOffset() {
5651 return mScrollX;
5652 }
5653
5654 /**
5655 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
5656 * within the horizontal range. This value is used to compute the length
5657 * of the thumb within the scrollbar's track.</p>
5658 *
5659 * <p>The range is expressed in arbitrary units that must be the same as the
5660 * units used by {@link #computeHorizontalScrollRange()} and
5661 * {@link #computeHorizontalScrollOffset()}.</p>
5662 *
5663 * <p>The default extent is the drawing width of this view.</p>
5664 *
5665 * @return the horizontal extent of the scrollbar's thumb
5666 *
5667 * @see #computeHorizontalScrollRange()
5668 * @see #computeHorizontalScrollOffset()
5669 * @see android.widget.ScrollBarDrawable
5670 */
5671 protected int computeHorizontalScrollExtent() {
5672 return getWidth();
5673 }
5674
5675 /**
5676 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
5677 *
5678 * <p>The range is expressed in arbitrary units that must be the same as the
5679 * units used by {@link #computeVerticalScrollExtent()} and
5680 * {@link #computeVerticalScrollOffset()}.</p>
5681 *
5682 * @return the total vertical range represented by the vertical scrollbar
5683 *
5684 * <p>The default range is the drawing height of this view.</p>
5685 *
5686 * @see #computeVerticalScrollExtent()
5687 * @see #computeVerticalScrollOffset()
5688 * @see android.widget.ScrollBarDrawable
5689 */
5690 protected int computeVerticalScrollRange() {
5691 return getHeight();
5692 }
5693
5694 /**
5695 * <p>Compute the vertical offset of the vertical scrollbar's thumb
5696 * within the horizontal range. This value is used to compute the position
5697 * of the thumb within the scrollbar's track.</p>
5698 *
5699 * <p>The range is expressed in arbitrary units that must be the same as the
5700 * units used by {@link #computeVerticalScrollRange()} and
5701 * {@link #computeVerticalScrollExtent()}.</p>
5702 *
5703 * <p>The default offset is the scroll offset of this view.</p>
5704 *
5705 * @return the vertical offset of the scrollbar's thumb
5706 *
5707 * @see #computeVerticalScrollRange()
5708 * @see #computeVerticalScrollExtent()
5709 * @see android.widget.ScrollBarDrawable
5710 */
5711 protected int computeVerticalScrollOffset() {
5712 return mScrollY;
5713 }
5714
5715 /**
5716 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
5717 * within the vertical range. This value is used to compute the length
5718 * of the thumb within the scrollbar's track.</p>
5719 *
5720 * <p>The range is expressed in arbitrary units that must be the same as the
5721 * units used by {@link #computeHorizontalScrollRange()} and
5722 * {@link #computeVerticalScrollOffset()}.</p>
5723 *
5724 * <p>The default extent is the drawing height of this view.</p>
5725 *
5726 * @return the vertical extent of the scrollbar's thumb
5727 *
5728 * @see #computeVerticalScrollRange()
5729 * @see #computeVerticalScrollOffset()
5730 * @see android.widget.ScrollBarDrawable
5731 */
5732 protected int computeVerticalScrollExtent() {
5733 return getHeight();
5734 }
5735
5736 /**
5737 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
5738 * scrollbars are painted only if they have been awakened first.</p>
5739 *
5740 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07005741 *
5742 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08005744 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 // scrollbars are drawn only when the animation is running
5746 final ScrollabilityCache cache = mScrollCache;
5747 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07005748
5749 int state = cache.state;
5750
5751 if (state == ScrollabilityCache.OFF) {
5752 return;
5753 }
5754
5755 boolean invalidate = false;
5756
5757 if (state == ScrollabilityCache.FADING) {
5758 // We're fading -- get our fade interpolation
5759 if (cache.interpolatorValues == null) {
5760 cache.interpolatorValues = new float[1];
5761 }
5762
5763 float[] values = cache.interpolatorValues;
5764
5765 // Stops the animation if we're done
5766 if (cache.scrollBarInterpolator.timeToValues(values) ==
5767 Interpolator.Result.FREEZE_END) {
5768 cache.state = ScrollabilityCache.OFF;
5769 } else {
5770 cache.scrollBar.setAlpha(Math.round(values[0]));
5771 }
5772
5773 // This will make the scroll bars inval themselves after
5774 // drawing. We only want this when we're fading so that
5775 // we prevent excessive redraws
5776 invalidate = true;
5777 } else {
5778 // We're just on -- but we may have been fading before so
5779 // reset alpha
5780 cache.scrollBar.setAlpha(255);
5781 }
5782
5783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 final int viewFlags = mViewFlags;
5785
5786 final boolean drawHorizontalScrollBar =
5787 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
5788 final boolean drawVerticalScrollBar =
5789 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
5790 && !isVerticalScrollBarHidden();
5791
5792 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
5793 final int width = mRight - mLeft;
5794 final int height = mBottom - mTop;
5795
5796 final ScrollBarDrawable scrollBar = cache.scrollBar;
5797 int size = scrollBar.getSize(false);
5798 if (size <= 0) {
5799 size = cache.scrollBarSize;
5800 }
5801
Mike Reede8853fc2009-09-04 14:01:48 -04005802 final int scrollX = mScrollX;
5803 final int scrollY = mScrollY;
5804 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
5805
Mike Cleronf116bf82009-09-27 19:14:12 -07005806 int left, top, right, bottom;
5807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07005809 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04005810 computeHorizontalScrollOffset(),
5811 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04005812 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07005813 getVerticalScrollbarWidth() : 0;
5814 top = scrollY + height - size - (mUserPaddingBottom & inside);
5815 left = scrollX + (mPaddingLeft & inside);
5816 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
5817 bottom = top + size;
5818 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
5819 if (invalidate) {
5820 invalidate(left, top, right, bottom);
5821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 }
5823
5824 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04005825 scrollBar.setParameters(computeVerticalScrollRange(),
5826 computeVerticalScrollOffset(),
5827 computeVerticalScrollExtent(), true);
5828 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07005829 left = scrollX + width - size - (mUserPaddingRight & inside);
5830 top = scrollY + (mPaddingTop & inside);
5831 right = left + size;
5832 bottom = scrollY + height - (mUserPaddingBottom & inside);
5833 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
5834 if (invalidate) {
5835 invalidate(left, top, right, bottom);
5836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 }
5838 }
5839 }
5840 }
Romain Guy8506ab42009-06-11 17:35:47 -07005841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005842 /**
Romain Guy8506ab42009-06-11 17:35:47 -07005843 * 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 -08005844 * FastScroller is visible.
5845 * @return whether to temporarily hide the vertical scrollbar
5846 * @hide
5847 */
5848 protected boolean isVerticalScrollBarHidden() {
5849 return false;
5850 }
5851
5852 /**
5853 * <p>Draw the horizontal scrollbar if
5854 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
5855 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 * @param canvas the canvas on which to draw the scrollbar
5857 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858 *
5859 * @see #isHorizontalScrollBarEnabled()
5860 * @see #computeHorizontalScrollRange()
5861 * @see #computeHorizontalScrollExtent()
5862 * @see #computeHorizontalScrollOffset()
5863 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07005864 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005865 */
Mike Reede8853fc2009-09-04 14:01:48 -04005866 protected void onDrawHorizontalScrollBar(Canvas canvas,
5867 Drawable scrollBar,
5868 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005869 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005870 scrollBar.draw(canvas);
5871 }
Mike Reede8853fc2009-09-04 14:01:48 -04005872
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005873 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
5875 * returns true.</p>
5876 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 * @param canvas the canvas on which to draw the scrollbar
5878 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879 *
5880 * @see #isVerticalScrollBarEnabled()
5881 * @see #computeVerticalScrollRange()
5882 * @see #computeVerticalScrollExtent()
5883 * @see #computeVerticalScrollOffset()
5884 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04005885 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005886 */
Mike Reede8853fc2009-09-04 14:01:48 -04005887 protected void onDrawVerticalScrollBar(Canvas canvas,
5888 Drawable scrollBar,
5889 int l, int t, int r, int b) {
5890 scrollBar.setBounds(l, t, r, b);
5891 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892 }
5893
5894 /**
5895 * Implement this to do your drawing.
5896 *
5897 * @param canvas the canvas on which the background will be drawn
5898 */
5899 protected void onDraw(Canvas canvas) {
5900 }
5901
5902 /*
5903 * Caller is responsible for calling requestLayout if necessary.
5904 * (This allows addViewInLayout to not request a new layout.)
5905 */
5906 void assignParent(ViewParent parent) {
5907 if (mParent == null) {
5908 mParent = parent;
5909 } else if (parent == null) {
5910 mParent = null;
5911 } else {
5912 throw new RuntimeException("view " + this + " being added, but"
5913 + " it already has a parent");
5914 }
5915 }
5916
5917 /**
5918 * This is called when the view is attached to a window. At this point it
5919 * has a Surface and will start drawing. Note that this function is
5920 * guaranteed to be called before {@link #onDraw}, however it may be called
5921 * any time before the first onDraw -- including before or after
5922 * {@link #onMeasure}.
5923 *
5924 * @see #onDetachedFromWindow()
5925 */
5926 protected void onAttachedToWindow() {
5927 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
5928 mParent.requestTransparentRegion(this);
5929 }
5930 }
5931
5932 /**
5933 * This is called when the view is detached from a window. At this point it
5934 * no longer has a surface for drawing.
5935 *
5936 * @see #onAttachedToWindow()
5937 */
5938 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08005939 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08005940 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05005941 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 destroyDrawingCache();
5943 }
5944
5945 /**
5946 * @return The number of times this view has been attached to a window
5947 */
5948 protected int getWindowAttachCount() {
5949 return mWindowAttachCount;
5950 }
5951
5952 /**
5953 * Retrieve a unique token identifying the window this view is attached to.
5954 * @return Return the window's token for use in
5955 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
5956 */
5957 public IBinder getWindowToken() {
5958 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
5959 }
5960
5961 /**
5962 * Retrieve a unique token identifying the top-level "real" window of
5963 * the window that this view is attached to. That is, this is like
5964 * {@link #getWindowToken}, except if the window this view in is a panel
5965 * window (attached to another containing window), then the token of
5966 * the containing window is returned instead.
5967 *
5968 * @return Returns the associated window token, either
5969 * {@link #getWindowToken()} or the containing window's token.
5970 */
5971 public IBinder getApplicationWindowToken() {
5972 AttachInfo ai = mAttachInfo;
5973 if (ai != null) {
5974 IBinder appWindowToken = ai.mPanelParentWindowToken;
5975 if (appWindowToken == null) {
5976 appWindowToken = ai.mWindowToken;
5977 }
5978 return appWindowToken;
5979 }
5980 return null;
5981 }
5982
5983 /**
5984 * Retrieve private session object this view hierarchy is using to
5985 * communicate with the window manager.
5986 * @return the session object to communicate with the window manager
5987 */
5988 /*package*/ IWindowSession getWindowSession() {
5989 return mAttachInfo != null ? mAttachInfo.mSession : null;
5990 }
5991
5992 /**
5993 * @param info the {@link android.view.View.AttachInfo} to associated with
5994 * this view
5995 */
5996 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
5997 //System.out.println("Attached! " + this);
5998 mAttachInfo = info;
5999 mWindowAttachCount++;
6000 if (mFloatingTreeObserver != null) {
6001 info.mTreeObserver.merge(mFloatingTreeObserver);
6002 mFloatingTreeObserver = null;
6003 }
6004 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
6005 mAttachInfo.mScrollContainers.add(this);
6006 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
6007 }
6008 performCollectViewAttributes(visibility);
6009 onAttachedToWindow();
6010 int vis = info.mWindowVisibility;
6011 if (vis != GONE) {
6012 onWindowVisibilityChanged(vis);
6013 }
6014 }
6015
6016 void dispatchDetachedFromWindow() {
6017 //System.out.println("Detached! " + this);
6018 AttachInfo info = mAttachInfo;
6019 if (info != null) {
6020 int vis = info.mWindowVisibility;
6021 if (vis != GONE) {
6022 onWindowVisibilityChanged(GONE);
6023 }
6024 }
6025
6026 onDetachedFromWindow();
6027 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
6028 mAttachInfo.mScrollContainers.remove(this);
6029 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
6030 }
6031 mAttachInfo = null;
6032 }
6033
6034 /**
6035 * Store this view hierarchy's frozen state into the given container.
6036 *
6037 * @param container The SparseArray in which to save the view's state.
6038 *
6039 * @see #restoreHierarchyState
6040 * @see #dispatchSaveInstanceState
6041 * @see #onSaveInstanceState
6042 */
6043 public void saveHierarchyState(SparseArray<Parcelable> container) {
6044 dispatchSaveInstanceState(container);
6045 }
6046
6047 /**
6048 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
6049 * May be overridden to modify how freezing happens to a view's children; for example, some
6050 * views may want to not store state for their children.
6051 *
6052 * @param container The SparseArray in which to save the view's state.
6053 *
6054 * @see #dispatchRestoreInstanceState
6055 * @see #saveHierarchyState
6056 * @see #onSaveInstanceState
6057 */
6058 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
6059 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
6060 mPrivateFlags &= ~SAVE_STATE_CALLED;
6061 Parcelable state = onSaveInstanceState();
6062 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
6063 throw new IllegalStateException(
6064 "Derived class did not call super.onSaveInstanceState()");
6065 }
6066 if (state != null) {
6067 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
6068 // + ": " + state);
6069 container.put(mID, state);
6070 }
6071 }
6072 }
6073
6074 /**
6075 * Hook allowing a view to generate a representation of its internal state
6076 * that can later be used to create a new instance with that same state.
6077 * This state should only contain information that is not persistent or can
6078 * not be reconstructed later. For example, you will never store your
6079 * current position on screen because that will be computed again when a
6080 * new instance of the view is placed in its view hierarchy.
6081 * <p>
6082 * Some examples of things you may store here: the current cursor position
6083 * in a text view (but usually not the text itself since that is stored in a
6084 * content provider or other persistent storage), the currently selected
6085 * item in a list view.
6086 *
6087 * @return Returns a Parcelable object containing the view's current dynamic
6088 * state, or null if there is nothing interesting to save. The
6089 * default implementation returns null.
6090 * @see #onRestoreInstanceState
6091 * @see #saveHierarchyState
6092 * @see #dispatchSaveInstanceState
6093 * @see #setSaveEnabled(boolean)
6094 */
6095 protected Parcelable onSaveInstanceState() {
6096 mPrivateFlags |= SAVE_STATE_CALLED;
6097 return BaseSavedState.EMPTY_STATE;
6098 }
6099
6100 /**
6101 * Restore this view hierarchy's frozen state from the given container.
6102 *
6103 * @param container The SparseArray which holds previously frozen states.
6104 *
6105 * @see #saveHierarchyState
6106 * @see #dispatchRestoreInstanceState
6107 * @see #onRestoreInstanceState
6108 */
6109 public void restoreHierarchyState(SparseArray<Parcelable> container) {
6110 dispatchRestoreInstanceState(container);
6111 }
6112
6113 /**
6114 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
6115 * children. May be overridden to modify how restoreing happens to a view's children; for
6116 * example, some views may want to not store state for their children.
6117 *
6118 * @param container The SparseArray which holds previously saved state.
6119 *
6120 * @see #dispatchSaveInstanceState
6121 * @see #restoreHierarchyState
6122 * @see #onRestoreInstanceState
6123 */
6124 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
6125 if (mID != NO_ID) {
6126 Parcelable state = container.get(mID);
6127 if (state != null) {
6128 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
6129 // + ": " + state);
6130 mPrivateFlags &= ~SAVE_STATE_CALLED;
6131 onRestoreInstanceState(state);
6132 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
6133 throw new IllegalStateException(
6134 "Derived class did not call super.onRestoreInstanceState()");
6135 }
6136 }
6137 }
6138 }
6139
6140 /**
6141 * Hook allowing a view to re-apply a representation of its internal state that had previously
6142 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
6143 * null state.
6144 *
6145 * @param state The frozen state that had previously been returned by
6146 * {@link #onSaveInstanceState}.
6147 *
6148 * @see #onSaveInstanceState
6149 * @see #restoreHierarchyState
6150 * @see #dispatchRestoreInstanceState
6151 */
6152 protected void onRestoreInstanceState(Parcelable state) {
6153 mPrivateFlags |= SAVE_STATE_CALLED;
6154 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08006155 throw new IllegalArgumentException("Wrong state class, expecting View State but "
6156 + "received " + state.getClass().toString() + " instead. This usually happens "
6157 + "when two views of different type have the same id in the same hierarchy. "
6158 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
6159 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 }
6161 }
6162
6163 /**
6164 * <p>Return the time at which the drawing of the view hierarchy started.</p>
6165 *
6166 * @return the drawing start time in milliseconds
6167 */
6168 public long getDrawingTime() {
6169 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
6170 }
6171
6172 /**
6173 * <p>Enables or disables the duplication of the parent's state into this view. When
6174 * duplication is enabled, this view gets its drawable state from its parent rather
6175 * than from its own internal properties.</p>
6176 *
6177 * <p>Note: in the current implementation, setting this property to true after the
6178 * view was added to a ViewGroup might have no effect at all. This property should
6179 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
6180 *
6181 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
6182 * property is enabled, an exception will be thrown.</p>
6183 *
6184 * @param enabled True to enable duplication of the parent's drawable state, false
6185 * to disable it.
6186 *
6187 * @see #getDrawableState()
6188 * @see #isDuplicateParentStateEnabled()
6189 */
6190 public void setDuplicateParentStateEnabled(boolean enabled) {
6191 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
6192 }
6193
6194 /**
6195 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
6196 *
6197 * @return True if this view's drawable state is duplicated from the parent,
6198 * false otherwise
6199 *
6200 * @see #getDrawableState()
6201 * @see #setDuplicateParentStateEnabled(boolean)
6202 */
6203 public boolean isDuplicateParentStateEnabled() {
6204 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
6205 }
6206
6207 /**
6208 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
6209 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
6210 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
6211 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
6212 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
6213 * null.</p>
6214 *
6215 * @param enabled true to enable the drawing cache, false otherwise
6216 *
6217 * @see #isDrawingCacheEnabled()
6218 * @see #getDrawingCache()
6219 * @see #buildDrawingCache()
6220 */
6221 public void setDrawingCacheEnabled(boolean enabled) {
6222 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
6223 }
6224
6225 /**
6226 * <p>Indicates whether the drawing cache is enabled for this view.</p>
6227 *
6228 * @return true if the drawing cache is enabled
6229 *
6230 * @see #setDrawingCacheEnabled(boolean)
6231 * @see #getDrawingCache()
6232 */
6233 @ViewDebug.ExportedProperty
6234 public boolean isDrawingCacheEnabled() {
6235 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
6236 }
6237
6238 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07006239 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
6240 *
6241 * @return A non-scaled bitmap representing this view or null if cache is disabled.
6242 *
6243 * @see #getDrawingCache(boolean)
6244 */
6245 public Bitmap getDrawingCache() {
6246 return getDrawingCache(false);
6247 }
6248
6249 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
6251 * is null when caching is disabled. If caching is enabled and the cache is not ready,
6252 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
6253 * draw from the cache when the cache is enabled. To benefit from the cache, you must
6254 * request the drawing cache by calling this method and draw it on screen if the
6255 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07006256 *
6257 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
6258 * this method will create a bitmap of the same size as this view. Because this bitmap
6259 * will be drawn scaled by the parent ViewGroup, the result on screen might show
6260 * scaling artifacts. To avoid such artifacts, you should call this method by setting
6261 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
6262 * size than the view. This implies that your application must be able to handle this
6263 * size.</p>
6264 *
6265 * @param autoScale Indicates whether the generated bitmap should be scaled based on
6266 * the current density of the screen when the application is in compatibility
6267 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 *
Romain Guyfbd8f692009-06-26 14:51:58 -07006269 * @return A bitmap representing this view or null if cache is disabled.
6270 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 * @see #setDrawingCacheEnabled(boolean)
6272 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07006273 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 * @see #destroyDrawingCache()
6275 */
Romain Guyfbd8f692009-06-26 14:51:58 -07006276 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
6278 return null;
6279 }
6280 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07006281 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 }
Romain Guyfbd8f692009-06-26 14:51:58 -07006283 return autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) :
6284 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 }
6286
6287 /**
6288 * <p>Frees the resources used by the drawing cache. If you call
6289 * {@link #buildDrawingCache()} manually without calling
6290 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
6291 * should cleanup the cache with this method afterwards.</p>
6292 *
6293 * @see #setDrawingCacheEnabled(boolean)
6294 * @see #buildDrawingCache()
6295 * @see #getDrawingCache()
6296 */
6297 public void destroyDrawingCache() {
6298 if (mDrawingCache != null) {
6299 final Bitmap bitmap = mDrawingCache.get();
6300 if (bitmap != null) bitmap.recycle();
6301 mDrawingCache = null;
6302 }
Romain Guyfbd8f692009-06-26 14:51:58 -07006303 if (mUnscaledDrawingCache != null) {
6304 final Bitmap bitmap = mUnscaledDrawingCache.get();
6305 if (bitmap != null) bitmap.recycle();
6306 mUnscaledDrawingCache = null;
6307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 }
6309
6310 /**
6311 * Setting a solid background color for the drawing cache's bitmaps will improve
6312 * perfromance and memory usage. Note, though that this should only be used if this
6313 * view will always be drawn on top of a solid color.
6314 *
6315 * @param color The background color to use for the drawing cache's bitmap
6316 *
6317 * @see #setDrawingCacheEnabled(boolean)
6318 * @see #buildDrawingCache()
6319 * @see #getDrawingCache()
6320 */
6321 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08006322 if (color != mDrawingCacheBackgroundColor) {
6323 mDrawingCacheBackgroundColor = color;
6324 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006326 }
6327
6328 /**
6329 * @see #setDrawingCacheBackgroundColor(int)
6330 *
6331 * @return The background color to used for the drawing cache's bitmap
6332 */
6333 public int getDrawingCacheBackgroundColor() {
6334 return mDrawingCacheBackgroundColor;
6335 }
6336
6337 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07006338 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
6339 *
6340 * @see #buildDrawingCache(boolean)
6341 */
6342 public void buildDrawingCache() {
6343 buildDrawingCache(false);
6344 }
6345
6346 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
6348 *
6349 * <p>If you call {@link #buildDrawingCache()} manually without calling
6350 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
6351 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07006352 *
6353 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
6354 * this method will create a bitmap of the same size as this view. Because this bitmap
6355 * will be drawn scaled by the parent ViewGroup, the result on screen might show
6356 * scaling artifacts. To avoid such artifacts, you should call this method by setting
6357 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
6358 * size than the view. This implies that your application must be able to handle this
6359 * size.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 *
6361 * @see #getDrawingCache()
6362 * @see #destroyDrawingCache()
6363 */
Romain Guyfbd8f692009-06-26 14:51:58 -07006364 public void buildDrawingCache(boolean autoScale) {
6365 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
6366 (mDrawingCache == null || mDrawingCache.get() == null) :
6367 (mUnscaledDrawingCache == null || mUnscaledDrawingCache.get() == null))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368
6369 if (ViewDebug.TRACE_HIERARCHY) {
6370 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
6371 }
Romain Guy13922e02009-05-12 17:56:14 -07006372 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 EventLog.writeEvent(60002, hashCode());
6374 }
6375
Romain Guy8506ab42009-06-11 17:35:47 -07006376 int width = mRight - mLeft;
6377 int height = mBottom - mTop;
6378
6379 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07006380 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07006381
Romain Guye1123222009-06-29 14:24:56 -07006382 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07006383 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
6384 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07006385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386
6387 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07006388 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Romain Guya62e4702009-10-08 10:48:54 -07006389 final boolean translucentWindow = attachInfo != null && attachInfo.mTranslucentWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390
6391 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07006392 // Projected bitmap size in bytes
6393 (width * height * (opaque && !translucentWindow ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
6395 destroyDrawingCache();
6396 return;
6397 }
6398
6399 boolean clear = true;
Romain Guyfbd8f692009-06-26 14:51:58 -07006400 Bitmap bitmap = autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) :
6401 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402
6403 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 Bitmap.Config quality;
6405 if (!opaque) {
6406 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
6407 case DRAWING_CACHE_QUALITY_AUTO:
6408 quality = Bitmap.Config.ARGB_8888;
6409 break;
6410 case DRAWING_CACHE_QUALITY_LOW:
6411 quality = Bitmap.Config.ARGB_4444;
6412 break;
6413 case DRAWING_CACHE_QUALITY_HIGH:
6414 quality = Bitmap.Config.ARGB_8888;
6415 break;
6416 default:
6417 quality = Bitmap.Config.ARGB_8888;
6418 break;
6419 }
6420 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07006421 // Optimization for translucent windows
6422 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
6423 quality = translucentWindow ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424 }
6425
6426 // Try to cleanup memory
6427 if (bitmap != null) bitmap.recycle();
6428
6429 try {
6430 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07006431 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07006432 if (autoScale) {
6433 mDrawingCache = new SoftReference<Bitmap>(bitmap);
6434 } else {
6435 mUnscaledDrawingCache = new SoftReference<Bitmap>(bitmap);
6436 }
Romain Guy35b38ce2009-10-07 13:38:55 -07006437 if (opaque && translucentWindow) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 } catch (OutOfMemoryError e) {
6439 // If there is not enough memory to create the bitmap cache, just
6440 // ignore the issue as bitmap caches are not required to draw the
6441 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07006442 if (autoScale) {
6443 mDrawingCache = null;
6444 } else {
6445 mUnscaledDrawingCache = null;
6446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 return;
6448 }
6449
6450 clear = drawingCacheBackgroundColor != 0;
6451 }
6452
6453 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 if (attachInfo != null) {
6455 canvas = attachInfo.mCanvas;
6456 if (canvas == null) {
6457 canvas = new Canvas();
6458 }
6459 canvas.setBitmap(bitmap);
6460 // Temporarily clobber the cached Canvas in case one of our children
6461 // is also using a drawing cache. Without this, the children would
6462 // steal the canvas by attaching their own bitmap to it and bad, bad
6463 // thing would happen (invisible views, corrupted drawings, etc.)
6464 attachInfo.mCanvas = null;
6465 } else {
6466 // This case should hopefully never or seldom happen
6467 canvas = new Canvas(bitmap);
6468 }
6469
6470 if (clear) {
6471 bitmap.eraseColor(drawingCacheBackgroundColor);
6472 }
6473
6474 computeScroll();
6475 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07006476
Romain Guye1123222009-06-29 14:24:56 -07006477 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07006478 final float scale = attachInfo.mApplicationScale;
6479 canvas.scale(scale, scale);
6480 }
6481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 canvas.translate(-mScrollX, -mScrollY);
6483
Romain Guy5bcdff42009-05-14 21:27:18 -07006484 mPrivateFlags |= DRAWN;
Romain Guyecd80ee2009-12-03 17:13:02 -08006485 mPrivateFlags |= DRAWING_CACHE_VALID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486
6487 // Fast path for layouts with no backgrounds
6488 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
6489 if (ViewDebug.TRACE_HIERARCHY) {
6490 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
6491 }
Romain Guy5bcdff42009-05-14 21:27:18 -07006492 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 dispatchDraw(canvas);
6494 } else {
6495 draw(canvas);
6496 }
6497
6498 canvas.restoreToCount(restoreCount);
6499
6500 if (attachInfo != null) {
6501 // Restore the cached Canvas for our siblings
6502 attachInfo.mCanvas = canvas;
6503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 }
6505 }
6506
6507 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006508 * Create a snapshot of the view into a bitmap. We should probably make
6509 * some form of this public, but should think about the API.
6510 */
Romain Guy223ff5c2010-03-02 17:07:47 -08006511 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006512 int width = mRight - mLeft;
6513 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006514
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006515 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07006516 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006517 width = (int) ((width * scale) + 0.5f);
6518 height = (int) ((height * scale) + 0.5f);
6519
Romain Guy8c11e312009-09-14 15:15:30 -07006520 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006521 if (bitmap == null) {
6522 throw new OutOfMemoryError();
6523 }
6524
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006525 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
6526
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006527 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006528 if (attachInfo != null) {
6529 canvas = attachInfo.mCanvas;
6530 if (canvas == null) {
6531 canvas = new Canvas();
6532 }
6533 canvas.setBitmap(bitmap);
6534 // Temporarily clobber the cached Canvas in case one of our children
6535 // is also using a drawing cache. Without this, the children would
6536 // steal the canvas by attaching their own bitmap to it and bad, bad
6537 // things would happen (invisible views, corrupted drawings, etc.)
6538 attachInfo.mCanvas = null;
6539 } else {
6540 // This case should hopefully never or seldom happen
6541 canvas = new Canvas(bitmap);
6542 }
6543
Romain Guy5bcdff42009-05-14 21:27:18 -07006544 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006545 bitmap.eraseColor(backgroundColor);
6546 }
6547
6548 computeScroll();
6549 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006550 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006551 canvas.translate(-mScrollX, -mScrollY);
6552
Romain Guy5bcdff42009-05-14 21:27:18 -07006553 // Temporarily remove the dirty mask
6554 int flags = mPrivateFlags;
6555 mPrivateFlags &= ~DIRTY_MASK;
6556
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006557 // Fast path for layouts with no backgrounds
6558 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
6559 dispatchDraw(canvas);
6560 } else {
6561 draw(canvas);
6562 }
6563
Romain Guy5bcdff42009-05-14 21:27:18 -07006564 mPrivateFlags = flags;
6565
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006566 canvas.restoreToCount(restoreCount);
6567
6568 if (attachInfo != null) {
6569 // Restore the cached Canvas for our siblings
6570 attachInfo.mCanvas = canvas;
6571 }
Romain Guy8506ab42009-06-11 17:35:47 -07006572
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006573 return bitmap;
6574 }
6575
6576 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 * Indicates whether this View is currently in edit mode. A View is usually
6578 * in edit mode when displayed within a developer tool. For instance, if
6579 * this View is being drawn by a visual user interface builder, this method
6580 * should return true.
6581 *
6582 * Subclasses should check the return value of this method to provide
6583 * different behaviors if their normal behavior might interfere with the
6584 * host environment. For instance: the class spawns a thread in its
6585 * constructor, the drawing code relies on device-specific features, etc.
6586 *
6587 * This method is usually checked in the drawing code of custom widgets.
6588 *
6589 * @return True if this View is in edit mode, false otherwise.
6590 */
6591 public boolean isInEditMode() {
6592 return false;
6593 }
6594
6595 /**
6596 * If the View draws content inside its padding and enables fading edges,
6597 * it needs to support padding offsets. Padding offsets are added to the
6598 * fading edges to extend the length of the fade so that it covers pixels
6599 * drawn inside the padding.
6600 *
6601 * Subclasses of this class should override this method if they need
6602 * to draw content inside the padding.
6603 *
6604 * @return True if padding offset must be applied, false otherwise.
6605 *
6606 * @see #getLeftPaddingOffset()
6607 * @see #getRightPaddingOffset()
6608 * @see #getTopPaddingOffset()
6609 * @see #getBottomPaddingOffset()
6610 *
6611 * @since CURRENT
6612 */
6613 protected boolean isPaddingOffsetRequired() {
6614 return false;
6615 }
6616
6617 /**
6618 * Amount by which to extend the left fading region. Called only when
6619 * {@link #isPaddingOffsetRequired()} returns true.
6620 *
6621 * @return The left padding offset in pixels.
6622 *
6623 * @see #isPaddingOffsetRequired()
6624 *
6625 * @since CURRENT
6626 */
6627 protected int getLeftPaddingOffset() {
6628 return 0;
6629 }
6630
6631 /**
6632 * Amount by which to extend the right fading region. Called only when
6633 * {@link #isPaddingOffsetRequired()} returns true.
6634 *
6635 * @return The right padding offset in pixels.
6636 *
6637 * @see #isPaddingOffsetRequired()
6638 *
6639 * @since CURRENT
6640 */
6641 protected int getRightPaddingOffset() {
6642 return 0;
6643 }
6644
6645 /**
6646 * Amount by which to extend the top fading region. Called only when
6647 * {@link #isPaddingOffsetRequired()} returns true.
6648 *
6649 * @return The top padding offset in pixels.
6650 *
6651 * @see #isPaddingOffsetRequired()
6652 *
6653 * @since CURRENT
6654 */
6655 protected int getTopPaddingOffset() {
6656 return 0;
6657 }
6658
6659 /**
6660 * Amount by which to extend the bottom fading region. Called only when
6661 * {@link #isPaddingOffsetRequired()} returns true.
6662 *
6663 * @return The bottom padding offset in pixels.
6664 *
6665 * @see #isPaddingOffsetRequired()
6666 *
6667 * @since CURRENT
6668 */
6669 protected int getBottomPaddingOffset() {
6670 return 0;
6671 }
6672
6673 /**
6674 * Manually render this view (and all of its children) to the given Canvas.
6675 * The view must have already done a full layout before this function is
6676 * called. When implementing a view, do not override this method; instead,
6677 * you should implement {@link #onDraw}.
6678 *
6679 * @param canvas The Canvas to which the View is rendered.
6680 */
6681 public void draw(Canvas canvas) {
6682 if (ViewDebug.TRACE_HIERARCHY) {
6683 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
6684 }
6685
Romain Guy5bcdff42009-05-14 21:27:18 -07006686 final int privateFlags = mPrivateFlags;
6687 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
6688 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
6689 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07006690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006691 /*
6692 * Draw traversal performs several drawing steps which must be executed
6693 * in the appropriate order:
6694 *
6695 * 1. Draw the background
6696 * 2. If necessary, save the canvas' layers to prepare for fading
6697 * 3. Draw view's content
6698 * 4. Draw children
6699 * 5. If necessary, draw the fading edges and restore layers
6700 * 6. Draw decorations (scrollbars for instance)
6701 */
6702
6703 // Step 1, draw the background, if needed
6704 int saveCount;
6705
Romain Guy24443ea2009-05-11 11:56:30 -07006706 if (!dirtyOpaque) {
6707 final Drawable background = mBGDrawable;
6708 if (background != null) {
6709 final int scrollX = mScrollX;
6710 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711
Romain Guy24443ea2009-05-11 11:56:30 -07006712 if (mBackgroundSizeChanged) {
6713 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
6714 mBackgroundSizeChanged = false;
6715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716
Romain Guy24443ea2009-05-11 11:56:30 -07006717 if ((scrollX | scrollY) == 0) {
6718 background.draw(canvas);
6719 } else {
6720 canvas.translate(scrollX, scrollY);
6721 background.draw(canvas);
6722 canvas.translate(-scrollX, -scrollY);
6723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 }
6725 }
6726
6727 // skip step 2 & 5 if possible (common case)
6728 final int viewFlags = mViewFlags;
6729 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
6730 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
6731 if (!verticalEdges && !horizontalEdges) {
6732 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07006733 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734
6735 // Step 4, draw the children
6736 dispatchDraw(canvas);
6737
6738 // Step 6, draw decorations (scrollbars)
6739 onDrawScrollBars(canvas);
6740
6741 // we're done...
6742 return;
6743 }
6744
6745 /*
6746 * Here we do the full fledged routine...
6747 * (this is an uncommon case where speed matters less,
6748 * this is why we repeat some of the tests that have been
6749 * done above)
6750 */
6751
6752 boolean drawTop = false;
6753 boolean drawBottom = false;
6754 boolean drawLeft = false;
6755 boolean drawRight = false;
6756
6757 float topFadeStrength = 0.0f;
6758 float bottomFadeStrength = 0.0f;
6759 float leftFadeStrength = 0.0f;
6760 float rightFadeStrength = 0.0f;
6761
6762 // Step 2, save the canvas' layers
6763 int paddingLeft = mPaddingLeft;
6764 int paddingTop = mPaddingTop;
6765
6766 final boolean offsetRequired = isPaddingOffsetRequired();
6767 if (offsetRequired) {
6768 paddingLeft += getLeftPaddingOffset();
6769 paddingTop += getTopPaddingOffset();
6770 }
6771
6772 int left = mScrollX + paddingLeft;
6773 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
6774 int top = mScrollY + paddingTop;
6775 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
6776
6777 if (offsetRequired) {
6778 right += getRightPaddingOffset();
6779 bottom += getBottomPaddingOffset();
6780 }
6781
6782 final ScrollabilityCache scrollabilityCache = mScrollCache;
6783 int length = scrollabilityCache.fadingEdgeLength;
6784
6785 // clip the fade length if top and bottom fades overlap
6786 // overlapping fades produce odd-looking artifacts
6787 if (verticalEdges && (top + length > bottom - length)) {
6788 length = (bottom - top) / 2;
6789 }
6790
6791 // also clip horizontal fades if necessary
6792 if (horizontalEdges && (left + length > right - length)) {
6793 length = (right - left) / 2;
6794 }
6795
6796 if (verticalEdges) {
6797 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
6798 drawTop = topFadeStrength >= 0.0f;
6799 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
6800 drawBottom = bottomFadeStrength >= 0.0f;
6801 }
6802
6803 if (horizontalEdges) {
6804 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
6805 drawLeft = leftFadeStrength >= 0.0f;
6806 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
6807 drawRight = rightFadeStrength >= 0.0f;
6808 }
6809
6810 saveCount = canvas.getSaveCount();
6811
6812 int solidColor = getSolidColor();
6813 if (solidColor == 0) {
6814 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
6815
6816 if (drawTop) {
6817 canvas.saveLayer(left, top, right, top + length, null, flags);
6818 }
6819
6820 if (drawBottom) {
6821 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
6822 }
6823
6824 if (drawLeft) {
6825 canvas.saveLayer(left, top, left + length, bottom, null, flags);
6826 }
6827
6828 if (drawRight) {
6829 canvas.saveLayer(right - length, top, right, bottom, null, flags);
6830 }
6831 } else {
6832 scrollabilityCache.setFadeColor(solidColor);
6833 }
6834
6835 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07006836 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837
6838 // Step 4, draw the children
6839 dispatchDraw(canvas);
6840
6841 // Step 5, draw the fade effect and restore layers
6842 final Paint p = scrollabilityCache.paint;
6843 final Matrix matrix = scrollabilityCache.matrix;
6844 final Shader fade = scrollabilityCache.shader;
6845 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
6846
6847 if (drawTop) {
6848 matrix.setScale(1, fadeHeight * topFadeStrength);
6849 matrix.postTranslate(left, top);
6850 fade.setLocalMatrix(matrix);
6851 canvas.drawRect(left, top, right, top + length, p);
6852 }
6853
6854 if (drawBottom) {
6855 matrix.setScale(1, fadeHeight * bottomFadeStrength);
6856 matrix.postRotate(180);
6857 matrix.postTranslate(left, bottom);
6858 fade.setLocalMatrix(matrix);
6859 canvas.drawRect(left, bottom - length, right, bottom, p);
6860 }
6861
6862 if (drawLeft) {
6863 matrix.setScale(1, fadeHeight * leftFadeStrength);
6864 matrix.postRotate(-90);
6865 matrix.postTranslate(left, top);
6866 fade.setLocalMatrix(matrix);
6867 canvas.drawRect(left, top, left + length, bottom, p);
6868 }
6869
6870 if (drawRight) {
6871 matrix.setScale(1, fadeHeight * rightFadeStrength);
6872 matrix.postRotate(90);
6873 matrix.postTranslate(right, top);
6874 fade.setLocalMatrix(matrix);
6875 canvas.drawRect(right - length, top, right, bottom, p);
6876 }
6877
6878 canvas.restoreToCount(saveCount);
6879
6880 // Step 6, draw decorations (scrollbars)
6881 onDrawScrollBars(canvas);
6882 }
6883
6884 /**
6885 * Override this if your view is known to always be drawn on top of a solid color background,
6886 * and needs to draw fading edges. Returning a non-zero color enables the view system to
6887 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
6888 * should be set to 0xFF.
6889 *
6890 * @see #setVerticalFadingEdgeEnabled
6891 * @see #setHorizontalFadingEdgeEnabled
6892 *
6893 * @return The known solid color background for this view, or 0 if the color may vary
6894 */
6895 public int getSolidColor() {
6896 return 0;
6897 }
6898
6899 /**
6900 * Build a human readable string representation of the specified view flags.
6901 *
6902 * @param flags the view flags to convert to a string
6903 * @return a String representing the supplied flags
6904 */
6905 private static String printFlags(int flags) {
6906 String output = "";
6907 int numFlags = 0;
6908 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
6909 output += "TAKES_FOCUS";
6910 numFlags++;
6911 }
6912
6913 switch (flags & VISIBILITY_MASK) {
6914 case INVISIBLE:
6915 if (numFlags > 0) {
6916 output += " ";
6917 }
6918 output += "INVISIBLE";
6919 // USELESS HERE numFlags++;
6920 break;
6921 case GONE:
6922 if (numFlags > 0) {
6923 output += " ";
6924 }
6925 output += "GONE";
6926 // USELESS HERE numFlags++;
6927 break;
6928 default:
6929 break;
6930 }
6931 return output;
6932 }
6933
6934 /**
6935 * Build a human readable string representation of the specified private
6936 * view flags.
6937 *
6938 * @param privateFlags the private view flags to convert to a string
6939 * @return a String representing the supplied flags
6940 */
6941 private static String printPrivateFlags(int privateFlags) {
6942 String output = "";
6943 int numFlags = 0;
6944
6945 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
6946 output += "WANTS_FOCUS";
6947 numFlags++;
6948 }
6949
6950 if ((privateFlags & FOCUSED) == FOCUSED) {
6951 if (numFlags > 0) {
6952 output += " ";
6953 }
6954 output += "FOCUSED";
6955 numFlags++;
6956 }
6957
6958 if ((privateFlags & SELECTED) == SELECTED) {
6959 if (numFlags > 0) {
6960 output += " ";
6961 }
6962 output += "SELECTED";
6963 numFlags++;
6964 }
6965
6966 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
6967 if (numFlags > 0) {
6968 output += " ";
6969 }
6970 output += "IS_ROOT_NAMESPACE";
6971 numFlags++;
6972 }
6973
6974 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
6975 if (numFlags > 0) {
6976 output += " ";
6977 }
6978 output += "HAS_BOUNDS";
6979 numFlags++;
6980 }
6981
6982 if ((privateFlags & DRAWN) == DRAWN) {
6983 if (numFlags > 0) {
6984 output += " ";
6985 }
6986 output += "DRAWN";
6987 // USELESS HERE numFlags++;
6988 }
6989 return output;
6990 }
6991
6992 /**
6993 * <p>Indicates whether or not this view's layout will be requested during
6994 * the next hierarchy layout pass.</p>
6995 *
6996 * @return true if the layout will be forced during next layout pass
6997 */
6998 public boolean isLayoutRequested() {
6999 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
7000 }
7001
7002 /**
7003 * Assign a size and position to a view and all of its
7004 * descendants
7005 *
7006 * <p>This is the second phase of the layout mechanism.
7007 * (The first is measuring). In this phase, each parent calls
7008 * layout on all of its children to position them.
7009 * This is typically done using the child measurements
7010 * that were stored in the measure pass().
7011 *
7012 * Derived classes with children should override
7013 * onLayout. In that method, they should
7014 * call layout on each of their their children.
7015 *
7016 * @param l Left position, relative to parent
7017 * @param t Top position, relative to parent
7018 * @param r Right position, relative to parent
7019 * @param b Bottom position, relative to parent
7020 */
7021 public final void layout(int l, int t, int r, int b) {
7022 boolean changed = setFrame(l, t, r, b);
7023 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
7024 if (ViewDebug.TRACE_HIERARCHY) {
7025 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
7026 }
7027
7028 onLayout(changed, l, t, r, b);
7029 mPrivateFlags &= ~LAYOUT_REQUIRED;
7030 }
7031 mPrivateFlags &= ~FORCE_LAYOUT;
7032 }
7033
7034 /**
7035 * Called from layout when this view should
7036 * assign a size and position to each of its children.
7037 *
7038 * Derived classes with children should override
7039 * this method and call layout on each of
7040 * their their children.
7041 * @param changed This is a new size or position for this view
7042 * @param left Left position, relative to parent
7043 * @param top Top position, relative to parent
7044 * @param right Right position, relative to parent
7045 * @param bottom Bottom position, relative to parent
7046 */
7047 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
7048 }
7049
7050 /**
7051 * Assign a size and position to this view.
7052 *
7053 * This is called from layout.
7054 *
7055 * @param left Left position, relative to parent
7056 * @param top Top position, relative to parent
7057 * @param right Right position, relative to parent
7058 * @param bottom Bottom position, relative to parent
7059 * @return true if the new size and position are different than the
7060 * previous ones
7061 * {@hide}
7062 */
7063 protected boolean setFrame(int left, int top, int right, int bottom) {
7064 boolean changed = false;
7065
7066 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07007067 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007068 + right + "," + bottom + ")");
7069 }
7070
7071 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
7072 changed = true;
7073
7074 // Remember our drawn bit
7075 int drawn = mPrivateFlags & DRAWN;
7076
7077 // Invalidate our old position
7078 invalidate();
7079
7080
7081 int oldWidth = mRight - mLeft;
7082 int oldHeight = mBottom - mTop;
7083
7084 mLeft = left;
7085 mTop = top;
7086 mRight = right;
7087 mBottom = bottom;
7088
7089 mPrivateFlags |= HAS_BOUNDS;
7090
7091 int newWidth = right - left;
7092 int newHeight = bottom - top;
7093
7094 if (newWidth != oldWidth || newHeight != oldHeight) {
7095 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
7096 }
7097
7098 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
7099 // If we are visible, force the DRAWN bit to on so that
7100 // this invalidate will go through (at least to our parent).
7101 // This is because someone may have invalidated this view
7102 // before this call to setFrame came in, therby clearing
7103 // the DRAWN bit.
7104 mPrivateFlags |= DRAWN;
7105 invalidate();
7106 }
7107
7108 // Reset drawn bit to original value (invalidate turns it off)
7109 mPrivateFlags |= drawn;
7110
7111 mBackgroundSizeChanged = true;
7112 }
7113 return changed;
7114 }
7115
7116 /**
7117 * Finalize inflating a view from XML. This is called as the last phase
7118 * of inflation, after all child views have been added.
7119 *
7120 * <p>Even if the subclass overrides onFinishInflate, they should always be
7121 * sure to call the super method, so that we get called.
7122 */
7123 protected void onFinishInflate() {
7124 }
7125
7126 /**
7127 * Returns the resources associated with this view.
7128 *
7129 * @return Resources object.
7130 */
7131 public Resources getResources() {
7132 return mResources;
7133 }
7134
7135 /**
7136 * Invalidates the specified Drawable.
7137 *
7138 * @param drawable the drawable to invalidate
7139 */
7140 public void invalidateDrawable(Drawable drawable) {
7141 if (verifyDrawable(drawable)) {
7142 final Rect dirty = drawable.getBounds();
7143 final int scrollX = mScrollX;
7144 final int scrollY = mScrollY;
7145
7146 invalidate(dirty.left + scrollX, dirty.top + scrollY,
7147 dirty.right + scrollX, dirty.bottom + scrollY);
7148 }
7149 }
7150
7151 /**
7152 * Schedules an action on a drawable to occur at a specified time.
7153 *
7154 * @param who the recipient of the action
7155 * @param what the action to run on the drawable
7156 * @param when the time at which the action must occur. Uses the
7157 * {@link SystemClock#uptimeMillis} timebase.
7158 */
7159 public void scheduleDrawable(Drawable who, Runnable what, long when) {
7160 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
7161 mAttachInfo.mHandler.postAtTime(what, who, when);
7162 }
7163 }
7164
7165 /**
7166 * Cancels a scheduled action on a drawable.
7167 *
7168 * @param who the recipient of the action
7169 * @param what the action to cancel
7170 */
7171 public void unscheduleDrawable(Drawable who, Runnable what) {
7172 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
7173 mAttachInfo.mHandler.removeCallbacks(what, who);
7174 }
7175 }
7176
7177 /**
7178 * Unschedule any events associated with the given Drawable. This can be
7179 * used when selecting a new Drawable into a view, so that the previous
7180 * one is completely unscheduled.
7181 *
7182 * @param who The Drawable to unschedule.
7183 *
7184 * @see #drawableStateChanged
7185 */
7186 public void unscheduleDrawable(Drawable who) {
7187 if (mAttachInfo != null) {
7188 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
7189 }
7190 }
7191
7192 /**
7193 * If your view subclass is displaying its own Drawable objects, it should
7194 * override this function and return true for any Drawable it is
7195 * displaying. This allows animations for those drawables to be
7196 * scheduled.
7197 *
7198 * <p>Be sure to call through to the super class when overriding this
7199 * function.
7200 *
7201 * @param who The Drawable to verify. Return true if it is one you are
7202 * displaying, else return the result of calling through to the
7203 * super class.
7204 *
7205 * @return boolean If true than the Drawable is being displayed in the
7206 * view; else false and it is not allowed to animate.
7207 *
7208 * @see #unscheduleDrawable
7209 * @see #drawableStateChanged
7210 */
7211 protected boolean verifyDrawable(Drawable who) {
7212 return who == mBGDrawable;
7213 }
7214
7215 /**
7216 * This function is called whenever the state of the view changes in such
7217 * a way that it impacts the state of drawables being shown.
7218 *
7219 * <p>Be sure to call through to the superclass when overriding this
7220 * function.
7221 *
7222 * @see Drawable#setState
7223 */
7224 protected void drawableStateChanged() {
7225 Drawable d = mBGDrawable;
7226 if (d != null && d.isStateful()) {
7227 d.setState(getDrawableState());
7228 }
7229 }
7230
7231 /**
7232 * Call this to force a view to update its drawable state. This will cause
7233 * drawableStateChanged to be called on this view. Views that are interested
7234 * in the new state should call getDrawableState.
7235 *
7236 * @see #drawableStateChanged
7237 * @see #getDrawableState
7238 */
7239 public void refreshDrawableState() {
7240 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
7241 drawableStateChanged();
7242
7243 ViewParent parent = mParent;
7244 if (parent != null) {
7245 parent.childDrawableStateChanged(this);
7246 }
7247 }
7248
7249 /**
7250 * Return an array of resource IDs of the drawable states representing the
7251 * current state of the view.
7252 *
7253 * @return The current drawable state
7254 *
7255 * @see Drawable#setState
7256 * @see #drawableStateChanged
7257 * @see #onCreateDrawableState
7258 */
7259 public final int[] getDrawableState() {
7260 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
7261 return mDrawableState;
7262 } else {
7263 mDrawableState = onCreateDrawableState(0);
7264 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
7265 return mDrawableState;
7266 }
7267 }
7268
7269 /**
7270 * Generate the new {@link android.graphics.drawable.Drawable} state for
7271 * this view. This is called by the view
7272 * system when the cached Drawable state is determined to be invalid. To
7273 * retrieve the current state, you should use {@link #getDrawableState}.
7274 *
7275 * @param extraSpace if non-zero, this is the number of extra entries you
7276 * would like in the returned array in which you can place your own
7277 * states.
7278 *
7279 * @return Returns an array holding the current {@link Drawable} state of
7280 * the view.
7281 *
7282 * @see #mergeDrawableStates
7283 */
7284 protected int[] onCreateDrawableState(int extraSpace) {
7285 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
7286 mParent instanceof View) {
7287 return ((View) mParent).onCreateDrawableState(extraSpace);
7288 }
7289
7290 int[] drawableState;
7291
7292 int privateFlags = mPrivateFlags;
7293
7294 int viewStateIndex = (((privateFlags & PRESSED) != 0) ? 1 : 0);
7295
7296 viewStateIndex = (viewStateIndex << 1)
7297 + (((mViewFlags & ENABLED_MASK) == ENABLED) ? 1 : 0);
7298
7299 viewStateIndex = (viewStateIndex << 1) + (isFocused() ? 1 : 0);
7300
7301 viewStateIndex = (viewStateIndex << 1)
7302 + (((privateFlags & SELECTED) != 0) ? 1 : 0);
7303
7304 final boolean hasWindowFocus = hasWindowFocus();
7305 viewStateIndex = (viewStateIndex << 1) + (hasWindowFocus ? 1 : 0);
7306
7307 drawableState = VIEW_STATE_SETS[viewStateIndex];
7308
7309 //noinspection ConstantIfStatement
7310 if (false) {
7311 Log.i("View", "drawableStateIndex=" + viewStateIndex);
7312 Log.i("View", toString()
7313 + " pressed=" + ((privateFlags & PRESSED) != 0)
7314 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
7315 + " fo=" + hasFocus()
7316 + " sl=" + ((privateFlags & SELECTED) != 0)
7317 + " wf=" + hasWindowFocus
7318 + ": " + Arrays.toString(drawableState));
7319 }
7320
7321 if (extraSpace == 0) {
7322 return drawableState;
7323 }
7324
7325 final int[] fullState;
7326 if (drawableState != null) {
7327 fullState = new int[drawableState.length + extraSpace];
7328 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
7329 } else {
7330 fullState = new int[extraSpace];
7331 }
7332
7333 return fullState;
7334 }
7335
7336 /**
7337 * Merge your own state values in <var>additionalState</var> into the base
7338 * state values <var>baseState</var> that were returned by
7339 * {@link #onCreateDrawableState}.
7340 *
7341 * @param baseState The base state values returned by
7342 * {@link #onCreateDrawableState}, which will be modified to also hold your
7343 * own additional state values.
7344 *
7345 * @param additionalState The additional state values you would like
7346 * added to <var>baseState</var>; this array is not modified.
7347 *
7348 * @return As a convenience, the <var>baseState</var> array you originally
7349 * passed into the function is returned.
7350 *
7351 * @see #onCreateDrawableState
7352 */
7353 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
7354 final int N = baseState.length;
7355 int i = N - 1;
7356 while (i >= 0 && baseState[i] == 0) {
7357 i--;
7358 }
7359 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
7360 return baseState;
7361 }
7362
7363 /**
7364 * Sets the background color for this view.
7365 * @param color the color of the background
7366 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00007367 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007368 public void setBackgroundColor(int color) {
7369 setBackgroundDrawable(new ColorDrawable(color));
7370 }
7371
7372 /**
7373 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07007374 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007375 * @param resid The identifier of the resource.
7376 * @attr ref android.R.styleable#View_background
7377 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00007378 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007379 public void setBackgroundResource(int resid) {
7380 if (resid != 0 && resid == mBackgroundResource) {
7381 return;
7382 }
7383
7384 Drawable d= null;
7385 if (resid != 0) {
7386 d = mResources.getDrawable(resid);
7387 }
7388 setBackgroundDrawable(d);
7389
7390 mBackgroundResource = resid;
7391 }
7392
7393 /**
7394 * Set the background to a given Drawable, or remove the background. If the
7395 * background has padding, this View's padding is set to the background's
7396 * padding. However, when a background is removed, this View's padding isn't
7397 * touched. If setting the padding is desired, please use
7398 * {@link #setPadding(int, int, int, int)}.
7399 *
7400 * @param d The Drawable to use as the background, or null to remove the
7401 * background
7402 */
7403 public void setBackgroundDrawable(Drawable d) {
7404 boolean requestLayout = false;
7405
7406 mBackgroundResource = 0;
7407
7408 /*
7409 * Regardless of whether we're setting a new background or not, we want
7410 * to clear the previous drawable.
7411 */
7412 if (mBGDrawable != null) {
7413 mBGDrawable.setCallback(null);
7414 unscheduleDrawable(mBGDrawable);
7415 }
7416
7417 if (d != null) {
7418 Rect padding = sThreadLocal.get();
7419 if (padding == null) {
7420 padding = new Rect();
7421 sThreadLocal.set(padding);
7422 }
7423 if (d.getPadding(padding)) {
7424 setPadding(padding.left, padding.top, padding.right, padding.bottom);
7425 }
7426
7427 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
7428 // if it has a different minimum size, we should layout again
7429 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
7430 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
7431 requestLayout = true;
7432 }
7433
7434 d.setCallback(this);
7435 if (d.isStateful()) {
7436 d.setState(getDrawableState());
7437 }
7438 d.setVisible(getVisibility() == VISIBLE, false);
7439 mBGDrawable = d;
7440
7441 if ((mPrivateFlags & SKIP_DRAW) != 0) {
7442 mPrivateFlags &= ~SKIP_DRAW;
7443 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
7444 requestLayout = true;
7445 }
7446 } else {
7447 /* Remove the background */
7448 mBGDrawable = null;
7449
7450 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
7451 /*
7452 * This view ONLY drew the background before and we're removing
7453 * the background, so now it won't draw anything
7454 * (hence we SKIP_DRAW)
7455 */
7456 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
7457 mPrivateFlags |= SKIP_DRAW;
7458 }
7459
7460 /*
7461 * When the background is set, we try to apply its padding to this
7462 * View. When the background is removed, we don't touch this View's
7463 * padding. This is noted in the Javadocs. Hence, we don't need to
7464 * requestLayout(), the invalidate() below is sufficient.
7465 */
7466
7467 // The old background's minimum size could have affected this
7468 // View's layout, so let's requestLayout
7469 requestLayout = true;
7470 }
7471
Romain Guy8f1344f52009-05-15 16:03:59 -07007472 computeOpaqueFlags();
7473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474 if (requestLayout) {
7475 requestLayout();
7476 }
7477
7478 mBackgroundSizeChanged = true;
7479 invalidate();
7480 }
7481
7482 /**
7483 * Gets the background drawable
7484 * @return The drawable used as the background for this view, if any.
7485 */
7486 public Drawable getBackground() {
7487 return mBGDrawable;
7488 }
7489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007490 /**
7491 * Sets the padding. The view may add on the space required to display
7492 * the scrollbars, depending on the style and visibility of the scrollbars.
7493 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
7494 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
7495 * from the values set in this call.
7496 *
7497 * @attr ref android.R.styleable#View_padding
7498 * @attr ref android.R.styleable#View_paddingBottom
7499 * @attr ref android.R.styleable#View_paddingLeft
7500 * @attr ref android.R.styleable#View_paddingRight
7501 * @attr ref android.R.styleable#View_paddingTop
7502 * @param left the left padding in pixels
7503 * @param top the top padding in pixels
7504 * @param right the right padding in pixels
7505 * @param bottom the bottom padding in pixels
7506 */
7507 public void setPadding(int left, int top, int right, int bottom) {
7508 boolean changed = false;
7509
7510 mUserPaddingRight = right;
7511 mUserPaddingBottom = bottom;
7512
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007513 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07007514
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007515 // Common case is there are no scroll bars.
7516 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
7517 // TODO: Deal with RTL languages to adjust left padding instead of right.
7518 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
7519 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
7520 ? 0 : getVerticalScrollbarWidth();
7521 }
7522 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
7523 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
7524 ? 0 : getHorizontalScrollbarHeight();
7525 }
7526 }
Romain Guy8506ab42009-06-11 17:35:47 -07007527
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007528 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007529 changed = true;
7530 mPaddingLeft = left;
7531 }
7532 if (mPaddingTop != top) {
7533 changed = true;
7534 mPaddingTop = top;
7535 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007536 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007537 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007538 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007540 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007541 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007542 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007543 }
7544
7545 if (changed) {
7546 requestLayout();
7547 }
7548 }
7549
7550 /**
7551 * Returns the top padding of this view.
7552 *
7553 * @return the top padding in pixels
7554 */
7555 public int getPaddingTop() {
7556 return mPaddingTop;
7557 }
7558
7559 /**
7560 * Returns the bottom padding of this view. If there are inset and enabled
7561 * scrollbars, this value may include the space required to display the
7562 * scrollbars as well.
7563 *
7564 * @return the bottom padding in pixels
7565 */
7566 public int getPaddingBottom() {
7567 return mPaddingBottom;
7568 }
7569
7570 /**
7571 * Returns the left padding of this view. If there are inset and enabled
7572 * scrollbars, this value may include the space required to display the
7573 * scrollbars as well.
7574 *
7575 * @return the left padding in pixels
7576 */
7577 public int getPaddingLeft() {
7578 return mPaddingLeft;
7579 }
7580
7581 /**
7582 * Returns the right padding of this view. If there are inset and enabled
7583 * scrollbars, this value may include the space required to display the
7584 * scrollbars as well.
7585 *
7586 * @return the right padding in pixels
7587 */
7588 public int getPaddingRight() {
7589 return mPaddingRight;
7590 }
7591
7592 /**
7593 * Changes the selection state of this view. A view can be selected or not.
7594 * Note that selection is not the same as focus. Views are typically
7595 * selected in the context of an AdapterView like ListView or GridView;
7596 * the selected view is the view that is highlighted.
7597 *
7598 * @param selected true if the view must be selected, false otherwise
7599 */
7600 public void setSelected(boolean selected) {
7601 if (((mPrivateFlags & SELECTED) != 0) != selected) {
7602 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07007603 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007604 invalidate();
7605 refreshDrawableState();
7606 dispatchSetSelected(selected);
7607 }
7608 }
7609
7610 /**
7611 * Dispatch setSelected to all of this View's children.
7612 *
7613 * @see #setSelected(boolean)
7614 *
7615 * @param selected The new selected state
7616 */
7617 protected void dispatchSetSelected(boolean selected) {
7618 }
7619
7620 /**
7621 * Indicates the selection state of this view.
7622 *
7623 * @return true if the view is selected, false otherwise
7624 */
7625 @ViewDebug.ExportedProperty
7626 public boolean isSelected() {
7627 return (mPrivateFlags & SELECTED) != 0;
7628 }
7629
7630 /**
7631 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
7632 * observer can be used to get notifications when global events, like
7633 * layout, happen.
7634 *
7635 * The returned ViewTreeObserver observer is not guaranteed to remain
7636 * valid for the lifetime of this View. If the caller of this method keeps
7637 * a long-lived reference to ViewTreeObserver, it should always check for
7638 * the return value of {@link ViewTreeObserver#isAlive()}.
7639 *
7640 * @return The ViewTreeObserver for this view's hierarchy.
7641 */
7642 public ViewTreeObserver getViewTreeObserver() {
7643 if (mAttachInfo != null) {
7644 return mAttachInfo.mTreeObserver;
7645 }
7646 if (mFloatingTreeObserver == null) {
7647 mFloatingTreeObserver = new ViewTreeObserver();
7648 }
7649 return mFloatingTreeObserver;
7650 }
7651
7652 /**
7653 * <p>Finds the topmost view in the current view hierarchy.</p>
7654 *
7655 * @return the topmost view containing this view
7656 */
7657 public View getRootView() {
7658 if (mAttachInfo != null) {
7659 final View v = mAttachInfo.mRootView;
7660 if (v != null) {
7661 return v;
7662 }
7663 }
Romain Guy8506ab42009-06-11 17:35:47 -07007664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007665 View parent = this;
7666
7667 while (parent.mParent != null && parent.mParent instanceof View) {
7668 parent = (View) parent.mParent;
7669 }
7670
7671 return parent;
7672 }
7673
7674 /**
7675 * <p>Computes the coordinates of this view on the screen. The argument
7676 * must be an array of two integers. After the method returns, the array
7677 * contains the x and y location in that order.</p>
7678 *
7679 * @param location an array of two integers in which to hold the coordinates
7680 */
7681 public void getLocationOnScreen(int[] location) {
7682 getLocationInWindow(location);
7683
7684 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07007685 if (info != null) {
7686 location[0] += info.mWindowLeft;
7687 location[1] += info.mWindowTop;
7688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689 }
7690
7691 /**
7692 * <p>Computes the coordinates of this view in its window. The argument
7693 * must be an array of two integers. After the method returns, the array
7694 * contains the x and y location in that order.</p>
7695 *
7696 * @param location an array of two integers in which to hold the coordinates
7697 */
7698 public void getLocationInWindow(int[] location) {
7699 if (location == null || location.length < 2) {
7700 throw new IllegalArgumentException("location must be an array of "
7701 + "two integers");
7702 }
7703
7704 location[0] = mLeft;
7705 location[1] = mTop;
7706
7707 ViewParent viewParent = mParent;
7708 while (viewParent instanceof View) {
7709 final View view = (View)viewParent;
7710 location[0] += view.mLeft - view.mScrollX;
7711 location[1] += view.mTop - view.mScrollY;
7712 viewParent = view.mParent;
7713 }
Romain Guy8506ab42009-06-11 17:35:47 -07007714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 if (viewParent instanceof ViewRoot) {
7716 // *cough*
7717 final ViewRoot vr = (ViewRoot)viewParent;
7718 location[1] -= vr.mCurScrollY;
7719 }
7720 }
7721
7722 /**
7723 * {@hide}
7724 * @param id the id of the view to be found
7725 * @return the view of the specified id, null if cannot be found
7726 */
7727 protected View findViewTraversal(int id) {
7728 if (id == mID) {
7729 return this;
7730 }
7731 return null;
7732 }
7733
7734 /**
7735 * {@hide}
7736 * @param tag the tag of the view to be found
7737 * @return the view of specified tag, null if cannot be found
7738 */
7739 protected View findViewWithTagTraversal(Object tag) {
7740 if (tag != null && tag.equals(mTag)) {
7741 return this;
7742 }
7743 return null;
7744 }
7745
7746 /**
7747 * Look for a child view with the given id. If this view has the given
7748 * id, return this view.
7749 *
7750 * @param id The id to search for.
7751 * @return The view that has the given id in the hierarchy or null
7752 */
7753 public final View findViewById(int id) {
7754 if (id < 0) {
7755 return null;
7756 }
7757 return findViewTraversal(id);
7758 }
7759
7760 /**
7761 * Look for a child view with the given tag. If this view has the given
7762 * tag, return this view.
7763 *
7764 * @param tag The tag to search for, using "tag.equals(getTag())".
7765 * @return The View that has the given tag in the hierarchy or null
7766 */
7767 public final View findViewWithTag(Object tag) {
7768 if (tag == null) {
7769 return null;
7770 }
7771 return findViewWithTagTraversal(tag);
7772 }
7773
7774 /**
7775 * Sets the identifier for this view. The identifier does not have to be
7776 * unique in this view's hierarchy. The identifier should be a positive
7777 * number.
7778 *
7779 * @see #NO_ID
7780 * @see #getId
7781 * @see #findViewById
7782 *
7783 * @param id a number used to identify the view
7784 *
7785 * @attr ref android.R.styleable#View_id
7786 */
7787 public void setId(int id) {
7788 mID = id;
7789 }
7790
7791 /**
7792 * {@hide}
7793 *
7794 * @param isRoot true if the view belongs to the root namespace, false
7795 * otherwise
7796 */
7797 public void setIsRootNamespace(boolean isRoot) {
7798 if (isRoot) {
7799 mPrivateFlags |= IS_ROOT_NAMESPACE;
7800 } else {
7801 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
7802 }
7803 }
7804
7805 /**
7806 * {@hide}
7807 *
7808 * @return true if the view belongs to the root namespace, false otherwise
7809 */
7810 public boolean isRootNamespace() {
7811 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
7812 }
7813
7814 /**
7815 * Returns this view's identifier.
7816 *
7817 * @return a positive integer used to identify the view or {@link #NO_ID}
7818 * if the view has no ID
7819 *
7820 * @see #setId
7821 * @see #findViewById
7822 * @attr ref android.R.styleable#View_id
7823 */
7824 @ViewDebug.CapturedViewProperty
7825 public int getId() {
7826 return mID;
7827 }
7828
7829 /**
7830 * Returns this view's tag.
7831 *
7832 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07007833 *
7834 * @see #setTag(Object)
7835 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 */
7837 @ViewDebug.ExportedProperty
7838 public Object getTag() {
7839 return mTag;
7840 }
7841
7842 /**
7843 * Sets the tag associated with this view. A tag can be used to mark
7844 * a view in its hierarchy and does not have to be unique within the
7845 * hierarchy. Tags can also be used to store data within a view without
7846 * resorting to another data structure.
7847 *
7848 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07007849 *
7850 * @see #getTag()
7851 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 */
7853 public void setTag(final Object tag) {
7854 mTag = tag;
7855 }
7856
7857 /**
Romain Guyd90a3312009-05-06 14:54:28 -07007858 * Returns the tag associated with this view and the specified key.
7859 *
7860 * @param key The key identifying the tag
7861 *
7862 * @return the Object stored in this view as a tag
7863 *
7864 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07007865 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07007866 */
7867 public Object getTag(int key) {
7868 SparseArray<Object> tags = null;
7869 synchronized (sTagsLock) {
7870 if (sTags != null) {
7871 tags = sTags.get(this);
7872 }
7873 }
7874
7875 if (tags != null) return tags.get(key);
7876 return null;
7877 }
7878
7879 /**
7880 * Sets a tag associated with this view and a key. A tag can be used
7881 * to mark a view in its hierarchy and does not have to be unique within
7882 * the hierarchy. Tags can also be used to store data within a view
7883 * without resorting to another data structure.
7884 *
7885 * The specified key should be an id declared in the resources of the
7886 * application to ensure it is unique. Keys identified as belonging to
7887 * the Android framework or not associated with any package will cause
7888 * an {@link IllegalArgumentException} to be thrown.
7889 *
7890 * @param key The key identifying the tag
7891 * @param tag An Object to tag the view with
7892 *
7893 * @throws IllegalArgumentException If they specified key is not valid
7894 *
7895 * @see #setTag(Object)
7896 * @see #getTag(int)
7897 */
7898 public void setTag(int key, final Object tag) {
7899 // If the package id is 0x00 or 0x01, it's either an undefined package
7900 // or a framework id
7901 if ((key >>> 24) < 2) {
7902 throw new IllegalArgumentException("The key must be an application-specific "
7903 + "resource id.");
7904 }
7905
7906 setTagInternal(this, key, tag);
7907 }
7908
7909 /**
7910 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
7911 * framework id.
7912 *
7913 * @hide
7914 */
7915 public void setTagInternal(int key, Object tag) {
7916 if ((key >>> 24) != 0x1) {
7917 throw new IllegalArgumentException("The key must be a framework-specific "
7918 + "resource id.");
7919 }
7920
Romain Guy8506ab42009-06-11 17:35:47 -07007921 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07007922 }
7923
7924 private static void setTagInternal(View view, int key, Object tag) {
7925 SparseArray<Object> tags = null;
7926 synchronized (sTagsLock) {
7927 if (sTags == null) {
7928 sTags = new WeakHashMap<View, SparseArray<Object>>();
7929 } else {
7930 tags = sTags.get(view);
7931 }
7932 }
7933
7934 if (tags == null) {
7935 tags = new SparseArray<Object>(2);
7936 synchronized (sTagsLock) {
7937 sTags.put(view, tags);
7938 }
7939 }
7940
7941 tags.put(key, tag);
7942 }
7943
7944 /**
Romain Guy13922e02009-05-12 17:56:14 -07007945 * @param consistency The type of consistency. See ViewDebug for more information.
7946 *
7947 * @hide
7948 */
7949 protected boolean dispatchConsistencyCheck(int consistency) {
7950 return onConsistencyCheck(consistency);
7951 }
7952
7953 /**
7954 * Method that subclasses should implement to check their consistency. The type of
7955 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07007956 *
Romain Guy13922e02009-05-12 17:56:14 -07007957 * @param consistency The type of consistency. See ViewDebug for more information.
7958 *
7959 * @throws IllegalStateException if the view is in an inconsistent state.
7960 *
7961 * @hide
7962 */
7963 protected boolean onConsistencyCheck(int consistency) {
7964 boolean result = true;
7965
7966 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
7967 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
7968
7969 if (checkLayout) {
7970 if (getParent() == null) {
7971 result = false;
7972 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
7973 "View " + this + " does not have a parent.");
7974 }
7975
7976 if (mAttachInfo == null) {
7977 result = false;
7978 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
7979 "View " + this + " is not attached to a window.");
7980 }
7981 }
7982
7983 if (checkDrawing) {
7984 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
7985 // from their draw() method
7986
7987 if ((mPrivateFlags & DRAWN) != DRAWN &&
7988 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
7989 result = false;
7990 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
7991 "View " + this + " was invalidated but its drawing cache is valid.");
7992 }
7993 }
7994
7995 return result;
7996 }
7997
7998 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007999 * Prints information about this view in the log output, with the tag
8000 * {@link #VIEW_LOG_TAG}.
8001 *
8002 * @hide
8003 */
8004 public void debug() {
8005 debug(0);
8006 }
8007
8008 /**
8009 * Prints information about this view in the log output, with the tag
8010 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
8011 * indentation defined by the <code>depth</code>.
8012 *
8013 * @param depth the indentation level
8014 *
8015 * @hide
8016 */
8017 protected void debug(int depth) {
8018 String output = debugIndent(depth - 1);
8019
8020 output += "+ " + this;
8021 int id = getId();
8022 if (id != -1) {
8023 output += " (id=" + id + ")";
8024 }
8025 Object tag = getTag();
8026 if (tag != null) {
8027 output += " (tag=" + tag + ")";
8028 }
8029 Log.d(VIEW_LOG_TAG, output);
8030
8031 if ((mPrivateFlags & FOCUSED) != 0) {
8032 output = debugIndent(depth) + " FOCUSED";
8033 Log.d(VIEW_LOG_TAG, output);
8034 }
8035
8036 output = debugIndent(depth);
8037 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
8038 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
8039 + "} ";
8040 Log.d(VIEW_LOG_TAG, output);
8041
8042 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
8043 || mPaddingBottom != 0) {
8044 output = debugIndent(depth);
8045 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
8046 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
8047 Log.d(VIEW_LOG_TAG, output);
8048 }
8049
8050 output = debugIndent(depth);
8051 output += "mMeasureWidth=" + mMeasuredWidth +
8052 " mMeasureHeight=" + mMeasuredHeight;
8053 Log.d(VIEW_LOG_TAG, output);
8054
8055 output = debugIndent(depth);
8056 if (mLayoutParams == null) {
8057 output += "BAD! no layout params";
8058 } else {
8059 output = mLayoutParams.debug(output);
8060 }
8061 Log.d(VIEW_LOG_TAG, output);
8062
8063 output = debugIndent(depth);
8064 output += "flags={";
8065 output += View.printFlags(mViewFlags);
8066 output += "}";
8067 Log.d(VIEW_LOG_TAG, output);
8068
8069 output = debugIndent(depth);
8070 output += "privateFlags={";
8071 output += View.printPrivateFlags(mPrivateFlags);
8072 output += "}";
8073 Log.d(VIEW_LOG_TAG, output);
8074 }
8075
8076 /**
8077 * Creates an string of whitespaces used for indentation.
8078 *
8079 * @param depth the indentation level
8080 * @return a String containing (depth * 2 + 3) * 2 white spaces
8081 *
8082 * @hide
8083 */
8084 protected static String debugIndent(int depth) {
8085 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
8086 for (int i = 0; i < (depth * 2) + 3; i++) {
8087 spaces.append(' ').append(' ');
8088 }
8089 return spaces.toString();
8090 }
8091
8092 /**
8093 * <p>Return the offset of the widget's text baseline from the widget's top
8094 * boundary. If this widget does not support baseline alignment, this
8095 * method returns -1. </p>
8096 *
8097 * @return the offset of the baseline within the widget's bounds or -1
8098 * if baseline alignment is not supported
8099 */
8100 @ViewDebug.ExportedProperty
8101 public int getBaseline() {
8102 return -1;
8103 }
8104
8105 /**
8106 * Call this when something has changed which has invalidated the
8107 * layout of this view. This will schedule a layout pass of the view
8108 * tree.
8109 */
8110 public void requestLayout() {
8111 if (ViewDebug.TRACE_HIERARCHY) {
8112 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
8113 }
8114
8115 mPrivateFlags |= FORCE_LAYOUT;
8116
8117 if (mParent != null && !mParent.isLayoutRequested()) {
8118 mParent.requestLayout();
8119 }
8120 }
8121
8122 /**
8123 * Forces this view to be laid out during the next layout pass.
8124 * This method does not call requestLayout() or forceLayout()
8125 * on the parent.
8126 */
8127 public void forceLayout() {
8128 mPrivateFlags |= FORCE_LAYOUT;
8129 }
8130
8131 /**
8132 * <p>
8133 * This is called to find out how big a view should be. The parent
8134 * supplies constraint information in the width and height parameters.
8135 * </p>
8136 *
8137 * <p>
8138 * The actual mesurement work of a view is performed in
8139 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
8140 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
8141 * </p>
8142 *
8143 *
8144 * @param widthMeasureSpec Horizontal space requirements as imposed by the
8145 * parent
8146 * @param heightMeasureSpec Vertical space requirements as imposed by the
8147 * parent
8148 *
8149 * @see #onMeasure(int, int)
8150 */
8151 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
8152 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
8153 widthMeasureSpec != mOldWidthMeasureSpec ||
8154 heightMeasureSpec != mOldHeightMeasureSpec) {
8155
8156 // first clears the measured dimension flag
8157 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
8158
8159 if (ViewDebug.TRACE_HIERARCHY) {
8160 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
8161 }
8162
8163 // measure ourselves, this should set the measured dimension flag back
8164 onMeasure(widthMeasureSpec, heightMeasureSpec);
8165
8166 // flag not set, setMeasuredDimension() was not invoked, we raise
8167 // an exception to warn the developer
8168 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
8169 throw new IllegalStateException("onMeasure() did not set the"
8170 + " measured dimension by calling"
8171 + " setMeasuredDimension()");
8172 }
8173
8174 mPrivateFlags |= LAYOUT_REQUIRED;
8175 }
8176
8177 mOldWidthMeasureSpec = widthMeasureSpec;
8178 mOldHeightMeasureSpec = heightMeasureSpec;
8179 }
8180
8181 /**
8182 * <p>
8183 * Measure the view and its content to determine the measured width and the
8184 * measured height. This method is invoked by {@link #measure(int, int)} and
8185 * should be overriden by subclasses to provide accurate and efficient
8186 * measurement of their contents.
8187 * </p>
8188 *
8189 * <p>
8190 * <strong>CONTRACT:</strong> When overriding this method, you
8191 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
8192 * measured width and height of this view. Failure to do so will trigger an
8193 * <code>IllegalStateException</code>, thrown by
8194 * {@link #measure(int, int)}. Calling the superclass'
8195 * {@link #onMeasure(int, int)} is a valid use.
8196 * </p>
8197 *
8198 * <p>
8199 * The base class implementation of measure defaults to the background size,
8200 * unless a larger size is allowed by the MeasureSpec. Subclasses should
8201 * override {@link #onMeasure(int, int)} to provide better measurements of
8202 * their content.
8203 * </p>
8204 *
8205 * <p>
8206 * If this method is overridden, it is the subclass's responsibility to make
8207 * sure the measured height and width are at least the view's minimum height
8208 * and width ({@link #getSuggestedMinimumHeight()} and
8209 * {@link #getSuggestedMinimumWidth()}).
8210 * </p>
8211 *
8212 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
8213 * The requirements are encoded with
8214 * {@link android.view.View.MeasureSpec}.
8215 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
8216 * The requirements are encoded with
8217 * {@link android.view.View.MeasureSpec}.
8218 *
8219 * @see #getMeasuredWidth()
8220 * @see #getMeasuredHeight()
8221 * @see #setMeasuredDimension(int, int)
8222 * @see #getSuggestedMinimumHeight()
8223 * @see #getSuggestedMinimumWidth()
8224 * @see android.view.View.MeasureSpec#getMode(int)
8225 * @see android.view.View.MeasureSpec#getSize(int)
8226 */
8227 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
8228 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
8229 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
8230 }
8231
8232 /**
8233 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
8234 * measured width and measured height. Failing to do so will trigger an
8235 * exception at measurement time.</p>
8236 *
8237 * @param measuredWidth the measured width of this view
8238 * @param measuredHeight the measured height of this view
8239 */
8240 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
8241 mMeasuredWidth = measuredWidth;
8242 mMeasuredHeight = measuredHeight;
8243
8244 mPrivateFlags |= MEASURED_DIMENSION_SET;
8245 }
8246
8247 /**
8248 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
8249 * Will take the desired size, unless a different size is imposed by the constraints.
8250 *
8251 * @param size How big the view wants to be
8252 * @param measureSpec Constraints imposed by the parent
8253 * @return The size this view should be.
8254 */
8255 public static int resolveSize(int size, int measureSpec) {
8256 int result = size;
8257 int specMode = MeasureSpec.getMode(measureSpec);
8258 int specSize = MeasureSpec.getSize(measureSpec);
8259 switch (specMode) {
8260 case MeasureSpec.UNSPECIFIED:
8261 result = size;
8262 break;
8263 case MeasureSpec.AT_MOST:
8264 result = Math.min(size, specSize);
8265 break;
8266 case MeasureSpec.EXACTLY:
8267 result = specSize;
8268 break;
8269 }
8270 return result;
8271 }
8272
8273 /**
8274 * Utility to return a default size. Uses the supplied size if the
8275 * MeasureSpec imposed no contraints. Will get larger if allowed
8276 * by the MeasureSpec.
8277 *
8278 * @param size Default size for this view
8279 * @param measureSpec Constraints imposed by the parent
8280 * @return The size this view should be.
8281 */
8282 public static int getDefaultSize(int size, int measureSpec) {
8283 int result = size;
8284 int specMode = MeasureSpec.getMode(measureSpec);
8285 int specSize = MeasureSpec.getSize(measureSpec);
8286
8287 switch (specMode) {
8288 case MeasureSpec.UNSPECIFIED:
8289 result = size;
8290 break;
8291 case MeasureSpec.AT_MOST:
8292 case MeasureSpec.EXACTLY:
8293 result = specSize;
8294 break;
8295 }
8296 return result;
8297 }
8298
8299 /**
8300 * Returns the suggested minimum height that the view should use. This
8301 * returns the maximum of the view's minimum height
8302 * and the background's minimum height
8303 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
8304 * <p>
8305 * When being used in {@link #onMeasure(int, int)}, the caller should still
8306 * ensure the returned height is within the requirements of the parent.
8307 *
8308 * @return The suggested minimum height of the view.
8309 */
8310 protected int getSuggestedMinimumHeight() {
8311 int suggestedMinHeight = mMinHeight;
8312
8313 if (mBGDrawable != null) {
8314 final int bgMinHeight = mBGDrawable.getMinimumHeight();
8315 if (suggestedMinHeight < bgMinHeight) {
8316 suggestedMinHeight = bgMinHeight;
8317 }
8318 }
8319
8320 return suggestedMinHeight;
8321 }
8322
8323 /**
8324 * Returns the suggested minimum width that the view should use. This
8325 * returns the maximum of the view's minimum width)
8326 * and the background's minimum width
8327 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
8328 * <p>
8329 * When being used in {@link #onMeasure(int, int)}, the caller should still
8330 * ensure the returned width is within the requirements of the parent.
8331 *
8332 * @return The suggested minimum width of the view.
8333 */
8334 protected int getSuggestedMinimumWidth() {
8335 int suggestedMinWidth = mMinWidth;
8336
8337 if (mBGDrawable != null) {
8338 final int bgMinWidth = mBGDrawable.getMinimumWidth();
8339 if (suggestedMinWidth < bgMinWidth) {
8340 suggestedMinWidth = bgMinWidth;
8341 }
8342 }
8343
8344 return suggestedMinWidth;
8345 }
8346
8347 /**
8348 * Sets the minimum height of the view. It is not guaranteed the view will
8349 * be able to achieve this minimum height (for example, if its parent layout
8350 * constrains it with less available height).
8351 *
8352 * @param minHeight The minimum height the view will try to be.
8353 */
8354 public void setMinimumHeight(int minHeight) {
8355 mMinHeight = minHeight;
8356 }
8357
8358 /**
8359 * Sets the minimum width of the view. It is not guaranteed the view will
8360 * be able to achieve this minimum width (for example, if its parent layout
8361 * constrains it with less available width).
8362 *
8363 * @param minWidth The minimum width the view will try to be.
8364 */
8365 public void setMinimumWidth(int minWidth) {
8366 mMinWidth = minWidth;
8367 }
8368
8369 /**
8370 * Get the animation currently associated with this view.
8371 *
8372 * @return The animation that is currently playing or
8373 * scheduled to play for this view.
8374 */
8375 public Animation getAnimation() {
8376 return mCurrentAnimation;
8377 }
8378
8379 /**
8380 * Start the specified animation now.
8381 *
8382 * @param animation the animation to start now
8383 */
8384 public void startAnimation(Animation animation) {
8385 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
8386 setAnimation(animation);
8387 invalidate();
8388 }
8389
8390 /**
8391 * Cancels any animations for this view.
8392 */
8393 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08008394 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08008395 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08008396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008397 mCurrentAnimation = null;
8398 }
8399
8400 /**
8401 * Sets the next animation to play for this view.
8402 * If you want the animation to play immediately, use
8403 * startAnimation. This method provides allows fine-grained
8404 * control over the start time and invalidation, but you
8405 * must make sure that 1) the animation has a start time set, and
8406 * 2) the view will be invalidated when the animation is supposed to
8407 * start.
8408 *
8409 * @param animation The next animation, or null.
8410 */
8411 public void setAnimation(Animation animation) {
8412 mCurrentAnimation = animation;
8413 if (animation != null) {
8414 animation.reset();
8415 }
8416 }
8417
8418 /**
8419 * Invoked by a parent ViewGroup to notify the start of the animation
8420 * currently associated with this view. If you override this method,
8421 * always call super.onAnimationStart();
8422 *
8423 * @see #setAnimation(android.view.animation.Animation)
8424 * @see #getAnimation()
8425 */
8426 protected void onAnimationStart() {
8427 mPrivateFlags |= ANIMATION_STARTED;
8428 }
8429
8430 /**
8431 * Invoked by a parent ViewGroup to notify the end of the animation
8432 * currently associated with this view. If you override this method,
8433 * always call super.onAnimationEnd();
8434 *
8435 * @see #setAnimation(android.view.animation.Animation)
8436 * @see #getAnimation()
8437 */
8438 protected void onAnimationEnd() {
8439 mPrivateFlags &= ~ANIMATION_STARTED;
8440 }
8441
8442 /**
8443 * Invoked if there is a Transform that involves alpha. Subclass that can
8444 * draw themselves with the specified alpha should return true, and then
8445 * respect that alpha when their onDraw() is called. If this returns false
8446 * then the view may be redirected to draw into an offscreen buffer to
8447 * fulfill the request, which will look fine, but may be slower than if the
8448 * subclass handles it internally. The default implementation returns false.
8449 *
8450 * @param alpha The alpha (0..255) to apply to the view's drawing
8451 * @return true if the view can draw with the specified alpha.
8452 */
8453 protected boolean onSetAlpha(int alpha) {
8454 return false;
8455 }
8456
8457 /**
8458 * This is used by the RootView to perform an optimization when
8459 * the view hierarchy contains one or several SurfaceView.
8460 * SurfaceView is always considered transparent, but its children are not,
8461 * therefore all View objects remove themselves from the global transparent
8462 * region (passed as a parameter to this function).
8463 *
8464 * @param region The transparent region for this ViewRoot (window).
8465 *
8466 * @return Returns true if the effective visibility of the view at this
8467 * point is opaque, regardless of the transparent region; returns false
8468 * if it is possible for underlying windows to be seen behind the view.
8469 *
8470 * {@hide}
8471 */
8472 public boolean gatherTransparentRegion(Region region) {
8473 final AttachInfo attachInfo = mAttachInfo;
8474 if (region != null && attachInfo != null) {
8475 final int pflags = mPrivateFlags;
8476 if ((pflags & SKIP_DRAW) == 0) {
8477 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
8478 // remove it from the transparent region.
8479 final int[] location = attachInfo.mTransparentLocation;
8480 getLocationInWindow(location);
8481 region.op(location[0], location[1], location[0] + mRight - mLeft,
8482 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
8483 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
8484 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
8485 // exists, so we remove the background drawable's non-transparent
8486 // parts from this transparent region.
8487 applyDrawableToTransparentRegion(mBGDrawable, region);
8488 }
8489 }
8490 return true;
8491 }
8492
8493 /**
8494 * Play a sound effect for this view.
8495 *
8496 * <p>The framework will play sound effects for some built in actions, such as
8497 * clicking, but you may wish to play these effects in your widget,
8498 * for instance, for internal navigation.
8499 *
8500 * <p>The sound effect will only be played if sound effects are enabled by the user, and
8501 * {@link #isSoundEffectsEnabled()} is true.
8502 *
8503 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
8504 */
8505 public void playSoundEffect(int soundConstant) {
8506 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
8507 return;
8508 }
8509 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
8510 }
8511
8512 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008513 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07008514 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008515 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516 *
8517 * <p>The framework will provide haptic feedback for some built in actions,
8518 * such as long presses, but you may wish to provide feedback for your
8519 * own widget.
8520 *
8521 * <p>The feedback will only be performed if
8522 * {@link #isHapticFeedbackEnabled()} is true.
8523 *
8524 * @param feedbackConstant One of the constants defined in
8525 * {@link HapticFeedbackConstants}
8526 */
8527 public boolean performHapticFeedback(int feedbackConstant) {
8528 return performHapticFeedback(feedbackConstant, 0);
8529 }
8530
8531 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008532 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07008533 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008534 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008535 *
8536 * @param feedbackConstant One of the constants defined in
8537 * {@link HapticFeedbackConstants}
8538 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
8539 */
8540 public boolean performHapticFeedback(int feedbackConstant, int flags) {
8541 if (mAttachInfo == null) {
8542 return false;
8543 }
8544 if ((flags&HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
8545 && !isHapticFeedbackEnabled()) {
8546 return false;
8547 }
8548 return mAttachInfo.mRootCallbacks.performHapticFeedback(
8549 feedbackConstant,
8550 (flags&HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
8551 }
8552
8553 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -07008554 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
8555 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -07008556 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -07008557 */
8558 public void onCloseSystemDialogs(String reason) {
8559 }
8560
8561 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008562 * Given a Drawable whose bounds have been set to draw into this view,
8563 * update a Region being computed for {@link #gatherTransparentRegion} so
8564 * that any non-transparent parts of the Drawable are removed from the
8565 * given transparent region.
8566 *
8567 * @param dr The Drawable whose transparency is to be applied to the region.
8568 * @param region A Region holding the current transparency information,
8569 * where any parts of the region that are set are considered to be
8570 * transparent. On return, this region will be modified to have the
8571 * transparency information reduced by the corresponding parts of the
8572 * Drawable that are not transparent.
8573 * {@hide}
8574 */
8575 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
8576 if (DBG) {
8577 Log.i("View", "Getting transparent region for: " + this);
8578 }
8579 final Region r = dr.getTransparentRegion();
8580 final Rect db = dr.getBounds();
8581 final AttachInfo attachInfo = mAttachInfo;
8582 if (r != null && attachInfo != null) {
8583 final int w = getRight()-getLeft();
8584 final int h = getBottom()-getTop();
8585 if (db.left > 0) {
8586 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
8587 r.op(0, 0, db.left, h, Region.Op.UNION);
8588 }
8589 if (db.right < w) {
8590 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
8591 r.op(db.right, 0, w, h, Region.Op.UNION);
8592 }
8593 if (db.top > 0) {
8594 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
8595 r.op(0, 0, w, db.top, Region.Op.UNION);
8596 }
8597 if (db.bottom < h) {
8598 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
8599 r.op(0, db.bottom, w, h, Region.Op.UNION);
8600 }
8601 final int[] location = attachInfo.mTransparentLocation;
8602 getLocationInWindow(location);
8603 r.translate(location[0], location[1]);
8604 region.op(r, Region.Op.INTERSECT);
8605 } else {
8606 region.op(db, Region.Op.DIFFERENCE);
8607 }
8608 }
8609
Adam Powelle14579b2009-12-16 18:39:52 -08008610 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 mHasPerformedLongPress = false;
8612
8613 if (mPendingCheckForLongPress == null) {
8614 mPendingCheckForLongPress = new CheckForLongPress();
8615 }
8616 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -08008617 postDelayed(mPendingCheckForLongPress,
8618 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008619 }
8620
8621 private static int[] stateSetUnion(final int[] stateSet1,
8622 final int[] stateSet2) {
8623 final int stateSet1Length = stateSet1.length;
8624 final int stateSet2Length = stateSet2.length;
8625 final int[] newSet = new int[stateSet1Length + stateSet2Length];
8626 int k = 0;
8627 int i = 0;
8628 int j = 0;
8629 // This is a merge of the two input state sets and assumes that the
8630 // input sets are sorted by the order imposed by ViewDrawableStates.
8631 for (int viewState : R.styleable.ViewDrawableStates) {
8632 if (i < stateSet1Length && stateSet1[i] == viewState) {
8633 newSet[k++] = viewState;
8634 i++;
8635 } else if (j < stateSet2Length && stateSet2[j] == viewState) {
8636 newSet[k++] = viewState;
8637 j++;
8638 }
8639 if (k > 1) {
8640 assert(newSet[k - 1] > newSet[k - 2]);
8641 }
8642 }
8643 return newSet;
8644 }
8645
8646 /**
8647 * Inflate a view from an XML resource. This convenience method wraps the {@link
8648 * LayoutInflater} class, which provides a full range of options for view inflation.
8649 *
8650 * @param context The Context object for your activity or application.
8651 * @param resource The resource ID to inflate
8652 * @param root A view group that will be the parent. Used to properly inflate the
8653 * layout_* parameters.
8654 * @see LayoutInflater
8655 */
8656 public static View inflate(Context context, int resource, ViewGroup root) {
8657 LayoutInflater factory = LayoutInflater.from(context);
8658 return factory.inflate(resource, root);
8659 }
Adam Powell0b8bb422010-02-08 14:30:45 -08008660
8661 /**
8662 * Scroll the view with standard behavior for scrolling beyond the normal
8663 * content boundaries. Views that call this method should override
Adam Powell4886d402010-02-12 11:32:47 -08008664 * {@link #onOverscrolled(int, int, boolean, boolean)} to respond to the
8665 * results of an overscroll operation.
Adam Powell0b8bb422010-02-08 14:30:45 -08008666 *
8667 * Views can use this method to handle any touch or fling-based scrolling.
8668 *
8669 * @param deltaX Change in X in pixels
8670 * @param deltaY Change in Y in pixels
8671 * @param scrollX Current X scroll value in pixels before applying deltaX
8672 * @param scrollY Current Y scroll value in pixels before applying deltaY
8673 * @param scrollRangeX Maximum content scroll range along the X axis
8674 * @param scrollRangeY Maximum content scroll range along the Y axis
8675 * @param maxOverscrollX Number of pixels to overscroll by in either direction
8676 * along the X axis.
8677 * @param maxOverscrollY Number of pixels to overscroll by in either direction
8678 * along the Y axis.
8679 * @return true if scrolling was clamped to an overscroll boundary along either
8680 * axis, false otherwise.
8681 */
8682 protected boolean overscrollBy(int deltaX, int deltaY,
8683 int scrollX, int scrollY,
8684 int scrollRangeX, int scrollRangeY,
8685 int maxOverscrollX, int maxOverscrollY) {
Adam Powellc9fbaab2010-02-16 17:16:19 -08008686 final int overscrollMode = mOverscrollMode;
8687 final boolean canScrollHorizontal =
8688 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
8689 final boolean canScrollVertical =
8690 computeVerticalScrollRange() > computeVerticalScrollExtent();
8691 final boolean overscrollHorizontal = overscrollMode == OVERSCROLL_ALWAYS ||
8692 (overscrollMode == OVERSCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
8693 final boolean overscrollVertical = overscrollMode == OVERSCROLL_ALWAYS ||
8694 (overscrollMode == OVERSCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
Adam Powell0b8bb422010-02-08 14:30:45 -08008695
Adam Powellc9fbaab2010-02-16 17:16:19 -08008696 int newScrollX = scrollX + deltaX;
8697 if (overscrollHorizontal) {
8698 // Scale the scroll amount if we're in the dropoff zone
8699 final int dropoffX = maxOverscrollX / 2;
8700 final int dropoffLeft = -dropoffX;
8701 final int dropoffRight = dropoffX + scrollRangeX;
8702 if ((scrollX < dropoffLeft && deltaX < 0) ||
8703 (scrollX > dropoffRight && deltaX > 0)) {
8704 newScrollX = scrollX + deltaX / 2;
8705 } else {
8706 if (newScrollX > dropoffRight && deltaX > 0) {
8707 int extra = newScrollX - dropoffRight;
8708 newScrollX = dropoffRight + extra / 2;
8709 } else if (newScrollX < dropoffLeft && deltaX < 0) {
8710 int extra = newScrollX - dropoffLeft;
8711 newScrollX = dropoffLeft + extra / 2;
8712 }
Adam Powell0b8bb422010-02-08 14:30:45 -08008713 }
Adam Powellc9fbaab2010-02-16 17:16:19 -08008714 } else {
8715 maxOverscrollX = 0;
Adam Powell0b8bb422010-02-08 14:30:45 -08008716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008717
Adam Powellc9fbaab2010-02-16 17:16:19 -08008718 int newScrollY = scrollY + deltaY;
8719 if (overscrollVertical) {
8720 final int dropoffY = maxOverscrollY / 2;
8721 final int dropoffTop = -dropoffY;
8722 final int dropoffBottom = dropoffY + scrollRangeY;
8723 if ((scrollY < dropoffTop && deltaY < 0) ||
8724 (scrollY > dropoffBottom && deltaY > 0)) {
8725 newScrollY = scrollY + deltaY / 2;
8726 } else {
8727 if (newScrollY > dropoffBottom && deltaY > 0) {
8728 int extra = newScrollY - dropoffBottom;
8729 newScrollY = dropoffBottom + extra / 2;
8730 } else if (newScrollY < dropoffTop && deltaY < 0) {
8731 int extra = newScrollY - dropoffTop;
8732 newScrollY = dropoffTop + extra / 2;
8733 }
8734 }
8735 } else {
8736 maxOverscrollY = 0;
8737 }
8738
Adam Powell0b8bb422010-02-08 14:30:45 -08008739 // Clamp values if at the limits and record
8740 final int left = -maxOverscrollX;
8741 final int right = maxOverscrollX + scrollRangeX;
8742 final int top = -maxOverscrollY;
8743 final int bottom = maxOverscrollY + scrollRangeY;
8744
8745 boolean clampedX = false;
8746 if (newScrollX > right) {
8747 newScrollX = right;
8748 clampedX = true;
8749 } else if (newScrollX < left) {
8750 newScrollX = left;
8751 clampedX = true;
8752 }
8753
8754 boolean clampedY = false;
8755 if (newScrollY > bottom) {
8756 newScrollY = bottom;
8757 clampedY = true;
8758 } else if (newScrollY < top) {
8759 newScrollY = top;
8760 clampedY = true;
8761 }
8762
8763 // Bump the device with some haptic feedback if we're at the edge
8764 // and didn't start there.
Adam Powellc9fbaab2010-02-16 17:16:19 -08008765 if ((overscrollHorizontal && clampedX && scrollX != left && scrollX != right) ||
8766 (overscrollVertical && clampedY && scrollY != top && scrollY != bottom)) {
Adam Powell0b8bb422010-02-08 14:30:45 -08008767 performHapticFeedback(HapticFeedbackConstants.SCROLL_BARRIER);
8768 }
8769
8770 onOverscrolled(newScrollX, newScrollY, clampedX, clampedY);
8771
8772 return clampedX || clampedY;
8773 }
8774
8775 /**
8776 * Called by {@link #overscrollBy(int, int, int, int, int, int, int, int)} to
8777 * respond to the results of an overscroll operation.
8778 *
8779 * @param scrollX New X scroll value in pixels
8780 * @param scrollY New Y scroll value in pixels
8781 * @param clampedX True if scrollX was clamped to an overscroll boundary
8782 * @param clampedY True if scrollY was clamped to an overscroll boundary
8783 */
8784 protected void onOverscrolled(int scrollX, int scrollY,
8785 boolean clampedX, boolean clampedY) {
8786 // Intentionally empty.
8787 }
Adam Powell51c5a0c2010-03-05 10:50:38 -08008788
8789 /**
8790 * Returns the overscroll mode for this view. The result will be
8791 * one of {@link #OVERSCROLL_ALWAYS} (default), {@link #OVERSCROLL_IF_CONTENT_SCROLLS}
8792 * (allow overscrolling only if the view content is larger than the container),
8793 * or {@link #OVERSCROLL_NEVER}.
8794 *
8795 * @return This view's overscroll mode.
8796 */
8797 public int getOverscrollMode() {
8798 return mOverscrollMode;
8799 }
8800
8801 /**
8802 * Set the overscroll mode for this view. Valid overscroll modes are
8803 * {@link #OVERSCROLL_ALWAYS} (default), {@link #OVERSCROLL_IF_CONTENT_SCROLLS}
8804 * (allow overscrolling only if the view content is larger than the container),
8805 * or {@link #OVERSCROLL_NEVER}.
8806 *
8807 * Setting the overscroll mode of a view will have an effect only if the
8808 * view is capable of scrolling.
8809 *
8810 * @param overscrollMode The new overscroll mode for this view.
8811 */
8812 public void setOverscrollMode(int overscrollMode) {
8813 if (overscrollMode != OVERSCROLL_ALWAYS &&
8814 overscrollMode != OVERSCROLL_IF_CONTENT_SCROLLS &&
8815 overscrollMode != OVERSCROLL_NEVER) {
8816 throw new IllegalArgumentException("Invalid overscroll mode " + overscrollMode);
8817 }
8818 mOverscrollMode = overscrollMode;
8819 }
Romain Guya440b002010-02-24 15:57:54 -08008820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008821 /**
8822 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
8823 * Each MeasureSpec represents a requirement for either the width or the height.
8824 * A MeasureSpec is comprised of a size and a mode. There are three possible
8825 * modes:
8826 * <dl>
8827 * <dt>UNSPECIFIED</dt>
8828 * <dd>
8829 * The parent has not imposed any constraint on the child. It can be whatever size
8830 * it wants.
8831 * </dd>
8832 *
8833 * <dt>EXACTLY</dt>
8834 * <dd>
8835 * The parent has determined an exact size for the child. The child is going to be
8836 * given those bounds regardless of how big it wants to be.
8837 * </dd>
8838 *
8839 * <dt>AT_MOST</dt>
8840 * <dd>
8841 * The child can be as large as it wants up to the specified size.
8842 * </dd>
8843 * </dl>
8844 *
8845 * MeasureSpecs are implemented as ints to reduce object allocation. This class
8846 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
8847 */
8848 public static class MeasureSpec {
8849 private static final int MODE_SHIFT = 30;
8850 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
8851
8852 /**
8853 * Measure specification mode: The parent has not imposed any constraint
8854 * on the child. It can be whatever size it wants.
8855 */
8856 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
8857
8858 /**
8859 * Measure specification mode: The parent has determined an exact size
8860 * for the child. The child is going to be given those bounds regardless
8861 * of how big it wants to be.
8862 */
8863 public static final int EXACTLY = 1 << MODE_SHIFT;
8864
8865 /**
8866 * Measure specification mode: The child can be as large as it wants up
8867 * to the specified size.
8868 */
8869 public static final int AT_MOST = 2 << MODE_SHIFT;
8870
8871 /**
8872 * Creates a measure specification based on the supplied size and mode.
8873 *
8874 * The mode must always be one of the following:
8875 * <ul>
8876 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
8877 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
8878 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
8879 * </ul>
8880 *
8881 * @param size the size of the measure specification
8882 * @param mode the mode of the measure specification
8883 * @return the measure specification based on size and mode
8884 */
8885 public static int makeMeasureSpec(int size, int mode) {
8886 return size + mode;
8887 }
8888
8889 /**
8890 * Extracts the mode from the supplied measure specification.
8891 *
8892 * @param measureSpec the measure specification to extract the mode from
8893 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
8894 * {@link android.view.View.MeasureSpec#AT_MOST} or
8895 * {@link android.view.View.MeasureSpec#EXACTLY}
8896 */
8897 public static int getMode(int measureSpec) {
8898 return (measureSpec & MODE_MASK);
8899 }
8900
8901 /**
8902 * Extracts the size from the supplied measure specification.
8903 *
8904 * @param measureSpec the measure specification to extract the size from
8905 * @return the size in pixels defined in the supplied measure specification
8906 */
8907 public static int getSize(int measureSpec) {
8908 return (measureSpec & ~MODE_MASK);
8909 }
8910
8911 /**
8912 * Returns a String representation of the specified measure
8913 * specification.
8914 *
8915 * @param measureSpec the measure specification to convert to a String
8916 * @return a String with the following format: "MeasureSpec: MODE SIZE"
8917 */
8918 public static String toString(int measureSpec) {
8919 int mode = getMode(measureSpec);
8920 int size = getSize(measureSpec);
8921
8922 StringBuilder sb = new StringBuilder("MeasureSpec: ");
8923
8924 if (mode == UNSPECIFIED)
8925 sb.append("UNSPECIFIED ");
8926 else if (mode == EXACTLY)
8927 sb.append("EXACTLY ");
8928 else if (mode == AT_MOST)
8929 sb.append("AT_MOST ");
8930 else
8931 sb.append(mode).append(" ");
8932
8933 sb.append(size);
8934 return sb.toString();
8935 }
8936 }
8937
8938 class CheckForLongPress implements Runnable {
8939
8940 private int mOriginalWindowAttachCount;
8941
8942 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -07008943 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 && mOriginalWindowAttachCount == mWindowAttachCount) {
8945 if (performLongClick()) {
8946 mHasPerformedLongPress = true;
8947 }
8948 }
8949 }
8950
8951 public void rememberWindowAttachCount() {
8952 mOriginalWindowAttachCount = mWindowAttachCount;
8953 }
8954 }
Adam Powelle14579b2009-12-16 18:39:52 -08008955
8956 private final class CheckForTap implements Runnable {
8957 public void run() {
8958 mPrivateFlags &= ~PREPRESSED;
8959 mPrivateFlags |= PRESSED;
8960 refreshDrawableState();
8961 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
8962 postCheckForLongClick(ViewConfiguration.getTapTimeout());
8963 }
8964 }
8965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008966
8967 /**
8968 * Interface definition for a callback to be invoked when a key event is
8969 * dispatched to this view. The callback will be invoked before the key
8970 * event is given to the view.
8971 */
8972 public interface OnKeyListener {
8973 /**
8974 * Called when a key is dispatched to a view. This allows listeners to
8975 * get a chance to respond before the target view.
8976 *
8977 * @param v The view the key has been dispatched to.
8978 * @param keyCode The code for the physical key that was pressed
8979 * @param event The KeyEvent object containing full information about
8980 * the event.
8981 * @return True if the listener has consumed the event, false otherwise.
8982 */
8983 boolean onKey(View v, int keyCode, KeyEvent event);
8984 }
8985
8986 /**
8987 * Interface definition for a callback to be invoked when a touch event is
8988 * dispatched to this view. The callback will be invoked before the touch
8989 * event is given to the view.
8990 */
8991 public interface OnTouchListener {
8992 /**
8993 * Called when a touch event is dispatched to a view. This allows listeners to
8994 * get a chance to respond before the target view.
8995 *
8996 * @param v The view the touch event has been dispatched to.
8997 * @param event The MotionEvent object containing full information about
8998 * the event.
8999 * @return True if the listener has consumed the event, false otherwise.
9000 */
9001 boolean onTouch(View v, MotionEvent event);
9002 }
9003
9004 /**
9005 * Interface definition for a callback to be invoked when a view has been clicked and held.
9006 */
9007 public interface OnLongClickListener {
9008 /**
9009 * Called when a view has been clicked and held.
9010 *
9011 * @param v The view that was clicked and held.
9012 *
9013 * return True if the callback consumed the long click, false otherwise
9014 */
9015 boolean onLongClick(View v);
9016 }
9017
9018 /**
9019 * Interface definition for a callback to be invoked when the focus state of
9020 * a view changed.
9021 */
9022 public interface OnFocusChangeListener {
9023 /**
9024 * Called when the focus state of a view has changed.
9025 *
9026 * @param v The view whose state has changed.
9027 * @param hasFocus The new focus state of v.
9028 */
9029 void onFocusChange(View v, boolean hasFocus);
9030 }
9031
9032 /**
9033 * Interface definition for a callback to be invoked when a view is clicked.
9034 */
9035 public interface OnClickListener {
9036 /**
9037 * Called when a view has been clicked.
9038 *
9039 * @param v The view that was clicked.
9040 */
9041 void onClick(View v);
9042 }
9043
9044 /**
9045 * Interface definition for a callback to be invoked when the context menu
9046 * for this view is being built.
9047 */
9048 public interface OnCreateContextMenuListener {
9049 /**
9050 * Called when the context menu for this view is being built. It is not
9051 * safe to hold onto the menu after this method returns.
9052 *
9053 * @param menu The context menu that is being built
9054 * @param v The view for which the context menu is being built
9055 * @param menuInfo Extra information about the item for which the
9056 * context menu should be shown. This information will vary
9057 * depending on the class of v.
9058 */
9059 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
9060 }
9061
9062 private final class UnsetPressedState implements Runnable {
9063 public void run() {
9064 setPressed(false);
9065 }
9066 }
9067
9068 /**
9069 * Base class for derived classes that want to save and restore their own
9070 * state in {@link android.view.View#onSaveInstanceState()}.
9071 */
9072 public static class BaseSavedState extends AbsSavedState {
9073 /**
9074 * Constructor used when reading from a parcel. Reads the state of the superclass.
9075 *
9076 * @param source
9077 */
9078 public BaseSavedState(Parcel source) {
9079 super(source);
9080 }
9081
9082 /**
9083 * Constructor called by derived classes when creating their SavedState objects
9084 *
9085 * @param superState The state of the superclass of this view
9086 */
9087 public BaseSavedState(Parcelable superState) {
9088 super(superState);
9089 }
9090
9091 public static final Parcelable.Creator<BaseSavedState> CREATOR =
9092 new Parcelable.Creator<BaseSavedState>() {
9093 public BaseSavedState createFromParcel(Parcel in) {
9094 return new BaseSavedState(in);
9095 }
9096
9097 public BaseSavedState[] newArray(int size) {
9098 return new BaseSavedState[size];
9099 }
9100 };
9101 }
9102
9103 /**
9104 * A set of information given to a view when it is attached to its parent
9105 * window.
9106 */
9107 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108 interface Callbacks {
9109 void playSoundEffect(int effectId);
9110 boolean performHapticFeedback(int effectId, boolean always);
9111 }
9112
9113 /**
9114 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
9115 * to a Handler. This class contains the target (View) to invalidate and
9116 * the coordinates of the dirty rectangle.
9117 *
9118 * For performance purposes, this class also implements a pool of up to
9119 * POOL_LIMIT objects that get reused. This reduces memory allocations
9120 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009121 */
Romain Guyd928d682009-03-31 17:52:16 -07009122 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009123 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -07009124 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
9125 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -07009126 public InvalidateInfo newInstance() {
9127 return new InvalidateInfo();
9128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129
Romain Guyd928d682009-03-31 17:52:16 -07009130 public void onAcquired(InvalidateInfo element) {
9131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009132
Romain Guyd928d682009-03-31 17:52:16 -07009133 public void onReleased(InvalidateInfo element) {
9134 }
9135 }, POOL_LIMIT)
9136 );
9137
9138 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009139
9140 View target;
9141
9142 int left;
9143 int top;
9144 int right;
9145 int bottom;
9146
Romain Guyd928d682009-03-31 17:52:16 -07009147 public void setNextPoolable(InvalidateInfo element) {
9148 mNext = element;
9149 }
9150
9151 public InvalidateInfo getNextPoolable() {
9152 return mNext;
9153 }
9154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009155 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -07009156 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009157 }
9158
9159 void release() {
Romain Guyd928d682009-03-31 17:52:16 -07009160 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009161 }
9162 }
9163
9164 final IWindowSession mSession;
9165
9166 final IWindow mWindow;
9167
9168 final IBinder mWindowToken;
9169
9170 final Callbacks mRootCallbacks;
9171
9172 /**
9173 * The top view of the hierarchy.
9174 */
9175 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -07009176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009177 IBinder mPanelParentWindowToken;
9178 Surface mSurface;
9179
9180 /**
Romain Guy8506ab42009-06-11 17:35:47 -07009181 * Scale factor used by the compatibility mode
9182 */
9183 float mApplicationScale;
9184
9185 /**
9186 * Indicates whether the application is in compatibility mode
9187 */
9188 boolean mScalingRequired;
9189
9190 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009191 * Left position of this view's window
9192 */
9193 int mWindowLeft;
9194
9195 /**
9196 * Top position of this view's window
9197 */
9198 int mWindowTop;
9199
9200 /**
Romain Guy35b38ce2009-10-07 13:38:55 -07009201 * Indicates whether the window is translucent/transparent
9202 */
9203 boolean mTranslucentWindow;
9204
9205 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009206 * For windows that are full-screen but using insets to layout inside
9207 * of the screen decorations, these are the current insets for the
9208 * content of the window.
9209 */
9210 final Rect mContentInsets = new Rect();
9211
9212 /**
9213 * For windows that are full-screen but using insets to layout inside
9214 * of the screen decorations, these are the current insets for the
9215 * actual visible parts of the window.
9216 */
9217 final Rect mVisibleInsets = new Rect();
9218
9219 /**
9220 * The internal insets given by this window. This value is
9221 * supplied by the client (through
9222 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
9223 * be given to the window manager when changed to be used in laying
9224 * out windows behind it.
9225 */
9226 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
9227 = new ViewTreeObserver.InternalInsetsInfo();
9228
9229 /**
9230 * All views in the window's hierarchy that serve as scroll containers,
9231 * used to determine if the window can be resized or must be panned
9232 * to adjust for a soft input area.
9233 */
9234 final ArrayList<View> mScrollContainers = new ArrayList<View>();
9235
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07009236 final KeyEvent.DispatcherState mKeyDispatchState
9237 = new KeyEvent.DispatcherState();
9238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009239 /**
9240 * Indicates whether the view's window currently has the focus.
9241 */
9242 boolean mHasWindowFocus;
9243
9244 /**
9245 * The current visibility of the window.
9246 */
9247 int mWindowVisibility;
9248
9249 /**
9250 * Indicates the time at which drawing started to occur.
9251 */
9252 long mDrawingTime;
9253
9254 /**
Romain Guy5bcdff42009-05-14 21:27:18 -07009255 * Indicates whether or not ignoring the DIRTY_MASK flags.
9256 */
9257 boolean mIgnoreDirtyState;
9258
9259 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009260 * Indicates whether the view's window is currently in touch mode.
9261 */
9262 boolean mInTouchMode;
9263
9264 /**
9265 * Indicates that ViewRoot should trigger a global layout change
9266 * the next time it performs a traversal
9267 */
9268 boolean mRecomputeGlobalAttributes;
9269
9270 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009271 * Set during a traveral if any views want to keep the screen on.
9272 */
9273 boolean mKeepScreenOn;
9274
9275 /**
9276 * Set if the visibility of any views has changed.
9277 */
9278 boolean mViewVisibilityChanged;
9279
9280 /**
9281 * Set to true if a view has been scrolled.
9282 */
9283 boolean mViewScrollChanged;
9284
9285 /**
9286 * Global to the view hierarchy used as a temporary for dealing with
9287 * x/y points in the transparent region computations.
9288 */
9289 final int[] mTransparentLocation = new int[2];
9290
9291 /**
9292 * Global to the view hierarchy used as a temporary for dealing with
9293 * x/y points in the ViewGroup.invalidateChild implementation.
9294 */
9295 final int[] mInvalidateChildLocation = new int[2];
9296
9297 /**
9298 * The view tree observer used to dispatch global events like
9299 * layout, pre-draw, touch mode change, etc.
9300 */
9301 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
9302
9303 /**
9304 * A Canvas used by the view hierarchy to perform bitmap caching.
9305 */
9306 Canvas mCanvas;
9307
9308 /**
9309 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
9310 * handler can be used to pump events in the UI events queue.
9311 */
9312 final Handler mHandler;
9313
9314 /**
9315 * Identifier for messages requesting the view to be invalidated.
9316 * Such messages should be sent to {@link #mHandler}.
9317 */
9318 static final int INVALIDATE_MSG = 0x1;
9319
9320 /**
9321 * Identifier for messages requesting the view to invalidate a region.
9322 * Such messages should be sent to {@link #mHandler}.
9323 */
9324 static final int INVALIDATE_RECT_MSG = 0x2;
9325
9326 /**
9327 * Temporary for use in computing invalidate rectangles while
9328 * calling up the hierarchy.
9329 */
9330 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -07009331
9332 /**
9333 * Temporary list for use in collecting focusable descendents of a view.
9334 */
9335 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
9336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 /**
9338 * Creates a new set of attachment information with the specified
9339 * events handler and thread.
9340 *
9341 * @param handler the events handler the view must use
9342 */
9343 AttachInfo(IWindowSession session, IWindow window,
9344 Handler handler, Callbacks effectPlayer) {
9345 mSession = session;
9346 mWindow = window;
9347 mWindowToken = window.asBinder();
9348 mHandler = handler;
9349 mRootCallbacks = effectPlayer;
9350 }
9351 }
9352
9353 /**
9354 * <p>ScrollabilityCache holds various fields used by a View when scrolling
9355 * is supported. This avoids keeping too many unused fields in most
9356 * instances of View.</p>
9357 */
Mike Cleronf116bf82009-09-27 19:14:12 -07009358 private static class ScrollabilityCache implements Runnable {
9359
9360 /**
9361 * Scrollbars are not visible
9362 */
9363 public static final int OFF = 0;
9364
9365 /**
9366 * Scrollbars are visible
9367 */
9368 public static final int ON = 1;
9369
9370 /**
9371 * Scrollbars are fading away
9372 */
9373 public static final int FADING = 2;
9374
9375 public boolean fadeScrollBars;
9376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009377 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -07009378 public int scrollBarDefaultDelayBeforeFade;
9379 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009380
9381 public int scrollBarSize;
9382 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -07009383 public float[] interpolatorValues;
9384 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009385
9386 public final Paint paint;
9387 public final Matrix matrix;
9388 public Shader shader;
9389
Mike Cleronf116bf82009-09-27 19:14:12 -07009390 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
9391
9392 private final float[] mOpaque = {255.0f};
9393 private final float[] mTransparent = {0.0f};
9394
9395 /**
9396 * When fading should start. This time moves into the future every time
9397 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
9398 */
9399 public long fadeStartTime;
9400
9401
9402 /**
9403 * The current state of the scrollbars: ON, OFF, or FADING
9404 */
9405 public int state = OFF;
9406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009407 private int mLastColor;
9408
Mike Cleronf116bf82009-09-27 19:14:12 -07009409 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009410 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
9411 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -07009412 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
9413 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009414
9415 paint = new Paint();
9416 matrix = new Matrix();
9417 // use use a height of 1, and then wack the matrix each time we
9418 // actually use it.
9419 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -07009420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009421 paint.setShader(shader);
9422 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -07009423 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009424 }
Romain Guy8506ab42009-06-11 17:35:47 -07009425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009426 public void setFadeColor(int color) {
9427 if (color != 0 && color != mLastColor) {
9428 mLastColor = color;
9429 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -07009430
Romain Guye55e1a72009-08-27 10:42:26 -07009431 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
9432 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -07009433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 paint.setShader(shader);
9435 // Restore the default transfer mode (src_over)
9436 paint.setXfermode(null);
9437 }
9438 }
Mike Cleronf116bf82009-09-27 19:14:12 -07009439
9440 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -07009441 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -07009442 if (now >= fadeStartTime) {
9443
9444 // the animation fades the scrollbars out by changing
9445 // the opacity (alpha) from fully opaque to fully
9446 // transparent
9447 int nextFrame = (int) now;
9448 int framesCount = 0;
9449
9450 Interpolator interpolator = scrollBarInterpolator;
9451
9452 // Start opaque
9453 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
9454
9455 // End transparent
9456 nextFrame += scrollBarFadeDuration;
9457 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
9458
9459 state = FADING;
9460
9461 // Kick off the fade animation
9462 host.invalidate();
9463 }
9464 }
9465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009466 }
9467}