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