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