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