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