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