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