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