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