blob: 363aced9b7e9e4d54d4d79eff9bdee8cbd647f9d [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;
Adam Powell6e346362010-07-23 10:18:23 -070037import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.graphics.Region;
39import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.graphics.drawable.ColorDrawable;
41import android.graphics.drawable.Drawable;
42import android.os.Handler;
43import android.os.IBinder;
44import android.os.Message;
45import android.os.Parcel;
46import android.os.Parcelable;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.os.SystemProperties;
50import android.util.AttributeSet;
svetoslavganov75986cf2009-05-14 22:28:01 -070051import android.util.Config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.util.EventLog;
53import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070054import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070055import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070056import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070057import android.util.Pools;
58import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.ContextMenu.ContextMenuInfo;
Adam Powell6e346362010-07-23 10:18:23 -070060import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070061import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070065import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070066import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.view.inputmethod.InputConnection;
68import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.widget.ScrollBarDrawable;
70
svetoslavganov75986cf2009-05-14 22:28:01 -070071import java.lang.ref.SoftReference;
72import java.lang.reflect.InvocationTargetException;
73import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import java.util.ArrayList;
75import java.util.Arrays;
Romain Guyd90a3312009-05-06 14:54:28 -070076import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077
78/**
79 * <p>
80 * This class represents the basic building block for user interface components. A View
81 * occupies a rectangular area on the screen and is responsible for drawing and
82 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070083 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
85 * are invisible containers that hold other Views (or other ViewGroups) and define
86 * their layout properties.
87 * </p>
88 *
89 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070090 * <p>For an introduction to using this class to develop your
91 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070093 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
95 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
102 * </p>
103 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700104 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 * <a name="Using"></a>
106 * <h3>Using Views</h3>
107 * <p>
108 * All of the views in a window are arranged in a single tree. You can add views
109 * either from code or by specifying a tree of views in one or more XML layout
110 * files. There are many specialized subclasses of views that act as controls or
111 * are capable of displaying text, images, or other content.
112 * </p>
113 * <p>
114 * Once you have created a tree of views, there are typically a few types of
115 * common operations you may wish to perform:
116 * <ul>
117 * <li><strong>Set properties:</strong> for example setting the text of a
118 * {@link android.widget.TextView}. The available properties and the methods
119 * that set them will vary among the different subclasses of views. Note that
120 * properties that are known at build time can be set in the XML layout
121 * files.</li>
122 * <li><strong>Set focus:</strong> The framework will handled moving focus in
123 * response to user input. To force focus to a specific view, call
124 * {@link #requestFocus}.</li>
125 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
126 * that will be notified when something interesting happens to the view. For
127 * example, all views will let you set a listener to be notified when the view
128 * gains or loses focus. You can register such a listener using
129 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
130 * specialized listeners. For example, a Button exposes a listener to notify
131 * clients when the button is clicked.</li>
132 * <li><strong>Set visibility:</strong> You can hide or show views using
133 * {@link #setVisibility}.</li>
134 * </ul>
135 * </p>
136 * <p><em>
137 * Note: The Android framework is responsible for measuring, laying out and
138 * drawing views. You should not call methods that perform these actions on
139 * views yourself unless you are actually implementing a
140 * {@link android.view.ViewGroup}.
141 * </em></p>
142 *
143 * <a name="Lifecycle"></a>
144 * <h3>Implementing a Custom View</h3>
145 *
146 * <p>
147 * To implement a custom view, you will usually begin by providing overrides for
148 * some of the standard methods that the framework calls on all views. You do
149 * not need to override all of these methods. In fact, you can start by just
150 * overriding {@link #onDraw(android.graphics.Canvas)}.
151 * <table border="2" width="85%" align="center" cellpadding="5">
152 * <thead>
153 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
154 * </thead>
155 *
156 * <tbody>
157 * <tr>
158 * <td rowspan="2">Creation</td>
159 * <td>Constructors</td>
160 * <td>There is a form of the constructor that are called when the view
161 * is created from code and a form that is called when the view is
162 * inflated from a layout file. The second form should parse and apply
163 * any attributes defined in the layout file.
164 * </td>
165 * </tr>
166 * <tr>
167 * <td><code>{@link #onFinishInflate()}</code></td>
168 * <td>Called after a view and all of its children has been inflated
169 * from XML.</td>
170 * </tr>
171 *
172 * <tr>
173 * <td rowspan="3">Layout</td>
174 * <td><code>{@link #onMeasure}</code></td>
175 * <td>Called to determine the size requirements for this view and all
176 * of its children.
177 * </td>
178 * </tr>
179 * <tr>
180 * <td><code>{@link #onLayout}</code></td>
181 * <td>Called when this view should assign a size and position to all
182 * of its children.
183 * </td>
184 * </tr>
185 * <tr>
186 * <td><code>{@link #onSizeChanged}</code></td>
187 * <td>Called when the size of this view has changed.
188 * </td>
189 * </tr>
190 *
191 * <tr>
192 * <td>Drawing</td>
193 * <td><code>{@link #onDraw}</code></td>
194 * <td>Called when the view should render its content.
195 * </td>
196 * </tr>
197 *
198 * <tr>
199 * <td rowspan="4">Event processing</td>
200 * <td><code>{@link #onKeyDown}</code></td>
201 * <td>Called when a new key event occurs.
202 * </td>
203 * </tr>
204 * <tr>
205 * <td><code>{@link #onKeyUp}</code></td>
206 * <td>Called when a key up event occurs.
207 * </td>
208 * </tr>
209 * <tr>
210 * <td><code>{@link #onTrackballEvent}</code></td>
211 * <td>Called when a trackball motion event occurs.
212 * </td>
213 * </tr>
214 * <tr>
215 * <td><code>{@link #onTouchEvent}</code></td>
216 * <td>Called when a touch screen motion event occurs.
217 * </td>
218 * </tr>
219 *
220 * <tr>
221 * <td rowspan="2">Focus</td>
222 * <td><code>{@link #onFocusChanged}</code></td>
223 * <td>Called when the view gains or loses focus.
224 * </td>
225 * </tr>
226 *
227 * <tr>
228 * <td><code>{@link #onWindowFocusChanged}</code></td>
229 * <td>Called when the window containing the view gains or loses focus.
230 * </td>
231 * </tr>
232 *
233 * <tr>
234 * <td rowspan="3">Attaching</td>
235 * <td><code>{@link #onAttachedToWindow()}</code></td>
236 * <td>Called when the view is attached to a window.
237 * </td>
238 * </tr>
239 *
240 * <tr>
241 * <td><code>{@link #onDetachedFromWindow}</code></td>
242 * <td>Called when the view is detached from its window.
243 * </td>
244 * </tr>
245 *
246 * <tr>
247 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
248 * <td>Called when the visibility of the window containing the view
249 * has changed.
250 * </td>
251 * </tr>
252 * </tbody>
253 *
254 * </table>
255 * </p>
256 *
257 * <a name="IDs"></a>
258 * <h3>IDs</h3>
259 * Views may have an integer id associated with them. These ids are typically
260 * assigned in the layout XML files, and are used to find specific views within
261 * the view tree. A common pattern is to:
262 * <ul>
263 * <li>Define a Button in the layout file and assign it a unique ID.
264 * <pre>
265 * &lt;Button id="@+id/my_button"
266 * android:layout_width="wrap_content"
267 * android:layout_height="wrap_content"
268 * android:text="@string/my_button_text"/&gt;
269 * </pre></li>
270 * <li>From the onCreate method of an Activity, find the Button
271 * <pre class="prettyprint">
272 * Button myButton = (Button) findViewById(R.id.my_button);
273 * </pre></li>
274 * </ul>
275 * <p>
276 * View IDs need not be unique throughout the tree, but it is good practice to
277 * ensure that they are at least unique within the part of the tree you are
278 * searching.
279 * </p>
280 *
281 * <a name="Position"></a>
282 * <h3>Position</h3>
283 * <p>
284 * The geometry of a view is that of a rectangle. A view has a location,
285 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
286 * two dimensions, expressed as a width and a height. The unit for location
287 * and dimensions is the pixel.
288 * </p>
289 *
290 * <p>
291 * It is possible to retrieve the location of a view by invoking the methods
292 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
293 * coordinate of the rectangle representing the view. The latter returns the
294 * top, or Y, coordinate of the rectangle representing the view. These methods
295 * both return the location of the view relative to its parent. For instance,
296 * when getLeft() returns 20, that means the view is located 20 pixels to the
297 * right of the left edge of its direct parent.
298 * </p>
299 *
300 * <p>
301 * In addition, several convenience methods are offered to avoid unnecessary
302 * computations, namely {@link #getRight()} and {@link #getBottom()}.
303 * These methods return the coordinates of the right and bottom edges of the
304 * rectangle representing the view. For instance, calling {@link #getRight()}
305 * is similar to the following computation: <code>getLeft() + getWidth()</code>
306 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
307 * </p>
308 *
309 * <a name="SizePaddingMargins"></a>
310 * <h3>Size, padding and margins</h3>
311 * <p>
312 * The size of a view is expressed with a width and a height. A view actually
313 * possess two pairs of width and height values.
314 * </p>
315 *
316 * <p>
317 * The first pair is known as <em>measured width</em> and
318 * <em>measured height</em>. These dimensions define how big a view wants to be
319 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
320 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
321 * and {@link #getMeasuredHeight()}.
322 * </p>
323 *
324 * <p>
325 * The second pair is simply known as <em>width</em> and <em>height</em>, or
326 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
327 * dimensions define the actual size of the view on screen, at drawing time and
328 * after layout. These values may, but do not have to, be different from the
329 * measured width and height. The width and height can be obtained by calling
330 * {@link #getWidth()} and {@link #getHeight()}.
331 * </p>
332 *
333 * <p>
334 * To measure its dimensions, a view takes into account its padding. The padding
335 * is expressed in pixels for the left, top, right and bottom parts of the view.
336 * Padding can be used to offset the content of the view by a specific amount of
337 * pixels. For instance, a left padding of 2 will push the view's content by
338 * 2 pixels to the right of the left edge. Padding can be set using the
339 * {@link #setPadding(int, int, int, int)} method and queried by calling
340 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
341 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
342 * </p>
343 *
344 * <p>
345 * Even though a view can define a padding, it does not provide any support for
346 * margins. However, view groups provide such a support. Refer to
347 * {@link android.view.ViewGroup} and
348 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
349 * </p>
350 *
351 * <a name="Layout"></a>
352 * <h3>Layout</h3>
353 * <p>
354 * Layout is a two pass process: a measure pass and a layout pass. The measuring
355 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
356 * of the view tree. Each view pushes dimension specifications down the tree
357 * during the recursion. At the end of the measure pass, every view has stored
358 * its measurements. The second pass happens in
359 * {@link #layout(int,int,int,int)} and is also top-down. During
360 * this pass each parent is responsible for positioning all of its children
361 * using the sizes computed in the measure pass.
362 * </p>
363 *
364 * <p>
365 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
366 * {@link #getMeasuredHeight()} values must be set, along with those for all of
367 * that view's descendants. A view's measured width and measured height values
368 * must respect the constraints imposed by the view's parents. This guarantees
369 * that at the end of the measure pass, all parents accept all of their
370 * children's measurements. A parent view may call measure() more than once on
371 * its children. For example, the parent may measure each child once with
372 * unspecified dimensions to find out how big they want to be, then call
373 * measure() on them again with actual numbers if the sum of all the children's
374 * unconstrained sizes is too big or too small.
375 * </p>
376 *
377 * <p>
378 * The measure pass uses two classes to communicate dimensions. The
379 * {@link MeasureSpec} class is used by views to tell their parents how they
380 * want to be measured and positioned. The base LayoutParams class just
381 * describes how big the view wants to be for both width and height. For each
382 * dimension, it can specify one of:
383 * <ul>
384 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800385 * <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 -0800386 * (minus padding)
387 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
388 * enclose its content (plus padding).
389 * </ul>
390 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
391 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
392 * an X and Y value.
393 * </p>
394 *
395 * <p>
396 * MeasureSpecs are used to push requirements down the tree from parent to
397 * child. A MeasureSpec can be in one of three modes:
398 * <ul>
399 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
400 * of a child view. For example, a LinearLayout may call measure() on its child
401 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
402 * tall the child view wants to be given a width of 240 pixels.
403 * <li>EXACTLY: This is used by the parent to impose an exact size on the
404 * child. The child must use this size, and guarantee that all of its
405 * descendants will fit within this size.
406 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
407 * child. The child must gurantee that it and all of its descendants will fit
408 * within this size.
409 * </ul>
410 * </p>
411 *
412 * <p>
413 * To intiate a layout, call {@link #requestLayout}. This method is typically
414 * called by a view on itself when it believes that is can no longer fit within
415 * its current bounds.
416 * </p>
417 *
418 * <a name="Drawing"></a>
419 * <h3>Drawing</h3>
420 * <p>
421 * Drawing is handled by walking the tree and rendering each view that
422 * intersects the the invalid region. Because the tree is traversed in-order,
423 * this means that parents will draw before (i.e., behind) their children, with
424 * siblings drawn in the order they appear in the tree.
425 * If you set a background drawable for a View, then the View will draw it for you
426 * before calling back to its <code>onDraw()</code> method.
427 * </p>
428 *
429 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700430 * 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 -0800431 * </p>
432 *
433 * <p>
434 * To force a view to draw, call {@link #invalidate()}.
435 * </p>
436 *
437 * <a name="EventHandlingThreading"></a>
438 * <h3>Event Handling and Threading</h3>
439 * <p>
440 * The basic cycle of a view is as follows:
441 * <ol>
442 * <li>An event comes in and is dispatched to the appropriate view. The view
443 * handles the event and notifies any listeners.</li>
444 * <li>If in the course of processing the event, the view's bounds may need
445 * to be changed, the view will call {@link #requestLayout()}.</li>
446 * <li>Similarly, if in the course of processing the event the view's appearance
447 * may need to be changed, the view will call {@link #invalidate()}.</li>
448 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
449 * the framework will take care of measuring, laying out, and drawing the tree
450 * as appropriate.</li>
451 * </ol>
452 * </p>
453 *
454 * <p><em>Note: The entire view tree is single threaded. You must always be on
455 * the UI thread when calling any method on any view.</em>
456 * If you are doing work on other threads and want to update the state of a view
457 * from that thread, you should use a {@link Handler}.
458 * </p>
459 *
460 * <a name="FocusHandling"></a>
461 * <h3>Focus Handling</h3>
462 * <p>
463 * The framework will handle routine focus movement in response to user input.
464 * This includes changing the focus as views are removed or hidden, or as new
465 * views become available. Views indicate their willingness to take focus
466 * through the {@link #isFocusable} method. To change whether a view can take
467 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
468 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
469 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
470 * </p>
471 * <p>
472 * Focus movement is based on an algorithm which finds the nearest neighbor in a
473 * given direction. In rare cases, the default algorithm may not match the
474 * intended behavior of the developer. In these situations, you can provide
475 * explicit overrides by using these XML attributes in the layout file:
476 * <pre>
477 * nextFocusDown
478 * nextFocusLeft
479 * nextFocusRight
480 * nextFocusUp
481 * </pre>
482 * </p>
483 *
484 *
485 * <p>
486 * To get a particular view to take focus, call {@link #requestFocus()}.
487 * </p>
488 *
489 * <a name="TouchMode"></a>
490 * <h3>Touch Mode</h3>
491 * <p>
492 * When a user is navigating a user interface via directional keys such as a D-pad, it is
493 * necessary to give focus to actionable items such as buttons so the user can see
494 * what will take input. If the device has touch capabilities, however, and the user
495 * begins interacting with the interface by touching it, it is no longer necessary to
496 * always highlight, or give focus to, a particular view. This motivates a mode
497 * for interaction named 'touch mode'.
498 * </p>
499 * <p>
500 * For a touch capable device, once the user touches the screen, the device
501 * will enter touch mode. From this point onward, only views for which
502 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
503 * Other views that are touchable, like buttons, will not take focus when touched; they will
504 * only fire the on click listeners.
505 * </p>
506 * <p>
507 * Any time a user hits a directional key, such as a D-pad direction, the view device will
508 * exit touch mode, and find a view to take focus, so that the user may resume interacting
509 * with the user interface without touching the screen again.
510 * </p>
511 * <p>
512 * The touch mode state is maintained across {@link android.app.Activity}s. Call
513 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
514 * </p>
515 *
516 * <a name="Scrolling"></a>
517 * <h3>Scrolling</h3>
518 * <p>
519 * The framework provides basic support for views that wish to internally
520 * scroll their content. This includes keeping track of the X and Y scroll
521 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700522 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
523 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 * </p>
525 *
526 * <a name="Tags"></a>
527 * <h3>Tags</h3>
528 * <p>
529 * Unlike IDs, tags are not used to identify views. Tags are essentially an
530 * extra piece of information that can be associated with a view. They are most
531 * often used as a convenience to store data related to views in the views
532 * themselves rather than by putting them in a separate structure.
533 * </p>
534 *
535 * <a name="Animation"></a>
536 * <h3>Animation</h3>
537 * <p>
538 * You can attach an {@link Animation} object to a view using
539 * {@link #setAnimation(Animation)} or
540 * {@link #startAnimation(Animation)}. The animation can alter the scale,
541 * rotation, translation and alpha of a view over time. If the animation is
542 * attached to a view that has children, the animation will affect the entire
543 * subtree rooted by that node. When an animation is started, the framework will
544 * take care of redrawing the appropriate views until the animation completes.
545 * </p>
546 *
Romain Guyd6a463a2009-05-21 23:10:10 -0700547 * @attr ref android.R.styleable#View_background
548 * @attr ref android.R.styleable#View_clickable
549 * @attr ref android.R.styleable#View_contentDescription
550 * @attr ref android.R.styleable#View_drawingCacheQuality
551 * @attr ref android.R.styleable#View_duplicateParentState
552 * @attr ref android.R.styleable#View_id
553 * @attr ref android.R.styleable#View_fadingEdge
554 * @attr ref android.R.styleable#View_fadingEdgeLength
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700556 * @attr ref android.R.styleable#View_isScrollContainer
557 * @attr ref android.R.styleable#View_focusable
558 * @attr ref android.R.styleable#View_focusableInTouchMode
559 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
560 * @attr ref android.R.styleable#View_keepScreenOn
561 * @attr ref android.R.styleable#View_longClickable
562 * @attr ref android.R.styleable#View_minHeight
563 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 * @attr ref android.R.styleable#View_nextFocusDown
565 * @attr ref android.R.styleable#View_nextFocusLeft
566 * @attr ref android.R.styleable#View_nextFocusRight
567 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700568 * @attr ref android.R.styleable#View_onClick
569 * @attr ref android.R.styleable#View_padding
570 * @attr ref android.R.styleable#View_paddingBottom
571 * @attr ref android.R.styleable#View_paddingLeft
572 * @attr ref android.R.styleable#View_paddingRight
573 * @attr ref android.R.styleable#View_paddingTop
574 * @attr ref android.R.styleable#View_saveEnabled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 * @attr ref android.R.styleable#View_scrollX
576 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700577 * @attr ref android.R.styleable#View_scrollbarSize
578 * @attr ref android.R.styleable#View_scrollbarStyle
579 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700580 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
581 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
583 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 * @attr ref android.R.styleable#View_scrollbarThumbVertical
585 * @attr ref android.R.styleable#View_scrollbarTrackVertical
586 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
587 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700588 * @attr ref android.R.styleable#View_soundEffectsEnabled
589 * @attr ref android.R.styleable#View_tag
590 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 *
592 * @see android.view.ViewGroup
593 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700594public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 private static final boolean DBG = false;
596
597 /**
598 * The logging tag used by this class with android.util.Log.
599 */
600 protected static final String VIEW_LOG_TAG = "View";
601
602 /**
603 * Used to mark a View that has no ID.
604 */
605 public static final int NO_ID = -1;
606
607 /**
608 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
609 * calling setFlags.
610 */
611 private static final int NOT_FOCUSABLE = 0x00000000;
612
613 /**
614 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
615 * setFlags.
616 */
617 private static final int FOCUSABLE = 0x00000001;
618
619 /**
620 * Mask for use with setFlags indicating bits used for focus.
621 */
622 private static final int FOCUSABLE_MASK = 0x00000001;
623
624 /**
625 * This view will adjust its padding to fit sytem windows (e.g. status bar)
626 */
627 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
628
629 /**
630 * This view is visible. Use with {@link #setVisibility}.
631 */
632 public static final int VISIBLE = 0x00000000;
633
634 /**
635 * This view is invisible, but it still takes up space for layout purposes.
636 * Use with {@link #setVisibility}.
637 */
638 public static final int INVISIBLE = 0x00000004;
639
640 /**
641 * This view is invisible, and it doesn't take any space for layout
642 * purposes. Use with {@link #setVisibility}.
643 */
644 public static final int GONE = 0x00000008;
645
646 /**
647 * Mask for use with setFlags indicating bits used for visibility.
648 * {@hide}
649 */
650 static final int VISIBILITY_MASK = 0x0000000C;
651
652 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
653
654 /**
655 * This view is enabled. Intrepretation varies by subclass.
656 * Use with ENABLED_MASK when calling setFlags.
657 * {@hide}
658 */
659 static final int ENABLED = 0x00000000;
660
661 /**
662 * This view is disabled. Intrepretation varies by subclass.
663 * Use with ENABLED_MASK when calling setFlags.
664 * {@hide}
665 */
666 static final int DISABLED = 0x00000020;
667
668 /**
669 * Mask for use with setFlags indicating bits used for indicating whether
670 * this view is enabled
671 * {@hide}
672 */
673 static final int ENABLED_MASK = 0x00000020;
674
675 /**
676 * This view won't draw. {@link #onDraw} won't be called and further
677 * optimizations
678 * will be performed. It is okay to have this flag set and a background.
679 * Use with DRAW_MASK when calling setFlags.
680 * {@hide}
681 */
682 static final int WILL_NOT_DRAW = 0x00000080;
683
684 /**
685 * Mask for use with setFlags indicating bits used for indicating whether
686 * this view is will draw
687 * {@hide}
688 */
689 static final int DRAW_MASK = 0x00000080;
690
691 /**
692 * <p>This view doesn't show scrollbars.</p>
693 * {@hide}
694 */
695 static final int SCROLLBARS_NONE = 0x00000000;
696
697 /**
698 * <p>This view shows horizontal scrollbars.</p>
699 * {@hide}
700 */
701 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
702
703 /**
704 * <p>This view shows vertical scrollbars.</p>
705 * {@hide}
706 */
707 static final int SCROLLBARS_VERTICAL = 0x00000200;
708
709 /**
710 * <p>Mask for use with setFlags indicating bits used for indicating which
711 * scrollbars are enabled.</p>
712 * {@hide}
713 */
714 static final int SCROLLBARS_MASK = 0x00000300;
715
716 // note 0x00000400 and 0x00000800 are now available for next flags...
717
718 /**
719 * <p>This view doesn't show fading edges.</p>
720 * {@hide}
721 */
722 static final int FADING_EDGE_NONE = 0x00000000;
723
724 /**
725 * <p>This view shows horizontal fading edges.</p>
726 * {@hide}
727 */
728 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
729
730 /**
731 * <p>This view shows vertical fading edges.</p>
732 * {@hide}
733 */
734 static final int FADING_EDGE_VERTICAL = 0x00002000;
735
736 /**
737 * <p>Mask for use with setFlags indicating bits used for indicating which
738 * fading edges are enabled.</p>
739 * {@hide}
740 */
741 static final int FADING_EDGE_MASK = 0x00003000;
742
743 /**
744 * <p>Indicates this view can be clicked. When clickable, a View reacts
745 * to clicks by notifying the OnClickListener.<p>
746 * {@hide}
747 */
748 static final int CLICKABLE = 0x00004000;
749
750 /**
751 * <p>Indicates this view is caching its drawing into a bitmap.</p>
752 * {@hide}
753 */
754 static final int DRAWING_CACHE_ENABLED = 0x00008000;
755
756 /**
757 * <p>Indicates that no icicle should be saved for this view.<p>
758 * {@hide}
759 */
760 static final int SAVE_DISABLED = 0x000010000;
761
762 /**
763 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
764 * property.</p>
765 * {@hide}
766 */
767 static final int SAVE_DISABLED_MASK = 0x000010000;
768
769 /**
770 * <p>Indicates that no drawing cache should ever be created for this view.<p>
771 * {@hide}
772 */
773 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
774
775 /**
776 * <p>Indicates this view can take / keep focus when int touch mode.</p>
777 * {@hide}
778 */
779 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
780
781 /**
782 * <p>Enables low quality mode for the drawing cache.</p>
783 */
784 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
785
786 /**
787 * <p>Enables high quality mode for the drawing cache.</p>
788 */
789 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
790
791 /**
792 * <p>Enables automatic quality mode for the drawing cache.</p>
793 */
794 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
795
796 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
797 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
798 };
799
800 /**
801 * <p>Mask for use with setFlags indicating bits used for the cache
802 * quality property.</p>
803 * {@hide}
804 */
805 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
806
807 /**
808 * <p>
809 * Indicates this view can be long clicked. When long clickable, a View
810 * reacts to long clicks by notifying the OnLongClickListener or showing a
811 * context menu.
812 * </p>
813 * {@hide}
814 */
815 static final int LONG_CLICKABLE = 0x00200000;
816
817 /**
818 * <p>Indicates that this view gets its drawable states from its direct parent
819 * and ignores its original internal states.</p>
820 *
821 * @hide
822 */
823 static final int DUPLICATE_PARENT_STATE = 0x00400000;
824
825 /**
826 * The scrollbar style to display the scrollbars inside the content area,
827 * without increasing the padding. The scrollbars will be overlaid with
828 * translucency on the view's content.
829 */
830 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
831
832 /**
833 * The scrollbar style to display the scrollbars inside the padded area,
834 * increasing the padding of the view. The scrollbars will not overlap the
835 * content area of the view.
836 */
837 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
838
839 /**
840 * The scrollbar style to display the scrollbars at the edge of the view,
841 * without increasing the padding. The scrollbars will be overlaid with
842 * translucency.
843 */
844 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
845
846 /**
847 * The scrollbar style to display the scrollbars at the edge of the view,
848 * increasing the padding of the view. The scrollbars will only overlap the
849 * background, if any.
850 */
851 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
852
853 /**
854 * Mask to check if the scrollbar style is overlay or inset.
855 * {@hide}
856 */
857 static final int SCROLLBARS_INSET_MASK = 0x01000000;
858
859 /**
860 * Mask to check if the scrollbar style is inside or outside.
861 * {@hide}
862 */
863 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
864
865 /**
866 * Mask for scrollbar style.
867 * {@hide}
868 */
869 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
870
871 /**
872 * View flag indicating that the screen should remain on while the
873 * window containing this view is visible to the user. This effectively
874 * takes care of automatically setting the WindowManager's
875 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
876 */
877 public static final int KEEP_SCREEN_ON = 0x04000000;
878
879 /**
880 * View flag indicating whether this view should have sound effects enabled
881 * for events such as clicking and touching.
882 */
883 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
884
885 /**
886 * View flag indicating whether this view should have haptic feedback
887 * enabled for events such as long presses.
888 */
889 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
890
891 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700892 * <p>Indicates that the view hierarchy should stop saving state when
893 * it reaches this view. If state saving is initiated immediately at
894 * the view, it will be allowed.
895 * {@hide}
896 */
897 static final int PARENT_SAVE_DISABLED = 0x20000000;
898
899 /**
900 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
901 * {@hide}
902 */
903 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
904
905 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700906 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
907 * should add all focusable Views regardless if they are focusable in touch mode.
908 */
909 public static final int FOCUSABLES_ALL = 0x00000000;
910
911 /**
912 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
913 * should add only Views focusable in touch mode.
914 */
915 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
916
917 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 * Use with {@link #focusSearch}. Move focus to the previous selectable
919 * item.
920 */
921 public static final int FOCUS_BACKWARD = 0x00000001;
922
923 /**
924 * Use with {@link #focusSearch}. Move focus to the next selectable
925 * item.
926 */
927 public static final int FOCUS_FORWARD = 0x00000002;
928
929 /**
930 * Use with {@link #focusSearch}. Move focus to the left.
931 */
932 public static final int FOCUS_LEFT = 0x00000011;
933
934 /**
935 * Use with {@link #focusSearch}. Move focus up.
936 */
937 public static final int FOCUS_UP = 0x00000021;
938
939 /**
940 * Use with {@link #focusSearch}. Move focus to the right.
941 */
942 public static final int FOCUS_RIGHT = 0x00000042;
943
944 /**
945 * Use with {@link #focusSearch}. Move focus down.
946 */
947 public static final int FOCUS_DOWN = 0x00000082;
948
949 /**
950 * Base View state sets
951 */
952 // Singles
953 /**
954 * Indicates the view has no states set. States are used with
955 * {@link android.graphics.drawable.Drawable} to change the drawing of the
956 * view depending on its state.
957 *
958 * @see android.graphics.drawable.Drawable
959 * @see #getDrawableState()
960 */
961 protected static final int[] EMPTY_STATE_SET = {};
962 /**
963 * Indicates the view is enabled. States are used with
964 * {@link android.graphics.drawable.Drawable} to change the drawing of the
965 * view depending on its state.
966 *
967 * @see android.graphics.drawable.Drawable
968 * @see #getDrawableState()
969 */
970 protected static final int[] ENABLED_STATE_SET = {R.attr.state_enabled};
971 /**
972 * Indicates the view is focused. States are used with
973 * {@link android.graphics.drawable.Drawable} to change the drawing of the
974 * view depending on its state.
975 *
976 * @see android.graphics.drawable.Drawable
977 * @see #getDrawableState()
978 */
979 protected static final int[] FOCUSED_STATE_SET = {R.attr.state_focused};
980 /**
981 * Indicates the view is selected. States are used with
982 * {@link android.graphics.drawable.Drawable} to change the drawing of the
983 * view depending on its state.
984 *
985 * @see android.graphics.drawable.Drawable
986 * @see #getDrawableState()
987 */
988 protected static final int[] SELECTED_STATE_SET = {R.attr.state_selected};
989 /**
990 * Indicates the view is pressed. States are used with
991 * {@link android.graphics.drawable.Drawable} to change the drawing of the
992 * view depending on its state.
993 *
994 * @see android.graphics.drawable.Drawable
995 * @see #getDrawableState()
996 * @hide
997 */
998 protected static final int[] PRESSED_STATE_SET = {R.attr.state_pressed};
999 /**
1000 * Indicates the view's window has focus. States are used with
1001 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1002 * view depending on its state.
1003 *
1004 * @see android.graphics.drawable.Drawable
1005 * @see #getDrawableState()
1006 */
1007 protected static final int[] WINDOW_FOCUSED_STATE_SET =
1008 {R.attr.state_window_focused};
1009 // Doubles
1010 /**
1011 * Indicates the view is enabled and has the focus.
1012 *
1013 * @see #ENABLED_STATE_SET
1014 * @see #FOCUSED_STATE_SET
1015 */
1016 protected static final int[] ENABLED_FOCUSED_STATE_SET =
1017 stateSetUnion(ENABLED_STATE_SET, FOCUSED_STATE_SET);
1018 /**
1019 * Indicates the view is enabled and selected.
1020 *
1021 * @see #ENABLED_STATE_SET
1022 * @see #SELECTED_STATE_SET
1023 */
1024 protected static final int[] ENABLED_SELECTED_STATE_SET =
1025 stateSetUnion(ENABLED_STATE_SET, SELECTED_STATE_SET);
1026 /**
1027 * Indicates the view is enabled and that its window has focus.
1028 *
1029 * @see #ENABLED_STATE_SET
1030 * @see #WINDOW_FOCUSED_STATE_SET
1031 */
1032 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET =
1033 stateSetUnion(ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1034 /**
1035 * Indicates the view is focused and selected.
1036 *
1037 * @see #FOCUSED_STATE_SET
1038 * @see #SELECTED_STATE_SET
1039 */
1040 protected static final int[] FOCUSED_SELECTED_STATE_SET =
1041 stateSetUnion(FOCUSED_STATE_SET, SELECTED_STATE_SET);
1042 /**
1043 * Indicates the view has the focus and that its window has the focus.
1044 *
1045 * @see #FOCUSED_STATE_SET
1046 * @see #WINDOW_FOCUSED_STATE_SET
1047 */
1048 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET =
1049 stateSetUnion(FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1050 /**
1051 * Indicates the view is selected and that its window has the focus.
1052 *
1053 * @see #SELECTED_STATE_SET
1054 * @see #WINDOW_FOCUSED_STATE_SET
1055 */
1056 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET =
1057 stateSetUnion(SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1058 // Triples
1059 /**
1060 * Indicates the view is enabled, focused and selected.
1061 *
1062 * @see #ENABLED_STATE_SET
1063 * @see #FOCUSED_STATE_SET
1064 * @see #SELECTED_STATE_SET
1065 */
1066 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET =
1067 stateSetUnion(ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1068 /**
1069 * Indicates the view is enabled, focused and its window has the focus.
1070 *
1071 * @see #ENABLED_STATE_SET
1072 * @see #FOCUSED_STATE_SET
1073 * @see #WINDOW_FOCUSED_STATE_SET
1074 */
1075 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1076 stateSetUnion(ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1077 /**
1078 * Indicates the view is enabled, selected and its window has the focus.
1079 *
1080 * @see #ENABLED_STATE_SET
1081 * @see #SELECTED_STATE_SET
1082 * @see #WINDOW_FOCUSED_STATE_SET
1083 */
1084 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1085 stateSetUnion(ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1086 /**
1087 * Indicates the view is focused, selected and its window has the focus.
1088 *
1089 * @see #FOCUSED_STATE_SET
1090 * @see #SELECTED_STATE_SET
1091 * @see #WINDOW_FOCUSED_STATE_SET
1092 */
1093 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1094 stateSetUnion(FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1095 /**
1096 * Indicates the view is enabled, focused, selected and its window
1097 * has the focus.
1098 *
1099 * @see #ENABLED_STATE_SET
1100 * @see #FOCUSED_STATE_SET
1101 * @see #SELECTED_STATE_SET
1102 * @see #WINDOW_FOCUSED_STATE_SET
1103 */
1104 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1105 stateSetUnion(ENABLED_FOCUSED_SELECTED_STATE_SET,
1106 WINDOW_FOCUSED_STATE_SET);
1107
1108 /**
1109 * Indicates the view is pressed and its window has the focus.
1110 *
1111 * @see #PRESSED_STATE_SET
1112 * @see #WINDOW_FOCUSED_STATE_SET
1113 */
1114 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET =
1115 stateSetUnion(PRESSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1116
1117 /**
1118 * Indicates the view is pressed and selected.
1119 *
1120 * @see #PRESSED_STATE_SET
1121 * @see #SELECTED_STATE_SET
1122 */
1123 protected static final int[] PRESSED_SELECTED_STATE_SET =
1124 stateSetUnion(PRESSED_STATE_SET, SELECTED_STATE_SET);
1125
1126 /**
1127 * Indicates the view is pressed, selected and its window has the focus.
1128 *
1129 * @see #PRESSED_STATE_SET
1130 * @see #SELECTED_STATE_SET
1131 * @see #WINDOW_FOCUSED_STATE_SET
1132 */
1133 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1134 stateSetUnion(PRESSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1135
1136 /**
1137 * Indicates the view is pressed and focused.
1138 *
1139 * @see #PRESSED_STATE_SET
1140 * @see #FOCUSED_STATE_SET
1141 */
1142 protected static final int[] PRESSED_FOCUSED_STATE_SET =
1143 stateSetUnion(PRESSED_STATE_SET, FOCUSED_STATE_SET);
1144
1145 /**
1146 * Indicates the view is pressed, focused and its window has the focus.
1147 *
1148 * @see #PRESSED_STATE_SET
1149 * @see #FOCUSED_STATE_SET
1150 * @see #WINDOW_FOCUSED_STATE_SET
1151 */
1152 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1153 stateSetUnion(PRESSED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1154
1155 /**
1156 * Indicates the view is pressed, focused and selected.
1157 *
1158 * @see #PRESSED_STATE_SET
1159 * @see #SELECTED_STATE_SET
1160 * @see #FOCUSED_STATE_SET
1161 */
1162 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET =
1163 stateSetUnion(PRESSED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1164
1165 /**
1166 * Indicates the view is pressed, focused, selected and its window has the focus.
1167 *
1168 * @see #PRESSED_STATE_SET
1169 * @see #FOCUSED_STATE_SET
1170 * @see #SELECTED_STATE_SET
1171 * @see #WINDOW_FOCUSED_STATE_SET
1172 */
1173 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1174 stateSetUnion(PRESSED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1175
1176 /**
1177 * Indicates the view is pressed and enabled.
1178 *
1179 * @see #PRESSED_STATE_SET
1180 * @see #ENABLED_STATE_SET
1181 */
1182 protected static final int[] PRESSED_ENABLED_STATE_SET =
1183 stateSetUnion(PRESSED_STATE_SET, ENABLED_STATE_SET);
1184
1185 /**
1186 * Indicates the view is pressed, enabled and its window has the focus.
1187 *
1188 * @see #PRESSED_STATE_SET
1189 * @see #ENABLED_STATE_SET
1190 * @see #WINDOW_FOCUSED_STATE_SET
1191 */
1192 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET =
1193 stateSetUnion(PRESSED_ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1194
1195 /**
1196 * Indicates the view is pressed, enabled and selected.
1197 *
1198 * @see #PRESSED_STATE_SET
1199 * @see #ENABLED_STATE_SET
1200 * @see #SELECTED_STATE_SET
1201 */
1202 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET =
1203 stateSetUnion(PRESSED_ENABLED_STATE_SET, SELECTED_STATE_SET);
1204
1205 /**
1206 * Indicates the view is pressed, enabled, selected and its window has the
1207 * focus.
1208 *
1209 * @see #PRESSED_STATE_SET
1210 * @see #ENABLED_STATE_SET
1211 * @see #SELECTED_STATE_SET
1212 * @see #WINDOW_FOCUSED_STATE_SET
1213 */
1214 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1215 stateSetUnion(PRESSED_ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1216
1217 /**
1218 * Indicates the view is pressed, enabled and focused.
1219 *
1220 * @see #PRESSED_STATE_SET
1221 * @see #ENABLED_STATE_SET
1222 * @see #FOCUSED_STATE_SET
1223 */
1224 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET =
1225 stateSetUnion(PRESSED_ENABLED_STATE_SET, FOCUSED_STATE_SET);
1226
1227 /**
1228 * Indicates the view is pressed, enabled, focused and its window has the
1229 * focus.
1230 *
1231 * @see #PRESSED_STATE_SET
1232 * @see #ENABLED_STATE_SET
1233 * @see #FOCUSED_STATE_SET
1234 * @see #WINDOW_FOCUSED_STATE_SET
1235 */
1236 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1237 stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1238
1239 /**
1240 * Indicates the view is pressed, enabled, focused and selected.
1241 *
1242 * @see #PRESSED_STATE_SET
1243 * @see #ENABLED_STATE_SET
1244 * @see #SELECTED_STATE_SET
1245 * @see #FOCUSED_STATE_SET
1246 */
1247 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET =
1248 stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1249
1250 /**
1251 * Indicates the view is pressed, enabled, focused, selected and its window
1252 * has the focus.
1253 *
1254 * @see #PRESSED_STATE_SET
1255 * @see #ENABLED_STATE_SET
1256 * @see #SELECTED_STATE_SET
1257 * @see #FOCUSED_STATE_SET
1258 * @see #WINDOW_FOCUSED_STATE_SET
1259 */
1260 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1261 stateSetUnion(PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1262
1263 /**
1264 * The order here is very important to {@link #getDrawableState()}
1265 */
1266 private static final int[][] VIEW_STATE_SETS = {
1267 EMPTY_STATE_SET, // 0 0 0 0 0
1268 WINDOW_FOCUSED_STATE_SET, // 0 0 0 0 1
1269 SELECTED_STATE_SET, // 0 0 0 1 0
1270 SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 0 1 1
1271 FOCUSED_STATE_SET, // 0 0 1 0 0
1272 FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 0 1
1273 FOCUSED_SELECTED_STATE_SET, // 0 0 1 1 0
1274 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 1 1
1275 ENABLED_STATE_SET, // 0 1 0 0 0
1276 ENABLED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 0 1
1277 ENABLED_SELECTED_STATE_SET, // 0 1 0 1 0
1278 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 1 1
1279 ENABLED_FOCUSED_STATE_SET, // 0 1 1 0 0
1280 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 0 1
1281 ENABLED_FOCUSED_SELECTED_STATE_SET, // 0 1 1 1 0
1282 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 1 1
1283 PRESSED_STATE_SET, // 1 0 0 0 0
1284 PRESSED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 0 1
1285 PRESSED_SELECTED_STATE_SET, // 1 0 0 1 0
1286 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 1 1
1287 PRESSED_FOCUSED_STATE_SET, // 1 0 1 0 0
1288 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 0 1
1289 PRESSED_FOCUSED_SELECTED_STATE_SET, // 1 0 1 1 0
1290 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 1 1
1291 PRESSED_ENABLED_STATE_SET, // 1 1 0 0 0
1292 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 0 1
1293 PRESSED_ENABLED_SELECTED_STATE_SET, // 1 1 0 1 0
1294 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 1 1
1295 PRESSED_ENABLED_FOCUSED_STATE_SET, // 1 1 1 0 0
1296 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 0 1
1297 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, // 1 1 1 1 0
1298 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 1 1
1299 };
1300
1301 /**
1302 * Used by views that contain lists of items. This state indicates that
1303 * the view is showing the last item.
1304 * @hide
1305 */
1306 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1307 /**
1308 * Used by views that contain lists of items. This state indicates that
1309 * the view is showing the first item.
1310 * @hide
1311 */
1312 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1313 /**
1314 * Used by views that contain lists of items. This state indicates that
1315 * the view is showing the middle item.
1316 * @hide
1317 */
1318 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1319 /**
1320 * Used by views that contain lists of items. This state indicates that
1321 * the view is showing only one item.
1322 * @hide
1323 */
1324 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1325 /**
1326 * Used by views that contain lists of items. This state indicates that
1327 * the view is pressed and showing the last item.
1328 * @hide
1329 */
1330 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1331 /**
1332 * Used by views that contain lists of items. This state indicates that
1333 * the view is pressed and showing the first item.
1334 * @hide
1335 */
1336 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1337 /**
1338 * Used by views that contain lists of items. This state indicates that
1339 * the view is pressed and showing the middle item.
1340 * @hide
1341 */
1342 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1343 /**
1344 * Used by views that contain lists of items. This state indicates that
1345 * the view is pressed and showing only one item.
1346 * @hide
1347 */
1348 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1349
1350 /**
1351 * Temporary Rect currently for use in setBackground(). This will probably
1352 * be extended in the future to hold our own class with more than just
1353 * a Rect. :)
1354 */
1355 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001356
1357 /**
1358 * Map used to store views' tags.
1359 */
1360 private static WeakHashMap<View, SparseArray<Object>> sTags;
1361
1362 /**
1363 * Lock used to access sTags.
1364 */
1365 private static final Object sTagsLock = new Object();
1366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 /**
1368 * The animation currently associated with this view.
1369 * @hide
1370 */
1371 protected Animation mCurrentAnimation = null;
1372
1373 /**
1374 * Width as measured during measure pass.
1375 * {@hide}
1376 */
1377 @ViewDebug.ExportedProperty
1378 protected int mMeasuredWidth;
1379
1380 /**
1381 * Height as measured during measure pass.
1382 * {@hide}
1383 */
1384 @ViewDebug.ExportedProperty
1385 protected int mMeasuredHeight;
1386
1387 /**
1388 * The view's identifier.
1389 * {@hide}
1390 *
1391 * @see #setId(int)
1392 * @see #getId()
1393 */
1394 @ViewDebug.ExportedProperty(resolveId = true)
1395 int mID = NO_ID;
1396
1397 /**
1398 * The view's tag.
1399 * {@hide}
1400 *
1401 * @see #setTag(Object)
1402 * @see #getTag()
1403 */
1404 protected Object mTag;
1405
1406 // for mPrivateFlags:
1407 /** {@hide} */
1408 static final int WANTS_FOCUS = 0x00000001;
1409 /** {@hide} */
1410 static final int FOCUSED = 0x00000002;
1411 /** {@hide} */
1412 static final int SELECTED = 0x00000004;
1413 /** {@hide} */
1414 static final int IS_ROOT_NAMESPACE = 0x00000008;
1415 /** {@hide} */
1416 static final int HAS_BOUNDS = 0x00000010;
1417 /** {@hide} */
1418 static final int DRAWN = 0x00000020;
1419 /**
1420 * When this flag is set, this view is running an animation on behalf of its
1421 * children and should therefore not cancel invalidate requests, even if they
1422 * lie outside of this view's bounds.
1423 *
1424 * {@hide}
1425 */
1426 static final int DRAW_ANIMATION = 0x00000040;
1427 /** {@hide} */
1428 static final int SKIP_DRAW = 0x00000080;
1429 /** {@hide} */
1430 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1431 /** {@hide} */
1432 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1433 /** {@hide} */
1434 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1435 /** {@hide} */
1436 static final int MEASURED_DIMENSION_SET = 0x00000800;
1437 /** {@hide} */
1438 static final int FORCE_LAYOUT = 0x00001000;
1439
1440 private static final int LAYOUT_REQUIRED = 0x00002000;
1441
1442 private static final int PRESSED = 0x00004000;
1443
1444 /** {@hide} */
1445 static final int DRAWING_CACHE_VALID = 0x00008000;
1446 /**
1447 * Flag used to indicate that this view should be drawn once more (and only once
1448 * more) after its animation has completed.
1449 * {@hide}
1450 */
1451 static final int ANIMATION_STARTED = 0x00010000;
1452
1453 private static final int SAVE_STATE_CALLED = 0x00020000;
1454
1455 /**
1456 * Indicates that the View returned true when onSetAlpha() was called and that
1457 * the alpha must be restored.
1458 * {@hide}
1459 */
1460 static final int ALPHA_SET = 0x00040000;
1461
1462 /**
1463 * Set by {@link #setScrollContainer(boolean)}.
1464 */
1465 static final int SCROLL_CONTAINER = 0x00080000;
1466
1467 /**
1468 * Set by {@link #setScrollContainer(boolean)}.
1469 */
1470 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1471
1472 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001473 * View flag indicating whether this view was invalidated (fully or partially.)
1474 *
1475 * @hide
1476 */
1477 static final int DIRTY = 0x00200000;
1478
1479 /**
1480 * View flag indicating whether this view was invalidated by an opaque
1481 * invalidate request.
1482 *
1483 * @hide
1484 */
1485 static final int DIRTY_OPAQUE = 0x00400000;
1486
1487 /**
1488 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1489 *
1490 * @hide
1491 */
1492 static final int DIRTY_MASK = 0x00600000;
1493
1494 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001495 * Indicates whether the background is opaque.
1496 *
1497 * @hide
1498 */
1499 static final int OPAQUE_BACKGROUND = 0x00800000;
1500
1501 /**
1502 * Indicates whether the scrollbars are opaque.
1503 *
1504 * @hide
1505 */
1506 static final int OPAQUE_SCROLLBARS = 0x01000000;
1507
1508 /**
1509 * Indicates whether the view is opaque.
1510 *
1511 * @hide
1512 */
1513 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001514
1515 /**
1516 * Indicates a prepressed state;
1517 * the short time between ACTION_DOWN and recognizing
1518 * a 'real' press. Prepressed is used to recognize quick taps
1519 * even when they are shorter than ViewConfiguration.getTapTimeout().
1520 *
1521 * @hide
1522 */
1523 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001524
1525 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001526 * Indicates whether the view is temporarily detached.
1527 *
1528 * @hide
1529 */
1530 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001531
1532 /**
1533 * Indicates that we should awaken scroll bars once attached
1534 *
1535 * @hide
1536 */
1537 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001538
1539 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 * The parent this view is attached to.
1541 * {@hide}
1542 *
1543 * @see #getParent()
1544 */
1545 protected ViewParent mParent;
1546
1547 /**
1548 * {@hide}
1549 */
1550 AttachInfo mAttachInfo;
1551
1552 /**
1553 * {@hide}
1554 */
Romain Guy809a7f62009-05-14 15:44:42 -07001555 @ViewDebug.ExportedProperty(flagMapping = {
1556 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1557 name = "FORCE_LAYOUT"),
1558 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1559 name = "LAYOUT_REQUIRED"),
1560 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001561 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001562 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1563 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1564 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1565 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1566 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 int mPrivateFlags;
1568
1569 /**
1570 * Count of how many windows this view has been attached to.
1571 */
1572 int mWindowAttachCount;
1573
1574 /**
1575 * The layout parameters associated with this view and used by the parent
1576 * {@link android.view.ViewGroup} to determine how this view should be
1577 * laid out.
1578 * {@hide}
1579 */
1580 protected ViewGroup.LayoutParams mLayoutParams;
1581
1582 /**
1583 * The view flags hold various views states.
1584 * {@hide}
1585 */
1586 @ViewDebug.ExportedProperty
1587 int mViewFlags;
1588
1589 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001590 * The transform matrix for the View. This transform is calculated internally
1591 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1592 * is used by default. Do *not* use this variable directly; instead call
1593 * getMatrix(), which will automatically recalculate the matrix if necessary
1594 * to get the correct matrix based on the latest rotation and scale properties.
1595 */
1596 private final Matrix mMatrix = new Matrix();
1597
1598 /**
1599 * The transform matrix for the View. This transform is calculated internally
1600 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1601 * is used by default. Do *not* use this variable directly; instead call
1602 * getMatrix(), which will automatically recalculate the matrix if necessary
1603 * to get the correct matrix based on the latest rotation and scale properties.
1604 */
1605 private Matrix mInverseMatrix;
1606
1607 /**
1608 * An internal variable that tracks whether we need to recalculate the
1609 * transform matrix, based on whether the rotation or scaleX/Y properties
1610 * have changed since the matrix was last calculated.
1611 */
1612 private boolean mMatrixDirty = false;
1613
1614 /**
1615 * An internal variable that tracks whether we need to recalculate the
1616 * transform matrix, based on whether the rotation or scaleX/Y properties
1617 * have changed since the matrix was last calculated.
1618 */
1619 private boolean mInverseMatrixDirty = true;
1620
1621 /**
1622 * A variable that tracks whether we need to recalculate the
1623 * transform matrix, based on whether the rotation or scaleX/Y properties
1624 * have changed since the matrix was last calculated. This variable
1625 * is only valid after a call to getMatrix().
1626 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001627 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001628
1629 /**
1630 * The degrees rotation around the pivot point.
1631 */
1632 @ViewDebug.ExportedProperty
1633 private float mRotation = 0f;
1634
1635 /**
1636 * The amount of scale in the x direction around the pivot point. A
1637 * value of 1 means no scaling is applied.
1638 */
1639 @ViewDebug.ExportedProperty
1640 private float mScaleX = 1f;
1641
1642 /**
1643 * The amount of scale in the y direction around the pivot point. A
1644 * value of 1 means no scaling is applied.
1645 */
1646 @ViewDebug.ExportedProperty
1647 private float mScaleY = 1f;
1648
1649 /**
1650 * The amount of scale in the x direction around the pivot point. A
1651 * value of 1 means no scaling is applied.
1652 */
1653 @ViewDebug.ExportedProperty
1654 private float mPivotX = 0f;
1655
1656 /**
1657 * The amount of scale in the y direction around the pivot point. A
1658 * value of 1 means no scaling is applied.
1659 */
1660 @ViewDebug.ExportedProperty
1661 private float mPivotY = 0f;
1662
1663 /**
1664 * The opacity of the View. This is a value from 0 to 1, where 0 means
1665 * completely transparent and 1 means completely opaque.
1666 */
1667 @ViewDebug.ExportedProperty
1668 private float mAlpha = 1f;
1669
1670 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 * The distance in pixels from the left edge of this view's parent
1672 * to the left edge of this view.
1673 * {@hide}
1674 */
1675 @ViewDebug.ExportedProperty
1676 protected int mLeft;
1677 /**
1678 * The distance in pixels from the left edge of this view's parent
1679 * to the right edge of this view.
1680 * {@hide}
1681 */
1682 @ViewDebug.ExportedProperty
1683 protected int mRight;
1684 /**
1685 * The distance in pixels from the top edge of this view's parent
1686 * to the top edge of this view.
1687 * {@hide}
1688 */
1689 @ViewDebug.ExportedProperty
1690 protected int mTop;
1691 /**
1692 * The distance in pixels from the top edge of this view's parent
1693 * to the bottom edge of this view.
1694 * {@hide}
1695 */
1696 @ViewDebug.ExportedProperty
1697 protected int mBottom;
1698
1699 /**
1700 * The offset, in pixels, by which the content of this view is scrolled
1701 * horizontally.
1702 * {@hide}
1703 */
1704 @ViewDebug.ExportedProperty
1705 protected int mScrollX;
1706 /**
1707 * The offset, in pixels, by which the content of this view is scrolled
1708 * vertically.
1709 * {@hide}
1710 */
1711 @ViewDebug.ExportedProperty
1712 protected int mScrollY;
1713
1714 /**
1715 * The left padding in pixels, that is the distance in pixels between the
1716 * left edge of this view and the left edge of its content.
1717 * {@hide}
1718 */
1719 @ViewDebug.ExportedProperty
1720 protected int mPaddingLeft;
1721 /**
1722 * The right padding in pixels, that is the distance in pixels between the
1723 * right edge of this view and the right edge of its content.
1724 * {@hide}
1725 */
1726 @ViewDebug.ExportedProperty
1727 protected int mPaddingRight;
1728 /**
1729 * The top padding in pixels, that is the distance in pixels between the
1730 * top edge of this view and the top edge of its content.
1731 * {@hide}
1732 */
1733 @ViewDebug.ExportedProperty
1734 protected int mPaddingTop;
1735 /**
1736 * The bottom padding in pixels, that is the distance in pixels between the
1737 * bottom edge of this view and the bottom edge of its content.
1738 * {@hide}
1739 */
1740 @ViewDebug.ExportedProperty
1741 protected int mPaddingBottom;
1742
1743 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001744 * Briefly describes the view and is primarily used for accessibility support.
1745 */
1746 private CharSequence mContentDescription;
1747
1748 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 * Cache the paddingRight set by the user to append to the scrollbar's size.
1750 */
1751 @ViewDebug.ExportedProperty
1752 int mUserPaddingRight;
1753
1754 /**
1755 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1756 */
1757 @ViewDebug.ExportedProperty
1758 int mUserPaddingBottom;
1759
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001760 /**
1761 * @hide
1762 */
1763 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1764 /**
1765 * @hide
1766 */
1767 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768
1769 private Resources mResources = null;
1770
1771 private Drawable mBGDrawable;
1772
1773 private int mBackgroundResource;
1774 private boolean mBackgroundSizeChanged;
1775
1776 /**
1777 * Listener used to dispatch focus change events.
1778 * This field should be made private, so it is hidden from the SDK.
1779 * {@hide}
1780 */
1781 protected OnFocusChangeListener mOnFocusChangeListener;
1782
1783 /**
1784 * Listener used to dispatch click events.
1785 * This field should be made private, so it is hidden from the SDK.
1786 * {@hide}
1787 */
1788 protected OnClickListener mOnClickListener;
1789
1790 /**
1791 * Listener used to dispatch long click events.
1792 * This field should be made private, so it is hidden from the SDK.
1793 * {@hide}
1794 */
1795 protected OnLongClickListener mOnLongClickListener;
1796
1797 /**
1798 * Listener used to build the context menu.
1799 * This field should be made private, so it is hidden from the SDK.
1800 * {@hide}
1801 */
1802 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
1803
1804 private OnKeyListener mOnKeyListener;
1805
1806 private OnTouchListener mOnTouchListener;
1807
1808 /**
1809 * The application environment this view lives in.
1810 * This field should be made private, so it is hidden from the SDK.
1811 * {@hide}
1812 */
1813 protected Context mContext;
1814
1815 private ScrollabilityCache mScrollCache;
1816
1817 private int[] mDrawableState = null;
1818
1819 private SoftReference<Bitmap> mDrawingCache;
Romain Guyfbd8f692009-06-26 14:51:58 -07001820 private SoftReference<Bitmap> mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821
1822 /**
1823 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
1824 * the user may specify which view to go to next.
1825 */
1826 private int mNextFocusLeftId = View.NO_ID;
1827
1828 /**
1829 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
1830 * the user may specify which view to go to next.
1831 */
1832 private int mNextFocusRightId = View.NO_ID;
1833
1834 /**
1835 * When this view has focus and the next focus is {@link #FOCUS_UP},
1836 * the user may specify which view to go to next.
1837 */
1838 private int mNextFocusUpId = View.NO_ID;
1839
1840 /**
1841 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
1842 * the user may specify which view to go to next.
1843 */
1844 private int mNextFocusDownId = View.NO_ID;
1845
1846 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08001847 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08001848 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08001849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 private UnsetPressedState mUnsetPressedState;
1851
1852 /**
1853 * Whether the long press's action has been invoked. The tap's action is invoked on the
1854 * up event while a long press is invoked as soon as the long press duration is reached, so
1855 * a long press could be performed before the tap is checked, in which case the tap's action
1856 * should not be invoked.
1857 */
1858 private boolean mHasPerformedLongPress;
1859
1860 /**
1861 * The minimum height of the view. We'll try our best to have the height
1862 * of this view to at least this amount.
1863 */
1864 @ViewDebug.ExportedProperty
1865 private int mMinHeight;
1866
1867 /**
1868 * The minimum width of the view. We'll try our best to have the width
1869 * of this view to at least this amount.
1870 */
1871 @ViewDebug.ExportedProperty
1872 private int mMinWidth;
1873
1874 /**
1875 * The delegate to handle touch events that are physically in this view
1876 * but should be handled by another view.
1877 */
1878 private TouchDelegate mTouchDelegate = null;
1879
1880 /**
1881 * Solid color to use as a background when creating the drawing cache. Enables
1882 * the cache to use 16 bit bitmaps instead of 32 bit.
1883 */
1884 private int mDrawingCacheBackgroundColor = 0;
1885
1886 /**
1887 * Special tree observer used when mAttachInfo is null.
1888 */
1889 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08001890
1891 /**
1892 * Cache the touch slop from the context that created the view.
1893 */
1894 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895
1896 // Used for debug only
1897 static long sInstanceCount = 0;
1898
1899 /**
1900 * Simple constructor to use when creating a view from code.
1901 *
1902 * @param context The Context the view is running in, through which it can
1903 * access the current theme, resources, etc.
1904 */
1905 public View(Context context) {
1906 mContext = context;
1907 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07001908 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Carl Shapiro82fe5642010-02-24 00:14:23 -08001909 // Used for debug only
1910 //++sInstanceCount;
Adam Powelle14579b2009-12-16 18:39:52 -08001911 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 }
1913
1914 /**
1915 * Constructor that is called when inflating a view from XML. This is called
1916 * when a view is being constructed from an XML file, supplying attributes
1917 * that were specified in the XML file. This version uses a default style of
1918 * 0, so the only attribute values applied are those in the Context's Theme
1919 * and the given AttributeSet.
1920 *
1921 * <p>
1922 * The method onFinishInflate() will be called after all children have been
1923 * added.
1924 *
1925 * @param context The Context the view is running in, through which it can
1926 * access the current theme, resources, etc.
1927 * @param attrs The attributes of the XML tag that is inflating the view.
1928 * @see #View(Context, AttributeSet, int)
1929 */
1930 public View(Context context, AttributeSet attrs) {
1931 this(context, attrs, 0);
1932 }
1933
1934 /**
1935 * Perform inflation from XML and apply a class-specific base style. This
1936 * constructor of View allows subclasses to use their own base style when
1937 * they are inflating. For example, a Button class's constructor would call
1938 * this version of the super class constructor and supply
1939 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
1940 * the theme's button style to modify all of the base view attributes (in
1941 * particular its background) as well as the Button class's attributes.
1942 *
1943 * @param context The Context the view is running in, through which it can
1944 * access the current theme, resources, etc.
1945 * @param attrs The attributes of the XML tag that is inflating the view.
1946 * @param defStyle The default style to apply to this view. If 0, no style
1947 * will be applied (beyond what is included in the theme). This may
1948 * either be an attribute resource, whose value will be retrieved
1949 * from the current theme, or an explicit style resource.
1950 * @see #View(Context, AttributeSet)
1951 */
1952 public View(Context context, AttributeSet attrs, int defStyle) {
1953 this(context);
1954
1955 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
1956 defStyle, 0);
1957
1958 Drawable background = null;
1959
1960 int leftPadding = -1;
1961 int topPadding = -1;
1962 int rightPadding = -1;
1963 int bottomPadding = -1;
1964
1965 int padding = -1;
1966
1967 int viewFlagValues = 0;
1968 int viewFlagMasks = 0;
1969
1970 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 int x = 0;
1973 int y = 0;
1974
1975 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
1976
1977 final int N = a.getIndexCount();
1978 for (int i = 0; i < N; i++) {
1979 int attr = a.getIndex(i);
1980 switch (attr) {
1981 case com.android.internal.R.styleable.View_background:
1982 background = a.getDrawable(attr);
1983 break;
1984 case com.android.internal.R.styleable.View_padding:
1985 padding = a.getDimensionPixelSize(attr, -1);
1986 break;
1987 case com.android.internal.R.styleable.View_paddingLeft:
1988 leftPadding = a.getDimensionPixelSize(attr, -1);
1989 break;
1990 case com.android.internal.R.styleable.View_paddingTop:
1991 topPadding = a.getDimensionPixelSize(attr, -1);
1992 break;
1993 case com.android.internal.R.styleable.View_paddingRight:
1994 rightPadding = a.getDimensionPixelSize(attr, -1);
1995 break;
1996 case com.android.internal.R.styleable.View_paddingBottom:
1997 bottomPadding = a.getDimensionPixelSize(attr, -1);
1998 break;
1999 case com.android.internal.R.styleable.View_scrollX:
2000 x = a.getDimensionPixelOffset(attr, 0);
2001 break;
2002 case com.android.internal.R.styleable.View_scrollY:
2003 y = a.getDimensionPixelOffset(attr, 0);
2004 break;
2005 case com.android.internal.R.styleable.View_id:
2006 mID = a.getResourceId(attr, NO_ID);
2007 break;
2008 case com.android.internal.R.styleable.View_tag:
2009 mTag = a.getText(attr);
2010 break;
2011 case com.android.internal.R.styleable.View_fitsSystemWindows:
2012 if (a.getBoolean(attr, false)) {
2013 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2014 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2015 }
2016 break;
2017 case com.android.internal.R.styleable.View_focusable:
2018 if (a.getBoolean(attr, false)) {
2019 viewFlagValues |= FOCUSABLE;
2020 viewFlagMasks |= FOCUSABLE_MASK;
2021 }
2022 break;
2023 case com.android.internal.R.styleable.View_focusableInTouchMode:
2024 if (a.getBoolean(attr, false)) {
2025 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2026 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2027 }
2028 break;
2029 case com.android.internal.R.styleable.View_clickable:
2030 if (a.getBoolean(attr, false)) {
2031 viewFlagValues |= CLICKABLE;
2032 viewFlagMasks |= CLICKABLE;
2033 }
2034 break;
2035 case com.android.internal.R.styleable.View_longClickable:
2036 if (a.getBoolean(attr, false)) {
2037 viewFlagValues |= LONG_CLICKABLE;
2038 viewFlagMasks |= LONG_CLICKABLE;
2039 }
2040 break;
2041 case com.android.internal.R.styleable.View_saveEnabled:
2042 if (!a.getBoolean(attr, true)) {
2043 viewFlagValues |= SAVE_DISABLED;
2044 viewFlagMasks |= SAVE_DISABLED_MASK;
2045 }
2046 break;
2047 case com.android.internal.R.styleable.View_duplicateParentState:
2048 if (a.getBoolean(attr, false)) {
2049 viewFlagValues |= DUPLICATE_PARENT_STATE;
2050 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2051 }
2052 break;
2053 case com.android.internal.R.styleable.View_visibility:
2054 final int visibility = a.getInt(attr, 0);
2055 if (visibility != 0) {
2056 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2057 viewFlagMasks |= VISIBILITY_MASK;
2058 }
2059 break;
2060 case com.android.internal.R.styleable.View_drawingCacheQuality:
2061 final int cacheQuality = a.getInt(attr, 0);
2062 if (cacheQuality != 0) {
2063 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2064 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2065 }
2066 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002067 case com.android.internal.R.styleable.View_contentDescription:
2068 mContentDescription = a.getString(attr);
2069 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2071 if (!a.getBoolean(attr, true)) {
2072 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2073 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2074 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002075 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2077 if (!a.getBoolean(attr, true)) {
2078 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2079 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2080 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002081 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 case R.styleable.View_scrollbars:
2083 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2084 if (scrollbars != SCROLLBARS_NONE) {
2085 viewFlagValues |= scrollbars;
2086 viewFlagMasks |= SCROLLBARS_MASK;
2087 initializeScrollbars(a);
2088 }
2089 break;
2090 case R.styleable.View_fadingEdge:
2091 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2092 if (fadingEdge != FADING_EDGE_NONE) {
2093 viewFlagValues |= fadingEdge;
2094 viewFlagMasks |= FADING_EDGE_MASK;
2095 initializeFadingEdge(a);
2096 }
2097 break;
2098 case R.styleable.View_scrollbarStyle:
2099 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2100 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2101 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2102 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2103 }
2104 break;
2105 case R.styleable.View_isScrollContainer:
2106 setScrollContainer = true;
2107 if (a.getBoolean(attr, false)) {
2108 setScrollContainer(true);
2109 }
2110 break;
2111 case com.android.internal.R.styleable.View_keepScreenOn:
2112 if (a.getBoolean(attr, false)) {
2113 viewFlagValues |= KEEP_SCREEN_ON;
2114 viewFlagMasks |= KEEP_SCREEN_ON;
2115 }
2116 break;
2117 case R.styleable.View_nextFocusLeft:
2118 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2119 break;
2120 case R.styleable.View_nextFocusRight:
2121 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2122 break;
2123 case R.styleable.View_nextFocusUp:
2124 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2125 break;
2126 case R.styleable.View_nextFocusDown:
2127 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2128 break;
2129 case R.styleable.View_minWidth:
2130 mMinWidth = a.getDimensionPixelSize(attr, 0);
2131 break;
2132 case R.styleable.View_minHeight:
2133 mMinHeight = a.getDimensionPixelSize(attr, 0);
2134 break;
Romain Guy9a817362009-05-01 10:57:14 -07002135 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002136 if (context.isRestricted()) {
2137 throw new IllegalStateException("The android:onClick attribute cannot "
2138 + "be used within a restricted context");
2139 }
2140
Romain Guy9a817362009-05-01 10:57:14 -07002141 final String handlerName = a.getString(attr);
2142 if (handlerName != null) {
2143 setOnClickListener(new OnClickListener() {
2144 private Method mHandler;
2145
2146 public void onClick(View v) {
2147 if (mHandler == null) {
2148 try {
2149 mHandler = getContext().getClass().getMethod(handlerName,
2150 View.class);
2151 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002152 int id = getId();
2153 String idText = id == NO_ID ? "" : " with id '"
2154 + getContext().getResources().getResourceEntryName(
2155 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002156 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002157 handlerName + "(View) in the activity "
2158 + getContext().getClass() + " for onClick handler"
2159 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002160 }
2161 }
2162
2163 try {
2164 mHandler.invoke(getContext(), View.this);
2165 } catch (IllegalAccessException e) {
2166 throw new IllegalStateException("Could not execute non "
2167 + "public method of the activity", e);
2168 } catch (InvocationTargetException e) {
2169 throw new IllegalStateException("Could not execute "
2170 + "method of the activity", e);
2171 }
2172 }
2173 });
2174 }
2175 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 }
2177 }
2178
2179 if (background != null) {
2180 setBackgroundDrawable(background);
2181 }
2182
2183 if (padding >= 0) {
2184 leftPadding = padding;
2185 topPadding = padding;
2186 rightPadding = padding;
2187 bottomPadding = padding;
2188 }
2189
2190 // If the user specified the padding (either with android:padding or
2191 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2192 // use the default padding or the padding from the background drawable
2193 // (stored at this point in mPadding*)
2194 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2195 topPadding >= 0 ? topPadding : mPaddingTop,
2196 rightPadding >= 0 ? rightPadding : mPaddingRight,
2197 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2198
2199 if (viewFlagMasks != 0) {
2200 setFlags(viewFlagValues, viewFlagMasks);
2201 }
2202
2203 // Needs to be called after mViewFlags is set
2204 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2205 recomputePadding();
2206 }
2207
2208 if (x != 0 || y != 0) {
2209 scrollTo(x, y);
2210 }
2211
2212 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2213 setScrollContainer(true);
2214 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002215
2216 computeOpaqueFlags();
2217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 a.recycle();
2219 }
2220
2221 /**
2222 * Non-public constructor for use in testing
2223 */
2224 View() {
2225 }
2226
Carl Shapiro82fe5642010-02-24 00:14:23 -08002227 // Used for debug only
2228 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229 @Override
2230 protected void finalize() throws Throwable {
2231 super.finalize();
2232 --sInstanceCount;
2233 }
Carl Shapiro82fe5642010-02-24 00:14:23 -08002234 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235
2236 /**
2237 * <p>
2238 * Initializes the fading edges from a given set of styled attributes. This
2239 * method should be called by subclasses that need fading edges and when an
2240 * instance of these subclasses is created programmatically rather than
2241 * being inflated from XML. This method is automatically called when the XML
2242 * is inflated.
2243 * </p>
2244 *
2245 * @param a the styled attributes set to initialize the fading edges from
2246 */
2247 protected void initializeFadingEdge(TypedArray a) {
2248 initScrollCache();
2249
2250 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2251 R.styleable.View_fadingEdgeLength,
2252 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2253 }
2254
2255 /**
2256 * Returns the size of the vertical faded edges used to indicate that more
2257 * content in this view is visible.
2258 *
2259 * @return The size in pixels of the vertical faded edge or 0 if vertical
2260 * faded edges are not enabled for this view.
2261 * @attr ref android.R.styleable#View_fadingEdgeLength
2262 */
2263 public int getVerticalFadingEdgeLength() {
2264 if (isVerticalFadingEdgeEnabled()) {
2265 ScrollabilityCache cache = mScrollCache;
2266 if (cache != null) {
2267 return cache.fadingEdgeLength;
2268 }
2269 }
2270 return 0;
2271 }
2272
2273 /**
2274 * Set the size of the faded edge used to indicate that more content in this
2275 * view is available. Will not change whether the fading edge is enabled; use
2276 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2277 * to enable the fading edge for the vertical or horizontal fading edges.
2278 *
2279 * @param length The size in pixels of the faded edge used to indicate that more
2280 * content in this view is visible.
2281 */
2282 public void setFadingEdgeLength(int length) {
2283 initScrollCache();
2284 mScrollCache.fadingEdgeLength = length;
2285 }
2286
2287 /**
2288 * Returns the size of the horizontal faded edges used to indicate that more
2289 * content in this view is visible.
2290 *
2291 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2292 * faded edges are not enabled for this view.
2293 * @attr ref android.R.styleable#View_fadingEdgeLength
2294 */
2295 public int getHorizontalFadingEdgeLength() {
2296 if (isHorizontalFadingEdgeEnabled()) {
2297 ScrollabilityCache cache = mScrollCache;
2298 if (cache != null) {
2299 return cache.fadingEdgeLength;
2300 }
2301 }
2302 return 0;
2303 }
2304
2305 /**
2306 * Returns the width of the vertical scrollbar.
2307 *
2308 * @return The width in pixels of the vertical scrollbar or 0 if there
2309 * is no vertical scrollbar.
2310 */
2311 public int getVerticalScrollbarWidth() {
2312 ScrollabilityCache cache = mScrollCache;
2313 if (cache != null) {
2314 ScrollBarDrawable scrollBar = cache.scrollBar;
2315 if (scrollBar != null) {
2316 int size = scrollBar.getSize(true);
2317 if (size <= 0) {
2318 size = cache.scrollBarSize;
2319 }
2320 return size;
2321 }
2322 return 0;
2323 }
2324 return 0;
2325 }
2326
2327 /**
2328 * Returns the height of the horizontal scrollbar.
2329 *
2330 * @return The height in pixels of the horizontal scrollbar or 0 if
2331 * there is no horizontal scrollbar.
2332 */
2333 protected int getHorizontalScrollbarHeight() {
2334 ScrollabilityCache cache = mScrollCache;
2335 if (cache != null) {
2336 ScrollBarDrawable scrollBar = cache.scrollBar;
2337 if (scrollBar != null) {
2338 int size = scrollBar.getSize(false);
2339 if (size <= 0) {
2340 size = cache.scrollBarSize;
2341 }
2342 return size;
2343 }
2344 return 0;
2345 }
2346 return 0;
2347 }
2348
2349 /**
2350 * <p>
2351 * Initializes the scrollbars from a given set of styled attributes. This
2352 * method should be called by subclasses that need scrollbars and when an
2353 * instance of these subclasses is created programmatically rather than
2354 * being inflated from XML. This method is automatically called when the XML
2355 * is inflated.
2356 * </p>
2357 *
2358 * @param a the styled attributes set to initialize the scrollbars from
2359 */
2360 protected void initializeScrollbars(TypedArray a) {
2361 initScrollCache();
2362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002364
2365 if (scrollabilityCache.scrollBar == null) {
2366 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2367 }
2368
Romain Guy8bda2482010-03-02 11:42:11 -08002369 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370
Mike Cleronf116bf82009-09-27 19:14:12 -07002371 if (!fadeScrollbars) {
2372 scrollabilityCache.state = ScrollabilityCache.ON;
2373 }
2374 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2375
2376
2377 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2378 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2379 .getScrollBarFadeDuration());
2380 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2381 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2382 ViewConfiguration.getScrollDefaultDelay());
2383
2384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2386 com.android.internal.R.styleable.View_scrollbarSize,
2387 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2388
2389 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2390 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2391
2392 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2393 if (thumb != null) {
2394 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2395 }
2396
2397 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2398 false);
2399 if (alwaysDraw) {
2400 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2401 }
2402
2403 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2404 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2405
2406 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2407 if (thumb != null) {
2408 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2409 }
2410
2411 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2412 false);
2413 if (alwaysDraw) {
2414 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2415 }
2416
2417 // Re-apply user/background padding so that scrollbar(s) get added
2418 recomputePadding();
2419 }
2420
2421 /**
2422 * <p>
2423 * Initalizes the scrollability cache if necessary.
2424 * </p>
2425 */
2426 private void initScrollCache() {
2427 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002428 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 }
2430 }
2431
2432 /**
2433 * Register a callback to be invoked when focus of this view changed.
2434 *
2435 * @param l The callback that will run.
2436 */
2437 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2438 mOnFocusChangeListener = l;
2439 }
2440
2441 /**
2442 * Returns the focus-change callback registered for this view.
2443 *
2444 * @return The callback, or null if one is not registered.
2445 */
2446 public OnFocusChangeListener getOnFocusChangeListener() {
2447 return mOnFocusChangeListener;
2448 }
2449
2450 /**
2451 * Register a callback to be invoked when this view is clicked. If this view is not
2452 * clickable, it becomes clickable.
2453 *
2454 * @param l The callback that will run
2455 *
2456 * @see #setClickable(boolean)
2457 */
2458 public void setOnClickListener(OnClickListener l) {
2459 if (!isClickable()) {
2460 setClickable(true);
2461 }
2462 mOnClickListener = l;
2463 }
2464
2465 /**
2466 * Register a callback to be invoked when this view is clicked and held. If this view is not
2467 * long clickable, it becomes long clickable.
2468 *
2469 * @param l The callback that will run
2470 *
2471 * @see #setLongClickable(boolean)
2472 */
2473 public void setOnLongClickListener(OnLongClickListener l) {
2474 if (!isLongClickable()) {
2475 setLongClickable(true);
2476 }
2477 mOnLongClickListener = l;
2478 }
2479
2480 /**
2481 * Register a callback to be invoked when the context menu for this view is
2482 * being built. If this view is not long clickable, it becomes long clickable.
2483 *
2484 * @param l The callback that will run
2485 *
2486 */
2487 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2488 if (!isLongClickable()) {
2489 setLongClickable(true);
2490 }
2491 mOnCreateContextMenuListener = l;
2492 }
2493
2494 /**
2495 * Call this view's OnClickListener, if it is defined.
2496 *
2497 * @return True there was an assigned OnClickListener that was called, false
2498 * otherwise is returned.
2499 */
2500 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002501 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 if (mOnClickListener != null) {
2504 playSoundEffect(SoundEffectConstants.CLICK);
2505 mOnClickListener.onClick(this);
2506 return true;
2507 }
2508
2509 return false;
2510 }
2511
2512 /**
2513 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu
2514 * if the OnLongClickListener did not consume the event.
2515 *
2516 * @return True there was an assigned OnLongClickListener that was called, false
2517 * otherwise is returned.
2518 */
2519 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002520 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 boolean handled = false;
2523 if (mOnLongClickListener != null) {
2524 handled = mOnLongClickListener.onLongClick(View.this);
2525 }
2526 if (!handled) {
2527 handled = showContextMenu();
2528 }
2529 if (handled) {
2530 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2531 }
2532 return handled;
2533 }
2534
2535 /**
2536 * Bring up the context menu for this view.
2537 *
2538 * @return Whether a context menu was displayed.
2539 */
2540 public boolean showContextMenu() {
2541 return getParent().showContextMenuForChild(this);
2542 }
2543
2544 /**
Adam Powell6e346362010-07-23 10:18:23 -07002545 * Start an action mode.
2546 *
2547 * @param callback Callback that will control the lifecycle of the action mode
2548 * @return The new action mode if it is started, null otherwise
2549 *
2550 * @see ActionMode
2551 */
2552 public ActionMode startActionMode(ActionMode.Callback callback) {
2553 return getParent().startActionModeForChild(this, callback);
2554 }
2555
2556 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 * Register a callback to be invoked when a key is pressed in this view.
2558 * @param l the key listener to attach to this view
2559 */
2560 public void setOnKeyListener(OnKeyListener l) {
2561 mOnKeyListener = l;
2562 }
2563
2564 /**
2565 * Register a callback to be invoked when a touch event is sent to this view.
2566 * @param l the touch listener to attach to this view
2567 */
2568 public void setOnTouchListener(OnTouchListener l) {
2569 mOnTouchListener = l;
2570 }
2571
2572 /**
2573 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2574 *
2575 * Note: this does not check whether this {@link View} should get focus, it just
2576 * gives it focus no matter what. It should only be called internally by framework
2577 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2578 *
2579 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2580 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2581 * focus moved when requestFocus() is called. It may not always
2582 * apply, in which case use the default View.FOCUS_DOWN.
2583 * @param previouslyFocusedRect The rectangle of the view that had focus
2584 * prior in this View's coordinate system.
2585 */
2586 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2587 if (DBG) {
2588 System.out.println(this + " requestFocus()");
2589 }
2590
2591 if ((mPrivateFlags & FOCUSED) == 0) {
2592 mPrivateFlags |= FOCUSED;
2593
2594 if (mParent != null) {
2595 mParent.requestChildFocus(this, this);
2596 }
2597
2598 onFocusChanged(true, direction, previouslyFocusedRect);
2599 refreshDrawableState();
2600 }
2601 }
2602
2603 /**
2604 * Request that a rectangle of this view be visible on the screen,
2605 * scrolling if necessary just enough.
2606 *
2607 * <p>A View should call this if it maintains some notion of which part
2608 * of its content is interesting. For example, a text editing view
2609 * should call this when its cursor moves.
2610 *
2611 * @param rectangle The rectangle.
2612 * @return Whether any parent scrolled.
2613 */
2614 public boolean requestRectangleOnScreen(Rect rectangle) {
2615 return requestRectangleOnScreen(rectangle, false);
2616 }
2617
2618 /**
2619 * Request that a rectangle of this view be visible on the screen,
2620 * scrolling if necessary just enough.
2621 *
2622 * <p>A View should call this if it maintains some notion of which part
2623 * of its content is interesting. For example, a text editing view
2624 * should call this when its cursor moves.
2625 *
2626 * <p>When <code>immediate</code> is set to true, scrolling will not be
2627 * animated.
2628 *
2629 * @param rectangle The rectangle.
2630 * @param immediate True to forbid animated scrolling, false otherwise
2631 * @return Whether any parent scrolled.
2632 */
2633 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
2634 View child = this;
2635 ViewParent parent = mParent;
2636 boolean scrolled = false;
2637 while (parent != null) {
2638 scrolled |= parent.requestChildRectangleOnScreen(child,
2639 rectangle, immediate);
2640
2641 // offset rect so next call has the rectangle in the
2642 // coordinate system of its direct child.
2643 rectangle.offset(child.getLeft(), child.getTop());
2644 rectangle.offset(-child.getScrollX(), -child.getScrollY());
2645
2646 if (!(parent instanceof View)) {
2647 break;
2648 }
Romain Guy8506ab42009-06-11 17:35:47 -07002649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 child = (View) parent;
2651 parent = child.getParent();
2652 }
2653 return scrolled;
2654 }
2655
2656 /**
2657 * Called when this view wants to give up focus. This will cause
2658 * {@link #onFocusChanged} to be called.
2659 */
2660 public void clearFocus() {
2661 if (DBG) {
2662 System.out.println(this + " clearFocus()");
2663 }
2664
2665 if ((mPrivateFlags & FOCUSED) != 0) {
2666 mPrivateFlags &= ~FOCUSED;
2667
2668 if (mParent != null) {
2669 mParent.clearChildFocus(this);
2670 }
2671
2672 onFocusChanged(false, 0, null);
2673 refreshDrawableState();
2674 }
2675 }
2676
2677 /**
2678 * Called to clear the focus of a view that is about to be removed.
2679 * Doesn't call clearChildFocus, which prevents this view from taking
2680 * focus again before it has been removed from the parent
2681 */
2682 void clearFocusForRemoval() {
2683 if ((mPrivateFlags & FOCUSED) != 0) {
2684 mPrivateFlags &= ~FOCUSED;
2685
2686 onFocusChanged(false, 0, null);
2687 refreshDrawableState();
2688 }
2689 }
2690
2691 /**
2692 * Called internally by the view system when a new view is getting focus.
2693 * This is what clears the old focus.
2694 */
2695 void unFocus() {
2696 if (DBG) {
2697 System.out.println(this + " unFocus()");
2698 }
2699
2700 if ((mPrivateFlags & FOCUSED) != 0) {
2701 mPrivateFlags &= ~FOCUSED;
2702
2703 onFocusChanged(false, 0, null);
2704 refreshDrawableState();
2705 }
2706 }
2707
2708 /**
2709 * Returns true if this view has focus iteself, or is the ancestor of the
2710 * view that has focus.
2711 *
2712 * @return True if this view has or contains focus, false otherwise.
2713 */
2714 @ViewDebug.ExportedProperty
2715 public boolean hasFocus() {
2716 return (mPrivateFlags & FOCUSED) != 0;
2717 }
2718
2719 /**
2720 * Returns true if this view is focusable or if it contains a reachable View
2721 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
2722 * is a View whose parents do not block descendants focus.
2723 *
2724 * Only {@link #VISIBLE} views are considered focusable.
2725 *
2726 * @return True if the view is focusable or if the view contains a focusable
2727 * View, false otherwise.
2728 *
2729 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
2730 */
2731 public boolean hasFocusable() {
2732 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
2733 }
2734
2735 /**
2736 * Called by the view system when the focus state of this view changes.
2737 * When the focus change event is caused by directional navigation, direction
2738 * and previouslyFocusedRect provide insight into where the focus is coming from.
2739 * When overriding, be sure to call up through to the super class so that
2740 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07002741 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 * @param gainFocus True if the View has focus; false otherwise.
2743 * @param direction The direction focus has moved when requestFocus()
2744 * is called to give this view focus. Values are
Romain Guyea4823c2009-12-08 15:03:39 -08002745 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT} or
2746 * {@link #FOCUS_RIGHT}. It may not always apply, in which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 * case use the default.
2748 * @param previouslyFocusedRect The rectangle, in this view's coordinate
2749 * system, of the previously focused view. If applicable, this will be
2750 * passed in as finer grained information about where the focus is coming
2751 * from (in addition to direction). Will be <code>null</code> otherwise.
2752 */
2753 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07002754 if (gainFocus) {
2755 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2756 }
2757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 InputMethodManager imm = InputMethodManager.peekInstance();
2759 if (!gainFocus) {
2760 if (isPressed()) {
2761 setPressed(false);
2762 }
2763 if (imm != null && mAttachInfo != null
2764 && mAttachInfo.mHasWindowFocus) {
2765 imm.focusOut(this);
2766 }
Romain Guya2431d02009-04-30 16:30:00 -07002767 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 } else if (imm != null && mAttachInfo != null
2769 && mAttachInfo.mHasWindowFocus) {
2770 imm.focusIn(this);
2771 }
Romain Guy8506ab42009-06-11 17:35:47 -07002772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 invalidate();
2774 if (mOnFocusChangeListener != null) {
2775 mOnFocusChangeListener.onFocusChange(this, gainFocus);
2776 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002777
2778 if (mAttachInfo != null) {
2779 mAttachInfo.mKeyDispatchState.reset(this);
2780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 }
2782
2783 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002784 * {@inheritDoc}
2785 */
2786 public void sendAccessibilityEvent(int eventType) {
2787 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2788 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
2789 }
2790 }
2791
2792 /**
2793 * {@inheritDoc}
2794 */
2795 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
2796 event.setClassName(getClass().getName());
2797 event.setPackageName(getContext().getPackageName());
2798 event.setEnabled(isEnabled());
2799 event.setContentDescription(mContentDescription);
2800
2801 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
2802 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
2803 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
2804 event.setItemCount(focusablesTempList.size());
2805 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
2806 focusablesTempList.clear();
2807 }
2808
2809 dispatchPopulateAccessibilityEvent(event);
2810
2811 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
2812 }
2813
2814 /**
2815 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
2816 * to be populated.
2817 *
2818 * @param event The event.
2819 *
2820 * @return True if the event population was completed.
2821 */
2822 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2823 return false;
2824 }
2825
2826 /**
2827 * Gets the {@link View} description. It briefly describes the view and is
2828 * primarily used for accessibility support. Set this property to enable
2829 * better accessibility support for your application. This is especially
2830 * true for views that do not have textual representation (For example,
2831 * ImageButton).
2832 *
2833 * @return The content descriptiopn.
2834 *
2835 * @attr ref android.R.styleable#View_contentDescription
2836 */
2837 public CharSequence getContentDescription() {
2838 return mContentDescription;
2839 }
2840
2841 /**
2842 * Sets the {@link View} description. It briefly describes the view and is
2843 * primarily used for accessibility support. Set this property to enable
2844 * better accessibility support for your application. This is especially
2845 * true for views that do not have textual representation (For example,
2846 * ImageButton).
2847 *
2848 * @param contentDescription The content description.
2849 *
2850 * @attr ref android.R.styleable#View_contentDescription
2851 */
2852 public void setContentDescription(CharSequence contentDescription) {
2853 mContentDescription = contentDescription;
2854 }
2855
2856 /**
Romain Guya2431d02009-04-30 16:30:00 -07002857 * Invoked whenever this view loses focus, either by losing window focus or by losing
2858 * focus within its window. This method can be used to clear any state tied to the
2859 * focus. For instance, if a button is held pressed with the trackball and the window
2860 * loses focus, this method can be used to cancel the press.
2861 *
2862 * Subclasses of View overriding this method should always call super.onFocusLost().
2863 *
2864 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07002865 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07002866 *
2867 * @hide pending API council approval
2868 */
2869 protected void onFocusLost() {
2870 resetPressedState();
2871 }
2872
2873 private void resetPressedState() {
2874 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
2875 return;
2876 }
2877
2878 if (isPressed()) {
2879 setPressed(false);
2880
2881 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05002882 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07002883 }
2884 }
2885 }
2886
2887 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 * Returns true if this view has focus
2889 *
2890 * @return True if this view has focus, false otherwise.
2891 */
2892 @ViewDebug.ExportedProperty
2893 public boolean isFocused() {
2894 return (mPrivateFlags & FOCUSED) != 0;
2895 }
2896
2897 /**
2898 * Find the view in the hierarchy rooted at this view that currently has
2899 * focus.
2900 *
2901 * @return The view that currently has focus, or null if no focused view can
2902 * be found.
2903 */
2904 public View findFocus() {
2905 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
2906 }
2907
2908 /**
2909 * Change whether this view is one of the set of scrollable containers in
2910 * its window. This will be used to determine whether the window can
2911 * resize or must pan when a soft input area is open -- scrollable
2912 * containers allow the window to use resize mode since the container
2913 * will appropriately shrink.
2914 */
2915 public void setScrollContainer(boolean isScrollContainer) {
2916 if (isScrollContainer) {
2917 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
2918 mAttachInfo.mScrollContainers.add(this);
2919 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
2920 }
2921 mPrivateFlags |= SCROLL_CONTAINER;
2922 } else {
2923 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
2924 mAttachInfo.mScrollContainers.remove(this);
2925 }
2926 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
2927 }
2928 }
2929
2930 /**
2931 * Returns the quality of the drawing cache.
2932 *
2933 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
2934 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
2935 *
2936 * @see #setDrawingCacheQuality(int)
2937 * @see #setDrawingCacheEnabled(boolean)
2938 * @see #isDrawingCacheEnabled()
2939 *
2940 * @attr ref android.R.styleable#View_drawingCacheQuality
2941 */
2942 public int getDrawingCacheQuality() {
2943 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
2944 }
2945
2946 /**
2947 * Set the drawing cache quality of this view. This value is used only when the
2948 * drawing cache is enabled
2949 *
2950 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
2951 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
2952 *
2953 * @see #getDrawingCacheQuality()
2954 * @see #setDrawingCacheEnabled(boolean)
2955 * @see #isDrawingCacheEnabled()
2956 *
2957 * @attr ref android.R.styleable#View_drawingCacheQuality
2958 */
2959 public void setDrawingCacheQuality(int quality) {
2960 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
2961 }
2962
2963 /**
2964 * Returns whether the screen should remain on, corresponding to the current
2965 * value of {@link #KEEP_SCREEN_ON}.
2966 *
2967 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
2968 *
2969 * @see #setKeepScreenOn(boolean)
2970 *
2971 * @attr ref android.R.styleable#View_keepScreenOn
2972 */
2973 public boolean getKeepScreenOn() {
2974 return (mViewFlags & KEEP_SCREEN_ON) != 0;
2975 }
2976
2977 /**
2978 * Controls whether the screen should remain on, modifying the
2979 * value of {@link #KEEP_SCREEN_ON}.
2980 *
2981 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
2982 *
2983 * @see #getKeepScreenOn()
2984 *
2985 * @attr ref android.R.styleable#View_keepScreenOn
2986 */
2987 public void setKeepScreenOn(boolean keepScreenOn) {
2988 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
2989 }
2990
2991 /**
2992 * @return The user specified next focus ID.
2993 *
2994 * @attr ref android.R.styleable#View_nextFocusLeft
2995 */
2996 public int getNextFocusLeftId() {
2997 return mNextFocusLeftId;
2998 }
2999
3000 /**
3001 * Set the id of the view to use for the next focus
3002 *
3003 * @param nextFocusLeftId
3004 *
3005 * @attr ref android.R.styleable#View_nextFocusLeft
3006 */
3007 public void setNextFocusLeftId(int nextFocusLeftId) {
3008 mNextFocusLeftId = nextFocusLeftId;
3009 }
3010
3011 /**
3012 * @return The user specified next focus ID.
3013 *
3014 * @attr ref android.R.styleable#View_nextFocusRight
3015 */
3016 public int getNextFocusRightId() {
3017 return mNextFocusRightId;
3018 }
3019
3020 /**
3021 * Set the id of the view to use for the next focus
3022 *
3023 * @param nextFocusRightId
3024 *
3025 * @attr ref android.R.styleable#View_nextFocusRight
3026 */
3027 public void setNextFocusRightId(int nextFocusRightId) {
3028 mNextFocusRightId = nextFocusRightId;
3029 }
3030
3031 /**
3032 * @return The user specified next focus ID.
3033 *
3034 * @attr ref android.R.styleable#View_nextFocusUp
3035 */
3036 public int getNextFocusUpId() {
3037 return mNextFocusUpId;
3038 }
3039
3040 /**
3041 * Set the id of the view to use for the next focus
3042 *
3043 * @param nextFocusUpId
3044 *
3045 * @attr ref android.R.styleable#View_nextFocusUp
3046 */
3047 public void setNextFocusUpId(int nextFocusUpId) {
3048 mNextFocusUpId = nextFocusUpId;
3049 }
3050
3051 /**
3052 * @return The user specified next focus ID.
3053 *
3054 * @attr ref android.R.styleable#View_nextFocusDown
3055 */
3056 public int getNextFocusDownId() {
3057 return mNextFocusDownId;
3058 }
3059
3060 /**
3061 * Set the id of the view to use for the next focus
3062 *
3063 * @param nextFocusDownId
3064 *
3065 * @attr ref android.R.styleable#View_nextFocusDown
3066 */
3067 public void setNextFocusDownId(int nextFocusDownId) {
3068 mNextFocusDownId = nextFocusDownId;
3069 }
3070
3071 /**
3072 * Returns the visibility of this view and all of its ancestors
3073 *
3074 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3075 */
3076 public boolean isShown() {
3077 View current = this;
3078 //noinspection ConstantConditions
3079 do {
3080 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3081 return false;
3082 }
3083 ViewParent parent = current.mParent;
3084 if (parent == null) {
3085 return false; // We are not attached to the view root
3086 }
3087 if (!(parent instanceof View)) {
3088 return true;
3089 }
3090 current = (View) parent;
3091 } while (current != null);
3092
3093 return false;
3094 }
3095
3096 /**
3097 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3098 * is set
3099 *
3100 * @param insets Insets for system windows
3101 *
3102 * @return True if this view applied the insets, false otherwise
3103 */
3104 protected boolean fitSystemWindows(Rect insets) {
3105 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3106 mPaddingLeft = insets.left;
3107 mPaddingTop = insets.top;
3108 mPaddingRight = insets.right;
3109 mPaddingBottom = insets.bottom;
3110 requestLayout();
3111 return true;
3112 }
3113 return false;
3114 }
3115
3116 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003117 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3118 * @return True if window has FITS_SYSTEM_WINDOWS set
3119 *
3120 * @hide
3121 */
3122 public boolean isFitsSystemWindowsFlagSet() {
3123 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3124 }
3125
3126 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 * Returns the visibility status for this view.
3128 *
3129 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3130 * @attr ref android.R.styleable#View_visibility
3131 */
3132 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003133 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3134 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3135 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 })
3137 public int getVisibility() {
3138 return mViewFlags & VISIBILITY_MASK;
3139 }
3140
3141 /**
3142 * Set the enabled state of this view.
3143 *
3144 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3145 * @attr ref android.R.styleable#View_visibility
3146 */
3147 @RemotableViewMethod
3148 public void setVisibility(int visibility) {
3149 setFlags(visibility, VISIBILITY_MASK);
3150 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3151 }
3152
3153 /**
3154 * Returns the enabled status for this view. The interpretation of the
3155 * enabled state varies by subclass.
3156 *
3157 * @return True if this view is enabled, false otherwise.
3158 */
3159 @ViewDebug.ExportedProperty
3160 public boolean isEnabled() {
3161 return (mViewFlags & ENABLED_MASK) == ENABLED;
3162 }
3163
3164 /**
3165 * Set the enabled state of this view. The interpretation of the enabled
3166 * state varies by subclass.
3167 *
3168 * @param enabled True if this view is enabled, false otherwise.
3169 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003170 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003172 if (enabled == isEnabled()) return;
3173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3175
3176 /*
3177 * The View most likely has to change its appearance, so refresh
3178 * the drawable state.
3179 */
3180 refreshDrawableState();
3181
3182 // Invalidate too, since the default behavior for views is to be
3183 // be drawn at 50% alpha rather than to change the drawable.
3184 invalidate();
3185 }
3186
3187 /**
3188 * Set whether this view can receive the focus.
3189 *
3190 * Setting this to false will also ensure that this view is not focusable
3191 * in touch mode.
3192 *
3193 * @param focusable If true, this view can receive the focus.
3194 *
3195 * @see #setFocusableInTouchMode(boolean)
3196 * @attr ref android.R.styleable#View_focusable
3197 */
3198 public void setFocusable(boolean focusable) {
3199 if (!focusable) {
3200 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3201 }
3202 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3203 }
3204
3205 /**
3206 * Set whether this view can receive focus while in touch mode.
3207 *
3208 * Setting this to true will also ensure that this view is focusable.
3209 *
3210 * @param focusableInTouchMode If true, this view can receive the focus while
3211 * in touch mode.
3212 *
3213 * @see #setFocusable(boolean)
3214 * @attr ref android.R.styleable#View_focusableInTouchMode
3215 */
3216 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3217 // Focusable in touch mode should always be set before the focusable flag
3218 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3219 // which, in touch mode, will not successfully request focus on this view
3220 // because the focusable in touch mode flag is not set
3221 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3222 if (focusableInTouchMode) {
3223 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3224 }
3225 }
3226
3227 /**
3228 * Set whether this view should have sound effects enabled for events such as
3229 * clicking and touching.
3230 *
3231 * <p>You may wish to disable sound effects for a view if you already play sounds,
3232 * for instance, a dial key that plays dtmf tones.
3233 *
3234 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3235 * @see #isSoundEffectsEnabled()
3236 * @see #playSoundEffect(int)
3237 * @attr ref android.R.styleable#View_soundEffectsEnabled
3238 */
3239 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3240 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3241 }
3242
3243 /**
3244 * @return whether this view should have sound effects enabled for events such as
3245 * clicking and touching.
3246 *
3247 * @see #setSoundEffectsEnabled(boolean)
3248 * @see #playSoundEffect(int)
3249 * @attr ref android.R.styleable#View_soundEffectsEnabled
3250 */
3251 @ViewDebug.ExportedProperty
3252 public boolean isSoundEffectsEnabled() {
3253 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3254 }
3255
3256 /**
3257 * Set whether this view should have haptic feedback for events such as
3258 * long presses.
3259 *
3260 * <p>You may wish to disable haptic feedback if your view already controls
3261 * its own haptic feedback.
3262 *
3263 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3264 * @see #isHapticFeedbackEnabled()
3265 * @see #performHapticFeedback(int)
3266 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3267 */
3268 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3269 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3270 }
3271
3272 /**
3273 * @return whether this view should have haptic feedback enabled for events
3274 * long presses.
3275 *
3276 * @see #setHapticFeedbackEnabled(boolean)
3277 * @see #performHapticFeedback(int)
3278 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3279 */
3280 @ViewDebug.ExportedProperty
3281 public boolean isHapticFeedbackEnabled() {
3282 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3283 }
3284
3285 /**
3286 * If this view doesn't do any drawing on its own, set this flag to
3287 * allow further optimizations. By default, this flag is not set on
3288 * View, but could be set on some View subclasses such as ViewGroup.
3289 *
3290 * Typically, if you override {@link #onDraw} you should clear this flag.
3291 *
3292 * @param willNotDraw whether or not this View draw on its own
3293 */
3294 public void setWillNotDraw(boolean willNotDraw) {
3295 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3296 }
3297
3298 /**
3299 * Returns whether or not this View draws on its own.
3300 *
3301 * @return true if this view has nothing to draw, false otherwise
3302 */
3303 @ViewDebug.ExportedProperty
3304 public boolean willNotDraw() {
3305 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3306 }
3307
3308 /**
3309 * When a View's drawing cache is enabled, drawing is redirected to an
3310 * offscreen bitmap. Some views, like an ImageView, must be able to
3311 * bypass this mechanism if they already draw a single bitmap, to avoid
3312 * unnecessary usage of the memory.
3313 *
3314 * @param willNotCacheDrawing true if this view does not cache its
3315 * drawing, false otherwise
3316 */
3317 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3318 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3319 }
3320
3321 /**
3322 * Returns whether or not this View can cache its drawing or not.
3323 *
3324 * @return true if this view does not cache its drawing, false otherwise
3325 */
3326 @ViewDebug.ExportedProperty
3327 public boolean willNotCacheDrawing() {
3328 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3329 }
3330
3331 /**
3332 * Indicates whether this view reacts to click events or not.
3333 *
3334 * @return true if the view is clickable, false otherwise
3335 *
3336 * @see #setClickable(boolean)
3337 * @attr ref android.R.styleable#View_clickable
3338 */
3339 @ViewDebug.ExportedProperty
3340 public boolean isClickable() {
3341 return (mViewFlags & CLICKABLE) == CLICKABLE;
3342 }
3343
3344 /**
3345 * Enables or disables click events for this view. When a view
3346 * is clickable it will change its state to "pressed" on every click.
3347 * Subclasses should set the view clickable to visually react to
3348 * user's clicks.
3349 *
3350 * @param clickable true to make the view clickable, false otherwise
3351 *
3352 * @see #isClickable()
3353 * @attr ref android.R.styleable#View_clickable
3354 */
3355 public void setClickable(boolean clickable) {
3356 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3357 }
3358
3359 /**
3360 * Indicates whether this view reacts to long click events or not.
3361 *
3362 * @return true if the view is long clickable, false otherwise
3363 *
3364 * @see #setLongClickable(boolean)
3365 * @attr ref android.R.styleable#View_longClickable
3366 */
3367 public boolean isLongClickable() {
3368 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3369 }
3370
3371 /**
3372 * Enables or disables long click events for this view. When a view is long
3373 * clickable it reacts to the user holding down the button for a longer
3374 * duration than a tap. This event can either launch the listener or a
3375 * context menu.
3376 *
3377 * @param longClickable true to make the view long clickable, false otherwise
3378 * @see #isLongClickable()
3379 * @attr ref android.R.styleable#View_longClickable
3380 */
3381 public void setLongClickable(boolean longClickable) {
3382 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3383 }
3384
3385 /**
3386 * Sets the pressed that for this view.
3387 *
3388 * @see #isClickable()
3389 * @see #setClickable(boolean)
3390 *
3391 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3392 * the View's internal state from a previously set "pressed" state.
3393 */
3394 public void setPressed(boolean pressed) {
3395 if (pressed) {
3396 mPrivateFlags |= PRESSED;
3397 } else {
3398 mPrivateFlags &= ~PRESSED;
3399 }
3400 refreshDrawableState();
3401 dispatchSetPressed(pressed);
3402 }
3403
3404 /**
3405 * Dispatch setPressed to all of this View's children.
3406 *
3407 * @see #setPressed(boolean)
3408 *
3409 * @param pressed The new pressed state
3410 */
3411 protected void dispatchSetPressed(boolean pressed) {
3412 }
3413
3414 /**
3415 * Indicates whether the view is currently in pressed state. Unless
3416 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3417 * the pressed state.
3418 *
3419 * @see #setPressed
3420 * @see #isClickable()
3421 * @see #setClickable(boolean)
3422 *
3423 * @return true if the view is currently pressed, false otherwise
3424 */
3425 public boolean isPressed() {
3426 return (mPrivateFlags & PRESSED) == PRESSED;
3427 }
3428
3429 /**
3430 * Indicates whether this view will save its state (that is,
3431 * whether its {@link #onSaveInstanceState} method will be called).
3432 *
3433 * @return Returns true if the view state saving is enabled, else false.
3434 *
3435 * @see #setSaveEnabled(boolean)
3436 * @attr ref android.R.styleable#View_saveEnabled
3437 */
3438 public boolean isSaveEnabled() {
3439 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3440 }
3441
3442 /**
3443 * Controls whether the saving of this view's state is
3444 * enabled (that is, whether its {@link #onSaveInstanceState} method
3445 * will be called). Note that even if freezing is enabled, the
3446 * view still must have an id assigned to it (via {@link #setId setId()})
3447 * for its state to be saved. This flag can only disable the
3448 * saving of this view; any child views may still have their state saved.
3449 *
3450 * @param enabled Set to false to <em>disable</em> state saving, or true
3451 * (the default) to allow it.
3452 *
3453 * @see #isSaveEnabled()
3454 * @see #setId(int)
3455 * @see #onSaveInstanceState()
3456 * @attr ref android.R.styleable#View_saveEnabled
3457 */
3458 public void setSaveEnabled(boolean enabled) {
3459 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3460 }
3461
3462
3463 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003464 * Indicates whether the entire hierarchy under this view will save its
3465 * state when a state saving traversal occurs from its parent. The default
3466 * is true; if false, these views will not be saved unless
3467 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3468 *
3469 * @return Returns true if the view state saving from parent is enabled, else false.
3470 *
3471 * @see #setSaveFromParentEnabled(boolean)
3472 */
3473 public boolean isSaveFromParentEnabled() {
3474 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3475 }
3476
3477 /**
3478 * Controls whether the entire hierarchy under this view will save its
3479 * state when a state saving traversal occurs from its parent. The default
3480 * is true; if false, these views will not be saved unless
3481 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3482 *
3483 * @param enabled Set to false to <em>disable</em> state saving, or true
3484 * (the default) to allow it.
3485 *
3486 * @see #isSaveFromParentEnabled()
3487 * @see #setId(int)
3488 * @see #onSaveInstanceState()
3489 */
3490 public void setSaveFromParentEnabled(boolean enabled) {
3491 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
3492 }
3493
3494
3495 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 * Returns whether this View is able to take focus.
3497 *
3498 * @return True if this view can take focus, or false otherwise.
3499 * @attr ref android.R.styleable#View_focusable
3500 */
3501 @ViewDebug.ExportedProperty
3502 public final boolean isFocusable() {
3503 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3504 }
3505
3506 /**
3507 * When a view is focusable, it may not want to take focus when in touch mode.
3508 * For example, a button would like focus when the user is navigating via a D-pad
3509 * so that the user can click on it, but once the user starts touching the screen,
3510 * the button shouldn't take focus
3511 * @return Whether the view is focusable in touch mode.
3512 * @attr ref android.R.styleable#View_focusableInTouchMode
3513 */
3514 @ViewDebug.ExportedProperty
3515 public final boolean isFocusableInTouchMode() {
3516 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3517 }
3518
3519 /**
3520 * Find the nearest view in the specified direction that can take focus.
3521 * This does not actually give focus to that view.
3522 *
3523 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3524 *
3525 * @return The nearest focusable in the specified direction, or null if none
3526 * can be found.
3527 */
3528 public View focusSearch(int direction) {
3529 if (mParent != null) {
3530 return mParent.focusSearch(this, direction);
3531 } else {
3532 return null;
3533 }
3534 }
3535
3536 /**
3537 * This method is the last chance for the focused view and its ancestors to
3538 * respond to an arrow key. This is called when the focused view did not
3539 * consume the key internally, nor could the view system find a new view in
3540 * the requested direction to give focus to.
3541 *
3542 * @param focused The currently focused view.
3543 * @param direction The direction focus wants to move. One of FOCUS_UP,
3544 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3545 * @return True if the this view consumed this unhandled move.
3546 */
3547 public boolean dispatchUnhandledMove(View focused, int direction) {
3548 return false;
3549 }
3550
3551 /**
3552 * If a user manually specified the next view id for a particular direction,
3553 * use the root to look up the view. Once a view is found, it is cached
3554 * for future lookups.
3555 * @param root The root view of the hierarchy containing this view.
3556 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3557 * @return The user specified next view, or null if there is none.
3558 */
3559 View findUserSetNextFocus(View root, int direction) {
3560 switch (direction) {
3561 case FOCUS_LEFT:
3562 if (mNextFocusLeftId == View.NO_ID) return null;
3563 return findViewShouldExist(root, mNextFocusLeftId);
3564 case FOCUS_RIGHT:
3565 if (mNextFocusRightId == View.NO_ID) return null;
3566 return findViewShouldExist(root, mNextFocusRightId);
3567 case FOCUS_UP:
3568 if (mNextFocusUpId == View.NO_ID) return null;
3569 return findViewShouldExist(root, mNextFocusUpId);
3570 case FOCUS_DOWN:
3571 if (mNextFocusDownId == View.NO_ID) return null;
3572 return findViewShouldExist(root, mNextFocusDownId);
3573 }
3574 return null;
3575 }
3576
3577 private static View findViewShouldExist(View root, int childViewId) {
3578 View result = root.findViewById(childViewId);
3579 if (result == null) {
3580 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3581 + "by user for id " + childViewId);
3582 }
3583 return result;
3584 }
3585
3586 /**
3587 * Find and return all focusable views that are descendants of this view,
3588 * possibly including this view if it is focusable itself.
3589 *
3590 * @param direction The direction of the focus
3591 * @return A list of focusable views
3592 */
3593 public ArrayList<View> getFocusables(int direction) {
3594 ArrayList<View> result = new ArrayList<View>(24);
3595 addFocusables(result, direction);
3596 return result;
3597 }
3598
3599 /**
3600 * Add any focusable views that are descendants of this view (possibly
3601 * including this view if it is focusable itself) to views. If we are in touch mode,
3602 * only add views that are also focusable in touch mode.
3603 *
3604 * @param views Focusable views found so far
3605 * @param direction The direction of the focus
3606 */
3607 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003608 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610
svetoslavganov75986cf2009-05-14 22:28:01 -07003611 /**
3612 * Adds any focusable views that are descendants of this view (possibly
3613 * including this view if it is focusable itself) to views. This method
3614 * adds all focusable views regardless if we are in touch mode or
3615 * only views focusable in touch mode if we are in touch mode depending on
3616 * the focusable mode paramater.
3617 *
3618 * @param views Focusable views found so far or null if all we are interested is
3619 * the number of focusables.
3620 * @param direction The direction of the focus.
3621 * @param focusableMode The type of focusables to be added.
3622 *
3623 * @see #FOCUSABLES_ALL
3624 * @see #FOCUSABLES_TOUCH_MODE
3625 */
3626 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3627 if (!isFocusable()) {
3628 return;
3629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630
svetoslavganov75986cf2009-05-14 22:28:01 -07003631 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3632 isInTouchMode() && !isFocusableInTouchMode()) {
3633 return;
3634 }
3635
3636 if (views != null) {
3637 views.add(this);
3638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 }
3640
3641 /**
3642 * Find and return all touchable views that are descendants of this view,
3643 * possibly including this view if it is touchable itself.
3644 *
3645 * @return A list of touchable views
3646 */
3647 public ArrayList<View> getTouchables() {
3648 ArrayList<View> result = new ArrayList<View>();
3649 addTouchables(result);
3650 return result;
3651 }
3652
3653 /**
3654 * Add any touchable views that are descendants of this view (possibly
3655 * including this view if it is touchable itself) to views.
3656 *
3657 * @param views Touchable views found so far
3658 */
3659 public void addTouchables(ArrayList<View> views) {
3660 final int viewFlags = mViewFlags;
3661
3662 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
3663 && (viewFlags & ENABLED_MASK) == ENABLED) {
3664 views.add(this);
3665 }
3666 }
3667
3668 /**
3669 * Call this to try to give focus to a specific view or to one of its
3670 * descendants.
3671 *
3672 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3673 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3674 * while the device is in touch mode.
3675 *
3676 * See also {@link #focusSearch}, which is what you call to say that you
3677 * have focus, and you want your parent to look for the next one.
3678 *
3679 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
3680 * {@link #FOCUS_DOWN} and <code>null</code>.
3681 *
3682 * @return Whether this view or one of its descendants actually took focus.
3683 */
3684 public final boolean requestFocus() {
3685 return requestFocus(View.FOCUS_DOWN);
3686 }
3687
3688
3689 /**
3690 * Call this to try to give focus to a specific view or to one of its
3691 * descendants and give it a hint about what direction focus is heading.
3692 *
3693 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3694 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3695 * while the device is in touch mode.
3696 *
3697 * See also {@link #focusSearch}, which is what you call to say that you
3698 * have focus, and you want your parent to look for the next one.
3699 *
3700 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
3701 * <code>null</code> set for the previously focused rectangle.
3702 *
3703 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3704 * @return Whether this view or one of its descendants actually took focus.
3705 */
3706 public final boolean requestFocus(int direction) {
3707 return requestFocus(direction, null);
3708 }
3709
3710 /**
3711 * Call this to try to give focus to a specific view or to one of its descendants
3712 * and give it hints about the direction and a specific rectangle that the focus
3713 * is coming from. The rectangle can help give larger views a finer grained hint
3714 * about where focus is coming from, and therefore, where to show selection, or
3715 * forward focus change internally.
3716 *
3717 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3718 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3719 * while the device is in touch mode.
3720 *
3721 * A View will not take focus if it is not visible.
3722 *
3723 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
3724 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
3725 *
3726 * See also {@link #focusSearch}, which is what you call to say that you
3727 * have focus, and you want your parent to look for the next one.
3728 *
3729 * You may wish to override this method if your custom {@link View} has an internal
3730 * {@link View} that it wishes to forward the request to.
3731 *
3732 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3733 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
3734 * to give a finer grained hint about where focus is coming from. May be null
3735 * if there is no hint.
3736 * @return Whether this view or one of its descendants actually took focus.
3737 */
3738 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
3739 // need to be focusable
3740 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
3741 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3742 return false;
3743 }
3744
3745 // need to be focusable in touch mode if in touch mode
3746 if (isInTouchMode() &&
3747 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
3748 return false;
3749 }
3750
3751 // need to not have any parents blocking us
3752 if (hasAncestorThatBlocksDescendantFocus()) {
3753 return false;
3754 }
3755
3756 handleFocusGainInternal(direction, previouslyFocusedRect);
3757 return true;
3758 }
3759
3760 /**
3761 * Call this to try to give focus to a specific view or to one of its descendants. This is a
3762 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
3763 * touch mode to request focus when they are touched.
3764 *
3765 * @return Whether this view or one of its descendants actually took focus.
3766 *
3767 * @see #isInTouchMode()
3768 *
3769 */
3770 public final boolean requestFocusFromTouch() {
3771 // Leave touch mode if we need to
3772 if (isInTouchMode()) {
3773 View root = getRootView();
3774 if (root != null) {
3775 ViewRoot viewRoot = (ViewRoot)root.getParent();
3776 if (viewRoot != null) {
3777 viewRoot.ensureTouchMode(false);
3778 }
3779 }
3780 }
3781 return requestFocus(View.FOCUS_DOWN);
3782 }
3783
3784 /**
3785 * @return Whether any ancestor of this view blocks descendant focus.
3786 */
3787 private boolean hasAncestorThatBlocksDescendantFocus() {
3788 ViewParent ancestor = mParent;
3789 while (ancestor instanceof ViewGroup) {
3790 final ViewGroup vgAncestor = (ViewGroup) ancestor;
3791 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
3792 return true;
3793 } else {
3794 ancestor = vgAncestor.getParent();
3795 }
3796 }
3797 return false;
3798 }
3799
3800 /**
Romain Guya440b002010-02-24 15:57:54 -08003801 * @hide
3802 */
3803 public void dispatchStartTemporaryDetach() {
3804 onStartTemporaryDetach();
3805 }
3806
3807 /**
3808 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
3810 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08003811 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 */
3813 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08003814 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08003815 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08003816 }
3817
3818 /**
3819 * @hide
3820 */
3821 public void dispatchFinishTemporaryDetach() {
3822 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 }
Romain Guy8506ab42009-06-11 17:35:47 -07003824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 /**
3826 * Called after {@link #onStartTemporaryDetach} when the container is done
3827 * changing the view.
3828 */
3829 public void onFinishTemporaryDetach() {
3830 }
Romain Guy8506ab42009-06-11 17:35:47 -07003831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 /**
3833 * capture information of this view for later analysis: developement only
3834 * check dynamic switch to make sure we only dump view
3835 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
3836 */
3837 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003838 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 return;
3840 }
3841 ViewDebug.dumpCapturedView(subTag, v);
3842 }
3843
3844 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003845 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
3846 * for this view's window. Returns null if the view is not currently attached
3847 * to the window. Normally you will not need to use this directly, but
3848 * just use the standard high-level event callbacks like {@link #onKeyDown}.
3849 */
3850 public KeyEvent.DispatcherState getKeyDispatcherState() {
3851 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
3852 }
3853
3854 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 * Dispatch a key event before it is processed by any input method
3856 * associated with the view hierarchy. This can be used to intercept
3857 * key events in special situations before the IME consumes them; a
3858 * typical example would be handling the BACK key to update the application's
3859 * UI instead of allowing the IME to see it and close itself.
3860 *
3861 * @param event The key event to be dispatched.
3862 * @return True if the event was handled, false otherwise.
3863 */
3864 public boolean dispatchKeyEventPreIme(KeyEvent event) {
3865 return onKeyPreIme(event.getKeyCode(), event);
3866 }
3867
3868 /**
3869 * Dispatch a key event to the next view on the focus path. This path runs
3870 * from the top of the view tree down to the currently focused view. If this
3871 * view has focus, it will dispatch to itself. Otherwise it will dispatch
3872 * the next node down the focus path. This method also fires any key
3873 * listeners.
3874 *
3875 * @param event The key event to be dispatched.
3876 * @return True if the event was handled, false otherwise.
3877 */
3878 public boolean dispatchKeyEvent(KeyEvent event) {
3879 // If any attached key listener a first crack at the event.
3880 //noinspection SimplifiableIfStatement
3881
3882 if (android.util.Config.LOGV) {
3883 captureViewInfo("captureViewKeyEvent", this);
3884 }
3885
3886 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
3887 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
3888 return true;
3889 }
3890
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003891 return event.dispatch(this, mAttachInfo != null
3892 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 }
3894
3895 /**
3896 * Dispatches a key shortcut event.
3897 *
3898 * @param event The key event to be dispatched.
3899 * @return True if the event was handled by the view, false otherwise.
3900 */
3901 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3902 return onKeyShortcut(event.getKeyCode(), event);
3903 }
3904
3905 /**
3906 * Pass the touch screen motion event down to the target view, or this
3907 * view if it is the target.
3908 *
3909 * @param event The motion event to be dispatched.
3910 * @return True if the event was handled by the view, false otherwise.
3911 */
3912 public boolean dispatchTouchEvent(MotionEvent event) {
3913 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
3914 mOnTouchListener.onTouch(this, event)) {
3915 return true;
3916 }
3917 return onTouchEvent(event);
3918 }
3919
3920 /**
3921 * Pass a trackball motion event down to the focused view.
3922 *
3923 * @param event The motion event to be dispatched.
3924 * @return True if the event was handled by the view, false otherwise.
3925 */
3926 public boolean dispatchTrackballEvent(MotionEvent event) {
3927 //Log.i("view", "view=" + this + ", " + event.toString());
3928 return onTrackballEvent(event);
3929 }
3930
3931 /**
3932 * Called when the window containing this view gains or loses window focus.
3933 * ViewGroups should override to route to their children.
3934 *
3935 * @param hasFocus True if the window containing this view now has focus,
3936 * false otherwise.
3937 */
3938 public void dispatchWindowFocusChanged(boolean hasFocus) {
3939 onWindowFocusChanged(hasFocus);
3940 }
3941
3942 /**
3943 * Called when the window containing this view gains or loses focus. Note
3944 * that this is separate from view focus: to receive key events, both
3945 * your view and its window must have focus. If a window is displayed
3946 * on top of yours that takes input focus, then your own window will lose
3947 * focus but the view focus will remain unchanged.
3948 *
3949 * @param hasWindowFocus True if the window containing this view now has
3950 * focus, false otherwise.
3951 */
3952 public void onWindowFocusChanged(boolean hasWindowFocus) {
3953 InputMethodManager imm = InputMethodManager.peekInstance();
3954 if (!hasWindowFocus) {
3955 if (isPressed()) {
3956 setPressed(false);
3957 }
3958 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
3959 imm.focusOut(this);
3960 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05003961 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003962 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
3964 imm.focusIn(this);
3965 }
3966 refreshDrawableState();
3967 }
3968
3969 /**
3970 * Returns true if this view is in a window that currently has window focus.
3971 * Note that this is not the same as the view itself having focus.
3972 *
3973 * @return True if this view is in a window that currently has window focus.
3974 */
3975 public boolean hasWindowFocus() {
3976 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
3977 }
3978
3979 /**
Adam Powell326d8082009-12-09 15:10:07 -08003980 * Dispatch a view visibility change down the view hierarchy.
3981 * ViewGroups should override to route to their children.
3982 * @param changedView The view whose visibility changed. Could be 'this' or
3983 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08003984 * @param visibility The new visibility of changedView: {@link #VISIBLE},
3985 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08003986 */
3987 protected void dispatchVisibilityChanged(View changedView, int visibility) {
3988 onVisibilityChanged(changedView, visibility);
3989 }
3990
3991 /**
3992 * Called when the visibility of the view or an ancestor of the view is changed.
3993 * @param changedView The view whose visibility changed. Could be 'this' or
3994 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08003995 * @param visibility The new visibility of changedView: {@link #VISIBLE},
3996 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08003997 */
3998 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07003999 if (visibility == VISIBLE) {
4000 if (mAttachInfo != null) {
4001 initialAwakenScrollBars();
4002 } else {
4003 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4004 }
4005 }
Adam Powell326d8082009-12-09 15:10:07 -08004006 }
4007
4008 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004009 * Dispatch a hint about whether this view is displayed. For instance, when
4010 * a View moves out of the screen, it might receives a display hint indicating
4011 * the view is not displayed. Applications should not <em>rely</em> on this hint
4012 * as there is no guarantee that they will receive one.
4013 *
4014 * @param hint A hint about whether or not this view is displayed:
4015 * {@link #VISIBLE} or {@link #INVISIBLE}.
4016 */
4017 public void dispatchDisplayHint(int hint) {
4018 onDisplayHint(hint);
4019 }
4020
4021 /**
4022 * Gives this view a hint about whether is displayed or not. For instance, when
4023 * a View moves out of the screen, it might receives a display hint indicating
4024 * the view is not displayed. Applications should not <em>rely</em> on this hint
4025 * as there is no guarantee that they will receive one.
4026 *
4027 * @param hint A hint about whether or not this view is displayed:
4028 * {@link #VISIBLE} or {@link #INVISIBLE}.
4029 */
4030 protected void onDisplayHint(int hint) {
4031 }
4032
4033 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 * Dispatch a window visibility change down the view hierarchy.
4035 * ViewGroups should override to route to their children.
4036 *
4037 * @param visibility The new visibility of the window.
4038 *
4039 * @see #onWindowVisibilityChanged
4040 */
4041 public void dispatchWindowVisibilityChanged(int visibility) {
4042 onWindowVisibilityChanged(visibility);
4043 }
4044
4045 /**
4046 * Called when the window containing has change its visibility
4047 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4048 * that this tells you whether or not your window is being made visible
4049 * to the window manager; this does <em>not</em> tell you whether or not
4050 * your window is obscured by other windows on the screen, even if it
4051 * is itself visible.
4052 *
4053 * @param visibility The new visibility of the window.
4054 */
4055 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004056 if (visibility == VISIBLE) {
4057 initialAwakenScrollBars();
4058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 }
4060
4061 /**
4062 * Returns the current visibility of the window this view is attached to
4063 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4064 *
4065 * @return Returns the current visibility of the view's window.
4066 */
4067 public int getWindowVisibility() {
4068 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4069 }
4070
4071 /**
4072 * Retrieve the overall visible display size in which the window this view is
4073 * attached to has been positioned in. This takes into account screen
4074 * decorations above the window, for both cases where the window itself
4075 * is being position inside of them or the window is being placed under
4076 * then and covered insets are used for the window to position its content
4077 * inside. In effect, this tells you the available area where content can
4078 * be placed and remain visible to users.
4079 *
4080 * <p>This function requires an IPC back to the window manager to retrieve
4081 * the requested information, so should not be used in performance critical
4082 * code like drawing.
4083 *
4084 * @param outRect Filled in with the visible display frame. If the view
4085 * is not attached to a window, this is simply the raw display size.
4086 */
4087 public void getWindowVisibleDisplayFrame(Rect outRect) {
4088 if (mAttachInfo != null) {
4089 try {
4090 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4091 } catch (RemoteException e) {
4092 return;
4093 }
4094 // XXX This is really broken, and probably all needs to be done
4095 // in the window manager, and we need to know more about whether
4096 // we want the area behind or in front of the IME.
4097 final Rect insets = mAttachInfo.mVisibleInsets;
4098 outRect.left += insets.left;
4099 outRect.top += insets.top;
4100 outRect.right -= insets.right;
4101 outRect.bottom -= insets.bottom;
4102 return;
4103 }
4104 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4105 outRect.set(0, 0, d.getWidth(), d.getHeight());
4106 }
4107
4108 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004109 * Dispatch a notification about a resource configuration change down
4110 * the view hierarchy.
4111 * ViewGroups should override to route to their children.
4112 *
4113 * @param newConfig The new resource configuration.
4114 *
4115 * @see #onConfigurationChanged
4116 */
4117 public void dispatchConfigurationChanged(Configuration newConfig) {
4118 onConfigurationChanged(newConfig);
4119 }
4120
4121 /**
4122 * Called when the current configuration of the resources being used
4123 * by the application have changed. You can use this to decide when
4124 * to reload resources that can changed based on orientation and other
4125 * configuration characterstics. You only need to use this if you are
4126 * not relying on the normal {@link android.app.Activity} mechanism of
4127 * recreating the activity instance upon a configuration change.
4128 *
4129 * @param newConfig The new resource configuration.
4130 */
4131 protected void onConfigurationChanged(Configuration newConfig) {
4132 }
4133
4134 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 * Private function to aggregate all per-view attributes in to the view
4136 * root.
4137 */
4138 void dispatchCollectViewAttributes(int visibility) {
4139 performCollectViewAttributes(visibility);
4140 }
4141
4142 void performCollectViewAttributes(int visibility) {
4143 //noinspection PointlessBitwiseExpression
4144 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4145 == (VISIBLE | KEEP_SCREEN_ON)) {
4146 mAttachInfo.mKeepScreenOn = true;
4147 }
4148 }
4149
4150 void needGlobalAttributesUpdate(boolean force) {
4151 AttachInfo ai = mAttachInfo;
4152 if (ai != null) {
4153 if (ai.mKeepScreenOn || force) {
4154 ai.mRecomputeGlobalAttributes = true;
4155 }
4156 }
4157 }
4158
4159 /**
4160 * Returns whether the device is currently in touch mode. Touch mode is entered
4161 * once the user begins interacting with the device by touch, and affects various
4162 * things like whether focus is always visible to the user.
4163 *
4164 * @return Whether the device is in touch mode.
4165 */
4166 @ViewDebug.ExportedProperty
4167 public boolean isInTouchMode() {
4168 if (mAttachInfo != null) {
4169 return mAttachInfo.mInTouchMode;
4170 } else {
4171 return ViewRoot.isInTouchMode();
4172 }
4173 }
4174
4175 /**
4176 * Returns the context the view is running in, through which it can
4177 * access the current theme, resources, etc.
4178 *
4179 * @return The view's Context.
4180 */
4181 @ViewDebug.CapturedViewProperty
4182 public final Context getContext() {
4183 return mContext;
4184 }
4185
4186 /**
4187 * Handle a key event before it is processed by any input method
4188 * associated with the view hierarchy. This can be used to intercept
4189 * key events in special situations before the IME consumes them; a
4190 * typical example would be handling the BACK key to update the application's
4191 * UI instead of allowing the IME to see it and close itself.
4192 *
4193 * @param keyCode The value in event.getKeyCode().
4194 * @param event Description of the key event.
4195 * @return If you handled the event, return true. If you want to allow the
4196 * event to be handled by the next receiver, return false.
4197 */
4198 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4199 return false;
4200 }
4201
4202 /**
4203 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4204 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4205 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4206 * is released, if the view is enabled and clickable.
4207 *
4208 * @param keyCode A key code that represents the button pressed, from
4209 * {@link android.view.KeyEvent}.
4210 * @param event The KeyEvent object that defines the button action.
4211 */
4212 public boolean onKeyDown(int keyCode, KeyEvent event) {
4213 boolean result = false;
4214
4215 switch (keyCode) {
4216 case KeyEvent.KEYCODE_DPAD_CENTER:
4217 case KeyEvent.KEYCODE_ENTER: {
4218 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4219 return true;
4220 }
4221 // Long clickable items don't necessarily have to be clickable
4222 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4223 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4224 (event.getRepeatCount() == 0)) {
4225 setPressed(true);
4226 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004227 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 }
4229 return true;
4230 }
4231 break;
4232 }
4233 }
4234 return result;
4235 }
4236
4237 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004238 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4239 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4240 * the event).
4241 */
4242 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4243 return false;
4244 }
4245
4246 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4248 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4249 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4250 * {@link KeyEvent#KEYCODE_ENTER} is released.
4251 *
4252 * @param keyCode A key code that represents the button pressed, from
4253 * {@link android.view.KeyEvent}.
4254 * @param event The KeyEvent object that defines the button action.
4255 */
4256 public boolean onKeyUp(int keyCode, KeyEvent event) {
4257 boolean result = false;
4258
4259 switch (keyCode) {
4260 case KeyEvent.KEYCODE_DPAD_CENTER:
4261 case KeyEvent.KEYCODE_ENTER: {
4262 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4263 return true;
4264 }
4265 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4266 setPressed(false);
4267
4268 if (!mHasPerformedLongPress) {
4269 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004270 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271
4272 result = performClick();
4273 }
4274 }
4275 break;
4276 }
4277 }
4278 return result;
4279 }
4280
4281 /**
4282 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4283 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4284 * the event).
4285 *
4286 * @param keyCode A key code that represents the button pressed, from
4287 * {@link android.view.KeyEvent}.
4288 * @param repeatCount The number of times the action was made.
4289 * @param event The KeyEvent object that defines the button action.
4290 */
4291 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4292 return false;
4293 }
4294
4295 /**
4296 * Called when an unhandled key shortcut event occurs.
4297 *
4298 * @param keyCode The value in event.getKeyCode().
4299 * @param event Description of the key event.
4300 * @return If you handled the event, return true. If you want to allow the
4301 * event to be handled by the next receiver, return false.
4302 */
4303 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4304 return false;
4305 }
4306
4307 /**
4308 * Check whether the called view is a text editor, in which case it
4309 * would make sense to automatically display a soft input window for
4310 * it. Subclasses should override this if they implement
4311 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004312 * a call on that method would return a non-null InputConnection, and
4313 * they are really a first-class editor that the user would normally
4314 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004315 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004316 * <p>The default implementation always returns false. This does
4317 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4318 * will not be called or the user can not otherwise perform edits on your
4319 * view; it is just a hint to the system that this is not the primary
4320 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004321 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 * @return Returns true if this view is a text editor, else false.
4323 */
4324 public boolean onCheckIsTextEditor() {
4325 return false;
4326 }
Romain Guy8506ab42009-06-11 17:35:47 -07004327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 /**
4329 * Create a new InputConnection for an InputMethod to interact
4330 * with the view. The default implementation returns null, since it doesn't
4331 * support input methods. You can override this to implement such support.
4332 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004333 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 * <p>When implementing this, you probably also want to implement
4335 * {@link #onCheckIsTextEditor()} to indicate you will return a
4336 * non-null InputConnection.
4337 *
4338 * @param outAttrs Fill in with attribute information about the connection.
4339 */
4340 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4341 return null;
4342 }
4343
4344 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004345 * Called by the {@link android.view.inputmethod.InputMethodManager}
4346 * when a view who is not the current
4347 * input connection target is trying to make a call on the manager. The
4348 * default implementation returns false; you can override this to return
4349 * true for certain views if you are performing InputConnection proxying
4350 * to them.
4351 * @param view The View that is making the InputMethodManager call.
4352 * @return Return true to allow the call, false to reject.
4353 */
4354 public boolean checkInputConnectionProxy(View view) {
4355 return false;
4356 }
Romain Guy8506ab42009-06-11 17:35:47 -07004357
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004358 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 * Show the context menu for this view. It is not safe to hold on to the
4360 * menu after returning from this method.
4361 *
4362 * @param menu The context menu to populate
4363 */
4364 public void createContextMenu(ContextMenu menu) {
4365 ContextMenuInfo menuInfo = getContextMenuInfo();
4366
4367 // Sets the current menu info so all items added to menu will have
4368 // my extra info set.
4369 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4370
4371 onCreateContextMenu(menu);
4372 if (mOnCreateContextMenuListener != null) {
4373 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4374 }
4375
4376 // Clear the extra information so subsequent items that aren't mine don't
4377 // have my extra info.
4378 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4379
4380 if (mParent != null) {
4381 mParent.createContextMenu(menu);
4382 }
4383 }
4384
4385 /**
4386 * Views should implement this if they have extra information to associate
4387 * with the context menu. The return result is supplied as a parameter to
4388 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4389 * callback.
4390 *
4391 * @return Extra information about the item for which the context menu
4392 * should be shown. This information will vary across different
4393 * subclasses of View.
4394 */
4395 protected ContextMenuInfo getContextMenuInfo() {
4396 return null;
4397 }
4398
4399 /**
4400 * Views should implement this if the view itself is going to add items to
4401 * the context menu.
4402 *
4403 * @param menu the context menu to populate
4404 */
4405 protected void onCreateContextMenu(ContextMenu menu) {
4406 }
4407
4408 /**
4409 * Implement this method to handle trackball motion events. The
4410 * <em>relative</em> movement of the trackball since the last event
4411 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4412 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4413 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4414 * they will often be fractional values, representing the more fine-grained
4415 * movement information available from a trackball).
4416 *
4417 * @param event The motion event.
4418 * @return True if the event was handled, false otherwise.
4419 */
4420 public boolean onTrackballEvent(MotionEvent event) {
4421 return false;
4422 }
4423
4424 /**
4425 * Implement this method to handle touch screen motion events.
4426 *
4427 * @param event The motion event.
4428 * @return True if the event was handled, false otherwise.
4429 */
4430 public boolean onTouchEvent(MotionEvent event) {
4431 final int viewFlags = mViewFlags;
4432
4433 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4434 // A disabled view that is clickable still consumes the touch
4435 // events, it just doesn't respond to them.
4436 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4437 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4438 }
4439
4440 if (mTouchDelegate != null) {
4441 if (mTouchDelegate.onTouchEvent(event)) {
4442 return true;
4443 }
4444 }
4445
4446 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4447 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4448 switch (event.getAction()) {
4449 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004450 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4451 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 // take focus if we don't have it already and we should in
4453 // touch mode.
4454 boolean focusTaken = false;
4455 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4456 focusTaken = requestFocus();
4457 }
4458
4459 if (!mHasPerformedLongPress) {
4460 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004461 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004462
4463 // Only perform take click actions if we were in the pressed state
4464 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004465 // Use a Runnable and post this rather than calling
4466 // performClick directly. This lets other visual state
4467 // of the view update before click actions start.
4468 if (mPerformClick == null) {
4469 mPerformClick = new PerformClick();
4470 }
4471 if (!post(mPerformClick)) {
4472 performClick();
4473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 }
4475 }
4476
4477 if (mUnsetPressedState == null) {
4478 mUnsetPressedState = new UnsetPressedState();
4479 }
4480
Adam Powelle14579b2009-12-16 18:39:52 -08004481 if (prepressed) {
4482 mPrivateFlags |= PRESSED;
4483 refreshDrawableState();
4484 postDelayed(mUnsetPressedState,
4485 ViewConfiguration.getPressedStateDuration());
4486 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 // If the post failed, unpress right now
4488 mUnsetPressedState.run();
4489 }
Adam Powelle14579b2009-12-16 18:39:52 -08004490 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 }
4492 break;
4493
4494 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004495 if (mPendingCheckForTap == null) {
4496 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 }
Adam Powelle14579b2009-12-16 18:39:52 -08004498 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004499 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004500 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 break;
4502
4503 case MotionEvent.ACTION_CANCEL:
4504 mPrivateFlags &= ~PRESSED;
4505 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004506 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 break;
4508
4509 case MotionEvent.ACTION_MOVE:
4510 final int x = (int) event.getX();
4511 final int y = (int) event.getY();
4512
4513 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004514 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004515 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004516 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004518 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004519 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520
4521 // Need to switch from pressed to not pressed
4522 mPrivateFlags &= ~PRESSED;
4523 refreshDrawableState();
4524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 }
4526 break;
4527 }
4528 return true;
4529 }
4530
4531 return false;
4532 }
4533
4534 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004535 * Remove the longpress detection timer.
4536 */
4537 private void removeLongPressCallback() {
4538 if (mPendingCheckForLongPress != null) {
4539 removeCallbacks(mPendingCheckForLongPress);
4540 }
4541 }
Adam Powelle14579b2009-12-16 18:39:52 -08004542
4543 /**
Romain Guya440b002010-02-24 15:57:54 -08004544 * Remove the prepress detection timer.
4545 */
4546 private void removeUnsetPressCallback() {
4547 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4548 setPressed(false);
4549 removeCallbacks(mUnsetPressedState);
4550 }
4551 }
4552
4553 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004554 * Remove the tap detection timer.
4555 */
4556 private void removeTapCallback() {
4557 if (mPendingCheckForTap != null) {
4558 mPrivateFlags &= ~PREPRESSED;
4559 removeCallbacks(mPendingCheckForTap);
4560 }
4561 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004562
4563 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004564 * Cancels a pending long press. Your subclass can use this if you
4565 * want the context menu to come up if the user presses and holds
4566 * at the same place, but you don't want it to come up if they press
4567 * and then move around enough to cause scrolling.
4568 */
4569 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004570 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004571
4572 /*
4573 * The prepressed state handled by the tap callback is a display
4574 * construct, but the tap callback will post a long press callback
4575 * less its own timeout. Remove it here.
4576 */
4577 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004578 }
4579
4580 /**
4581 * Sets the TouchDelegate for this View.
4582 */
4583 public void setTouchDelegate(TouchDelegate delegate) {
4584 mTouchDelegate = delegate;
4585 }
4586
4587 /**
4588 * Gets the TouchDelegate for this View.
4589 */
4590 public TouchDelegate getTouchDelegate() {
4591 return mTouchDelegate;
4592 }
4593
4594 /**
4595 * Set flags controlling behavior of this view.
4596 *
4597 * @param flags Constant indicating the value which should be set
4598 * @param mask Constant indicating the bit range that should be changed
4599 */
4600 void setFlags(int flags, int mask) {
4601 int old = mViewFlags;
4602 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4603
4604 int changed = mViewFlags ^ old;
4605 if (changed == 0) {
4606 return;
4607 }
4608 int privateFlags = mPrivateFlags;
4609
4610 /* Check if the FOCUSABLE bit has changed */
4611 if (((changed & FOCUSABLE_MASK) != 0) &&
4612 ((privateFlags & HAS_BOUNDS) !=0)) {
4613 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4614 && ((privateFlags & FOCUSED) != 0)) {
4615 /* Give up focus if we are no longer focusable */
4616 clearFocus();
4617 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4618 && ((privateFlags & FOCUSED) == 0)) {
4619 /*
4620 * Tell the view system that we are now available to take focus
4621 * if no one else already has it.
4622 */
4623 if (mParent != null) mParent.focusableViewAvailable(this);
4624 }
4625 }
4626
4627 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4628 if ((changed & VISIBILITY_MASK) != 0) {
4629 /*
4630 * If this view is becoming visible, set the DRAWN flag so that
4631 * the next invalidate() will not be skipped.
4632 */
4633 mPrivateFlags |= DRAWN;
4634
4635 needGlobalAttributesUpdate(true);
4636
4637 // a view becoming visible is worth notifying the parent
4638 // about in case nothing has focus. even if this specific view
4639 // isn't focusable, it may contain something that is, so let
4640 // the root view try to give this focus if nothing else does.
4641 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4642 mParent.focusableViewAvailable(this);
4643 }
4644 }
4645 }
4646
4647 /* Check if the GONE bit has changed */
4648 if ((changed & GONE) != 0) {
4649 needGlobalAttributesUpdate(false);
4650 requestLayout();
4651 invalidate();
4652
Romain Guyecd80ee2009-12-03 17:13:02 -08004653 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
4654 if (hasFocus()) clearFocus();
4655 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004656 }
4657 if (mAttachInfo != null) {
4658 mAttachInfo.mViewVisibilityChanged = true;
4659 }
4660 }
4661
4662 /* Check if the VISIBLE bit has changed */
4663 if ((changed & INVISIBLE) != 0) {
4664 needGlobalAttributesUpdate(false);
4665 invalidate();
4666
4667 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4668 // root view becoming invisible shouldn't clear focus
4669 if (getRootView() != this) {
4670 clearFocus();
4671 }
4672 }
4673 if (mAttachInfo != null) {
4674 mAttachInfo.mViewVisibilityChanged = true;
4675 }
4676 }
4677
Adam Powell326d8082009-12-09 15:10:07 -08004678 if ((changed & VISIBILITY_MASK) != 0) {
4679 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
4680 }
4681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4683 destroyDrawingCache();
4684 }
4685
4686 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4687 destroyDrawingCache();
4688 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4689 }
4690
4691 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4692 destroyDrawingCache();
4693 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4694 }
4695
4696 if ((changed & DRAW_MASK) != 0) {
4697 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4698 if (mBGDrawable != null) {
4699 mPrivateFlags &= ~SKIP_DRAW;
4700 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4701 } else {
4702 mPrivateFlags |= SKIP_DRAW;
4703 }
4704 } else {
4705 mPrivateFlags &= ~SKIP_DRAW;
4706 }
4707 requestLayout();
4708 invalidate();
4709 }
4710
4711 if ((changed & KEEP_SCREEN_ON) != 0) {
4712 if (mParent != null) {
4713 mParent.recomputeViewAttributes(this);
4714 }
4715 }
4716 }
4717
4718 /**
4719 * Change the view's z order in the tree, so it's on top of other sibling
4720 * views
4721 */
4722 public void bringToFront() {
4723 if (mParent != null) {
4724 mParent.bringChildToFront(this);
4725 }
4726 }
4727
4728 /**
4729 * This is called in response to an internal scroll in this view (i.e., the
4730 * view scrolled its own contents). This is typically as a result of
4731 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4732 * called.
4733 *
4734 * @param l Current horizontal scroll origin.
4735 * @param t Current vertical scroll origin.
4736 * @param oldl Previous horizontal scroll origin.
4737 * @param oldt Previous vertical scroll origin.
4738 */
4739 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4740 mBackgroundSizeChanged = true;
4741
4742 final AttachInfo ai = mAttachInfo;
4743 if (ai != null) {
4744 ai.mViewScrollChanged = true;
4745 }
4746 }
4747
4748 /**
4749 * This is called during layout when the size of this view has changed. If
4750 * you were just added to the view hierarchy, you're called with the old
4751 * values of 0.
4752 *
4753 * @param w Current width of this view.
4754 * @param h Current height of this view.
4755 * @param oldw Old width of this view.
4756 * @param oldh Old height of this view.
4757 */
4758 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
4759 }
4760
4761 /**
4762 * Called by draw to draw the child views. This may be overridden
4763 * by derived classes to gain control just before its children are drawn
4764 * (but after its own view has been drawn).
4765 * @param canvas the canvas on which to draw the view
4766 */
4767 protected void dispatchDraw(Canvas canvas) {
4768 }
4769
4770 /**
4771 * Gets the parent of this view. Note that the parent is a
4772 * ViewParent and not necessarily a View.
4773 *
4774 * @return Parent of this view.
4775 */
4776 public final ViewParent getParent() {
4777 return mParent;
4778 }
4779
4780 /**
4781 * Return the scrolled left position of this view. This is the left edge of
4782 * the displayed part of your view. You do not need to draw any pixels
4783 * farther left, since those are outside of the frame of your view on
4784 * screen.
4785 *
4786 * @return The left edge of the displayed part of your view, in pixels.
4787 */
4788 public final int getScrollX() {
4789 return mScrollX;
4790 }
4791
4792 /**
4793 * Return the scrolled top position of this view. This is the top edge of
4794 * the displayed part of your view. You do not need to draw any pixels above
4795 * it, since those are outside of the frame of your view on screen.
4796 *
4797 * @return The top edge of the displayed part of your view, in pixels.
4798 */
4799 public final int getScrollY() {
4800 return mScrollY;
4801 }
4802
4803 /**
4804 * Return the width of the your view.
4805 *
4806 * @return The width of your view, in pixels.
4807 */
4808 @ViewDebug.ExportedProperty
4809 public final int getWidth() {
4810 return mRight - mLeft;
4811 }
4812
4813 /**
4814 * Return the height of your view.
4815 *
4816 * @return The height of your view, in pixels.
4817 */
4818 @ViewDebug.ExportedProperty
4819 public final int getHeight() {
4820 return mBottom - mTop;
4821 }
4822
4823 /**
4824 * Return the visible drawing bounds of your view. Fills in the output
4825 * rectangle with the values from getScrollX(), getScrollY(),
4826 * getWidth(), and getHeight().
4827 *
4828 * @param outRect The (scrolled) drawing bounds of the view.
4829 */
4830 public void getDrawingRect(Rect outRect) {
4831 outRect.left = mScrollX;
4832 outRect.top = mScrollY;
4833 outRect.right = mScrollX + (mRight - mLeft);
4834 outRect.bottom = mScrollY + (mBottom - mTop);
4835 }
4836
4837 /**
4838 * The width of this view as measured in the most recent call to measure().
4839 * This should be used during measurement and layout calculations only. Use
4840 * {@link #getWidth()} to see how wide a view is after layout.
4841 *
4842 * @return The measured width of this view.
4843 */
4844 public final int getMeasuredWidth() {
4845 return mMeasuredWidth;
4846 }
4847
4848 /**
4849 * The height of this view as measured in the most recent call to measure().
4850 * This should be used during measurement and layout calculations only. Use
4851 * {@link #getHeight()} to see how tall a view is after layout.
4852 *
4853 * @return The measured height of this view.
4854 */
4855 public final int getMeasuredHeight() {
4856 return mMeasuredHeight;
4857 }
4858
4859 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07004860 * The transform matrix of this view, which is calculated based on the current
4861 * roation, scale, and pivot properties.
4862 *
4863 * @see #getRotation()
4864 * @see #getScaleX()
4865 * @see #getScaleY()
4866 * @see #getPivotX()
4867 * @see #getPivotY()
4868 * @return The current transform matrix for the view
4869 */
4870 public Matrix getMatrix() {
Romain Guy33e72ae2010-07-17 12:40:29 -07004871 hasIdentityMatrix();
4872 return mMatrix;
4873 }
4874
4875 /**
4876 * Recomputes the transform matrix if necessary.
4877 *
4878 * @return True if the transform matrix is the identity matrix, false otherwise.
4879 */
4880 boolean hasIdentityMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07004881 if (mMatrixDirty) {
4882 // transform-related properties have changed since the last time someone
4883 // asked for the matrix; recalculate it with the current values
4884 mMatrix.reset();
4885 mMatrix.setRotate(mRotation, mPivotX, mPivotY);
4886 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
4887 mMatrixDirty = false;
4888 mMatrixIsIdentity = mMatrix.isIdentity();
4889 mInverseMatrixDirty = true;
4890 }
Romain Guy33e72ae2010-07-17 12:40:29 -07004891 return mMatrixIsIdentity;
Chet Haasec3aa3612010-06-17 08:50:37 -07004892 }
4893
4894 /**
4895 * Utility method to retrieve the inverse of the current mMatrix property.
4896 * We cache the matrix to avoid recalculating it when transform properties
4897 * have not changed.
4898 *
4899 * @return The inverse of the current matrix of this view.
4900 */
4901 Matrix getInverseMatrix() {
4902 if (mInverseMatrixDirty) {
4903 if (mInverseMatrix == null) {
4904 mInverseMatrix = new Matrix();
4905 }
4906 mMatrix.invert(mInverseMatrix);
4907 mInverseMatrixDirty = false;
4908 }
4909 return mInverseMatrix;
4910 }
4911
4912 /**
4913 * The degrees that the view is rotated around the pivot point.
4914 *
4915 * @see #getPivotX()
4916 * @see #getPivotY()
4917 * @return The degrees of rotation.
4918 */
4919 public float getRotation() {
4920 return mRotation;
4921 }
4922
4923 /**
4924 * Sets the degrees that the view is rotated around the pivot point.
4925 *
4926 * @param rotation The degrees of rotation.
4927 * @see #getPivotX()
4928 * @see #getPivotY()
4929 */
4930 public void setRotation(float rotation) {
4931 if (mRotation != rotation) {
4932 // Double-invalidation is necessary to capture view's old and new areas
4933 invalidate();
4934 mRotation = rotation;
4935 mMatrixDirty = true;
4936 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
4937 invalidate();
4938 }
4939 }
4940
4941 /**
4942 * The amount that the view is scaled in x around the pivot point, as a proportion of
4943 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
4944 *
4945 * @default 1.0f
4946 * @see #getPivotX()
4947 * @see #getPivotY()
4948 * @return The scaling factor.
4949 */
4950 public float getScaleX() {
4951 return mScaleX;
4952 }
4953
4954 /**
4955 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
4956 * the view's unscaled width. A value of 1 means that no scaling is applied.
4957 *
4958 * @param scaleX The scaling factor.
4959 * @see #getPivotX()
4960 * @see #getPivotY()
4961 */
4962 public void setScaleX(float scaleX) {
4963 if (mScaleX != scaleX) {
4964 // Double-invalidation is necessary to capture view's old and new areas
4965 invalidate();
4966 mScaleX = scaleX;
4967 mMatrixDirty = true;
4968 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
4969 invalidate();
4970 }
4971 }
4972
4973 /**
4974 * The amount that the view is scaled in y around the pivot point, as a proportion of
4975 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
4976 *
4977 * @default 1.0f
4978 * @see #getPivotX()
4979 * @see #getPivotY()
4980 * @return The scaling factor.
4981 */
4982 public float getScaleY() {
4983 return mScaleY;
4984 }
4985
4986 /**
4987 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
4988 * the view's unscaled width. A value of 1 means that no scaling is applied.
4989 *
4990 * @param scaleY The scaling factor.
4991 * @see #getPivotX()
4992 * @see #getPivotY()
4993 */
4994 public void setScaleY(float scaleY) {
4995 if (mScaleY != scaleY) {
4996 // Double-invalidation is necessary to capture view's old and new areas
4997 invalidate();
4998 mScaleY = scaleY;
4999 mMatrixDirty = true;
5000 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5001 invalidate();
5002 }
5003 }
5004
5005 /**
5006 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5007 * and {@link #setScaleX(float) scaled}.
5008 *
5009 * @see #getRotation()
5010 * @see #getScaleX()
5011 * @see #getScaleY()
5012 * @see #getPivotY()
5013 * @return The x location of the pivot point.
5014 */
5015 public float getPivotX() {
5016 return mPivotX;
5017 }
5018
5019 /**
5020 * Sets the x location of the point around which the view is
5021 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
5022 *
5023 * @param pivotX The x location of the pivot point.
5024 * @see #getRotation()
5025 * @see #getScaleX()
5026 * @see #getScaleY()
5027 * @see #getPivotY()
5028 */
5029 public void setPivotX(float pivotX) {
5030 if (mPivotX != pivotX) {
5031 // Double-invalidation is necessary to capture view's old and new areas
5032 invalidate();
5033 mPivotX = pivotX;
5034 mMatrixDirty = true;
5035 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5036 invalidate();
5037 }
5038 }
5039
5040 /**
5041 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5042 * and {@link #setScaleY(float) scaled}.
5043 *
5044 * @see #getRotation()
5045 * @see #getScaleX()
5046 * @see #getScaleY()
5047 * @see #getPivotY()
5048 * @return The y location of the pivot point.
5049 */
5050 public float getPivotY() {
5051 return mPivotY;
5052 }
5053
5054 /**
5055 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
5056 * and {@link #setScaleY(float) scaled}.
5057 *
5058 * @param pivotY The y location of the pivot point.
5059 * @see #getRotation()
5060 * @see #getScaleX()
5061 * @see #getScaleY()
5062 * @see #getPivotY()
5063 */
5064 public void setPivotY(float pivotY) {
5065 if (mPivotY != pivotY) {
5066 // Double-invalidation is necessary to capture view's old and new areas
5067 invalidate();
5068 mPivotY = pivotY;
5069 mMatrixDirty = true;
5070 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5071 invalidate();
5072 }
5073 }
5074
5075 /**
5076 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5077 * completely transparent and 1 means the view is completely opaque.
5078 *
5079 * @default 1.0f
5080 * @return The opacity of the view.
5081 */
5082 public float getAlpha() {
5083 return mAlpha;
5084 }
5085
5086 /**
5087 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5088 * completely transparent and 1 means the view is completely opaque.
5089 *
5090 * @param alpha The opacity of the view.
5091 */
5092 public void setAlpha(float alpha) {
5093 mAlpha = alpha;
5094 invalidate();
5095 }
5096
5097 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005098 * Top position of this view relative to its parent.
5099 *
5100 * @return The top of this view, in pixels.
5101 */
5102 @ViewDebug.CapturedViewProperty
5103 public final int getTop() {
5104 return mTop;
5105 }
5106
5107 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005108 * Sets the top position of this view relative to its parent.
5109 *
5110 * @param top The top of this view, in pixels.
5111 */
5112 public final void setTop(int top) {
5113 if (top != mTop) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005114 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005115 final ViewParent p = mParent;
5116 if (p != null && mAttachInfo != null) {
5117 final int[] location = mAttachInfo.mInvalidateChildLocation;
5118 final Rect r = mAttachInfo.mTmpInvalRect;
5119 int minTop = Math.min(mTop, top);
5120 location[0] = mLeft;
5121 location[1] = minTop;
5122 r.set(0, 0, mRight - mLeft, mBottom - minTop);
5123 p.invalidateChildInParent(location, r);
5124 }
5125 } else {
5126 // Double-invalidation is necessary to capture view's old and new areas
5127 invalidate();
5128 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005129
Chet Haasec3aa3612010-06-17 08:50:37 -07005130 mTop = top;
Romain Guy33e72ae2010-07-17 12:40:29 -07005131
Chet Haasec3aa3612010-06-17 08:50:37 -07005132 if (!mMatrixIsIdentity) {
5133 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5134 invalidate();
5135 }
5136 }
5137 }
5138
5139 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005140 * Bottom position of this view relative to its parent.
5141 *
5142 * @return The bottom of this view, in pixels.
5143 */
5144 @ViewDebug.CapturedViewProperty
5145 public final int getBottom() {
5146 return mBottom;
5147 }
5148
5149 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005150 * Sets the bottom position of this view relative to its parent.
5151 *
5152 * @param bottom The bottom of this view, in pixels.
5153 */
5154 public final void setBottom(int bottom) {
5155 if (bottom != mBottom) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005156 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005157 final ViewParent p = mParent;
5158 if (p != null && mAttachInfo != null) {
5159 final int[] location = mAttachInfo.mInvalidateChildLocation;
5160 final Rect r = mAttachInfo.mTmpInvalRect;
5161 int maxBottom = Math.max(mBottom, bottom);
5162 location[0] = mLeft;
5163 location[1] = mTop;
5164 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5165 p.invalidateChildInParent(location, r);
5166 }
5167 } else {
5168 // Double-invalidation is necessary to capture view's old and new areas
5169 invalidate();
5170 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005171
Chet Haasec3aa3612010-06-17 08:50:37 -07005172 mBottom = bottom;
Romain Guy33e72ae2010-07-17 12:40:29 -07005173
Chet Haasec3aa3612010-06-17 08:50:37 -07005174 if (!mMatrixIsIdentity) {
5175 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5176 invalidate();
5177 }
5178 }
5179 }
5180
5181 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005182 * Left position of this view relative to its parent.
5183 *
5184 * @return The left edge of this view, in pixels.
5185 */
5186 @ViewDebug.CapturedViewProperty
5187 public final int getLeft() {
5188 return mLeft;
5189 }
5190
5191 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005192 * Sets the left position of this view relative to its parent.
5193 *
5194 * @param left The bottom of this view, in pixels.
5195 */
5196 public final void setLeft(int left) {
5197 if (left != mLeft) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005198 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005199 final ViewParent p = mParent;
5200 if (p != null && mAttachInfo != null) {
5201 final int[] location = mAttachInfo.mInvalidateChildLocation;
5202 final Rect r = mAttachInfo.mTmpInvalRect;
5203 int minLeft = Math.min(mLeft, left);
5204 location[0] = minLeft;
5205 location[1] = mTop;
5206 r.set(0, 0, mRight - minLeft, mBottom - mTop);
5207 p.invalidateChildInParent(location, r);
5208 }
5209 } else {
5210 // Double-invalidation is necessary to capture view's old and new areas
5211 invalidate();
5212 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005213
Chet Haasec3aa3612010-06-17 08:50:37 -07005214 mLeft = left;
Romain Guy33e72ae2010-07-17 12:40:29 -07005215
Chet Haasec3aa3612010-06-17 08:50:37 -07005216 if (!mMatrixIsIdentity) {
5217 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5218 invalidate();
5219 }
5220 }
5221 }
5222
5223 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 * Right position of this view relative to its parent.
5225 *
5226 * @return The right edge of this view, in pixels.
5227 */
5228 @ViewDebug.CapturedViewProperty
5229 public final int getRight() {
5230 return mRight;
5231 }
5232
5233 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005234 * Sets the right position of this view relative to its parent.
5235 *
5236 * @param right The bottom of this view, in pixels.
5237 */
5238 public final void setRight(int right) {
5239 if (right != mRight) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005240 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005241 final ViewParent p = mParent;
5242 if (p != null && mAttachInfo != null) {
5243 final int[] location = mAttachInfo.mInvalidateChildLocation;
5244 final Rect r = mAttachInfo.mTmpInvalRect;
5245 int maxRight = Math.max(mRight, right);
5246 location[0] = mLeft;
5247 location[1] = mTop;
5248 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
5249 p.invalidateChildInParent(location, r);
5250 }
5251 } else {
5252 // Double-invalidation is necessary to capture view's old and new areas
5253 invalidate();
5254 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005255
Chet Haasec3aa3612010-06-17 08:50:37 -07005256 mRight = right;
Romain Guy33e72ae2010-07-17 12:40:29 -07005257
Chet Haasec3aa3612010-06-17 08:50:37 -07005258 if (!mMatrixIsIdentity) {
5259 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5260 invalidate();
5261 }
5262 }
5263 }
5264
5265 /**
5266 * The horizontal location of this view relative to its parent. This value is equivalent to the
5267 * {@link #getLeft() left} property.
5268 *
5269 * @return The horizontal position of this view, in pixels.
5270 */
5271 public int getX() {
5272 return mLeft;
5273 }
5274
5275 /**
5276 * Sets the horizontal location of this view relative to its parent. Setting this value will
5277 * affect both the {@link #setLeft(int) left} and {@link #setRight(int) right} properties
5278 * of this view.
5279 *
5280 * @param x The horizontal position of this view, in pixels.
5281 */
5282 public void setX(int x) {
5283 offsetLeftAndRight(x - mLeft);
5284 }
5285
5286 /**
5287 * The vertical location of this view relative to its parent. This value is equivalent to the
5288 * {@link #getTop() left} property.
5289 *
5290 * @return The vertical position of this view, in pixels.
5291 */
5292 public int getY() {
5293 return mTop;
5294 }
5295
5296 /**
5297 * Sets the vertical location of this view relative to its parent. Setting this value will
5298 * affect both the {@link #setTop(int) left} and {@link #setBottom(int) right} properties
5299 * of this view.
5300 *
5301 * @param y The vertical position of this view, in pixels.
5302 */
5303 public void setY(int y) {
5304 offsetTopAndBottom(y - mTop);
5305 }
5306
5307 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005308 * Hit rectangle in parent's coordinates
5309 *
5310 * @param outRect The hit rectangle of the view.
5311 */
5312 public void getHitRect(Rect outRect) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005313 if (hasIdentityMatrix() || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005314 outRect.set(mLeft, mTop, mRight, mBottom);
5315 } else {
Adam Powellb5de9f32010-07-17 01:00:53 -07005316 Matrix m = getMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005317 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07005318 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Chet Haasec3aa3612010-06-17 08:50:37 -07005319 m.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07005320 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
5321 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07005322 }
5323 }
5324
5325 /**
5326 * This method detects whether the given event is inside the view and, if so,
5327 * handles it via the dispatchEvent(MotionEvent) method.
5328 *
5329 * @param ev The event that is being dispatched.
5330 * @param parentX The x location of the event in the parent's coordinates.
5331 * @param parentY The y location of the event in the parent's coordinates.
5332 * @return true if the event was inside this view, false otherwise.
5333 */
5334 boolean dispatchTouchEvent(MotionEvent ev, float parentX, float parentY) {
5335 float localX = parentX - mLeft;
5336 float localY = parentY - mTop;
Romain Guy33e72ae2010-07-17 12:40:29 -07005337 if (!hasIdentityMatrix() && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005338 // non-identity matrix: transform the point into the view's coordinates
5339 final float[] localXY = mAttachInfo.mTmpTransformLocation;
5340 localXY[0] = localX;
5341 localXY[1] = localY;
5342 getInverseMatrix().mapPoints(localXY);
5343 localX = localXY[0];
5344 localY = localXY[1];
5345 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005346 if (localX >= 0 && localY >= 0 && localX < (mRight - mLeft) && localY < (mBottom - mTop)) {
Adam Powellb5de9f32010-07-17 01:00:53 -07005347 // It would be safer to clone the event here but we don't for performance.
5348 // There are many subtle interactions in touch event dispatch; change at your own risk.
5349 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Chet Haasec3aa3612010-06-17 08:50:37 -07005350 ev.setLocation(localX, localY);
5351 return dispatchTouchEvent(ev);
5352 }
5353 return false;
5354 }
5355
5356 /**
5357 * Utility method to determine whether the given point, in local coordinates,
5358 * is inside the view, where the area of the view is expanded by the slop factor.
5359 * This method is called while processing touch-move events to determine if the event
5360 * is still within the view.
5361 */
5362 private boolean pointInView(float localX, float localY, float slop) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005363 if (!hasIdentityMatrix() && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005364 // non-identity matrix: transform the point into the view's coordinates
5365 final float[] localXY = mAttachInfo.mTmpTransformLocation;
5366 localXY[0] = localX;
5367 localXY[1] = localY;
5368 getInverseMatrix().mapPoints(localXY);
5369 localX = localXY[0];
5370 localY = localXY[1];
5371 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005372 return localX > -slop && localY > -slop && localX < ((mRight - mLeft) + slop) &&
5373 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 }
5375
5376 /**
5377 * When a view has focus and the user navigates away from it, the next view is searched for
5378 * starting from the rectangle filled in by this method.
5379 *
5380 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
5381 * view maintains some idea of internal selection, such as a cursor, or a selected row
5382 * or column, you should override this method and fill in a more specific rectangle.
5383 *
5384 * @param r The rectangle to fill in, in this view's coordinates.
5385 */
5386 public void getFocusedRect(Rect r) {
5387 getDrawingRect(r);
5388 }
5389
5390 /**
5391 * If some part of this view is not clipped by any of its parents, then
5392 * return that area in r in global (root) coordinates. To convert r to local
5393 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
5394 * -globalOffset.y)) If the view is completely clipped or translated out,
5395 * return false.
5396 *
5397 * @param r If true is returned, r holds the global coordinates of the
5398 * visible portion of this view.
5399 * @param globalOffset If true is returned, globalOffset holds the dx,dy
5400 * between this view and its root. globalOffet may be null.
5401 * @return true if r is non-empty (i.e. part of the view is visible at the
5402 * root level.
5403 */
5404 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
5405 int width = mRight - mLeft;
5406 int height = mBottom - mTop;
5407 if (width > 0 && height > 0) {
5408 r.set(0, 0, width, height);
5409 if (globalOffset != null) {
5410 globalOffset.set(-mScrollX, -mScrollY);
5411 }
5412 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
5413 }
5414 return false;
5415 }
5416
5417 public final boolean getGlobalVisibleRect(Rect r) {
5418 return getGlobalVisibleRect(r, null);
5419 }
5420
5421 public final boolean getLocalVisibleRect(Rect r) {
5422 Point offset = new Point();
5423 if (getGlobalVisibleRect(r, offset)) {
5424 r.offset(-offset.x, -offset.y); // make r local
5425 return true;
5426 }
5427 return false;
5428 }
5429
5430 /**
5431 * Offset this view's vertical location by the specified number of pixels.
5432 *
5433 * @param offset the number of pixels to offset the view by
5434 */
5435 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005436 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005437 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005438 final ViewParent p = mParent;
5439 if (p != null && mAttachInfo != null) {
5440 final int[] location = mAttachInfo.mInvalidateChildLocation;
5441 final Rect r = mAttachInfo.mTmpInvalRect;
5442 int minTop = offset < 0 ? mTop + offset : mTop;
5443 int maxBottom = offset < 0 ? mBottom : mBottom + offset;
5444 location[0] = mLeft;
5445 location[1] = minTop;
5446 r.set(0, 0, mRight - mLeft, maxBottom - minTop);
5447 p.invalidateChildInParent(location, r);
5448 }
5449 } else {
5450 invalidate();
5451 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005452
Chet Haasec3aa3612010-06-17 08:50:37 -07005453 mTop += offset;
5454 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005455
Chet Haasec3aa3612010-06-17 08:50:37 -07005456 if (!mMatrixIsIdentity) {
5457 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5458 invalidate();
5459 }
5460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005461 }
5462
5463 /**
5464 * Offset this view's horizontal location by the specified amount of pixels.
5465 *
5466 * @param offset the numer of pixels to offset the view by
5467 */
5468 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005469 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005470 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005471 final ViewParent p = mParent;
5472 if (p != null && mAttachInfo != null) {
5473 final int[] location = mAttachInfo.mInvalidateChildLocation;
5474 final Rect r = mAttachInfo.mTmpInvalRect;
5475 int minLeft = offset < 0 ? mLeft + offset : mLeft;
5476 int maxRight = offset < 0 ? mRight : mRight + offset;
5477 location[0] = minLeft;
5478 location[1] = mTop;
5479 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
5480 p.invalidateChildInParent(location, r);
5481 }
5482 } else {
5483 invalidate();
5484 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005485
Chet Haasec3aa3612010-06-17 08:50:37 -07005486 mLeft += offset;
5487 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005488
Chet Haasec3aa3612010-06-17 08:50:37 -07005489 if (!mMatrixIsIdentity) {
5490 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5491 invalidate();
5492 }
5493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005494 }
5495
5496 /**
5497 * Get the LayoutParams associated with this view. All views should have
5498 * layout parameters. These supply parameters to the <i>parent</i> of this
5499 * view specifying how it should be arranged. There are many subclasses of
5500 * ViewGroup.LayoutParams, and these correspond to the different subclasses
5501 * of ViewGroup that are responsible for arranging their children.
5502 * @return The LayoutParams associated with this view
5503 */
5504 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
5505 public ViewGroup.LayoutParams getLayoutParams() {
5506 return mLayoutParams;
5507 }
5508
5509 /**
5510 * Set the layout parameters associated with this view. These supply
5511 * parameters to the <i>parent</i> of this view specifying how it should be
5512 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
5513 * correspond to the different subclasses of ViewGroup that are responsible
5514 * for arranging their children.
5515 *
5516 * @param params the layout parameters for this view
5517 */
5518 public void setLayoutParams(ViewGroup.LayoutParams params) {
5519 if (params == null) {
5520 throw new NullPointerException("params == null");
5521 }
5522 mLayoutParams = params;
5523 requestLayout();
5524 }
5525
5526 /**
5527 * Set the scrolled position of your view. This will cause a call to
5528 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5529 * invalidated.
5530 * @param x the x position to scroll to
5531 * @param y the y position to scroll to
5532 */
5533 public void scrollTo(int x, int y) {
5534 if (mScrollX != x || mScrollY != y) {
5535 int oldX = mScrollX;
5536 int oldY = mScrollY;
5537 mScrollX = x;
5538 mScrollY = y;
5539 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07005540 if (!awakenScrollBars()) {
5541 invalidate();
5542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 }
5544 }
5545
5546 /**
5547 * Move the scrolled position of your view. This will cause a call to
5548 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5549 * invalidated.
5550 * @param x the amount of pixels to scroll by horizontally
5551 * @param y the amount of pixels to scroll by vertically
5552 */
5553 public void scrollBy(int x, int y) {
5554 scrollTo(mScrollX + x, mScrollY + y);
5555 }
5556
5557 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07005558 * <p>Trigger the scrollbars to draw. When invoked this method starts an
5559 * animation to fade the scrollbars out after a default delay. If a subclass
5560 * provides animated scrolling, the start delay should equal the duration
5561 * of the scrolling animation.</p>
5562 *
5563 * <p>The animation starts only if at least one of the scrollbars is
5564 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
5565 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5566 * this method returns true, and false otherwise. If the animation is
5567 * started, this method calls {@link #invalidate()}; in that case the
5568 * caller should not call {@link #invalidate()}.</p>
5569 *
5570 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07005571 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07005572 *
5573 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
5574 * and {@link #scrollTo(int, int)}.</p>
5575 *
5576 * @return true if the animation is played, false otherwise
5577 *
5578 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07005579 * @see #scrollBy(int, int)
5580 * @see #scrollTo(int, int)
5581 * @see #isHorizontalScrollBarEnabled()
5582 * @see #isVerticalScrollBarEnabled()
5583 * @see #setHorizontalScrollBarEnabled(boolean)
5584 * @see #setVerticalScrollBarEnabled(boolean)
5585 */
5586 protected boolean awakenScrollBars() {
5587 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07005588 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07005589 }
5590
5591 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07005592 * Trigger the scrollbars to draw.
5593 * This method differs from awakenScrollBars() only in its default duration.
5594 * initialAwakenScrollBars() will show the scroll bars for longer than
5595 * usual to give the user more of a chance to notice them.
5596 *
5597 * @return true if the animation is played, false otherwise.
5598 */
5599 private boolean initialAwakenScrollBars() {
5600 return mScrollCache != null &&
5601 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
5602 }
5603
5604 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07005605 * <p>
5606 * Trigger the scrollbars to draw. When invoked this method starts an
5607 * animation to fade the scrollbars out after a fixed delay. If a subclass
5608 * provides animated scrolling, the start delay should equal the duration of
5609 * the scrolling animation.
5610 * </p>
5611 *
5612 * <p>
5613 * The animation starts only if at least one of the scrollbars is enabled,
5614 * as specified by {@link #isHorizontalScrollBarEnabled()} and
5615 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5616 * this method returns true, and false otherwise. If the animation is
5617 * started, this method calls {@link #invalidate()}; in that case the caller
5618 * should not call {@link #invalidate()}.
5619 * </p>
5620 *
5621 * <p>
5622 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07005623 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07005624 * </p>
5625 *
5626 * @param startDelay the delay, in milliseconds, after which the animation
5627 * should start; when the delay is 0, the animation starts
5628 * immediately
5629 * @return true if the animation is played, false otherwise
5630 *
Mike Cleronf116bf82009-09-27 19:14:12 -07005631 * @see #scrollBy(int, int)
5632 * @see #scrollTo(int, int)
5633 * @see #isHorizontalScrollBarEnabled()
5634 * @see #isVerticalScrollBarEnabled()
5635 * @see #setHorizontalScrollBarEnabled(boolean)
5636 * @see #setVerticalScrollBarEnabled(boolean)
5637 */
5638 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07005639 return awakenScrollBars(startDelay, true);
5640 }
5641
5642 /**
5643 * <p>
5644 * Trigger the scrollbars to draw. When invoked this method starts an
5645 * animation to fade the scrollbars out after a fixed delay. If a subclass
5646 * provides animated scrolling, the start delay should equal the duration of
5647 * the scrolling animation.
5648 * </p>
5649 *
5650 * <p>
5651 * The animation starts only if at least one of the scrollbars is enabled,
5652 * as specified by {@link #isHorizontalScrollBarEnabled()} and
5653 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5654 * this method returns true, and false otherwise. If the animation is
5655 * started, this method calls {@link #invalidate()} if the invalidate parameter
5656 * is set to true; in that case the caller
5657 * should not call {@link #invalidate()}.
5658 * </p>
5659 *
5660 * <p>
5661 * This method should be invoked everytime a subclass directly updates the
5662 * scroll parameters.
5663 * </p>
5664 *
5665 * @param startDelay the delay, in milliseconds, after which the animation
5666 * should start; when the delay is 0, the animation starts
5667 * immediately
5668 *
5669 * @param invalidate Wheter this method should call invalidate
5670 *
5671 * @return true if the animation is played, false otherwise
5672 *
5673 * @see #scrollBy(int, int)
5674 * @see #scrollTo(int, int)
5675 * @see #isHorizontalScrollBarEnabled()
5676 * @see #isVerticalScrollBarEnabled()
5677 * @see #setHorizontalScrollBarEnabled(boolean)
5678 * @see #setVerticalScrollBarEnabled(boolean)
5679 */
5680 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07005681 final ScrollabilityCache scrollCache = mScrollCache;
5682
5683 if (scrollCache == null || !scrollCache.fadeScrollBars) {
5684 return false;
5685 }
5686
5687 if (scrollCache.scrollBar == null) {
5688 scrollCache.scrollBar = new ScrollBarDrawable();
5689 }
5690
5691 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
5692
Mike Cleron290947b2009-09-29 18:34:32 -07005693 if (invalidate) {
5694 // Invalidate to show the scrollbars
5695 invalidate();
5696 }
Mike Cleronf116bf82009-09-27 19:14:12 -07005697
5698 if (scrollCache.state == ScrollabilityCache.OFF) {
5699 // FIXME: this is copied from WindowManagerService.
5700 // We should get this value from the system when it
5701 // is possible to do so.
5702 final int KEY_REPEAT_FIRST_DELAY = 750;
5703 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
5704 }
5705
5706 // Tell mScrollCache when we should start fading. This may
5707 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07005708 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07005709 scrollCache.fadeStartTime = fadeStartTime;
5710 scrollCache.state = ScrollabilityCache.ON;
5711
5712 // Schedule our fader to run, unscheduling any old ones first
5713 if (mAttachInfo != null) {
5714 mAttachInfo.mHandler.removeCallbacks(scrollCache);
5715 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
5716 }
5717
5718 return true;
5719 }
5720
5721 return false;
5722 }
5723
5724 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 * Mark the the area defined by dirty as needing to be drawn. If the view is
5726 * visible, {@link #onDraw} will be called at some point in the future.
5727 * This must be called from a UI thread. To call from a non-UI thread, call
5728 * {@link #postInvalidate()}.
5729 *
5730 * WARNING: This method is destructive to dirty.
5731 * @param dirty the rectangle representing the bounds of the dirty region
5732 */
5733 public void invalidate(Rect dirty) {
5734 if (ViewDebug.TRACE_HIERARCHY) {
5735 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5736 }
5737
5738 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5739 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5740 final ViewParent p = mParent;
5741 final AttachInfo ai = mAttachInfo;
5742 if (p != null && ai != null) {
5743 final int scrollX = mScrollX;
5744 final int scrollY = mScrollY;
5745 final Rect r = ai.mTmpInvalRect;
5746 r.set(dirty.left - scrollX, dirty.top - scrollY,
5747 dirty.right - scrollX, dirty.bottom - scrollY);
5748 mParent.invalidateChild(this, r);
5749 }
5750 }
5751 }
5752
5753 /**
5754 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
5755 * The coordinates of the dirty rect are relative to the view.
5756 * If the view is visible, {@link #onDraw} will be called at some point
5757 * in the future. This must be called from a UI thread. To call
5758 * from a non-UI thread, call {@link #postInvalidate()}.
5759 * @param l the left position of the dirty region
5760 * @param t the top position of the dirty region
5761 * @param r the right position of the dirty region
5762 * @param b the bottom position of the dirty region
5763 */
5764 public void invalidate(int l, int t, int r, int b) {
5765 if (ViewDebug.TRACE_HIERARCHY) {
5766 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5767 }
5768
5769 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5770 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5771 final ViewParent p = mParent;
5772 final AttachInfo ai = mAttachInfo;
5773 if (p != null && ai != null && l < r && t < b) {
5774 final int scrollX = mScrollX;
5775 final int scrollY = mScrollY;
5776 final Rect tmpr = ai.mTmpInvalRect;
5777 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
5778 p.invalidateChild(this, tmpr);
5779 }
5780 }
5781 }
5782
5783 /**
5784 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
5785 * be called at some point in the future. This must be called from a
5786 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
5787 */
5788 public void invalidate() {
5789 if (ViewDebug.TRACE_HIERARCHY) {
5790 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5791 }
5792
5793 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5794 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
5795 final ViewParent p = mParent;
5796 final AttachInfo ai = mAttachInfo;
5797 if (p != null && ai != null) {
5798 final Rect r = ai.mTmpInvalRect;
5799 r.set(0, 0, mRight - mLeft, mBottom - mTop);
5800 // Don't call invalidate -- we don't want to internally scroll
5801 // our own bounds
5802 p.invalidateChild(this, r);
5803 }
5804 }
5805 }
5806
5807 /**
Romain Guy24443ea2009-05-11 11:56:30 -07005808 * Indicates whether this View is opaque. An opaque View guarantees that it will
5809 * draw all the pixels overlapping its bounds using a fully opaque color.
5810 *
5811 * Subclasses of View should override this method whenever possible to indicate
5812 * whether an instance is opaque. Opaque Views are treated in a special way by
5813 * the View hierarchy, possibly allowing it to perform optimizations during
5814 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07005815 *
Romain Guy24443ea2009-05-11 11:56:30 -07005816 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07005817 */
Romain Guy83b21072009-05-12 10:54:51 -07005818 @ViewDebug.ExportedProperty
Romain Guy24443ea2009-05-11 11:56:30 -07005819 public boolean isOpaque() {
Romain Guy8f1344f52009-05-15 16:03:59 -07005820 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
5821 }
5822
5823 private void computeOpaqueFlags() {
5824 // Opaque if:
5825 // - Has a background
5826 // - Background is opaque
5827 // - Doesn't have scrollbars or scrollbars are inside overlay
5828
5829 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
5830 mPrivateFlags |= OPAQUE_BACKGROUND;
5831 } else {
5832 mPrivateFlags &= ~OPAQUE_BACKGROUND;
5833 }
5834
5835 final int flags = mViewFlags;
5836 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
5837 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
5838 mPrivateFlags |= OPAQUE_SCROLLBARS;
5839 } else {
5840 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
5841 }
5842 }
5843
5844 /**
5845 * @hide
5846 */
5847 protected boolean hasOpaqueScrollbars() {
5848 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07005849 }
5850
5851 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 * @return A handler associated with the thread running the View. This
5853 * handler can be used to pump events in the UI events queue.
5854 */
5855 public Handler getHandler() {
5856 if (mAttachInfo != null) {
5857 return mAttachInfo.mHandler;
5858 }
5859 return null;
5860 }
5861
5862 /**
5863 * Causes the Runnable to be added to the message queue.
5864 * The runnable will be run on the user interface thread.
5865 *
5866 * @param action The Runnable that will be executed.
5867 *
5868 * @return Returns true if the Runnable was successfully placed in to the
5869 * message queue. Returns false on failure, usually because the
5870 * looper processing the message queue is exiting.
5871 */
5872 public boolean post(Runnable action) {
5873 Handler handler;
5874 if (mAttachInfo != null) {
5875 handler = mAttachInfo.mHandler;
5876 } else {
5877 // Assume that post will succeed later
5878 ViewRoot.getRunQueue().post(action);
5879 return true;
5880 }
5881
5882 return handler.post(action);
5883 }
5884
5885 /**
5886 * Causes the Runnable to be added to the message queue, to be run
5887 * after the specified amount of time elapses.
5888 * The runnable will be run on the user interface thread.
5889 *
5890 * @param action The Runnable that will be executed.
5891 * @param delayMillis The delay (in milliseconds) until the Runnable
5892 * will be executed.
5893 *
5894 * @return true if the Runnable was successfully placed in to the
5895 * message queue. Returns false on failure, usually because the
5896 * looper processing the message queue is exiting. Note that a
5897 * result of true does not mean the Runnable will be processed --
5898 * if the looper is quit before the delivery time of the message
5899 * occurs then the message will be dropped.
5900 */
5901 public boolean postDelayed(Runnable action, long delayMillis) {
5902 Handler handler;
5903 if (mAttachInfo != null) {
5904 handler = mAttachInfo.mHandler;
5905 } else {
5906 // Assume that post will succeed later
5907 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
5908 return true;
5909 }
5910
5911 return handler.postDelayed(action, delayMillis);
5912 }
5913
5914 /**
5915 * Removes the specified Runnable from the message queue.
5916 *
5917 * @param action The Runnable to remove from the message handling queue
5918 *
5919 * @return true if this view could ask the Handler to remove the Runnable,
5920 * false otherwise. When the returned value is true, the Runnable
5921 * may or may not have been actually removed from the message queue
5922 * (for instance, if the Runnable was not in the queue already.)
5923 */
5924 public boolean removeCallbacks(Runnable action) {
5925 Handler handler;
5926 if (mAttachInfo != null) {
5927 handler = mAttachInfo.mHandler;
5928 } else {
5929 // Assume that post will succeed later
5930 ViewRoot.getRunQueue().removeCallbacks(action);
5931 return true;
5932 }
5933
5934 handler.removeCallbacks(action);
5935 return true;
5936 }
5937
5938 /**
5939 * Cause an invalidate to happen on a subsequent cycle through the event loop.
5940 * Use this to invalidate the View from a non-UI thread.
5941 *
5942 * @see #invalidate()
5943 */
5944 public void postInvalidate() {
5945 postInvalidateDelayed(0);
5946 }
5947
5948 /**
5949 * Cause an invalidate of the specified area to happen on a subsequent cycle
5950 * through the event loop. Use this to invalidate the View from a non-UI thread.
5951 *
5952 * @param left The left coordinate of the rectangle to invalidate.
5953 * @param top The top coordinate of the rectangle to invalidate.
5954 * @param right The right coordinate of the rectangle to invalidate.
5955 * @param bottom The bottom coordinate of the rectangle to invalidate.
5956 *
5957 * @see #invalidate(int, int, int, int)
5958 * @see #invalidate(Rect)
5959 */
5960 public void postInvalidate(int left, int top, int right, int bottom) {
5961 postInvalidateDelayed(0, left, top, right, bottom);
5962 }
5963
5964 /**
5965 * Cause an invalidate to happen on a subsequent cycle through the event
5966 * loop. Waits for the specified amount of time.
5967 *
5968 * @param delayMilliseconds the duration in milliseconds to delay the
5969 * invalidation by
5970 */
5971 public void postInvalidateDelayed(long delayMilliseconds) {
5972 // We try only with the AttachInfo because there's no point in invalidating
5973 // if we are not attached to our window
5974 if (mAttachInfo != null) {
5975 Message msg = Message.obtain();
5976 msg.what = AttachInfo.INVALIDATE_MSG;
5977 msg.obj = this;
5978 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
5979 }
5980 }
5981
5982 /**
5983 * Cause an invalidate of the specified area to happen on a subsequent cycle
5984 * through the event loop. Waits for the specified amount of time.
5985 *
5986 * @param delayMilliseconds the duration in milliseconds to delay the
5987 * invalidation by
5988 * @param left The left coordinate of the rectangle to invalidate.
5989 * @param top The top coordinate of the rectangle to invalidate.
5990 * @param right The right coordinate of the rectangle to invalidate.
5991 * @param bottom The bottom coordinate of the rectangle to invalidate.
5992 */
5993 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
5994 int right, int bottom) {
5995
5996 // We try only with the AttachInfo because there's no point in invalidating
5997 // if we are not attached to our window
5998 if (mAttachInfo != null) {
5999 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6000 info.target = this;
6001 info.left = left;
6002 info.top = top;
6003 info.right = right;
6004 info.bottom = bottom;
6005
6006 final Message msg = Message.obtain();
6007 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6008 msg.obj = info;
6009 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6010 }
6011 }
6012
6013 /**
6014 * Called by a parent to request that a child update its values for mScrollX
6015 * and mScrollY if necessary. This will typically be done if the child is
6016 * animating a scroll using a {@link android.widget.Scroller Scroller}
6017 * object.
6018 */
6019 public void computeScroll() {
6020 }
6021
6022 /**
6023 * <p>Indicate whether the horizontal edges are faded when the view is
6024 * scrolled horizontally.</p>
6025 *
6026 * @return true if the horizontal edges should are faded on scroll, false
6027 * otherwise
6028 *
6029 * @see #setHorizontalFadingEdgeEnabled(boolean)
6030 * @attr ref android.R.styleable#View_fadingEdge
6031 */
6032 public boolean isHorizontalFadingEdgeEnabled() {
6033 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6034 }
6035
6036 /**
6037 * <p>Define whether the horizontal edges should be faded when this view
6038 * is scrolled horizontally.</p>
6039 *
6040 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6041 * be faded when the view is scrolled
6042 * horizontally
6043 *
6044 * @see #isHorizontalFadingEdgeEnabled()
6045 * @attr ref android.R.styleable#View_fadingEdge
6046 */
6047 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6048 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6049 if (horizontalFadingEdgeEnabled) {
6050 initScrollCache();
6051 }
6052
6053 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6054 }
6055 }
6056
6057 /**
6058 * <p>Indicate whether the vertical edges are faded when the view is
6059 * scrolled horizontally.</p>
6060 *
6061 * @return true if the vertical edges should are faded on scroll, false
6062 * otherwise
6063 *
6064 * @see #setVerticalFadingEdgeEnabled(boolean)
6065 * @attr ref android.R.styleable#View_fadingEdge
6066 */
6067 public boolean isVerticalFadingEdgeEnabled() {
6068 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6069 }
6070
6071 /**
6072 * <p>Define whether the vertical edges should be faded when this view
6073 * is scrolled vertically.</p>
6074 *
6075 * @param verticalFadingEdgeEnabled true if the vertical edges should
6076 * be faded when the view is scrolled
6077 * vertically
6078 *
6079 * @see #isVerticalFadingEdgeEnabled()
6080 * @attr ref android.R.styleable#View_fadingEdge
6081 */
6082 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6083 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6084 if (verticalFadingEdgeEnabled) {
6085 initScrollCache();
6086 }
6087
6088 mViewFlags ^= FADING_EDGE_VERTICAL;
6089 }
6090 }
6091
6092 /**
6093 * Returns the strength, or intensity, of the top faded edge. The strength is
6094 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6095 * returns 0.0 or 1.0 but no value in between.
6096 *
6097 * Subclasses should override this method to provide a smoother fade transition
6098 * when scrolling occurs.
6099 *
6100 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6101 */
6102 protected float getTopFadingEdgeStrength() {
6103 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6104 }
6105
6106 /**
6107 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6108 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6109 * returns 0.0 or 1.0 but no value in between.
6110 *
6111 * Subclasses should override this method to provide a smoother fade transition
6112 * when scrolling occurs.
6113 *
6114 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6115 */
6116 protected float getBottomFadingEdgeStrength() {
6117 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6118 computeVerticalScrollRange() ? 1.0f : 0.0f;
6119 }
6120
6121 /**
6122 * Returns the strength, or intensity, of the left faded edge. The strength is
6123 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6124 * returns 0.0 or 1.0 but no value in between.
6125 *
6126 * Subclasses should override this method to provide a smoother fade transition
6127 * when scrolling occurs.
6128 *
6129 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6130 */
6131 protected float getLeftFadingEdgeStrength() {
6132 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6133 }
6134
6135 /**
6136 * Returns the strength, or intensity, of the right faded edge. The strength is
6137 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6138 * returns 0.0 or 1.0 but no value in between.
6139 *
6140 * Subclasses should override this method to provide a smoother fade transition
6141 * when scrolling occurs.
6142 *
6143 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6144 */
6145 protected float getRightFadingEdgeStrength() {
6146 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6147 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6148 }
6149
6150 /**
6151 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6152 * scrollbar is not drawn by default.</p>
6153 *
6154 * @return true if the horizontal scrollbar should be painted, false
6155 * otherwise
6156 *
6157 * @see #setHorizontalScrollBarEnabled(boolean)
6158 */
6159 public boolean isHorizontalScrollBarEnabled() {
6160 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6161 }
6162
6163 /**
6164 * <p>Define whether the horizontal scrollbar should be drawn or not. The
6165 * scrollbar is not drawn by default.</p>
6166 *
6167 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
6168 * be painted
6169 *
6170 * @see #isHorizontalScrollBarEnabled()
6171 */
6172 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
6173 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
6174 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006175 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 recomputePadding();
6177 }
6178 }
6179
6180 /**
6181 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
6182 * scrollbar is not drawn by default.</p>
6183 *
6184 * @return true if the vertical scrollbar should be painted, false
6185 * otherwise
6186 *
6187 * @see #setVerticalScrollBarEnabled(boolean)
6188 */
6189 public boolean isVerticalScrollBarEnabled() {
6190 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
6191 }
6192
6193 /**
6194 * <p>Define whether the vertical scrollbar should be drawn or not. The
6195 * scrollbar is not drawn by default.</p>
6196 *
6197 * @param verticalScrollBarEnabled true if the vertical scrollbar should
6198 * be painted
6199 *
6200 * @see #isVerticalScrollBarEnabled()
6201 */
6202 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
6203 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
6204 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006205 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 recomputePadding();
6207 }
6208 }
6209
6210 private void recomputePadding() {
6211 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
6212 }
Mike Cleronfe81d382009-09-28 14:22:16 -07006213
6214 /**
6215 * Define whether scrollbars will fade when the view is not scrolling.
6216 *
6217 * @param fadeScrollbars wheter to enable fading
6218 *
6219 */
6220 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
6221 initScrollCache();
6222 final ScrollabilityCache scrollabilityCache = mScrollCache;
6223 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07006224 if (fadeScrollbars) {
6225 scrollabilityCache.state = ScrollabilityCache.OFF;
6226 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07006227 scrollabilityCache.state = ScrollabilityCache.ON;
6228 }
6229 }
6230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07006232 *
6233 * Returns true if scrollbars will fade when this view is not scrolling
6234 *
6235 * @return true if scrollbar fading is enabled
6236 */
6237 public boolean isScrollbarFadingEnabled() {
6238 return mScrollCache != null && mScrollCache.fadeScrollBars;
6239 }
6240
6241 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
6243 * inset. When inset, they add to the padding of the view. And the scrollbars
6244 * can be drawn inside the padding area or on the edge of the view. For example,
6245 * if a view has a background drawable and you want to draw the scrollbars
6246 * inside the padding specified by the drawable, you can use
6247 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
6248 * appear at the edge of the view, ignoring the padding, then you can use
6249 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
6250 * @param style the style of the scrollbars. Should be one of
6251 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
6252 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
6253 * @see #SCROLLBARS_INSIDE_OVERLAY
6254 * @see #SCROLLBARS_INSIDE_INSET
6255 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6256 * @see #SCROLLBARS_OUTSIDE_INSET
6257 */
6258 public void setScrollBarStyle(int style) {
6259 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
6260 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07006261 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 recomputePadding();
6263 }
6264 }
6265
6266 /**
6267 * <p>Returns the current scrollbar style.</p>
6268 * @return the current scrollbar style
6269 * @see #SCROLLBARS_INSIDE_OVERLAY
6270 * @see #SCROLLBARS_INSIDE_INSET
6271 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6272 * @see #SCROLLBARS_OUTSIDE_INSET
6273 */
6274 public int getScrollBarStyle() {
6275 return mViewFlags & SCROLLBARS_STYLE_MASK;
6276 }
6277
6278 /**
6279 * <p>Compute the horizontal range that the horizontal scrollbar
6280 * represents.</p>
6281 *
6282 * <p>The range is expressed in arbitrary units that must be the same as the
6283 * units used by {@link #computeHorizontalScrollExtent()} and
6284 * {@link #computeHorizontalScrollOffset()}.</p>
6285 *
6286 * <p>The default range is the drawing width of this view.</p>
6287 *
6288 * @return the total horizontal range represented by the horizontal
6289 * scrollbar
6290 *
6291 * @see #computeHorizontalScrollExtent()
6292 * @see #computeHorizontalScrollOffset()
6293 * @see android.widget.ScrollBarDrawable
6294 */
6295 protected int computeHorizontalScrollRange() {
6296 return getWidth();
6297 }
6298
6299 /**
6300 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
6301 * within the horizontal range. This value is used to compute the position
6302 * of the thumb within the scrollbar's track.</p>
6303 *
6304 * <p>The range is expressed in arbitrary units that must be the same as the
6305 * units used by {@link #computeHorizontalScrollRange()} and
6306 * {@link #computeHorizontalScrollExtent()}.</p>
6307 *
6308 * <p>The default offset is the scroll offset of this view.</p>
6309 *
6310 * @return the horizontal offset of the scrollbar's thumb
6311 *
6312 * @see #computeHorizontalScrollRange()
6313 * @see #computeHorizontalScrollExtent()
6314 * @see android.widget.ScrollBarDrawable
6315 */
6316 protected int computeHorizontalScrollOffset() {
6317 return mScrollX;
6318 }
6319
6320 /**
6321 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
6322 * within the horizontal range. This value is used to compute the length
6323 * of the thumb within the scrollbar's track.</p>
6324 *
6325 * <p>The range is expressed in arbitrary units that must be the same as the
6326 * units used by {@link #computeHorizontalScrollRange()} and
6327 * {@link #computeHorizontalScrollOffset()}.</p>
6328 *
6329 * <p>The default extent is the drawing width of this view.</p>
6330 *
6331 * @return the horizontal extent of the scrollbar's thumb
6332 *
6333 * @see #computeHorizontalScrollRange()
6334 * @see #computeHorizontalScrollOffset()
6335 * @see android.widget.ScrollBarDrawable
6336 */
6337 protected int computeHorizontalScrollExtent() {
6338 return getWidth();
6339 }
6340
6341 /**
6342 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
6343 *
6344 * <p>The range is expressed in arbitrary units that must be the same as the
6345 * units used by {@link #computeVerticalScrollExtent()} and
6346 * {@link #computeVerticalScrollOffset()}.</p>
6347 *
6348 * @return the total vertical range represented by the vertical scrollbar
6349 *
6350 * <p>The default range is the drawing height of this view.</p>
6351 *
6352 * @see #computeVerticalScrollExtent()
6353 * @see #computeVerticalScrollOffset()
6354 * @see android.widget.ScrollBarDrawable
6355 */
6356 protected int computeVerticalScrollRange() {
6357 return getHeight();
6358 }
6359
6360 /**
6361 * <p>Compute the vertical offset of the vertical scrollbar's thumb
6362 * within the horizontal range. This value is used to compute the position
6363 * of the thumb within the scrollbar's track.</p>
6364 *
6365 * <p>The range is expressed in arbitrary units that must be the same as the
6366 * units used by {@link #computeVerticalScrollRange()} and
6367 * {@link #computeVerticalScrollExtent()}.</p>
6368 *
6369 * <p>The default offset is the scroll offset of this view.</p>
6370 *
6371 * @return the vertical offset of the scrollbar's thumb
6372 *
6373 * @see #computeVerticalScrollRange()
6374 * @see #computeVerticalScrollExtent()
6375 * @see android.widget.ScrollBarDrawable
6376 */
6377 protected int computeVerticalScrollOffset() {
6378 return mScrollY;
6379 }
6380
6381 /**
6382 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
6383 * within the vertical range. This value is used to compute the length
6384 * of the thumb within the scrollbar's track.</p>
6385 *
6386 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08006387 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 * {@link #computeVerticalScrollOffset()}.</p>
6389 *
6390 * <p>The default extent is the drawing height of this view.</p>
6391 *
6392 * @return the vertical extent of the scrollbar's thumb
6393 *
6394 * @see #computeVerticalScrollRange()
6395 * @see #computeVerticalScrollOffset()
6396 * @see android.widget.ScrollBarDrawable
6397 */
6398 protected int computeVerticalScrollExtent() {
6399 return getHeight();
6400 }
6401
6402 /**
6403 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
6404 * scrollbars are painted only if they have been awakened first.</p>
6405 *
6406 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07006407 *
6408 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08006410 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 // scrollbars are drawn only when the animation is running
6412 final ScrollabilityCache cache = mScrollCache;
6413 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006414
6415 int state = cache.state;
6416
6417 if (state == ScrollabilityCache.OFF) {
6418 return;
6419 }
6420
6421 boolean invalidate = false;
6422
6423 if (state == ScrollabilityCache.FADING) {
6424 // We're fading -- get our fade interpolation
6425 if (cache.interpolatorValues == null) {
6426 cache.interpolatorValues = new float[1];
6427 }
6428
6429 float[] values = cache.interpolatorValues;
6430
6431 // Stops the animation if we're done
6432 if (cache.scrollBarInterpolator.timeToValues(values) ==
6433 Interpolator.Result.FREEZE_END) {
6434 cache.state = ScrollabilityCache.OFF;
6435 } else {
6436 cache.scrollBar.setAlpha(Math.round(values[0]));
6437 }
6438
6439 // This will make the scroll bars inval themselves after
6440 // drawing. We only want this when we're fading so that
6441 // we prevent excessive redraws
6442 invalidate = true;
6443 } else {
6444 // We're just on -- but we may have been fading before so
6445 // reset alpha
6446 cache.scrollBar.setAlpha(255);
6447 }
6448
6449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006450 final int viewFlags = mViewFlags;
6451
6452 final boolean drawHorizontalScrollBar =
6453 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6454 final boolean drawVerticalScrollBar =
6455 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
6456 && !isVerticalScrollBarHidden();
6457
6458 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
6459 final int width = mRight - mLeft;
6460 final int height = mBottom - mTop;
6461
6462 final ScrollBarDrawable scrollBar = cache.scrollBar;
6463 int size = scrollBar.getSize(false);
6464 if (size <= 0) {
6465 size = cache.scrollBarSize;
6466 }
6467
Mike Reede8853fc2009-09-04 14:01:48 -04006468 final int scrollX = mScrollX;
6469 final int scrollY = mScrollY;
6470 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
6471
Mike Cleronf116bf82009-09-27 19:14:12 -07006472 int left, top, right, bottom;
6473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006475 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04006476 computeHorizontalScrollOffset(),
6477 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04006478 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07006479 getVerticalScrollbarWidth() : 0;
6480 top = scrollY + height - size - (mUserPaddingBottom & inside);
6481 left = scrollX + (mPaddingLeft & inside);
6482 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
6483 bottom = top + size;
6484 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
6485 if (invalidate) {
6486 invalidate(left, top, right, bottom);
6487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 }
6489
6490 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04006491 scrollBar.setParameters(computeVerticalScrollRange(),
6492 computeVerticalScrollOffset(),
6493 computeVerticalScrollExtent(), true);
6494 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07006495 left = scrollX + width - size - (mUserPaddingRight & inside);
6496 top = scrollY + (mPaddingTop & inside);
6497 right = left + size;
6498 bottom = scrollY + height - (mUserPaddingBottom & inside);
6499 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
6500 if (invalidate) {
6501 invalidate(left, top, right, bottom);
6502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006503 }
6504 }
6505 }
6506 }
Romain Guy8506ab42009-06-11 17:35:47 -07006507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 /**
Romain Guy8506ab42009-06-11 17:35:47 -07006509 * 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 -08006510 * FastScroller is visible.
6511 * @return whether to temporarily hide the vertical scrollbar
6512 * @hide
6513 */
6514 protected boolean isVerticalScrollBarHidden() {
6515 return false;
6516 }
6517
6518 /**
6519 * <p>Draw the horizontal scrollbar if
6520 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
6521 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 * @param canvas the canvas on which to draw the scrollbar
6523 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 *
6525 * @see #isHorizontalScrollBarEnabled()
6526 * @see #computeHorizontalScrollRange()
6527 * @see #computeHorizontalScrollExtent()
6528 * @see #computeHorizontalScrollOffset()
6529 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07006530 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006531 */
Mike Reede8853fc2009-09-04 14:01:48 -04006532 protected void onDrawHorizontalScrollBar(Canvas canvas,
6533 Drawable scrollBar,
6534 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006535 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006536 scrollBar.draw(canvas);
6537 }
Mike Reede8853fc2009-09-04 14:01:48 -04006538
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006539 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
6541 * returns true.</p>
6542 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 * @param canvas the canvas on which to draw the scrollbar
6544 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006545 *
6546 * @see #isVerticalScrollBarEnabled()
6547 * @see #computeVerticalScrollRange()
6548 * @see #computeVerticalScrollExtent()
6549 * @see #computeVerticalScrollOffset()
6550 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04006551 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552 */
Mike Reede8853fc2009-09-04 14:01:48 -04006553 protected void onDrawVerticalScrollBar(Canvas canvas,
6554 Drawable scrollBar,
6555 int l, int t, int r, int b) {
6556 scrollBar.setBounds(l, t, r, b);
6557 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006558 }
6559
6560 /**
6561 * Implement this to do your drawing.
6562 *
6563 * @param canvas the canvas on which the background will be drawn
6564 */
6565 protected void onDraw(Canvas canvas) {
6566 }
6567
6568 /*
6569 * Caller is responsible for calling requestLayout if necessary.
6570 * (This allows addViewInLayout to not request a new layout.)
6571 */
6572 void assignParent(ViewParent parent) {
6573 if (mParent == null) {
6574 mParent = parent;
6575 } else if (parent == null) {
6576 mParent = null;
6577 } else {
6578 throw new RuntimeException("view " + this + " being added, but"
6579 + " it already has a parent");
6580 }
6581 }
6582
6583 /**
6584 * This is called when the view is attached to a window. At this point it
6585 * has a Surface and will start drawing. Note that this function is
6586 * guaranteed to be called before {@link #onDraw}, however it may be called
6587 * any time before the first onDraw -- including before or after
6588 * {@link #onMeasure}.
6589 *
6590 * @see #onDetachedFromWindow()
6591 */
6592 protected void onAttachedToWindow() {
6593 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
6594 mParent.requestTransparentRegion(this);
6595 }
Adam Powell8568c3a2010-04-19 14:26:11 -07006596 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
6597 initialAwakenScrollBars();
6598 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
6599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006600 }
6601
6602 /**
6603 * This is called when the view is detached from a window. At this point it
6604 * no longer has a surface for drawing.
6605 *
6606 * @see #onAttachedToWindow()
6607 */
6608 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08006609 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08006610 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05006611 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 destroyDrawingCache();
6613 }
6614
6615 /**
6616 * @return The number of times this view has been attached to a window
6617 */
6618 protected int getWindowAttachCount() {
6619 return mWindowAttachCount;
6620 }
6621
6622 /**
6623 * Retrieve a unique token identifying the window this view is attached to.
6624 * @return Return the window's token for use in
6625 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
6626 */
6627 public IBinder getWindowToken() {
6628 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
6629 }
6630
6631 /**
6632 * Retrieve a unique token identifying the top-level "real" window of
6633 * the window that this view is attached to. That is, this is like
6634 * {@link #getWindowToken}, except if the window this view in is a panel
6635 * window (attached to another containing window), then the token of
6636 * the containing window is returned instead.
6637 *
6638 * @return Returns the associated window token, either
6639 * {@link #getWindowToken()} or the containing window's token.
6640 */
6641 public IBinder getApplicationWindowToken() {
6642 AttachInfo ai = mAttachInfo;
6643 if (ai != null) {
6644 IBinder appWindowToken = ai.mPanelParentWindowToken;
6645 if (appWindowToken == null) {
6646 appWindowToken = ai.mWindowToken;
6647 }
6648 return appWindowToken;
6649 }
6650 return null;
6651 }
6652
6653 /**
6654 * Retrieve private session object this view hierarchy is using to
6655 * communicate with the window manager.
6656 * @return the session object to communicate with the window manager
6657 */
6658 /*package*/ IWindowSession getWindowSession() {
6659 return mAttachInfo != null ? mAttachInfo.mSession : null;
6660 }
6661
6662 /**
6663 * @param info the {@link android.view.View.AttachInfo} to associated with
6664 * this view
6665 */
6666 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
6667 //System.out.println("Attached! " + this);
6668 mAttachInfo = info;
6669 mWindowAttachCount++;
6670 if (mFloatingTreeObserver != null) {
6671 info.mTreeObserver.merge(mFloatingTreeObserver);
6672 mFloatingTreeObserver = null;
6673 }
6674 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
6675 mAttachInfo.mScrollContainers.add(this);
6676 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
6677 }
6678 performCollectViewAttributes(visibility);
6679 onAttachedToWindow();
6680 int vis = info.mWindowVisibility;
6681 if (vis != GONE) {
6682 onWindowVisibilityChanged(vis);
6683 }
6684 }
6685
6686 void dispatchDetachedFromWindow() {
6687 //System.out.println("Detached! " + this);
6688 AttachInfo info = mAttachInfo;
6689 if (info != null) {
6690 int vis = info.mWindowVisibility;
6691 if (vis != GONE) {
6692 onWindowVisibilityChanged(GONE);
6693 }
6694 }
6695
6696 onDetachedFromWindow();
6697 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
6698 mAttachInfo.mScrollContainers.remove(this);
6699 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
6700 }
6701 mAttachInfo = null;
6702 }
6703
6704 /**
6705 * Store this view hierarchy's frozen state into the given container.
6706 *
6707 * @param container The SparseArray in which to save the view's state.
6708 *
6709 * @see #restoreHierarchyState
6710 * @see #dispatchSaveInstanceState
6711 * @see #onSaveInstanceState
6712 */
6713 public void saveHierarchyState(SparseArray<Parcelable> container) {
6714 dispatchSaveInstanceState(container);
6715 }
6716
6717 /**
6718 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
6719 * May be overridden to modify how freezing happens to a view's children; for example, some
6720 * views may want to not store state for their children.
6721 *
6722 * @param container The SparseArray in which to save the view's state.
6723 *
6724 * @see #dispatchRestoreInstanceState
6725 * @see #saveHierarchyState
6726 * @see #onSaveInstanceState
6727 */
6728 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
6729 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
6730 mPrivateFlags &= ~SAVE_STATE_CALLED;
6731 Parcelable state = onSaveInstanceState();
6732 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
6733 throw new IllegalStateException(
6734 "Derived class did not call super.onSaveInstanceState()");
6735 }
6736 if (state != null) {
6737 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
6738 // + ": " + state);
6739 container.put(mID, state);
6740 }
6741 }
6742 }
6743
6744 /**
6745 * Hook allowing a view to generate a representation of its internal state
6746 * that can later be used to create a new instance with that same state.
6747 * This state should only contain information that is not persistent or can
6748 * not be reconstructed later. For example, you will never store your
6749 * current position on screen because that will be computed again when a
6750 * new instance of the view is placed in its view hierarchy.
6751 * <p>
6752 * Some examples of things you may store here: the current cursor position
6753 * in a text view (but usually not the text itself since that is stored in a
6754 * content provider or other persistent storage), the currently selected
6755 * item in a list view.
6756 *
6757 * @return Returns a Parcelable object containing the view's current dynamic
6758 * state, or null if there is nothing interesting to save. The
6759 * default implementation returns null.
6760 * @see #onRestoreInstanceState
6761 * @see #saveHierarchyState
6762 * @see #dispatchSaveInstanceState
6763 * @see #setSaveEnabled(boolean)
6764 */
6765 protected Parcelable onSaveInstanceState() {
6766 mPrivateFlags |= SAVE_STATE_CALLED;
6767 return BaseSavedState.EMPTY_STATE;
6768 }
6769
6770 /**
6771 * Restore this view hierarchy's frozen state from the given container.
6772 *
6773 * @param container The SparseArray which holds previously frozen states.
6774 *
6775 * @see #saveHierarchyState
6776 * @see #dispatchRestoreInstanceState
6777 * @see #onRestoreInstanceState
6778 */
6779 public void restoreHierarchyState(SparseArray<Parcelable> container) {
6780 dispatchRestoreInstanceState(container);
6781 }
6782
6783 /**
6784 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
6785 * children. May be overridden to modify how restoreing happens to a view's children; for
6786 * example, some views may want to not store state for their children.
6787 *
6788 * @param container The SparseArray which holds previously saved state.
6789 *
6790 * @see #dispatchSaveInstanceState
6791 * @see #restoreHierarchyState
6792 * @see #onRestoreInstanceState
6793 */
6794 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
6795 if (mID != NO_ID) {
6796 Parcelable state = container.get(mID);
6797 if (state != null) {
6798 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
6799 // + ": " + state);
6800 mPrivateFlags &= ~SAVE_STATE_CALLED;
6801 onRestoreInstanceState(state);
6802 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
6803 throw new IllegalStateException(
6804 "Derived class did not call super.onRestoreInstanceState()");
6805 }
6806 }
6807 }
6808 }
6809
6810 /**
6811 * Hook allowing a view to re-apply a representation of its internal state that had previously
6812 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
6813 * null state.
6814 *
6815 * @param state The frozen state that had previously been returned by
6816 * {@link #onSaveInstanceState}.
6817 *
6818 * @see #onSaveInstanceState
6819 * @see #restoreHierarchyState
6820 * @see #dispatchRestoreInstanceState
6821 */
6822 protected void onRestoreInstanceState(Parcelable state) {
6823 mPrivateFlags |= SAVE_STATE_CALLED;
6824 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08006825 throw new IllegalArgumentException("Wrong state class, expecting View State but "
6826 + "received " + state.getClass().toString() + " instead. This usually happens "
6827 + "when two views of different type have the same id in the same hierarchy. "
6828 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
6829 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006830 }
6831 }
6832
6833 /**
6834 * <p>Return the time at which the drawing of the view hierarchy started.</p>
6835 *
6836 * @return the drawing start time in milliseconds
6837 */
6838 public long getDrawingTime() {
6839 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
6840 }
6841
6842 /**
6843 * <p>Enables or disables the duplication of the parent's state into this view. When
6844 * duplication is enabled, this view gets its drawable state from its parent rather
6845 * than from its own internal properties.</p>
6846 *
6847 * <p>Note: in the current implementation, setting this property to true after the
6848 * view was added to a ViewGroup might have no effect at all. This property should
6849 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
6850 *
6851 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
6852 * property is enabled, an exception will be thrown.</p>
6853 *
6854 * @param enabled True to enable duplication of the parent's drawable state, false
6855 * to disable it.
6856 *
6857 * @see #getDrawableState()
6858 * @see #isDuplicateParentStateEnabled()
6859 */
6860 public void setDuplicateParentStateEnabled(boolean enabled) {
6861 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
6862 }
6863
6864 /**
6865 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
6866 *
6867 * @return True if this view's drawable state is duplicated from the parent,
6868 * false otherwise
6869 *
6870 * @see #getDrawableState()
6871 * @see #setDuplicateParentStateEnabled(boolean)
6872 */
6873 public boolean isDuplicateParentStateEnabled() {
6874 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
6875 }
6876
6877 /**
6878 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
6879 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
6880 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
6881 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
6882 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
6883 * null.</p>
6884 *
6885 * @param enabled true to enable the drawing cache, false otherwise
6886 *
6887 * @see #isDrawingCacheEnabled()
6888 * @see #getDrawingCache()
6889 * @see #buildDrawingCache()
6890 */
6891 public void setDrawingCacheEnabled(boolean enabled) {
6892 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
6893 }
6894
6895 /**
6896 * <p>Indicates whether the drawing cache is enabled for this view.</p>
6897 *
6898 * @return true if the drawing cache is enabled
6899 *
6900 * @see #setDrawingCacheEnabled(boolean)
6901 * @see #getDrawingCache()
6902 */
6903 @ViewDebug.ExportedProperty
6904 public boolean isDrawingCacheEnabled() {
6905 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
6906 }
6907
6908 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07006909 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
6910 *
6911 * @return A non-scaled bitmap representing this view or null if cache is disabled.
6912 *
6913 * @see #getDrawingCache(boolean)
6914 */
6915 public Bitmap getDrawingCache() {
6916 return getDrawingCache(false);
6917 }
6918
6919 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006920 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
6921 * is null when caching is disabled. If caching is enabled and the cache is not ready,
6922 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
6923 * draw from the cache when the cache is enabled. To benefit from the cache, you must
6924 * request the drawing cache by calling this method and draw it on screen if the
6925 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07006926 *
6927 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
6928 * this method will create a bitmap of the same size as this view. Because this bitmap
6929 * will be drawn scaled by the parent ViewGroup, the result on screen might show
6930 * scaling artifacts. To avoid such artifacts, you should call this method by setting
6931 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
6932 * size than the view. This implies that your application must be able to handle this
6933 * size.</p>
6934 *
6935 * @param autoScale Indicates whether the generated bitmap should be scaled based on
6936 * the current density of the screen when the application is in compatibility
6937 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006938 *
Romain Guyfbd8f692009-06-26 14:51:58 -07006939 * @return A bitmap representing this view or null if cache is disabled.
6940 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006941 * @see #setDrawingCacheEnabled(boolean)
6942 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07006943 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 * @see #destroyDrawingCache()
6945 */
Romain Guyfbd8f692009-06-26 14:51:58 -07006946 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
6948 return null;
6949 }
6950 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07006951 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006952 }
Romain Guyfbd8f692009-06-26 14:51:58 -07006953 return autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) :
6954 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006955 }
6956
6957 /**
6958 * <p>Frees the resources used by the drawing cache. If you call
6959 * {@link #buildDrawingCache()} manually without calling
6960 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
6961 * should cleanup the cache with this method afterwards.</p>
6962 *
6963 * @see #setDrawingCacheEnabled(boolean)
6964 * @see #buildDrawingCache()
6965 * @see #getDrawingCache()
6966 */
6967 public void destroyDrawingCache() {
6968 if (mDrawingCache != null) {
6969 final Bitmap bitmap = mDrawingCache.get();
6970 if (bitmap != null) bitmap.recycle();
6971 mDrawingCache = null;
6972 }
Romain Guyfbd8f692009-06-26 14:51:58 -07006973 if (mUnscaledDrawingCache != null) {
6974 final Bitmap bitmap = mUnscaledDrawingCache.get();
6975 if (bitmap != null) bitmap.recycle();
6976 mUnscaledDrawingCache = null;
6977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 }
6979
6980 /**
6981 * Setting a solid background color for the drawing cache's bitmaps will improve
6982 * perfromance and memory usage. Note, though that this should only be used if this
6983 * view will always be drawn on top of a solid color.
6984 *
6985 * @param color The background color to use for the drawing cache's bitmap
6986 *
6987 * @see #setDrawingCacheEnabled(boolean)
6988 * @see #buildDrawingCache()
6989 * @see #getDrawingCache()
6990 */
6991 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08006992 if (color != mDrawingCacheBackgroundColor) {
6993 mDrawingCacheBackgroundColor = color;
6994 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006996 }
6997
6998 /**
6999 * @see #setDrawingCacheBackgroundColor(int)
7000 *
7001 * @return The background color to used for the drawing cache's bitmap
7002 */
7003 public int getDrawingCacheBackgroundColor() {
7004 return mDrawingCacheBackgroundColor;
7005 }
7006
7007 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007008 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
7009 *
7010 * @see #buildDrawingCache(boolean)
7011 */
7012 public void buildDrawingCache() {
7013 buildDrawingCache(false);
7014 }
7015
7016 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
7018 *
7019 * <p>If you call {@link #buildDrawingCache()} manually without calling
7020 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7021 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007022 *
7023 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7024 * this method will create a bitmap of the same size as this view. Because this bitmap
7025 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7026 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7027 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7028 * size than the view. This implies that your application must be able to handle this
7029 * size.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007030 *
7031 * @see #getDrawingCache()
7032 * @see #destroyDrawingCache()
7033 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007034 public void buildDrawingCache(boolean autoScale) {
7035 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
7036 (mDrawingCache == null || mDrawingCache.get() == null) :
7037 (mUnscaledDrawingCache == null || mUnscaledDrawingCache.get() == null))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007038
7039 if (ViewDebug.TRACE_HIERARCHY) {
7040 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7041 }
Romain Guy13922e02009-05-12 17:56:14 -07007042 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 EventLog.writeEvent(60002, hashCode());
7044 }
7045
Romain Guy8506ab42009-06-11 17:35:47 -07007046 int width = mRight - mLeft;
7047 int height = mBottom - mTop;
7048
7049 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007050 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007051
Romain Guye1123222009-06-29 14:24:56 -07007052 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007053 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7054 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056
7057 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007058 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Romain Guya62e4702009-10-08 10:48:54 -07007059 final boolean translucentWindow = attachInfo != null && attachInfo.mTranslucentWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007060
7061 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007062 // Projected bitmap size in bytes
7063 (width * height * (opaque && !translucentWindow ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007064 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7065 destroyDrawingCache();
7066 return;
7067 }
7068
7069 boolean clear = true;
Romain Guyfbd8f692009-06-26 14:51:58 -07007070 Bitmap bitmap = autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) :
7071 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072
7073 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 Bitmap.Config quality;
7075 if (!opaque) {
7076 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7077 case DRAWING_CACHE_QUALITY_AUTO:
7078 quality = Bitmap.Config.ARGB_8888;
7079 break;
7080 case DRAWING_CACHE_QUALITY_LOW:
7081 quality = Bitmap.Config.ARGB_4444;
7082 break;
7083 case DRAWING_CACHE_QUALITY_HIGH:
7084 quality = Bitmap.Config.ARGB_8888;
7085 break;
7086 default:
7087 quality = Bitmap.Config.ARGB_8888;
7088 break;
7089 }
7090 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07007091 // Optimization for translucent windows
7092 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
7093 quality = translucentWindow ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 }
7095
7096 // Try to cleanup memory
7097 if (bitmap != null) bitmap.recycle();
7098
7099 try {
7100 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07007101 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07007102 if (autoScale) {
7103 mDrawingCache = new SoftReference<Bitmap>(bitmap);
7104 } else {
7105 mUnscaledDrawingCache = new SoftReference<Bitmap>(bitmap);
7106 }
Romain Guy35b38ce2009-10-07 13:38:55 -07007107 if (opaque && translucentWindow) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007108 } catch (OutOfMemoryError e) {
7109 // If there is not enough memory to create the bitmap cache, just
7110 // ignore the issue as bitmap caches are not required to draw the
7111 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07007112 if (autoScale) {
7113 mDrawingCache = null;
7114 } else {
7115 mUnscaledDrawingCache = null;
7116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 return;
7118 }
7119
7120 clear = drawingCacheBackgroundColor != 0;
7121 }
7122
7123 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007124 if (attachInfo != null) {
7125 canvas = attachInfo.mCanvas;
7126 if (canvas == null) {
7127 canvas = new Canvas();
7128 }
7129 canvas.setBitmap(bitmap);
7130 // Temporarily clobber the cached Canvas in case one of our children
7131 // is also using a drawing cache. Without this, the children would
7132 // steal the canvas by attaching their own bitmap to it and bad, bad
7133 // thing would happen (invisible views, corrupted drawings, etc.)
7134 attachInfo.mCanvas = null;
7135 } else {
7136 // This case should hopefully never or seldom happen
7137 canvas = new Canvas(bitmap);
7138 }
7139
7140 if (clear) {
7141 bitmap.eraseColor(drawingCacheBackgroundColor);
7142 }
7143
7144 computeScroll();
7145 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07007146
Romain Guye1123222009-06-29 14:24:56 -07007147 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007148 final float scale = attachInfo.mApplicationScale;
7149 canvas.scale(scale, scale);
7150 }
7151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007152 canvas.translate(-mScrollX, -mScrollY);
7153
Romain Guy5bcdff42009-05-14 21:27:18 -07007154 mPrivateFlags |= DRAWN;
Romain Guyecd80ee2009-12-03 17:13:02 -08007155 mPrivateFlags |= DRAWING_CACHE_VALID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007156
7157 // Fast path for layouts with no backgrounds
7158 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7159 if (ViewDebug.TRACE_HIERARCHY) {
7160 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7161 }
Romain Guy5bcdff42009-05-14 21:27:18 -07007162 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007163 dispatchDraw(canvas);
7164 } else {
7165 draw(canvas);
7166 }
7167
7168 canvas.restoreToCount(restoreCount);
7169
7170 if (attachInfo != null) {
7171 // Restore the cached Canvas for our siblings
7172 attachInfo.mCanvas = canvas;
7173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007174 }
7175 }
7176
7177 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007178 * Create a snapshot of the view into a bitmap. We should probably make
7179 * some form of this public, but should think about the API.
7180 */
Romain Guy223ff5c2010-03-02 17:07:47 -08007181 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007182 int width = mRight - mLeft;
7183 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007184
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007185 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07007186 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007187 width = (int) ((width * scale) + 0.5f);
7188 height = (int) ((height * scale) + 0.5f);
7189
Romain Guy8c11e312009-09-14 15:15:30 -07007190 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007191 if (bitmap == null) {
7192 throw new OutOfMemoryError();
7193 }
7194
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007195 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
7196
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007197 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007198 if (attachInfo != null) {
7199 canvas = attachInfo.mCanvas;
7200 if (canvas == null) {
7201 canvas = new Canvas();
7202 }
7203 canvas.setBitmap(bitmap);
7204 // Temporarily clobber the cached Canvas in case one of our children
7205 // is also using a drawing cache. Without this, the children would
7206 // steal the canvas by attaching their own bitmap to it and bad, bad
7207 // things would happen (invisible views, corrupted drawings, etc.)
7208 attachInfo.mCanvas = null;
7209 } else {
7210 // This case should hopefully never or seldom happen
7211 canvas = new Canvas(bitmap);
7212 }
7213
Romain Guy5bcdff42009-05-14 21:27:18 -07007214 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007215 bitmap.eraseColor(backgroundColor);
7216 }
7217
7218 computeScroll();
7219 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007220 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007221 canvas.translate(-mScrollX, -mScrollY);
7222
Romain Guy5bcdff42009-05-14 21:27:18 -07007223 // Temporarily remove the dirty mask
7224 int flags = mPrivateFlags;
7225 mPrivateFlags &= ~DIRTY_MASK;
7226
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007227 // Fast path for layouts with no backgrounds
7228 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7229 dispatchDraw(canvas);
7230 } else {
7231 draw(canvas);
7232 }
7233
Romain Guy5bcdff42009-05-14 21:27:18 -07007234 mPrivateFlags = flags;
7235
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007236 canvas.restoreToCount(restoreCount);
7237
7238 if (attachInfo != null) {
7239 // Restore the cached Canvas for our siblings
7240 attachInfo.mCanvas = canvas;
7241 }
Romain Guy8506ab42009-06-11 17:35:47 -07007242
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007243 return bitmap;
7244 }
7245
7246 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007247 * Indicates whether this View is currently in edit mode. A View is usually
7248 * in edit mode when displayed within a developer tool. For instance, if
7249 * this View is being drawn by a visual user interface builder, this method
7250 * should return true.
7251 *
7252 * Subclasses should check the return value of this method to provide
7253 * different behaviors if their normal behavior might interfere with the
7254 * host environment. For instance: the class spawns a thread in its
7255 * constructor, the drawing code relies on device-specific features, etc.
7256 *
7257 * This method is usually checked in the drawing code of custom widgets.
7258 *
7259 * @return True if this View is in edit mode, false otherwise.
7260 */
7261 public boolean isInEditMode() {
7262 return false;
7263 }
7264
7265 /**
7266 * If the View draws content inside its padding and enables fading edges,
7267 * it needs to support padding offsets. Padding offsets are added to the
7268 * fading edges to extend the length of the fade so that it covers pixels
7269 * drawn inside the padding.
7270 *
7271 * Subclasses of this class should override this method if they need
7272 * to draw content inside the padding.
7273 *
7274 * @return True if padding offset must be applied, false otherwise.
7275 *
7276 * @see #getLeftPaddingOffset()
7277 * @see #getRightPaddingOffset()
7278 * @see #getTopPaddingOffset()
7279 * @see #getBottomPaddingOffset()
7280 *
7281 * @since CURRENT
7282 */
7283 protected boolean isPaddingOffsetRequired() {
7284 return false;
7285 }
7286
7287 /**
7288 * Amount by which to extend the left fading region. Called only when
7289 * {@link #isPaddingOffsetRequired()} returns true.
7290 *
7291 * @return The left padding offset in pixels.
7292 *
7293 * @see #isPaddingOffsetRequired()
7294 *
7295 * @since CURRENT
7296 */
7297 protected int getLeftPaddingOffset() {
7298 return 0;
7299 }
7300
7301 /**
7302 * Amount by which to extend the right fading region. Called only when
7303 * {@link #isPaddingOffsetRequired()} returns true.
7304 *
7305 * @return The right padding offset in pixels.
7306 *
7307 * @see #isPaddingOffsetRequired()
7308 *
7309 * @since CURRENT
7310 */
7311 protected int getRightPaddingOffset() {
7312 return 0;
7313 }
7314
7315 /**
7316 * Amount by which to extend the top fading region. Called only when
7317 * {@link #isPaddingOffsetRequired()} returns true.
7318 *
7319 * @return The top padding offset in pixels.
7320 *
7321 * @see #isPaddingOffsetRequired()
7322 *
7323 * @since CURRENT
7324 */
7325 protected int getTopPaddingOffset() {
7326 return 0;
7327 }
7328
7329 /**
7330 * Amount by which to extend the bottom fading region. Called only when
7331 * {@link #isPaddingOffsetRequired()} returns true.
7332 *
7333 * @return The bottom padding offset in pixels.
7334 *
7335 * @see #isPaddingOffsetRequired()
7336 *
7337 * @since CURRENT
7338 */
7339 protected int getBottomPaddingOffset() {
7340 return 0;
7341 }
7342
7343 /**
7344 * Manually render this view (and all of its children) to the given Canvas.
7345 * The view must have already done a full layout before this function is
7346 * called. When implementing a view, do not override this method; instead,
7347 * you should implement {@link #onDraw}.
7348 *
7349 * @param canvas The Canvas to which the View is rendered.
7350 */
7351 public void draw(Canvas canvas) {
7352 if (ViewDebug.TRACE_HIERARCHY) {
7353 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7354 }
7355
Romain Guy5bcdff42009-05-14 21:27:18 -07007356 final int privateFlags = mPrivateFlags;
7357 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
7358 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
7359 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07007360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007361 /*
7362 * Draw traversal performs several drawing steps which must be executed
7363 * in the appropriate order:
7364 *
7365 * 1. Draw the background
7366 * 2. If necessary, save the canvas' layers to prepare for fading
7367 * 3. Draw view's content
7368 * 4. Draw children
7369 * 5. If necessary, draw the fading edges and restore layers
7370 * 6. Draw decorations (scrollbars for instance)
7371 */
7372
7373 // Step 1, draw the background, if needed
7374 int saveCount;
7375
Romain Guy24443ea2009-05-11 11:56:30 -07007376 if (!dirtyOpaque) {
7377 final Drawable background = mBGDrawable;
7378 if (background != null) {
7379 final int scrollX = mScrollX;
7380 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007381
Romain Guy24443ea2009-05-11 11:56:30 -07007382 if (mBackgroundSizeChanged) {
7383 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
7384 mBackgroundSizeChanged = false;
7385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386
Romain Guy24443ea2009-05-11 11:56:30 -07007387 if ((scrollX | scrollY) == 0) {
7388 background.draw(canvas);
7389 } else {
7390 canvas.translate(scrollX, scrollY);
7391 background.draw(canvas);
7392 canvas.translate(-scrollX, -scrollY);
7393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007394 }
7395 }
7396
7397 // skip step 2 & 5 if possible (common case)
7398 final int viewFlags = mViewFlags;
7399 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
7400 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
7401 if (!verticalEdges && !horizontalEdges) {
7402 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007403 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007404
7405 // Step 4, draw the children
7406 dispatchDraw(canvas);
7407
7408 // Step 6, draw decorations (scrollbars)
7409 onDrawScrollBars(canvas);
7410
7411 // we're done...
7412 return;
7413 }
7414
7415 /*
7416 * Here we do the full fledged routine...
7417 * (this is an uncommon case where speed matters less,
7418 * this is why we repeat some of the tests that have been
7419 * done above)
7420 */
7421
7422 boolean drawTop = false;
7423 boolean drawBottom = false;
7424 boolean drawLeft = false;
7425 boolean drawRight = false;
7426
7427 float topFadeStrength = 0.0f;
7428 float bottomFadeStrength = 0.0f;
7429 float leftFadeStrength = 0.0f;
7430 float rightFadeStrength = 0.0f;
7431
7432 // Step 2, save the canvas' layers
7433 int paddingLeft = mPaddingLeft;
7434 int paddingTop = mPaddingTop;
7435
7436 final boolean offsetRequired = isPaddingOffsetRequired();
7437 if (offsetRequired) {
7438 paddingLeft += getLeftPaddingOffset();
7439 paddingTop += getTopPaddingOffset();
7440 }
7441
7442 int left = mScrollX + paddingLeft;
7443 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
7444 int top = mScrollY + paddingTop;
7445 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
7446
7447 if (offsetRequired) {
7448 right += getRightPaddingOffset();
7449 bottom += getBottomPaddingOffset();
7450 }
7451
7452 final ScrollabilityCache scrollabilityCache = mScrollCache;
7453 int length = scrollabilityCache.fadingEdgeLength;
7454
7455 // clip the fade length if top and bottom fades overlap
7456 // overlapping fades produce odd-looking artifacts
7457 if (verticalEdges && (top + length > bottom - length)) {
7458 length = (bottom - top) / 2;
7459 }
7460
7461 // also clip horizontal fades if necessary
7462 if (horizontalEdges && (left + length > right - length)) {
7463 length = (right - left) / 2;
7464 }
7465
7466 if (verticalEdges) {
7467 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007468 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007469 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007470 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007471 }
7472
7473 if (horizontalEdges) {
7474 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007475 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007476 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007477 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 }
7479
7480 saveCount = canvas.getSaveCount();
7481
7482 int solidColor = getSolidColor();
7483 if (solidColor == 0) {
7484 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
7485
7486 if (drawTop) {
7487 canvas.saveLayer(left, top, right, top + length, null, flags);
7488 }
7489
7490 if (drawBottom) {
7491 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
7492 }
7493
7494 if (drawLeft) {
7495 canvas.saveLayer(left, top, left + length, bottom, null, flags);
7496 }
7497
7498 if (drawRight) {
7499 canvas.saveLayer(right - length, top, right, bottom, null, flags);
7500 }
7501 } else {
7502 scrollabilityCache.setFadeColor(solidColor);
7503 }
7504
7505 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007506 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507
7508 // Step 4, draw the children
7509 dispatchDraw(canvas);
7510
7511 // Step 5, draw the fade effect and restore layers
7512 final Paint p = scrollabilityCache.paint;
7513 final Matrix matrix = scrollabilityCache.matrix;
7514 final Shader fade = scrollabilityCache.shader;
7515 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
7516
7517 if (drawTop) {
7518 matrix.setScale(1, fadeHeight * topFadeStrength);
7519 matrix.postTranslate(left, top);
7520 fade.setLocalMatrix(matrix);
7521 canvas.drawRect(left, top, right, top + length, p);
7522 }
7523
7524 if (drawBottom) {
7525 matrix.setScale(1, fadeHeight * bottomFadeStrength);
7526 matrix.postRotate(180);
7527 matrix.postTranslate(left, bottom);
7528 fade.setLocalMatrix(matrix);
7529 canvas.drawRect(left, bottom - length, right, bottom, p);
7530 }
7531
7532 if (drawLeft) {
7533 matrix.setScale(1, fadeHeight * leftFadeStrength);
7534 matrix.postRotate(-90);
7535 matrix.postTranslate(left, top);
7536 fade.setLocalMatrix(matrix);
7537 canvas.drawRect(left, top, left + length, bottom, p);
7538 }
7539
7540 if (drawRight) {
7541 matrix.setScale(1, fadeHeight * rightFadeStrength);
7542 matrix.postRotate(90);
7543 matrix.postTranslate(right, top);
7544 fade.setLocalMatrix(matrix);
7545 canvas.drawRect(right - length, top, right, bottom, p);
7546 }
7547
7548 canvas.restoreToCount(saveCount);
7549
7550 // Step 6, draw decorations (scrollbars)
7551 onDrawScrollBars(canvas);
7552 }
7553
7554 /**
7555 * Override this if your view is known to always be drawn on top of a solid color background,
7556 * and needs to draw fading edges. Returning a non-zero color enables the view system to
7557 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
7558 * should be set to 0xFF.
7559 *
7560 * @see #setVerticalFadingEdgeEnabled
7561 * @see #setHorizontalFadingEdgeEnabled
7562 *
7563 * @return The known solid color background for this view, or 0 if the color may vary
7564 */
7565 public int getSolidColor() {
7566 return 0;
7567 }
7568
7569 /**
7570 * Build a human readable string representation of the specified view flags.
7571 *
7572 * @param flags the view flags to convert to a string
7573 * @return a String representing the supplied flags
7574 */
7575 private static String printFlags(int flags) {
7576 String output = "";
7577 int numFlags = 0;
7578 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
7579 output += "TAKES_FOCUS";
7580 numFlags++;
7581 }
7582
7583 switch (flags & VISIBILITY_MASK) {
7584 case INVISIBLE:
7585 if (numFlags > 0) {
7586 output += " ";
7587 }
7588 output += "INVISIBLE";
7589 // USELESS HERE numFlags++;
7590 break;
7591 case GONE:
7592 if (numFlags > 0) {
7593 output += " ";
7594 }
7595 output += "GONE";
7596 // USELESS HERE numFlags++;
7597 break;
7598 default:
7599 break;
7600 }
7601 return output;
7602 }
7603
7604 /**
7605 * Build a human readable string representation of the specified private
7606 * view flags.
7607 *
7608 * @param privateFlags the private view flags to convert to a string
7609 * @return a String representing the supplied flags
7610 */
7611 private static String printPrivateFlags(int privateFlags) {
7612 String output = "";
7613 int numFlags = 0;
7614
7615 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
7616 output += "WANTS_FOCUS";
7617 numFlags++;
7618 }
7619
7620 if ((privateFlags & FOCUSED) == FOCUSED) {
7621 if (numFlags > 0) {
7622 output += " ";
7623 }
7624 output += "FOCUSED";
7625 numFlags++;
7626 }
7627
7628 if ((privateFlags & SELECTED) == SELECTED) {
7629 if (numFlags > 0) {
7630 output += " ";
7631 }
7632 output += "SELECTED";
7633 numFlags++;
7634 }
7635
7636 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
7637 if (numFlags > 0) {
7638 output += " ";
7639 }
7640 output += "IS_ROOT_NAMESPACE";
7641 numFlags++;
7642 }
7643
7644 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
7645 if (numFlags > 0) {
7646 output += " ";
7647 }
7648 output += "HAS_BOUNDS";
7649 numFlags++;
7650 }
7651
7652 if ((privateFlags & DRAWN) == DRAWN) {
7653 if (numFlags > 0) {
7654 output += " ";
7655 }
7656 output += "DRAWN";
7657 // USELESS HERE numFlags++;
7658 }
7659 return output;
7660 }
7661
7662 /**
7663 * <p>Indicates whether or not this view's layout will be requested during
7664 * the next hierarchy layout pass.</p>
7665 *
7666 * @return true if the layout will be forced during next layout pass
7667 */
7668 public boolean isLayoutRequested() {
7669 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
7670 }
7671
7672 /**
7673 * Assign a size and position to a view and all of its
7674 * descendants
7675 *
7676 * <p>This is the second phase of the layout mechanism.
7677 * (The first is measuring). In this phase, each parent calls
7678 * layout on all of its children to position them.
7679 * This is typically done using the child measurements
7680 * that were stored in the measure pass().
7681 *
7682 * Derived classes with children should override
7683 * onLayout. In that method, they should
7684 * call layout on each of their their children.
7685 *
7686 * @param l Left position, relative to parent
7687 * @param t Top position, relative to parent
7688 * @param r Right position, relative to parent
7689 * @param b Bottom position, relative to parent
7690 */
7691 public final void layout(int l, int t, int r, int b) {
7692 boolean changed = setFrame(l, t, r, b);
7693 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
7694 if (ViewDebug.TRACE_HIERARCHY) {
7695 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
7696 }
7697
7698 onLayout(changed, l, t, r, b);
7699 mPrivateFlags &= ~LAYOUT_REQUIRED;
7700 }
7701 mPrivateFlags &= ~FORCE_LAYOUT;
7702 }
7703
7704 /**
7705 * Called from layout when this view should
7706 * assign a size and position to each of its children.
7707 *
7708 * Derived classes with children should override
7709 * this method and call layout on each of
7710 * their their children.
7711 * @param changed This is a new size or position for this view
7712 * @param left Left position, relative to parent
7713 * @param top Top position, relative to parent
7714 * @param right Right position, relative to parent
7715 * @param bottom Bottom position, relative to parent
7716 */
7717 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
7718 }
7719
7720 /**
7721 * Assign a size and position to this view.
7722 *
7723 * This is called from layout.
7724 *
7725 * @param left Left position, relative to parent
7726 * @param top Top position, relative to parent
7727 * @param right Right position, relative to parent
7728 * @param bottom Bottom position, relative to parent
7729 * @return true if the new size and position are different than the
7730 * previous ones
7731 * {@hide}
7732 */
7733 protected boolean setFrame(int left, int top, int right, int bottom) {
7734 boolean changed = false;
7735
7736 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07007737 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 + right + "," + bottom + ")");
7739 }
7740
7741 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
7742 changed = true;
7743
7744 // Remember our drawn bit
7745 int drawn = mPrivateFlags & DRAWN;
7746
7747 // Invalidate our old position
7748 invalidate();
7749
7750
7751 int oldWidth = mRight - mLeft;
7752 int oldHeight = mBottom - mTop;
7753
7754 mLeft = left;
7755 mTop = top;
7756 mRight = right;
7757 mBottom = bottom;
7758
7759 mPrivateFlags |= HAS_BOUNDS;
7760
7761 int newWidth = right - left;
7762 int newHeight = bottom - top;
7763
7764 if (newWidth != oldWidth || newHeight != oldHeight) {
7765 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
7766 }
7767
7768 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
7769 // If we are visible, force the DRAWN bit to on so that
7770 // this invalidate will go through (at least to our parent).
7771 // This is because someone may have invalidated this view
7772 // before this call to setFrame came in, therby clearing
7773 // the DRAWN bit.
7774 mPrivateFlags |= DRAWN;
7775 invalidate();
7776 }
7777
7778 // Reset drawn bit to original value (invalidate turns it off)
7779 mPrivateFlags |= drawn;
7780
7781 mBackgroundSizeChanged = true;
7782 }
7783 return changed;
7784 }
7785
7786 /**
7787 * Finalize inflating a view from XML. This is called as the last phase
7788 * of inflation, after all child views have been added.
7789 *
7790 * <p>Even if the subclass overrides onFinishInflate, they should always be
7791 * sure to call the super method, so that we get called.
7792 */
7793 protected void onFinishInflate() {
7794 }
7795
7796 /**
7797 * Returns the resources associated with this view.
7798 *
7799 * @return Resources object.
7800 */
7801 public Resources getResources() {
7802 return mResources;
7803 }
7804
7805 /**
7806 * Invalidates the specified Drawable.
7807 *
7808 * @param drawable the drawable to invalidate
7809 */
7810 public void invalidateDrawable(Drawable drawable) {
7811 if (verifyDrawable(drawable)) {
7812 final Rect dirty = drawable.getBounds();
7813 final int scrollX = mScrollX;
7814 final int scrollY = mScrollY;
7815
7816 invalidate(dirty.left + scrollX, dirty.top + scrollY,
7817 dirty.right + scrollX, dirty.bottom + scrollY);
7818 }
7819 }
7820
7821 /**
7822 * Schedules an action on a drawable to occur at a specified time.
7823 *
7824 * @param who the recipient of the action
7825 * @param what the action to run on the drawable
7826 * @param when the time at which the action must occur. Uses the
7827 * {@link SystemClock#uptimeMillis} timebase.
7828 */
7829 public void scheduleDrawable(Drawable who, Runnable what, long when) {
7830 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
7831 mAttachInfo.mHandler.postAtTime(what, who, when);
7832 }
7833 }
7834
7835 /**
7836 * Cancels a scheduled action on a drawable.
7837 *
7838 * @param who the recipient of the action
7839 * @param what the action to cancel
7840 */
7841 public void unscheduleDrawable(Drawable who, Runnable what) {
7842 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
7843 mAttachInfo.mHandler.removeCallbacks(what, who);
7844 }
7845 }
7846
7847 /**
7848 * Unschedule any events associated with the given Drawable. This can be
7849 * used when selecting a new Drawable into a view, so that the previous
7850 * one is completely unscheduled.
7851 *
7852 * @param who The Drawable to unschedule.
7853 *
7854 * @see #drawableStateChanged
7855 */
7856 public void unscheduleDrawable(Drawable who) {
7857 if (mAttachInfo != null) {
7858 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
7859 }
7860 }
7861
7862 /**
7863 * If your view subclass is displaying its own Drawable objects, it should
7864 * override this function and return true for any Drawable it is
7865 * displaying. This allows animations for those drawables to be
7866 * scheduled.
7867 *
7868 * <p>Be sure to call through to the super class when overriding this
7869 * function.
7870 *
7871 * @param who The Drawable to verify. Return true if it is one you are
7872 * displaying, else return the result of calling through to the
7873 * super class.
7874 *
7875 * @return boolean If true than the Drawable is being displayed in the
7876 * view; else false and it is not allowed to animate.
7877 *
7878 * @see #unscheduleDrawable
7879 * @see #drawableStateChanged
7880 */
7881 protected boolean verifyDrawable(Drawable who) {
7882 return who == mBGDrawable;
7883 }
7884
7885 /**
7886 * This function is called whenever the state of the view changes in such
7887 * a way that it impacts the state of drawables being shown.
7888 *
7889 * <p>Be sure to call through to the superclass when overriding this
7890 * function.
7891 *
7892 * @see Drawable#setState
7893 */
7894 protected void drawableStateChanged() {
7895 Drawable d = mBGDrawable;
7896 if (d != null && d.isStateful()) {
7897 d.setState(getDrawableState());
7898 }
7899 }
7900
7901 /**
7902 * Call this to force a view to update its drawable state. This will cause
7903 * drawableStateChanged to be called on this view. Views that are interested
7904 * in the new state should call getDrawableState.
7905 *
7906 * @see #drawableStateChanged
7907 * @see #getDrawableState
7908 */
7909 public void refreshDrawableState() {
7910 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
7911 drawableStateChanged();
7912
7913 ViewParent parent = mParent;
7914 if (parent != null) {
7915 parent.childDrawableStateChanged(this);
7916 }
7917 }
7918
7919 /**
7920 * Return an array of resource IDs of the drawable states representing the
7921 * current state of the view.
7922 *
7923 * @return The current drawable state
7924 *
7925 * @see Drawable#setState
7926 * @see #drawableStateChanged
7927 * @see #onCreateDrawableState
7928 */
7929 public final int[] getDrawableState() {
7930 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
7931 return mDrawableState;
7932 } else {
7933 mDrawableState = onCreateDrawableState(0);
7934 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
7935 return mDrawableState;
7936 }
7937 }
7938
7939 /**
7940 * Generate the new {@link android.graphics.drawable.Drawable} state for
7941 * this view. This is called by the view
7942 * system when the cached Drawable state is determined to be invalid. To
7943 * retrieve the current state, you should use {@link #getDrawableState}.
7944 *
7945 * @param extraSpace if non-zero, this is the number of extra entries you
7946 * would like in the returned array in which you can place your own
7947 * states.
7948 *
7949 * @return Returns an array holding the current {@link Drawable} state of
7950 * the view.
7951 *
7952 * @see #mergeDrawableStates
7953 */
7954 protected int[] onCreateDrawableState(int extraSpace) {
7955 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
7956 mParent instanceof View) {
7957 return ((View) mParent).onCreateDrawableState(extraSpace);
7958 }
7959
7960 int[] drawableState;
7961
7962 int privateFlags = mPrivateFlags;
7963
7964 int viewStateIndex = (((privateFlags & PRESSED) != 0) ? 1 : 0);
7965
7966 viewStateIndex = (viewStateIndex << 1)
7967 + (((mViewFlags & ENABLED_MASK) == ENABLED) ? 1 : 0);
7968
7969 viewStateIndex = (viewStateIndex << 1) + (isFocused() ? 1 : 0);
7970
7971 viewStateIndex = (viewStateIndex << 1)
7972 + (((privateFlags & SELECTED) != 0) ? 1 : 0);
7973
7974 final boolean hasWindowFocus = hasWindowFocus();
7975 viewStateIndex = (viewStateIndex << 1) + (hasWindowFocus ? 1 : 0);
7976
7977 drawableState = VIEW_STATE_SETS[viewStateIndex];
7978
7979 //noinspection ConstantIfStatement
7980 if (false) {
7981 Log.i("View", "drawableStateIndex=" + viewStateIndex);
7982 Log.i("View", toString()
7983 + " pressed=" + ((privateFlags & PRESSED) != 0)
7984 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
7985 + " fo=" + hasFocus()
7986 + " sl=" + ((privateFlags & SELECTED) != 0)
7987 + " wf=" + hasWindowFocus
7988 + ": " + Arrays.toString(drawableState));
7989 }
7990
7991 if (extraSpace == 0) {
7992 return drawableState;
7993 }
7994
7995 final int[] fullState;
7996 if (drawableState != null) {
7997 fullState = new int[drawableState.length + extraSpace];
7998 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
7999 } else {
8000 fullState = new int[extraSpace];
8001 }
8002
8003 return fullState;
8004 }
8005
8006 /**
8007 * Merge your own state values in <var>additionalState</var> into the base
8008 * state values <var>baseState</var> that were returned by
8009 * {@link #onCreateDrawableState}.
8010 *
8011 * @param baseState The base state values returned by
8012 * {@link #onCreateDrawableState}, which will be modified to also hold your
8013 * own additional state values.
8014 *
8015 * @param additionalState The additional state values you would like
8016 * added to <var>baseState</var>; this array is not modified.
8017 *
8018 * @return As a convenience, the <var>baseState</var> array you originally
8019 * passed into the function is returned.
8020 *
8021 * @see #onCreateDrawableState
8022 */
8023 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
8024 final int N = baseState.length;
8025 int i = N - 1;
8026 while (i >= 0 && baseState[i] == 0) {
8027 i--;
8028 }
8029 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
8030 return baseState;
8031 }
8032
8033 /**
8034 * Sets the background color for this view.
8035 * @param color the color of the background
8036 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008037 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 public void setBackgroundColor(int color) {
8039 setBackgroundDrawable(new ColorDrawable(color));
8040 }
8041
8042 /**
8043 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07008044 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008045 * @param resid The identifier of the resource.
8046 * @attr ref android.R.styleable#View_background
8047 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008048 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 public void setBackgroundResource(int resid) {
8050 if (resid != 0 && resid == mBackgroundResource) {
8051 return;
8052 }
8053
8054 Drawable d= null;
8055 if (resid != 0) {
8056 d = mResources.getDrawable(resid);
8057 }
8058 setBackgroundDrawable(d);
8059
8060 mBackgroundResource = resid;
8061 }
8062
8063 /**
8064 * Set the background to a given Drawable, or remove the background. If the
8065 * background has padding, this View's padding is set to the background's
8066 * padding. However, when a background is removed, this View's padding isn't
8067 * touched. If setting the padding is desired, please use
8068 * {@link #setPadding(int, int, int, int)}.
8069 *
8070 * @param d The Drawable to use as the background, or null to remove the
8071 * background
8072 */
8073 public void setBackgroundDrawable(Drawable d) {
8074 boolean requestLayout = false;
8075
8076 mBackgroundResource = 0;
8077
8078 /*
8079 * Regardless of whether we're setting a new background or not, we want
8080 * to clear the previous drawable.
8081 */
8082 if (mBGDrawable != null) {
8083 mBGDrawable.setCallback(null);
8084 unscheduleDrawable(mBGDrawable);
8085 }
8086
8087 if (d != null) {
8088 Rect padding = sThreadLocal.get();
8089 if (padding == null) {
8090 padding = new Rect();
8091 sThreadLocal.set(padding);
8092 }
8093 if (d.getPadding(padding)) {
8094 setPadding(padding.left, padding.top, padding.right, padding.bottom);
8095 }
8096
8097 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
8098 // if it has a different minimum size, we should layout again
8099 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
8100 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
8101 requestLayout = true;
8102 }
8103
8104 d.setCallback(this);
8105 if (d.isStateful()) {
8106 d.setState(getDrawableState());
8107 }
8108 d.setVisible(getVisibility() == VISIBLE, false);
8109 mBGDrawable = d;
8110
8111 if ((mPrivateFlags & SKIP_DRAW) != 0) {
8112 mPrivateFlags &= ~SKIP_DRAW;
8113 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8114 requestLayout = true;
8115 }
8116 } else {
8117 /* Remove the background */
8118 mBGDrawable = null;
8119
8120 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
8121 /*
8122 * This view ONLY drew the background before and we're removing
8123 * the background, so now it won't draw anything
8124 * (hence we SKIP_DRAW)
8125 */
8126 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
8127 mPrivateFlags |= SKIP_DRAW;
8128 }
8129
8130 /*
8131 * When the background is set, we try to apply its padding to this
8132 * View. When the background is removed, we don't touch this View's
8133 * padding. This is noted in the Javadocs. Hence, we don't need to
8134 * requestLayout(), the invalidate() below is sufficient.
8135 */
8136
8137 // The old background's minimum size could have affected this
8138 // View's layout, so let's requestLayout
8139 requestLayout = true;
8140 }
8141
Romain Guy8f1344f52009-05-15 16:03:59 -07008142 computeOpaqueFlags();
8143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008144 if (requestLayout) {
8145 requestLayout();
8146 }
8147
8148 mBackgroundSizeChanged = true;
8149 invalidate();
8150 }
8151
8152 /**
8153 * Gets the background drawable
8154 * @return The drawable used as the background for this view, if any.
8155 */
8156 public Drawable getBackground() {
8157 return mBGDrawable;
8158 }
8159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 /**
8161 * Sets the padding. The view may add on the space required to display
8162 * the scrollbars, depending on the style and visibility of the scrollbars.
8163 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
8164 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
8165 * from the values set in this call.
8166 *
8167 * @attr ref android.R.styleable#View_padding
8168 * @attr ref android.R.styleable#View_paddingBottom
8169 * @attr ref android.R.styleable#View_paddingLeft
8170 * @attr ref android.R.styleable#View_paddingRight
8171 * @attr ref android.R.styleable#View_paddingTop
8172 * @param left the left padding in pixels
8173 * @param top the top padding in pixels
8174 * @param right the right padding in pixels
8175 * @param bottom the bottom padding in pixels
8176 */
8177 public void setPadding(int left, int top, int right, int bottom) {
8178 boolean changed = false;
8179
8180 mUserPaddingRight = right;
8181 mUserPaddingBottom = bottom;
8182
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008183 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07008184
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008185 // Common case is there are no scroll bars.
8186 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
8187 // TODO: Deal with RTL languages to adjust left padding instead of right.
8188 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
8189 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8190 ? 0 : getVerticalScrollbarWidth();
8191 }
8192 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
8193 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8194 ? 0 : getHorizontalScrollbarHeight();
8195 }
8196 }
Romain Guy8506ab42009-06-11 17:35:47 -07008197
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008198 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008199 changed = true;
8200 mPaddingLeft = left;
8201 }
8202 if (mPaddingTop != top) {
8203 changed = true;
8204 mPaddingTop = top;
8205 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008206 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008207 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008208 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008209 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008210 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008211 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008212 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008213 }
8214
8215 if (changed) {
8216 requestLayout();
8217 }
8218 }
8219
8220 /**
8221 * Returns the top padding of this view.
8222 *
8223 * @return the top padding in pixels
8224 */
8225 public int getPaddingTop() {
8226 return mPaddingTop;
8227 }
8228
8229 /**
8230 * Returns the bottom padding of this view. If there are inset and enabled
8231 * scrollbars, this value may include the space required to display the
8232 * scrollbars as well.
8233 *
8234 * @return the bottom padding in pixels
8235 */
8236 public int getPaddingBottom() {
8237 return mPaddingBottom;
8238 }
8239
8240 /**
8241 * Returns the left padding of this view. If there are inset and enabled
8242 * scrollbars, this value may include the space required to display the
8243 * scrollbars as well.
8244 *
8245 * @return the left padding in pixels
8246 */
8247 public int getPaddingLeft() {
8248 return mPaddingLeft;
8249 }
8250
8251 /**
8252 * Returns the right padding of this view. If there are inset and enabled
8253 * scrollbars, this value may include the space required to display the
8254 * scrollbars as well.
8255 *
8256 * @return the right padding in pixels
8257 */
8258 public int getPaddingRight() {
8259 return mPaddingRight;
8260 }
8261
8262 /**
8263 * Changes the selection state of this view. A view can be selected or not.
8264 * Note that selection is not the same as focus. Views are typically
8265 * selected in the context of an AdapterView like ListView or GridView;
8266 * the selected view is the view that is highlighted.
8267 *
8268 * @param selected true if the view must be selected, false otherwise
8269 */
8270 public void setSelected(boolean selected) {
8271 if (((mPrivateFlags & SELECTED) != 0) != selected) {
8272 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07008273 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008274 invalidate();
8275 refreshDrawableState();
8276 dispatchSetSelected(selected);
8277 }
8278 }
8279
8280 /**
8281 * Dispatch setSelected to all of this View's children.
8282 *
8283 * @see #setSelected(boolean)
8284 *
8285 * @param selected The new selected state
8286 */
8287 protected void dispatchSetSelected(boolean selected) {
8288 }
8289
8290 /**
8291 * Indicates the selection state of this view.
8292 *
8293 * @return true if the view is selected, false otherwise
8294 */
8295 @ViewDebug.ExportedProperty
8296 public boolean isSelected() {
8297 return (mPrivateFlags & SELECTED) != 0;
8298 }
8299
8300 /**
8301 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
8302 * observer can be used to get notifications when global events, like
8303 * layout, happen.
8304 *
8305 * The returned ViewTreeObserver observer is not guaranteed to remain
8306 * valid for the lifetime of this View. If the caller of this method keeps
8307 * a long-lived reference to ViewTreeObserver, it should always check for
8308 * the return value of {@link ViewTreeObserver#isAlive()}.
8309 *
8310 * @return The ViewTreeObserver for this view's hierarchy.
8311 */
8312 public ViewTreeObserver getViewTreeObserver() {
8313 if (mAttachInfo != null) {
8314 return mAttachInfo.mTreeObserver;
8315 }
8316 if (mFloatingTreeObserver == null) {
8317 mFloatingTreeObserver = new ViewTreeObserver();
8318 }
8319 return mFloatingTreeObserver;
8320 }
8321
8322 /**
8323 * <p>Finds the topmost view in the current view hierarchy.</p>
8324 *
8325 * @return the topmost view containing this view
8326 */
8327 public View getRootView() {
8328 if (mAttachInfo != null) {
8329 final View v = mAttachInfo.mRootView;
8330 if (v != null) {
8331 return v;
8332 }
8333 }
Romain Guy8506ab42009-06-11 17:35:47 -07008334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008335 View parent = this;
8336
8337 while (parent.mParent != null && parent.mParent instanceof View) {
8338 parent = (View) parent.mParent;
8339 }
8340
8341 return parent;
8342 }
8343
8344 /**
8345 * <p>Computes the coordinates of this view on the screen. The argument
8346 * must be an array of two integers. After the method returns, the array
8347 * contains the x and y location in that order.</p>
8348 *
8349 * @param location an array of two integers in which to hold the coordinates
8350 */
8351 public void getLocationOnScreen(int[] location) {
8352 getLocationInWindow(location);
8353
8354 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07008355 if (info != null) {
8356 location[0] += info.mWindowLeft;
8357 location[1] += info.mWindowTop;
8358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008359 }
8360
8361 /**
8362 * <p>Computes the coordinates of this view in its window. The argument
8363 * must be an array of two integers. After the method returns, the array
8364 * contains the x and y location in that order.</p>
8365 *
8366 * @param location an array of two integers in which to hold the coordinates
8367 */
8368 public void getLocationInWindow(int[] location) {
8369 if (location == null || location.length < 2) {
8370 throw new IllegalArgumentException("location must be an array of "
8371 + "two integers");
8372 }
8373
8374 location[0] = mLeft;
8375 location[1] = mTop;
8376
8377 ViewParent viewParent = mParent;
8378 while (viewParent instanceof View) {
8379 final View view = (View)viewParent;
8380 location[0] += view.mLeft - view.mScrollX;
8381 location[1] += view.mTop - view.mScrollY;
8382 viewParent = view.mParent;
8383 }
Romain Guy8506ab42009-06-11 17:35:47 -07008384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008385 if (viewParent instanceof ViewRoot) {
8386 // *cough*
8387 final ViewRoot vr = (ViewRoot)viewParent;
8388 location[1] -= vr.mCurScrollY;
8389 }
8390 }
8391
8392 /**
8393 * {@hide}
8394 * @param id the id of the view to be found
8395 * @return the view of the specified id, null if cannot be found
8396 */
8397 protected View findViewTraversal(int id) {
8398 if (id == mID) {
8399 return this;
8400 }
8401 return null;
8402 }
8403
8404 /**
8405 * {@hide}
8406 * @param tag the tag of the view to be found
8407 * @return the view of specified tag, null if cannot be found
8408 */
8409 protected View findViewWithTagTraversal(Object tag) {
8410 if (tag != null && tag.equals(mTag)) {
8411 return this;
8412 }
8413 return null;
8414 }
8415
8416 /**
8417 * Look for a child view with the given id. If this view has the given
8418 * id, return this view.
8419 *
8420 * @param id The id to search for.
8421 * @return The view that has the given id in the hierarchy or null
8422 */
8423 public final View findViewById(int id) {
8424 if (id < 0) {
8425 return null;
8426 }
8427 return findViewTraversal(id);
8428 }
8429
8430 /**
8431 * Look for a child view with the given tag. If this view has the given
8432 * tag, return this view.
8433 *
8434 * @param tag The tag to search for, using "tag.equals(getTag())".
8435 * @return The View that has the given tag in the hierarchy or null
8436 */
8437 public final View findViewWithTag(Object tag) {
8438 if (tag == null) {
8439 return null;
8440 }
8441 return findViewWithTagTraversal(tag);
8442 }
8443
8444 /**
8445 * Sets the identifier for this view. The identifier does not have to be
8446 * unique in this view's hierarchy. The identifier should be a positive
8447 * number.
8448 *
8449 * @see #NO_ID
8450 * @see #getId
8451 * @see #findViewById
8452 *
8453 * @param id a number used to identify the view
8454 *
8455 * @attr ref android.R.styleable#View_id
8456 */
8457 public void setId(int id) {
8458 mID = id;
8459 }
8460
8461 /**
8462 * {@hide}
8463 *
8464 * @param isRoot true if the view belongs to the root namespace, false
8465 * otherwise
8466 */
8467 public void setIsRootNamespace(boolean isRoot) {
8468 if (isRoot) {
8469 mPrivateFlags |= IS_ROOT_NAMESPACE;
8470 } else {
8471 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
8472 }
8473 }
8474
8475 /**
8476 * {@hide}
8477 *
8478 * @return true if the view belongs to the root namespace, false otherwise
8479 */
8480 public boolean isRootNamespace() {
8481 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
8482 }
8483
8484 /**
8485 * Returns this view's identifier.
8486 *
8487 * @return a positive integer used to identify the view or {@link #NO_ID}
8488 * if the view has no ID
8489 *
8490 * @see #setId
8491 * @see #findViewById
8492 * @attr ref android.R.styleable#View_id
8493 */
8494 @ViewDebug.CapturedViewProperty
8495 public int getId() {
8496 return mID;
8497 }
8498
8499 /**
8500 * Returns this view's tag.
8501 *
8502 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07008503 *
8504 * @see #setTag(Object)
8505 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 */
8507 @ViewDebug.ExportedProperty
8508 public Object getTag() {
8509 return mTag;
8510 }
8511
8512 /**
8513 * Sets the tag associated with this view. A tag can be used to mark
8514 * a view in its hierarchy and does not have to be unique within the
8515 * hierarchy. Tags can also be used to store data within a view without
8516 * resorting to another data structure.
8517 *
8518 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07008519 *
8520 * @see #getTag()
8521 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008522 */
8523 public void setTag(final Object tag) {
8524 mTag = tag;
8525 }
8526
8527 /**
Romain Guyd90a3312009-05-06 14:54:28 -07008528 * Returns the tag associated with this view and the specified key.
8529 *
8530 * @param key The key identifying the tag
8531 *
8532 * @return the Object stored in this view as a tag
8533 *
8534 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07008535 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07008536 */
8537 public Object getTag(int key) {
8538 SparseArray<Object> tags = null;
8539 synchronized (sTagsLock) {
8540 if (sTags != null) {
8541 tags = sTags.get(this);
8542 }
8543 }
8544
8545 if (tags != null) return tags.get(key);
8546 return null;
8547 }
8548
8549 /**
8550 * Sets a tag associated with this view and a key. A tag can be used
8551 * to mark a view in its hierarchy and does not have to be unique within
8552 * the hierarchy. Tags can also be used to store data within a view
8553 * without resorting to another data structure.
8554 *
8555 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07008556 * application to ensure it is unique (see the <a
8557 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
8558 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07008559 * the Android framework or not associated with any package will cause
8560 * an {@link IllegalArgumentException} to be thrown.
8561 *
8562 * @param key The key identifying the tag
8563 * @param tag An Object to tag the view with
8564 *
8565 * @throws IllegalArgumentException If they specified key is not valid
8566 *
8567 * @see #setTag(Object)
8568 * @see #getTag(int)
8569 */
8570 public void setTag(int key, final Object tag) {
8571 // If the package id is 0x00 or 0x01, it's either an undefined package
8572 // or a framework id
8573 if ((key >>> 24) < 2) {
8574 throw new IllegalArgumentException("The key must be an application-specific "
8575 + "resource id.");
8576 }
8577
8578 setTagInternal(this, key, tag);
8579 }
8580
8581 /**
8582 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
8583 * framework id.
8584 *
8585 * @hide
8586 */
8587 public void setTagInternal(int key, Object tag) {
8588 if ((key >>> 24) != 0x1) {
8589 throw new IllegalArgumentException("The key must be a framework-specific "
8590 + "resource id.");
8591 }
8592
Romain Guy8506ab42009-06-11 17:35:47 -07008593 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07008594 }
8595
8596 private static void setTagInternal(View view, int key, Object tag) {
8597 SparseArray<Object> tags = null;
8598 synchronized (sTagsLock) {
8599 if (sTags == null) {
8600 sTags = new WeakHashMap<View, SparseArray<Object>>();
8601 } else {
8602 tags = sTags.get(view);
8603 }
8604 }
8605
8606 if (tags == null) {
8607 tags = new SparseArray<Object>(2);
8608 synchronized (sTagsLock) {
8609 sTags.put(view, tags);
8610 }
8611 }
8612
8613 tags.put(key, tag);
8614 }
8615
8616 /**
Romain Guy13922e02009-05-12 17:56:14 -07008617 * @param consistency The type of consistency. See ViewDebug for more information.
8618 *
8619 * @hide
8620 */
8621 protected boolean dispatchConsistencyCheck(int consistency) {
8622 return onConsistencyCheck(consistency);
8623 }
8624
8625 /**
8626 * Method that subclasses should implement to check their consistency. The type of
8627 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07008628 *
Romain Guy13922e02009-05-12 17:56:14 -07008629 * @param consistency The type of consistency. See ViewDebug for more information.
8630 *
8631 * @throws IllegalStateException if the view is in an inconsistent state.
8632 *
8633 * @hide
8634 */
8635 protected boolean onConsistencyCheck(int consistency) {
8636 boolean result = true;
8637
8638 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
8639 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
8640
8641 if (checkLayout) {
8642 if (getParent() == null) {
8643 result = false;
8644 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
8645 "View " + this + " does not have a parent.");
8646 }
8647
8648 if (mAttachInfo == null) {
8649 result = false;
8650 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
8651 "View " + this + " is not attached to a window.");
8652 }
8653 }
8654
8655 if (checkDrawing) {
8656 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
8657 // from their draw() method
8658
8659 if ((mPrivateFlags & DRAWN) != DRAWN &&
8660 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
8661 result = false;
8662 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
8663 "View " + this + " was invalidated but its drawing cache is valid.");
8664 }
8665 }
8666
8667 return result;
8668 }
8669
8670 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008671 * Prints information about this view in the log output, with the tag
8672 * {@link #VIEW_LOG_TAG}.
8673 *
8674 * @hide
8675 */
8676 public void debug() {
8677 debug(0);
8678 }
8679
8680 /**
8681 * Prints information about this view in the log output, with the tag
8682 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
8683 * indentation defined by the <code>depth</code>.
8684 *
8685 * @param depth the indentation level
8686 *
8687 * @hide
8688 */
8689 protected void debug(int depth) {
8690 String output = debugIndent(depth - 1);
8691
8692 output += "+ " + this;
8693 int id = getId();
8694 if (id != -1) {
8695 output += " (id=" + id + ")";
8696 }
8697 Object tag = getTag();
8698 if (tag != null) {
8699 output += " (tag=" + tag + ")";
8700 }
8701 Log.d(VIEW_LOG_TAG, output);
8702
8703 if ((mPrivateFlags & FOCUSED) != 0) {
8704 output = debugIndent(depth) + " FOCUSED";
8705 Log.d(VIEW_LOG_TAG, output);
8706 }
8707
8708 output = debugIndent(depth);
8709 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
8710 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
8711 + "} ";
8712 Log.d(VIEW_LOG_TAG, output);
8713
8714 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
8715 || mPaddingBottom != 0) {
8716 output = debugIndent(depth);
8717 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
8718 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
8719 Log.d(VIEW_LOG_TAG, output);
8720 }
8721
8722 output = debugIndent(depth);
8723 output += "mMeasureWidth=" + mMeasuredWidth +
8724 " mMeasureHeight=" + mMeasuredHeight;
8725 Log.d(VIEW_LOG_TAG, output);
8726
8727 output = debugIndent(depth);
8728 if (mLayoutParams == null) {
8729 output += "BAD! no layout params";
8730 } else {
8731 output = mLayoutParams.debug(output);
8732 }
8733 Log.d(VIEW_LOG_TAG, output);
8734
8735 output = debugIndent(depth);
8736 output += "flags={";
8737 output += View.printFlags(mViewFlags);
8738 output += "}";
8739 Log.d(VIEW_LOG_TAG, output);
8740
8741 output = debugIndent(depth);
8742 output += "privateFlags={";
8743 output += View.printPrivateFlags(mPrivateFlags);
8744 output += "}";
8745 Log.d(VIEW_LOG_TAG, output);
8746 }
8747
8748 /**
8749 * Creates an string of whitespaces used for indentation.
8750 *
8751 * @param depth the indentation level
8752 * @return a String containing (depth * 2 + 3) * 2 white spaces
8753 *
8754 * @hide
8755 */
8756 protected static String debugIndent(int depth) {
8757 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
8758 for (int i = 0; i < (depth * 2) + 3; i++) {
8759 spaces.append(' ').append(' ');
8760 }
8761 return spaces.toString();
8762 }
8763
8764 /**
8765 * <p>Return the offset of the widget's text baseline from the widget's top
8766 * boundary. If this widget does not support baseline alignment, this
8767 * method returns -1. </p>
8768 *
8769 * @return the offset of the baseline within the widget's bounds or -1
8770 * if baseline alignment is not supported
8771 */
8772 @ViewDebug.ExportedProperty
8773 public int getBaseline() {
8774 return -1;
8775 }
8776
8777 /**
8778 * Call this when something has changed which has invalidated the
8779 * layout of this view. This will schedule a layout pass of the view
8780 * tree.
8781 */
8782 public void requestLayout() {
8783 if (ViewDebug.TRACE_HIERARCHY) {
8784 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
8785 }
8786
8787 mPrivateFlags |= FORCE_LAYOUT;
8788
8789 if (mParent != null && !mParent.isLayoutRequested()) {
8790 mParent.requestLayout();
8791 }
8792 }
8793
8794 /**
8795 * Forces this view to be laid out during the next layout pass.
8796 * This method does not call requestLayout() or forceLayout()
8797 * on the parent.
8798 */
8799 public void forceLayout() {
8800 mPrivateFlags |= FORCE_LAYOUT;
8801 }
8802
8803 /**
8804 * <p>
8805 * This is called to find out how big a view should be. The parent
8806 * supplies constraint information in the width and height parameters.
8807 * </p>
8808 *
8809 * <p>
8810 * The actual mesurement work of a view is performed in
8811 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
8812 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
8813 * </p>
8814 *
8815 *
8816 * @param widthMeasureSpec Horizontal space requirements as imposed by the
8817 * parent
8818 * @param heightMeasureSpec Vertical space requirements as imposed by the
8819 * parent
8820 *
8821 * @see #onMeasure(int, int)
8822 */
8823 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
8824 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
8825 widthMeasureSpec != mOldWidthMeasureSpec ||
8826 heightMeasureSpec != mOldHeightMeasureSpec) {
8827
8828 // first clears the measured dimension flag
8829 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
8830
8831 if (ViewDebug.TRACE_HIERARCHY) {
8832 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
8833 }
8834
8835 // measure ourselves, this should set the measured dimension flag back
8836 onMeasure(widthMeasureSpec, heightMeasureSpec);
8837
8838 // flag not set, setMeasuredDimension() was not invoked, we raise
8839 // an exception to warn the developer
8840 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
8841 throw new IllegalStateException("onMeasure() did not set the"
8842 + " measured dimension by calling"
8843 + " setMeasuredDimension()");
8844 }
8845
8846 mPrivateFlags |= LAYOUT_REQUIRED;
8847 }
8848
8849 mOldWidthMeasureSpec = widthMeasureSpec;
8850 mOldHeightMeasureSpec = heightMeasureSpec;
8851 }
8852
8853 /**
8854 * <p>
8855 * Measure the view and its content to determine the measured width and the
8856 * measured height. This method is invoked by {@link #measure(int, int)} and
8857 * should be overriden by subclasses to provide accurate and efficient
8858 * measurement of their contents.
8859 * </p>
8860 *
8861 * <p>
8862 * <strong>CONTRACT:</strong> When overriding this method, you
8863 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
8864 * measured width and height of this view. Failure to do so will trigger an
8865 * <code>IllegalStateException</code>, thrown by
8866 * {@link #measure(int, int)}. Calling the superclass'
8867 * {@link #onMeasure(int, int)} is a valid use.
8868 * </p>
8869 *
8870 * <p>
8871 * The base class implementation of measure defaults to the background size,
8872 * unless a larger size is allowed by the MeasureSpec. Subclasses should
8873 * override {@link #onMeasure(int, int)} to provide better measurements of
8874 * their content.
8875 * </p>
8876 *
8877 * <p>
8878 * If this method is overridden, it is the subclass's responsibility to make
8879 * sure the measured height and width are at least the view's minimum height
8880 * and width ({@link #getSuggestedMinimumHeight()} and
8881 * {@link #getSuggestedMinimumWidth()}).
8882 * </p>
8883 *
8884 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
8885 * The requirements are encoded with
8886 * {@link android.view.View.MeasureSpec}.
8887 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
8888 * The requirements are encoded with
8889 * {@link android.view.View.MeasureSpec}.
8890 *
8891 * @see #getMeasuredWidth()
8892 * @see #getMeasuredHeight()
8893 * @see #setMeasuredDimension(int, int)
8894 * @see #getSuggestedMinimumHeight()
8895 * @see #getSuggestedMinimumWidth()
8896 * @see android.view.View.MeasureSpec#getMode(int)
8897 * @see android.view.View.MeasureSpec#getSize(int)
8898 */
8899 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
8900 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
8901 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
8902 }
8903
8904 /**
8905 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
8906 * measured width and measured height. Failing to do so will trigger an
8907 * exception at measurement time.</p>
8908 *
8909 * @param measuredWidth the measured width of this view
8910 * @param measuredHeight the measured height of this view
8911 */
8912 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
8913 mMeasuredWidth = measuredWidth;
8914 mMeasuredHeight = measuredHeight;
8915
8916 mPrivateFlags |= MEASURED_DIMENSION_SET;
8917 }
8918
8919 /**
8920 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
8921 * Will take the desired size, unless a different size is imposed by the constraints.
8922 *
8923 * @param size How big the view wants to be
8924 * @param measureSpec Constraints imposed by the parent
8925 * @return The size this view should be.
8926 */
8927 public static int resolveSize(int size, int measureSpec) {
8928 int result = size;
8929 int specMode = MeasureSpec.getMode(measureSpec);
8930 int specSize = MeasureSpec.getSize(measureSpec);
8931 switch (specMode) {
8932 case MeasureSpec.UNSPECIFIED:
8933 result = size;
8934 break;
8935 case MeasureSpec.AT_MOST:
8936 result = Math.min(size, specSize);
8937 break;
8938 case MeasureSpec.EXACTLY:
8939 result = specSize;
8940 break;
8941 }
8942 return result;
8943 }
8944
8945 /**
8946 * Utility to return a default size. Uses the supplied size if the
8947 * MeasureSpec imposed no contraints. Will get larger if allowed
8948 * by the MeasureSpec.
8949 *
8950 * @param size Default size for this view
8951 * @param measureSpec Constraints imposed by the parent
8952 * @return The size this view should be.
8953 */
8954 public static int getDefaultSize(int size, int measureSpec) {
8955 int result = size;
8956 int specMode = MeasureSpec.getMode(measureSpec);
8957 int specSize = MeasureSpec.getSize(measureSpec);
8958
8959 switch (specMode) {
8960 case MeasureSpec.UNSPECIFIED:
8961 result = size;
8962 break;
8963 case MeasureSpec.AT_MOST:
8964 case MeasureSpec.EXACTLY:
8965 result = specSize;
8966 break;
8967 }
8968 return result;
8969 }
8970
8971 /**
8972 * Returns the suggested minimum height that the view should use. This
8973 * returns the maximum of the view's minimum height
8974 * and the background's minimum height
8975 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
8976 * <p>
8977 * When being used in {@link #onMeasure(int, int)}, the caller should still
8978 * ensure the returned height is within the requirements of the parent.
8979 *
8980 * @return The suggested minimum height of the view.
8981 */
8982 protected int getSuggestedMinimumHeight() {
8983 int suggestedMinHeight = mMinHeight;
8984
8985 if (mBGDrawable != null) {
8986 final int bgMinHeight = mBGDrawable.getMinimumHeight();
8987 if (suggestedMinHeight < bgMinHeight) {
8988 suggestedMinHeight = bgMinHeight;
8989 }
8990 }
8991
8992 return suggestedMinHeight;
8993 }
8994
8995 /**
8996 * Returns the suggested minimum width that the view should use. This
8997 * returns the maximum of the view's minimum width)
8998 * and the background's minimum width
8999 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
9000 * <p>
9001 * When being used in {@link #onMeasure(int, int)}, the caller should still
9002 * ensure the returned width is within the requirements of the parent.
9003 *
9004 * @return The suggested minimum width of the view.
9005 */
9006 protected int getSuggestedMinimumWidth() {
9007 int suggestedMinWidth = mMinWidth;
9008
9009 if (mBGDrawable != null) {
9010 final int bgMinWidth = mBGDrawable.getMinimumWidth();
9011 if (suggestedMinWidth < bgMinWidth) {
9012 suggestedMinWidth = bgMinWidth;
9013 }
9014 }
9015
9016 return suggestedMinWidth;
9017 }
9018
9019 /**
9020 * Sets the minimum height of the view. It is not guaranteed the view will
9021 * be able to achieve this minimum height (for example, if its parent layout
9022 * constrains it with less available height).
9023 *
9024 * @param minHeight The minimum height the view will try to be.
9025 */
9026 public void setMinimumHeight(int minHeight) {
9027 mMinHeight = minHeight;
9028 }
9029
9030 /**
9031 * Sets the minimum width of the view. It is not guaranteed the view will
9032 * be able to achieve this minimum width (for example, if its parent layout
9033 * constrains it with less available width).
9034 *
9035 * @param minWidth The minimum width the view will try to be.
9036 */
9037 public void setMinimumWidth(int minWidth) {
9038 mMinWidth = minWidth;
9039 }
9040
9041 /**
9042 * Get the animation currently associated with this view.
9043 *
9044 * @return The animation that is currently playing or
9045 * scheduled to play for this view.
9046 */
9047 public Animation getAnimation() {
9048 return mCurrentAnimation;
9049 }
9050
9051 /**
9052 * Start the specified animation now.
9053 *
9054 * @param animation the animation to start now
9055 */
9056 public void startAnimation(Animation animation) {
9057 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
9058 setAnimation(animation);
9059 invalidate();
9060 }
9061
9062 /**
9063 * Cancels any animations for this view.
9064 */
9065 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08009066 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08009067 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08009068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009069 mCurrentAnimation = null;
9070 }
9071
9072 /**
9073 * Sets the next animation to play for this view.
9074 * If you want the animation to play immediately, use
9075 * startAnimation. This method provides allows fine-grained
9076 * control over the start time and invalidation, but you
9077 * must make sure that 1) the animation has a start time set, and
9078 * 2) the view will be invalidated when the animation is supposed to
9079 * start.
9080 *
9081 * @param animation The next animation, or null.
9082 */
9083 public void setAnimation(Animation animation) {
9084 mCurrentAnimation = animation;
9085 if (animation != null) {
9086 animation.reset();
9087 }
9088 }
9089
9090 /**
9091 * Invoked by a parent ViewGroup to notify the start of the animation
9092 * currently associated with this view. If you override this method,
9093 * always call super.onAnimationStart();
9094 *
9095 * @see #setAnimation(android.view.animation.Animation)
9096 * @see #getAnimation()
9097 */
9098 protected void onAnimationStart() {
9099 mPrivateFlags |= ANIMATION_STARTED;
9100 }
9101
9102 /**
9103 * Invoked by a parent ViewGroup to notify the end of the animation
9104 * currently associated with this view. If you override this method,
9105 * always call super.onAnimationEnd();
9106 *
9107 * @see #setAnimation(android.view.animation.Animation)
9108 * @see #getAnimation()
9109 */
9110 protected void onAnimationEnd() {
9111 mPrivateFlags &= ~ANIMATION_STARTED;
9112 }
9113
9114 /**
9115 * Invoked if there is a Transform that involves alpha. Subclass that can
9116 * draw themselves with the specified alpha should return true, and then
9117 * respect that alpha when their onDraw() is called. If this returns false
9118 * then the view may be redirected to draw into an offscreen buffer to
9119 * fulfill the request, which will look fine, but may be slower than if the
9120 * subclass handles it internally. The default implementation returns false.
9121 *
9122 * @param alpha The alpha (0..255) to apply to the view's drawing
9123 * @return true if the view can draw with the specified alpha.
9124 */
9125 protected boolean onSetAlpha(int alpha) {
9126 return false;
9127 }
9128
9129 /**
9130 * This is used by the RootView to perform an optimization when
9131 * the view hierarchy contains one or several SurfaceView.
9132 * SurfaceView is always considered transparent, but its children are not,
9133 * therefore all View objects remove themselves from the global transparent
9134 * region (passed as a parameter to this function).
9135 *
9136 * @param region The transparent region for this ViewRoot (window).
9137 *
9138 * @return Returns true if the effective visibility of the view at this
9139 * point is opaque, regardless of the transparent region; returns false
9140 * if it is possible for underlying windows to be seen behind the view.
9141 *
9142 * {@hide}
9143 */
9144 public boolean gatherTransparentRegion(Region region) {
9145 final AttachInfo attachInfo = mAttachInfo;
9146 if (region != null && attachInfo != null) {
9147 final int pflags = mPrivateFlags;
9148 if ((pflags & SKIP_DRAW) == 0) {
9149 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
9150 // remove it from the transparent region.
9151 final int[] location = attachInfo.mTransparentLocation;
9152 getLocationInWindow(location);
9153 region.op(location[0], location[1], location[0] + mRight - mLeft,
9154 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
9155 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
9156 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
9157 // exists, so we remove the background drawable's non-transparent
9158 // parts from this transparent region.
9159 applyDrawableToTransparentRegion(mBGDrawable, region);
9160 }
9161 }
9162 return true;
9163 }
9164
9165 /**
9166 * Play a sound effect for this view.
9167 *
9168 * <p>The framework will play sound effects for some built in actions, such as
9169 * clicking, but you may wish to play these effects in your widget,
9170 * for instance, for internal navigation.
9171 *
9172 * <p>The sound effect will only be played if sound effects are enabled by the user, and
9173 * {@link #isSoundEffectsEnabled()} is true.
9174 *
9175 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
9176 */
9177 public void playSoundEffect(int soundConstant) {
9178 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
9179 return;
9180 }
9181 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
9182 }
9183
9184 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009185 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009186 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009187 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009188 *
9189 * <p>The framework will provide haptic feedback for some built in actions,
9190 * such as long presses, but you may wish to provide feedback for your
9191 * own widget.
9192 *
9193 * <p>The feedback will only be performed if
9194 * {@link #isHapticFeedbackEnabled()} is true.
9195 *
9196 * @param feedbackConstant One of the constants defined in
9197 * {@link HapticFeedbackConstants}
9198 */
9199 public boolean performHapticFeedback(int feedbackConstant) {
9200 return performHapticFeedback(feedbackConstant, 0);
9201 }
9202
9203 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009204 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009205 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009206 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009207 *
9208 * @param feedbackConstant One of the constants defined in
9209 * {@link HapticFeedbackConstants}
9210 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
9211 */
9212 public boolean performHapticFeedback(int feedbackConstant, int flags) {
9213 if (mAttachInfo == null) {
9214 return false;
9215 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009216 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009217 && !isHapticFeedbackEnabled()) {
9218 return false;
9219 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009220 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
9221 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009222 }
9223
9224 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -07009225 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
9226 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -07009227 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -07009228 */
9229 public void onCloseSystemDialogs(String reason) {
9230 }
9231
9232 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009233 * Given a Drawable whose bounds have been set to draw into this view,
9234 * update a Region being computed for {@link #gatherTransparentRegion} so
9235 * that any non-transparent parts of the Drawable are removed from the
9236 * given transparent region.
9237 *
9238 * @param dr The Drawable whose transparency is to be applied to the region.
9239 * @param region A Region holding the current transparency information,
9240 * where any parts of the region that are set are considered to be
9241 * transparent. On return, this region will be modified to have the
9242 * transparency information reduced by the corresponding parts of the
9243 * Drawable that are not transparent.
9244 * {@hide}
9245 */
9246 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
9247 if (DBG) {
9248 Log.i("View", "Getting transparent region for: " + this);
9249 }
9250 final Region r = dr.getTransparentRegion();
9251 final Rect db = dr.getBounds();
9252 final AttachInfo attachInfo = mAttachInfo;
9253 if (r != null && attachInfo != null) {
9254 final int w = getRight()-getLeft();
9255 final int h = getBottom()-getTop();
9256 if (db.left > 0) {
9257 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
9258 r.op(0, 0, db.left, h, Region.Op.UNION);
9259 }
9260 if (db.right < w) {
9261 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
9262 r.op(db.right, 0, w, h, Region.Op.UNION);
9263 }
9264 if (db.top > 0) {
9265 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
9266 r.op(0, 0, w, db.top, Region.Op.UNION);
9267 }
9268 if (db.bottom < h) {
9269 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
9270 r.op(0, db.bottom, w, h, Region.Op.UNION);
9271 }
9272 final int[] location = attachInfo.mTransparentLocation;
9273 getLocationInWindow(location);
9274 r.translate(location[0], location[1]);
9275 region.op(r, Region.Op.INTERSECT);
9276 } else {
9277 region.op(db, Region.Op.DIFFERENCE);
9278 }
9279 }
9280
Adam Powelle14579b2009-12-16 18:39:52 -08009281 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009282 mHasPerformedLongPress = false;
9283
9284 if (mPendingCheckForLongPress == null) {
9285 mPendingCheckForLongPress = new CheckForLongPress();
9286 }
9287 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -08009288 postDelayed(mPendingCheckForLongPress,
9289 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009290 }
9291
Romain Guy812ccbe2010-06-01 14:07:24 -07009292 private static int[] stateSetUnion(final int[] stateSet1, final int[] stateSet2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009293 final int stateSet1Length = stateSet1.length;
9294 final int stateSet2Length = stateSet2.length;
9295 final int[] newSet = new int[stateSet1Length + stateSet2Length];
9296 int k = 0;
9297 int i = 0;
9298 int j = 0;
9299 // This is a merge of the two input state sets and assumes that the
9300 // input sets are sorted by the order imposed by ViewDrawableStates.
9301 for (int viewState : R.styleable.ViewDrawableStates) {
9302 if (i < stateSet1Length && stateSet1[i] == viewState) {
9303 newSet[k++] = viewState;
9304 i++;
9305 } else if (j < stateSet2Length && stateSet2[j] == viewState) {
9306 newSet[k++] = viewState;
9307 j++;
9308 }
9309 if (k > 1) {
9310 assert(newSet[k - 1] > newSet[k - 2]);
9311 }
9312 }
9313 return newSet;
9314 }
9315
9316 /**
9317 * Inflate a view from an XML resource. This convenience method wraps the {@link
9318 * LayoutInflater} class, which provides a full range of options for view inflation.
9319 *
9320 * @param context The Context object for your activity or application.
9321 * @param resource The resource ID to inflate
9322 * @param root A view group that will be the parent. Used to properly inflate the
9323 * layout_* parameters.
9324 * @see LayoutInflater
9325 */
9326 public static View inflate(Context context, int resource, ViewGroup root) {
9327 LayoutInflater factory = LayoutInflater.from(context);
9328 return factory.inflate(resource, root);
9329 }
Romain Guy33e72ae2010-07-17 12:40:29 -07009330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 /**
9332 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
9333 * Each MeasureSpec represents a requirement for either the width or the height.
9334 * A MeasureSpec is comprised of a size and a mode. There are three possible
9335 * modes:
9336 * <dl>
9337 * <dt>UNSPECIFIED</dt>
9338 * <dd>
9339 * The parent has not imposed any constraint on the child. It can be whatever size
9340 * it wants.
9341 * </dd>
9342 *
9343 * <dt>EXACTLY</dt>
9344 * <dd>
9345 * The parent has determined an exact size for the child. The child is going to be
9346 * given those bounds regardless of how big it wants to be.
9347 * </dd>
9348 *
9349 * <dt>AT_MOST</dt>
9350 * <dd>
9351 * The child can be as large as it wants up to the specified size.
9352 * </dd>
9353 * </dl>
9354 *
9355 * MeasureSpecs are implemented as ints to reduce object allocation. This class
9356 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
9357 */
9358 public static class MeasureSpec {
9359 private static final int MODE_SHIFT = 30;
9360 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
9361
9362 /**
9363 * Measure specification mode: The parent has not imposed any constraint
9364 * on the child. It can be whatever size it wants.
9365 */
9366 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
9367
9368 /**
9369 * Measure specification mode: The parent has determined an exact size
9370 * for the child. The child is going to be given those bounds regardless
9371 * of how big it wants to be.
9372 */
9373 public static final int EXACTLY = 1 << MODE_SHIFT;
9374
9375 /**
9376 * Measure specification mode: The child can be as large as it wants up
9377 * to the specified size.
9378 */
9379 public static final int AT_MOST = 2 << MODE_SHIFT;
9380
9381 /**
9382 * Creates a measure specification based on the supplied size and mode.
9383 *
9384 * The mode must always be one of the following:
9385 * <ul>
9386 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
9387 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
9388 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
9389 * </ul>
9390 *
9391 * @param size the size of the measure specification
9392 * @param mode the mode of the measure specification
9393 * @return the measure specification based on size and mode
9394 */
9395 public static int makeMeasureSpec(int size, int mode) {
9396 return size + mode;
9397 }
9398
9399 /**
9400 * Extracts the mode from the supplied measure specification.
9401 *
9402 * @param measureSpec the measure specification to extract the mode from
9403 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
9404 * {@link android.view.View.MeasureSpec#AT_MOST} or
9405 * {@link android.view.View.MeasureSpec#EXACTLY}
9406 */
9407 public static int getMode(int measureSpec) {
9408 return (measureSpec & MODE_MASK);
9409 }
9410
9411 /**
9412 * Extracts the size from the supplied measure specification.
9413 *
9414 * @param measureSpec the measure specification to extract the size from
9415 * @return the size in pixels defined in the supplied measure specification
9416 */
9417 public static int getSize(int measureSpec) {
9418 return (measureSpec & ~MODE_MASK);
9419 }
9420
9421 /**
9422 * Returns a String representation of the specified measure
9423 * specification.
9424 *
9425 * @param measureSpec the measure specification to convert to a String
9426 * @return a String with the following format: "MeasureSpec: MODE SIZE"
9427 */
9428 public static String toString(int measureSpec) {
9429 int mode = getMode(measureSpec);
9430 int size = getSize(measureSpec);
9431
9432 StringBuilder sb = new StringBuilder("MeasureSpec: ");
9433
9434 if (mode == UNSPECIFIED)
9435 sb.append("UNSPECIFIED ");
9436 else if (mode == EXACTLY)
9437 sb.append("EXACTLY ");
9438 else if (mode == AT_MOST)
9439 sb.append("AT_MOST ");
9440 else
9441 sb.append(mode).append(" ");
9442
9443 sb.append(size);
9444 return sb.toString();
9445 }
9446 }
9447
9448 class CheckForLongPress implements Runnable {
9449
9450 private int mOriginalWindowAttachCount;
9451
9452 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -07009453 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009454 && mOriginalWindowAttachCount == mWindowAttachCount) {
9455 if (performLongClick()) {
9456 mHasPerformedLongPress = true;
9457 }
9458 }
9459 }
9460
9461 public void rememberWindowAttachCount() {
9462 mOriginalWindowAttachCount = mWindowAttachCount;
9463 }
9464 }
Adam Powelle14579b2009-12-16 18:39:52 -08009465
9466 private final class CheckForTap implements Runnable {
9467 public void run() {
9468 mPrivateFlags &= ~PREPRESSED;
9469 mPrivateFlags |= PRESSED;
9470 refreshDrawableState();
9471 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
9472 postCheckForLongClick(ViewConfiguration.getTapTimeout());
9473 }
9474 }
9475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476
Adam Powella35d7682010-03-12 14:48:13 -08009477 private final class PerformClick implements Runnable {
9478 public void run() {
9479 performClick();
9480 }
9481 }
9482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009483 /**
9484 * Interface definition for a callback to be invoked when a key event is
9485 * dispatched to this view. The callback will be invoked before the key
9486 * event is given to the view.
9487 */
9488 public interface OnKeyListener {
9489 /**
9490 * Called when a key is dispatched to a view. This allows listeners to
9491 * get a chance to respond before the target view.
9492 *
9493 * @param v The view the key has been dispatched to.
9494 * @param keyCode The code for the physical key that was pressed
9495 * @param event The KeyEvent object containing full information about
9496 * the event.
9497 * @return True if the listener has consumed the event, false otherwise.
9498 */
9499 boolean onKey(View v, int keyCode, KeyEvent event);
9500 }
9501
9502 /**
9503 * Interface definition for a callback to be invoked when a touch event is
9504 * dispatched to this view. The callback will be invoked before the touch
9505 * event is given to the view.
9506 */
9507 public interface OnTouchListener {
9508 /**
9509 * Called when a touch event is dispatched to a view. This allows listeners to
9510 * get a chance to respond before the target view.
9511 *
9512 * @param v The view the touch event has been dispatched to.
9513 * @param event The MotionEvent object containing full information about
9514 * the event.
9515 * @return True if the listener has consumed the event, false otherwise.
9516 */
9517 boolean onTouch(View v, MotionEvent event);
9518 }
9519
9520 /**
9521 * Interface definition for a callback to be invoked when a view has been clicked and held.
9522 */
9523 public interface OnLongClickListener {
9524 /**
9525 * Called when a view has been clicked and held.
9526 *
9527 * @param v The view that was clicked and held.
9528 *
9529 * return True if the callback consumed the long click, false otherwise
9530 */
9531 boolean onLongClick(View v);
9532 }
9533
9534 /**
9535 * Interface definition for a callback to be invoked when the focus state of
9536 * a view changed.
9537 */
9538 public interface OnFocusChangeListener {
9539 /**
9540 * Called when the focus state of a view has changed.
9541 *
9542 * @param v The view whose state has changed.
9543 * @param hasFocus The new focus state of v.
9544 */
9545 void onFocusChange(View v, boolean hasFocus);
9546 }
9547
9548 /**
9549 * Interface definition for a callback to be invoked when a view is clicked.
9550 */
9551 public interface OnClickListener {
9552 /**
9553 * Called when a view has been clicked.
9554 *
9555 * @param v The view that was clicked.
9556 */
9557 void onClick(View v);
9558 }
9559
9560 /**
9561 * Interface definition for a callback to be invoked when the context menu
9562 * for this view is being built.
9563 */
9564 public interface OnCreateContextMenuListener {
9565 /**
9566 * Called when the context menu for this view is being built. It is not
9567 * safe to hold onto the menu after this method returns.
9568 *
9569 * @param menu The context menu that is being built
9570 * @param v The view for which the context menu is being built
9571 * @param menuInfo Extra information about the item for which the
9572 * context menu should be shown. This information will vary
9573 * depending on the class of v.
9574 */
9575 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
9576 }
9577
9578 private final class UnsetPressedState implements Runnable {
9579 public void run() {
9580 setPressed(false);
9581 }
9582 }
9583
9584 /**
9585 * Base class for derived classes that want to save and restore their own
9586 * state in {@link android.view.View#onSaveInstanceState()}.
9587 */
9588 public static class BaseSavedState extends AbsSavedState {
9589 /**
9590 * Constructor used when reading from a parcel. Reads the state of the superclass.
9591 *
9592 * @param source
9593 */
9594 public BaseSavedState(Parcel source) {
9595 super(source);
9596 }
9597
9598 /**
9599 * Constructor called by derived classes when creating their SavedState objects
9600 *
9601 * @param superState The state of the superclass of this view
9602 */
9603 public BaseSavedState(Parcelable superState) {
9604 super(superState);
9605 }
9606
9607 public static final Parcelable.Creator<BaseSavedState> CREATOR =
9608 new Parcelable.Creator<BaseSavedState>() {
9609 public BaseSavedState createFromParcel(Parcel in) {
9610 return new BaseSavedState(in);
9611 }
9612
9613 public BaseSavedState[] newArray(int size) {
9614 return new BaseSavedState[size];
9615 }
9616 };
9617 }
9618
9619 /**
9620 * A set of information given to a view when it is attached to its parent
9621 * window.
9622 */
9623 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009624 interface Callbacks {
9625 void playSoundEffect(int effectId);
9626 boolean performHapticFeedback(int effectId, boolean always);
9627 }
9628
9629 /**
9630 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
9631 * to a Handler. This class contains the target (View) to invalidate and
9632 * the coordinates of the dirty rectangle.
9633 *
9634 * For performance purposes, this class also implements a pool of up to
9635 * POOL_LIMIT objects that get reused. This reduces memory allocations
9636 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009637 */
Romain Guyd928d682009-03-31 17:52:16 -07009638 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009639 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -07009640 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
9641 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -07009642 public InvalidateInfo newInstance() {
9643 return new InvalidateInfo();
9644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009645
Romain Guyd928d682009-03-31 17:52:16 -07009646 public void onAcquired(InvalidateInfo element) {
9647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009648
Romain Guyd928d682009-03-31 17:52:16 -07009649 public void onReleased(InvalidateInfo element) {
9650 }
9651 }, POOL_LIMIT)
9652 );
9653
9654 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009655
9656 View target;
9657
9658 int left;
9659 int top;
9660 int right;
9661 int bottom;
9662
Romain Guyd928d682009-03-31 17:52:16 -07009663 public void setNextPoolable(InvalidateInfo element) {
9664 mNext = element;
9665 }
9666
9667 public InvalidateInfo getNextPoolable() {
9668 return mNext;
9669 }
9670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009671 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -07009672 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009673 }
9674
9675 void release() {
Romain Guyd928d682009-03-31 17:52:16 -07009676 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009677 }
9678 }
9679
9680 final IWindowSession mSession;
9681
9682 final IWindow mWindow;
9683
9684 final IBinder mWindowToken;
9685
9686 final Callbacks mRootCallbacks;
9687
9688 /**
9689 * The top view of the hierarchy.
9690 */
9691 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -07009692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009693 IBinder mPanelParentWindowToken;
9694 Surface mSurface;
9695
9696 /**
Romain Guy8506ab42009-06-11 17:35:47 -07009697 * Scale factor used by the compatibility mode
9698 */
9699 float mApplicationScale;
9700
9701 /**
9702 * Indicates whether the application is in compatibility mode
9703 */
9704 boolean mScalingRequired;
9705
9706 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009707 * Left position of this view's window
9708 */
9709 int mWindowLeft;
9710
9711 /**
9712 * Top position of this view's window
9713 */
9714 int mWindowTop;
9715
9716 /**
Romain Guy35b38ce2009-10-07 13:38:55 -07009717 * Indicates whether the window is translucent/transparent
9718 */
9719 boolean mTranslucentWindow;
9720
9721 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009722 * For windows that are full-screen but using insets to layout inside
9723 * of the screen decorations, these are the current insets for the
9724 * content of the window.
9725 */
9726 final Rect mContentInsets = new Rect();
9727
9728 /**
9729 * For windows that are full-screen but using insets to layout inside
9730 * of the screen decorations, these are the current insets for the
9731 * actual visible parts of the window.
9732 */
9733 final Rect mVisibleInsets = new Rect();
9734
9735 /**
9736 * The internal insets given by this window. This value is
9737 * supplied by the client (through
9738 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
9739 * be given to the window manager when changed to be used in laying
9740 * out windows behind it.
9741 */
9742 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
9743 = new ViewTreeObserver.InternalInsetsInfo();
9744
9745 /**
9746 * All views in the window's hierarchy that serve as scroll containers,
9747 * used to determine if the window can be resized or must be panned
9748 * to adjust for a soft input area.
9749 */
9750 final ArrayList<View> mScrollContainers = new ArrayList<View>();
9751
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07009752 final KeyEvent.DispatcherState mKeyDispatchState
9753 = new KeyEvent.DispatcherState();
9754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009755 /**
9756 * Indicates whether the view's window currently has the focus.
9757 */
9758 boolean mHasWindowFocus;
9759
9760 /**
9761 * The current visibility of the window.
9762 */
9763 int mWindowVisibility;
9764
9765 /**
9766 * Indicates the time at which drawing started to occur.
9767 */
9768 long mDrawingTime;
9769
9770 /**
Romain Guy5bcdff42009-05-14 21:27:18 -07009771 * Indicates whether or not ignoring the DIRTY_MASK flags.
9772 */
9773 boolean mIgnoreDirtyState;
9774
9775 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009776 * Indicates whether the view's window is currently in touch mode.
9777 */
9778 boolean mInTouchMode;
9779
9780 /**
9781 * Indicates that ViewRoot should trigger a global layout change
9782 * the next time it performs a traversal
9783 */
9784 boolean mRecomputeGlobalAttributes;
9785
9786 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009787 * Set during a traveral if any views want to keep the screen on.
9788 */
9789 boolean mKeepScreenOn;
9790
9791 /**
9792 * Set if the visibility of any views has changed.
9793 */
9794 boolean mViewVisibilityChanged;
9795
9796 /**
9797 * Set to true if a view has been scrolled.
9798 */
9799 boolean mViewScrollChanged;
9800
9801 /**
9802 * Global to the view hierarchy used as a temporary for dealing with
9803 * x/y points in the transparent region computations.
9804 */
9805 final int[] mTransparentLocation = new int[2];
9806
9807 /**
9808 * Global to the view hierarchy used as a temporary for dealing with
9809 * x/y points in the ViewGroup.invalidateChild implementation.
9810 */
9811 final int[] mInvalidateChildLocation = new int[2];
9812
Chet Haasec3aa3612010-06-17 08:50:37 -07009813
9814 /**
9815 * Global to the view hierarchy used as a temporary for dealing with
9816 * x/y location when view is transformed.
9817 */
9818 final float[] mTmpTransformLocation = new float[2];
9819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009820 /**
9821 * The view tree observer used to dispatch global events like
9822 * layout, pre-draw, touch mode change, etc.
9823 */
9824 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
9825
9826 /**
9827 * A Canvas used by the view hierarchy to perform bitmap caching.
9828 */
9829 Canvas mCanvas;
9830
9831 /**
9832 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
9833 * handler can be used to pump events in the UI events queue.
9834 */
9835 final Handler mHandler;
9836
9837 /**
9838 * Identifier for messages requesting the view to be invalidated.
9839 * Such messages should be sent to {@link #mHandler}.
9840 */
9841 static final int INVALIDATE_MSG = 0x1;
9842
9843 /**
9844 * Identifier for messages requesting the view to invalidate a region.
9845 * Such messages should be sent to {@link #mHandler}.
9846 */
9847 static final int INVALIDATE_RECT_MSG = 0x2;
9848
9849 /**
9850 * Temporary for use in computing invalidate rectangles while
9851 * calling up the hierarchy.
9852 */
9853 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -07009854
9855 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07009856 * Temporary for use in computing hit areas with transformed views
9857 */
9858 final RectF mTmpTransformRect = new RectF();
9859
9860 /**
9861 * Temporary for use in computing invalidation areas with transformed views
9862 */
9863 final float[] mTmpTransformBounds = new float[8];
9864
9865 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07009866 * Temporary list for use in collecting focusable descendents of a view.
9867 */
9868 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
9869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009870 /**
9871 * Creates a new set of attachment information with the specified
9872 * events handler and thread.
9873 *
9874 * @param handler the events handler the view must use
9875 */
9876 AttachInfo(IWindowSession session, IWindow window,
9877 Handler handler, Callbacks effectPlayer) {
9878 mSession = session;
9879 mWindow = window;
9880 mWindowToken = window.asBinder();
9881 mHandler = handler;
9882 mRootCallbacks = effectPlayer;
9883 }
9884 }
9885
9886 /**
9887 * <p>ScrollabilityCache holds various fields used by a View when scrolling
9888 * is supported. This avoids keeping too many unused fields in most
9889 * instances of View.</p>
9890 */
Mike Cleronf116bf82009-09-27 19:14:12 -07009891 private static class ScrollabilityCache implements Runnable {
9892
9893 /**
9894 * Scrollbars are not visible
9895 */
9896 public static final int OFF = 0;
9897
9898 /**
9899 * Scrollbars are visible
9900 */
9901 public static final int ON = 1;
9902
9903 /**
9904 * Scrollbars are fading away
9905 */
9906 public static final int FADING = 2;
9907
9908 public boolean fadeScrollBars;
9909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009910 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -07009911 public int scrollBarDefaultDelayBeforeFade;
9912 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009913
9914 public int scrollBarSize;
9915 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -07009916 public float[] interpolatorValues;
9917 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009918
9919 public final Paint paint;
9920 public final Matrix matrix;
9921 public Shader shader;
9922
Mike Cleronf116bf82009-09-27 19:14:12 -07009923 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
9924
9925 private final float[] mOpaque = {255.0f};
9926 private final float[] mTransparent = {0.0f};
9927
9928 /**
9929 * When fading should start. This time moves into the future every time
9930 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
9931 */
9932 public long fadeStartTime;
9933
9934
9935 /**
9936 * The current state of the scrollbars: ON, OFF, or FADING
9937 */
9938 public int state = OFF;
9939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009940 private int mLastColor;
9941
Mike Cleronf116bf82009-09-27 19:14:12 -07009942 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009943 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
9944 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -07009945 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
9946 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009947
9948 paint = new Paint();
9949 matrix = new Matrix();
9950 // use use a height of 1, and then wack the matrix each time we
9951 // actually use it.
9952 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -07009953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009954 paint.setShader(shader);
9955 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -07009956 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009957 }
Romain Guy8506ab42009-06-11 17:35:47 -07009958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009959 public void setFadeColor(int color) {
9960 if (color != 0 && color != mLastColor) {
9961 mLastColor = color;
9962 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -07009963
Romain Guye55e1a72009-08-27 10:42:26 -07009964 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
9965 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -07009966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009967 paint.setShader(shader);
9968 // Restore the default transfer mode (src_over)
9969 paint.setXfermode(null);
9970 }
9971 }
Mike Cleronf116bf82009-09-27 19:14:12 -07009972
9973 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -07009974 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -07009975 if (now >= fadeStartTime) {
9976
9977 // the animation fades the scrollbars out by changing
9978 // the opacity (alpha) from fully opaque to fully
9979 // transparent
9980 int nextFrame = (int) now;
9981 int framesCount = 0;
9982
9983 Interpolator interpolator = scrollBarInterpolator;
9984
9985 // Start opaque
9986 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
9987
9988 // End transparent
9989 nextFrame += scrollBarFadeDuration;
9990 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
9991
9992 state = FADING;
9993
9994 // Kick off the fade animation
9995 host.invalidate();
9996 }
9997 }
9998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009999 }
10000}