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