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