blob: ac65e0935bcc6e4b70d6e2eee18183ce5f0cda05 [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
19import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080020import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.content.res.Resources;
22import android.content.res.TypedArray;
23import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070024import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070026import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.graphics.LinearGradient;
28import android.graphics.Matrix;
29import android.graphics.Paint;
30import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070031import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.graphics.PorterDuff;
33import android.graphics.PorterDuffXfermode;
34import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070035import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.graphics.Region;
37import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.graphics.drawable.ColorDrawable;
39import android.graphics.drawable.Drawable;
40import android.os.Handler;
41import android.os.IBinder;
42import android.os.Message;
43import android.os.Parcel;
44import android.os.Parcelable;
45import android.os.RemoteException;
46import android.os.SystemClock;
47import android.os.SystemProperties;
48import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070050import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070051import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070052import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070053import android.util.Pools;
54import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.view.ContextMenu.ContextMenuInfo;
svetoslavganov75986cf2009-05-14 22:28:01 -070056import android.view.accessibility.AccessibilityEvent;
57import android.view.accessibility.AccessibilityEventSource;
58import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070060import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070061import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.view.inputmethod.InputConnection;
63import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.widget.ScrollBarDrawable;
Romain Guyf607bdc2010-09-10 19:20:06 -070065import com.android.internal.R;
66import com.android.internal.view.menu.MenuBuilder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
svetoslavganov75986cf2009-05-14 22:28:01 -070068import java.lang.reflect.InvocationTargetException;
69import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import java.util.ArrayList;
71import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070072import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070073import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074
75/**
76 * <p>
77 * This class represents the basic building block for user interface components. A View
78 * occupies a rectangular area on the screen and is responsible for drawing and
79 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070080 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
82 * are invisible containers that hold other Views (or other ViewGroups) and define
83 * their layout properties.
84 * </p>
85 *
86 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070087 * <p>For an introduction to using this class to develop your
88 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070090 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
92 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
93 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
94 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
95 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
99 * </p>
100 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700101 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 * <a name="Using"></a>
103 * <h3>Using Views</h3>
104 * <p>
105 * All of the views in a window are arranged in a single tree. You can add views
106 * either from code or by specifying a tree of views in one or more XML layout
107 * files. There are many specialized subclasses of views that act as controls or
108 * are capable of displaying text, images, or other content.
109 * </p>
110 * <p>
111 * Once you have created a tree of views, there are typically a few types of
112 * common operations you may wish to perform:
113 * <ul>
114 * <li><strong>Set properties:</strong> for example setting the text of a
115 * {@link android.widget.TextView}. The available properties and the methods
116 * that set them will vary among the different subclasses of views. Note that
117 * properties that are known at build time can be set in the XML layout
118 * files.</li>
119 * <li><strong>Set focus:</strong> The framework will handled moving focus in
120 * response to user input. To force focus to a specific view, call
121 * {@link #requestFocus}.</li>
122 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
123 * that will be notified when something interesting happens to the view. For
124 * example, all views will let you set a listener to be notified when the view
125 * gains or loses focus. You can register such a listener using
126 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
127 * specialized listeners. For example, a Button exposes a listener to notify
128 * clients when the button is clicked.</li>
129 * <li><strong>Set visibility:</strong> You can hide or show views using
130 * {@link #setVisibility}.</li>
131 * </ul>
132 * </p>
133 * <p><em>
134 * Note: The Android framework is responsible for measuring, laying out and
135 * drawing views. You should not call methods that perform these actions on
136 * views yourself unless you are actually implementing a
137 * {@link android.view.ViewGroup}.
138 * </em></p>
139 *
140 * <a name="Lifecycle"></a>
141 * <h3>Implementing a Custom View</h3>
142 *
143 * <p>
144 * To implement a custom view, you will usually begin by providing overrides for
145 * some of the standard methods that the framework calls on all views. You do
146 * not need to override all of these methods. In fact, you can start by just
147 * overriding {@link #onDraw(android.graphics.Canvas)}.
148 * <table border="2" width="85%" align="center" cellpadding="5">
149 * <thead>
150 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
151 * </thead>
152 *
153 * <tbody>
154 * <tr>
155 * <td rowspan="2">Creation</td>
156 * <td>Constructors</td>
157 * <td>There is a form of the constructor that are called when the view
158 * is created from code and a form that is called when the view is
159 * inflated from a layout file. The second form should parse and apply
160 * any attributes defined in the layout file.
161 * </td>
162 * </tr>
163 * <tr>
164 * <td><code>{@link #onFinishInflate()}</code></td>
165 * <td>Called after a view and all of its children has been inflated
166 * from XML.</td>
167 * </tr>
168 *
169 * <tr>
170 * <td rowspan="3">Layout</td>
171 * <td><code>{@link #onMeasure}</code></td>
172 * <td>Called to determine the size requirements for this view and all
173 * of its children.
174 * </td>
175 * </tr>
176 * <tr>
177 * <td><code>{@link #onLayout}</code></td>
178 * <td>Called when this view should assign a size and position to all
179 * of its children.
180 * </td>
181 * </tr>
182 * <tr>
183 * <td><code>{@link #onSizeChanged}</code></td>
184 * <td>Called when the size of this view has changed.
185 * </td>
186 * </tr>
187 *
188 * <tr>
189 * <td>Drawing</td>
190 * <td><code>{@link #onDraw}</code></td>
191 * <td>Called when the view should render its content.
192 * </td>
193 * </tr>
194 *
195 * <tr>
196 * <td rowspan="4">Event processing</td>
197 * <td><code>{@link #onKeyDown}</code></td>
198 * <td>Called when a new key event occurs.
199 * </td>
200 * </tr>
201 * <tr>
202 * <td><code>{@link #onKeyUp}</code></td>
203 * <td>Called when a key up event occurs.
204 * </td>
205 * </tr>
206 * <tr>
207 * <td><code>{@link #onTrackballEvent}</code></td>
208 * <td>Called when a trackball motion event occurs.
209 * </td>
210 * </tr>
211 * <tr>
212 * <td><code>{@link #onTouchEvent}</code></td>
213 * <td>Called when a touch screen motion event occurs.
214 * </td>
215 * </tr>
216 *
217 * <tr>
218 * <td rowspan="2">Focus</td>
219 * <td><code>{@link #onFocusChanged}</code></td>
220 * <td>Called when the view gains or loses focus.
221 * </td>
222 * </tr>
223 *
224 * <tr>
225 * <td><code>{@link #onWindowFocusChanged}</code></td>
226 * <td>Called when the window containing the view gains or loses focus.
227 * </td>
228 * </tr>
229 *
230 * <tr>
231 * <td rowspan="3">Attaching</td>
232 * <td><code>{@link #onAttachedToWindow()}</code></td>
233 * <td>Called when the view is attached to a window.
234 * </td>
235 * </tr>
236 *
237 * <tr>
238 * <td><code>{@link #onDetachedFromWindow}</code></td>
239 * <td>Called when the view is detached from its window.
240 * </td>
241 * </tr>
242 *
243 * <tr>
244 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
245 * <td>Called when the visibility of the window containing the view
246 * has changed.
247 * </td>
248 * </tr>
249 * </tbody>
250 *
251 * </table>
252 * </p>
253 *
254 * <a name="IDs"></a>
255 * <h3>IDs</h3>
256 * Views may have an integer id associated with them. These ids are typically
257 * assigned in the layout XML files, and are used to find specific views within
258 * the view tree. A common pattern is to:
259 * <ul>
260 * <li>Define a Button in the layout file and assign it a unique ID.
261 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700262 * &lt;Button
263 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 * android:layout_width="wrap_content"
265 * android:layout_height="wrap_content"
266 * android:text="@string/my_button_text"/&gt;
267 * </pre></li>
268 * <li>From the onCreate method of an Activity, find the Button
269 * <pre class="prettyprint">
270 * Button myButton = (Button) findViewById(R.id.my_button);
271 * </pre></li>
272 * </ul>
273 * <p>
274 * View IDs need not be unique throughout the tree, but it is good practice to
275 * ensure that they are at least unique within the part of the tree you are
276 * searching.
277 * </p>
278 *
279 * <a name="Position"></a>
280 * <h3>Position</h3>
281 * <p>
282 * The geometry of a view is that of a rectangle. A view has a location,
283 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
284 * two dimensions, expressed as a width and a height. The unit for location
285 * and dimensions is the pixel.
286 * </p>
287 *
288 * <p>
289 * It is possible to retrieve the location of a view by invoking the methods
290 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
291 * coordinate of the rectangle representing the view. The latter returns the
292 * top, or Y, coordinate of the rectangle representing the view. These methods
293 * both return the location of the view relative to its parent. For instance,
294 * when getLeft() returns 20, that means the view is located 20 pixels to the
295 * right of the left edge of its direct parent.
296 * </p>
297 *
298 * <p>
299 * In addition, several convenience methods are offered to avoid unnecessary
300 * computations, namely {@link #getRight()} and {@link #getBottom()}.
301 * These methods return the coordinates of the right and bottom edges of the
302 * rectangle representing the view. For instance, calling {@link #getRight()}
303 * is similar to the following computation: <code>getLeft() + getWidth()</code>
304 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
305 * </p>
306 *
307 * <a name="SizePaddingMargins"></a>
308 * <h3>Size, padding and margins</h3>
309 * <p>
310 * The size of a view is expressed with a width and a height. A view actually
311 * possess two pairs of width and height values.
312 * </p>
313 *
314 * <p>
315 * The first pair is known as <em>measured width</em> and
316 * <em>measured height</em>. These dimensions define how big a view wants to be
317 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
318 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
319 * and {@link #getMeasuredHeight()}.
320 * </p>
321 *
322 * <p>
323 * The second pair is simply known as <em>width</em> and <em>height</em>, or
324 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
325 * dimensions define the actual size of the view on screen, at drawing time and
326 * after layout. These values may, but do not have to, be different from the
327 * measured width and height. The width and height can be obtained by calling
328 * {@link #getWidth()} and {@link #getHeight()}.
329 * </p>
330 *
331 * <p>
332 * To measure its dimensions, a view takes into account its padding. The padding
333 * is expressed in pixels for the left, top, right and bottom parts of the view.
334 * Padding can be used to offset the content of the view by a specific amount of
335 * pixels. For instance, a left padding of 2 will push the view's content by
336 * 2 pixels to the right of the left edge. Padding can be set using the
337 * {@link #setPadding(int, int, int, int)} method and queried by calling
338 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
339 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
340 * </p>
341 *
342 * <p>
343 * Even though a view can define a padding, it does not provide any support for
344 * margins. However, view groups provide such a support. Refer to
345 * {@link android.view.ViewGroup} and
346 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
347 * </p>
348 *
349 * <a name="Layout"></a>
350 * <h3>Layout</h3>
351 * <p>
352 * Layout is a two pass process: a measure pass and a layout pass. The measuring
353 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
354 * of the view tree. Each view pushes dimension specifications down the tree
355 * during the recursion. At the end of the measure pass, every view has stored
356 * its measurements. The second pass happens in
357 * {@link #layout(int,int,int,int)} and is also top-down. During
358 * this pass each parent is responsible for positioning all of its children
359 * using the sizes computed in the measure pass.
360 * </p>
361 *
362 * <p>
363 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
364 * {@link #getMeasuredHeight()} values must be set, along with those for all of
365 * that view's descendants. A view's measured width and measured height values
366 * must respect the constraints imposed by the view's parents. This guarantees
367 * that at the end of the measure pass, all parents accept all of their
368 * children's measurements. A parent view may call measure() more than once on
369 * its children. For example, the parent may measure each child once with
370 * unspecified dimensions to find out how big they want to be, then call
371 * measure() on them again with actual numbers if the sum of all the children's
372 * unconstrained sizes is too big or too small.
373 * </p>
374 *
375 * <p>
376 * The measure pass uses two classes to communicate dimensions. The
377 * {@link MeasureSpec} class is used by views to tell their parents how they
378 * want to be measured and positioned. The base LayoutParams class just
379 * describes how big the view wants to be for both width and height. For each
380 * dimension, it can specify one of:
381 * <ul>
382 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800383 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 * (minus padding)
385 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
386 * enclose its content (plus padding).
387 * </ul>
388 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
389 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
390 * an X and Y value.
391 * </p>
392 *
393 * <p>
394 * MeasureSpecs are used to push requirements down the tree from parent to
395 * child. A MeasureSpec can be in one of three modes:
396 * <ul>
397 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
398 * of a child view. For example, a LinearLayout may call measure() on its child
399 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
400 * tall the child view wants to be given a width of 240 pixels.
401 * <li>EXACTLY: This is used by the parent to impose an exact size on the
402 * child. The child must use this size, and guarantee that all of its
403 * descendants will fit within this size.
404 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
405 * child. The child must gurantee that it and all of its descendants will fit
406 * within this size.
407 * </ul>
408 * </p>
409 *
410 * <p>
411 * To intiate a layout, call {@link #requestLayout}. This method is typically
412 * called by a view on itself when it believes that is can no longer fit within
413 * its current bounds.
414 * </p>
415 *
416 * <a name="Drawing"></a>
417 * <h3>Drawing</h3>
418 * <p>
419 * Drawing is handled by walking the tree and rendering each view that
420 * intersects the the invalid region. Because the tree is traversed in-order,
421 * this means that parents will draw before (i.e., behind) their children, with
422 * siblings drawn in the order they appear in the tree.
423 * If you set a background drawable for a View, then the View will draw it for you
424 * before calling back to its <code>onDraw()</code> method.
425 * </p>
426 *
427 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700428 * Note that the framework will not draw views that are not in the invalid region.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 * </p>
430 *
431 * <p>
432 * To force a view to draw, call {@link #invalidate()}.
433 * </p>
434 *
435 * <a name="EventHandlingThreading"></a>
436 * <h3>Event Handling and Threading</h3>
437 * <p>
438 * The basic cycle of a view is as follows:
439 * <ol>
440 * <li>An event comes in and is dispatched to the appropriate view. The view
441 * handles the event and notifies any listeners.</li>
442 * <li>If in the course of processing the event, the view's bounds may need
443 * to be changed, the view will call {@link #requestLayout()}.</li>
444 * <li>Similarly, if in the course of processing the event the view's appearance
445 * may need to be changed, the view will call {@link #invalidate()}.</li>
446 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
447 * the framework will take care of measuring, laying out, and drawing the tree
448 * as appropriate.</li>
449 * </ol>
450 * </p>
451 *
452 * <p><em>Note: The entire view tree is single threaded. You must always be on
453 * the UI thread when calling any method on any view.</em>
454 * If you are doing work on other threads and want to update the state of a view
455 * from that thread, you should use a {@link Handler}.
456 * </p>
457 *
458 * <a name="FocusHandling"></a>
459 * <h3>Focus Handling</h3>
460 * <p>
461 * The framework will handle routine focus movement in response to user input.
462 * This includes changing the focus as views are removed or hidden, or as new
463 * views become available. Views indicate their willingness to take focus
464 * through the {@link #isFocusable} method. To change whether a view can take
465 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
466 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
467 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
468 * </p>
469 * <p>
470 * Focus movement is based on an algorithm which finds the nearest neighbor in a
471 * given direction. In rare cases, the default algorithm may not match the
472 * intended behavior of the developer. In these situations, you can provide
473 * explicit overrides by using these XML attributes in the layout file:
474 * <pre>
475 * nextFocusDown
476 * nextFocusLeft
477 * nextFocusRight
478 * nextFocusUp
479 * </pre>
480 * </p>
481 *
482 *
483 * <p>
484 * To get a particular view to take focus, call {@link #requestFocus()}.
485 * </p>
486 *
487 * <a name="TouchMode"></a>
488 * <h3>Touch Mode</h3>
489 * <p>
490 * When a user is navigating a user interface via directional keys such as a D-pad, it is
491 * necessary to give focus to actionable items such as buttons so the user can see
492 * what will take input. If the device has touch capabilities, however, and the user
493 * begins interacting with the interface by touching it, it is no longer necessary to
494 * always highlight, or give focus to, a particular view. This motivates a mode
495 * for interaction named 'touch mode'.
496 * </p>
497 * <p>
498 * For a touch capable device, once the user touches the screen, the device
499 * will enter touch mode. From this point onward, only views for which
500 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
501 * Other views that are touchable, like buttons, will not take focus when touched; they will
502 * only fire the on click listeners.
503 * </p>
504 * <p>
505 * Any time a user hits a directional key, such as a D-pad direction, the view device will
506 * exit touch mode, and find a view to take focus, so that the user may resume interacting
507 * with the user interface without touching the screen again.
508 * </p>
509 * <p>
510 * The touch mode state is maintained across {@link android.app.Activity}s. Call
511 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
512 * </p>
513 *
514 * <a name="Scrolling"></a>
515 * <h3>Scrolling</h3>
516 * <p>
517 * The framework provides basic support for views that wish to internally
518 * scroll their content. This includes keeping track of the X and Y scroll
519 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700520 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
521 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 * </p>
523 *
524 * <a name="Tags"></a>
525 * <h3>Tags</h3>
526 * <p>
527 * Unlike IDs, tags are not used to identify views. Tags are essentially an
528 * extra piece of information that can be associated with a view. They are most
529 * often used as a convenience to store data related to views in the views
530 * themselves rather than by putting them in a separate structure.
531 * </p>
532 *
533 * <a name="Animation"></a>
534 * <h3>Animation</h3>
535 * <p>
536 * You can attach an {@link Animation} object to a view using
537 * {@link #setAnimation(Animation)} or
538 * {@link #startAnimation(Animation)}. The animation can alter the scale,
539 * rotation, translation and alpha of a view over time. If the animation is
540 * attached to a view that has children, the animation will affect the entire
541 * subtree rooted by that node. When an animation is started, the framework will
542 * take care of redrawing the appropriate views until the animation completes.
543 * </p>
544 *
Jeff Brown85a31762010-09-01 17:01:00 -0700545 * <a name="Security"></a>
546 * <h3>Security</h3>
547 * <p>
548 * Sometimes it is essential that an application be able to verify that an action
549 * is being performed with the full knowledge and consent of the user, such as
550 * granting a permission request, making a purchase or clicking on an advertisement.
551 * Unfortunately, a malicious application could try to spoof the user into
552 * performing these actions, unaware, by concealing the intended purpose of the view.
553 * As a remedy, the framework offers a touch filtering mechanism that can be used to
554 * improve the security of views that provide access to sensitive functionality.
555 * </p><p>
556 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
557 * andoird:filterTouchesWhenObscured attribute to true. When enabled, the framework
558 * will discard touches that are received whenever the view's window is obscured by
559 * another visible window. As a result, the view will not receive touches whenever a
560 * toast, dialog or other window appears above the view's window.
561 * </p><p>
562 * For more fine-grained control over security, consider overriding the
563 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
564 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
565 * </p>
566 *
Romain Guyd6a463a2009-05-21 23:10:10 -0700567 * @attr ref android.R.styleable#View_background
568 * @attr ref android.R.styleable#View_clickable
569 * @attr ref android.R.styleable#View_contentDescription
570 * @attr ref android.R.styleable#View_drawingCacheQuality
571 * @attr ref android.R.styleable#View_duplicateParentState
572 * @attr ref android.R.styleable#View_id
573 * @attr ref android.R.styleable#View_fadingEdge
574 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700575 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700577 * @attr ref android.R.styleable#View_isScrollContainer
578 * @attr ref android.R.styleable#View_focusable
579 * @attr ref android.R.styleable#View_focusableInTouchMode
580 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
581 * @attr ref android.R.styleable#View_keepScreenOn
582 * @attr ref android.R.styleable#View_longClickable
583 * @attr ref android.R.styleable#View_minHeight
584 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 * @attr ref android.R.styleable#View_nextFocusDown
586 * @attr ref android.R.styleable#View_nextFocusLeft
587 * @attr ref android.R.styleable#View_nextFocusRight
588 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700589 * @attr ref android.R.styleable#View_onClick
590 * @attr ref android.R.styleable#View_padding
591 * @attr ref android.R.styleable#View_paddingBottom
592 * @attr ref android.R.styleable#View_paddingLeft
593 * @attr ref android.R.styleable#View_paddingRight
594 * @attr ref android.R.styleable#View_paddingTop
595 * @attr ref android.R.styleable#View_saveEnabled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 * @attr ref android.R.styleable#View_scrollX
597 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700598 * @attr ref android.R.styleable#View_scrollbarSize
599 * @attr ref android.R.styleable#View_scrollbarStyle
600 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700601 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
602 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
604 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 * @attr ref android.R.styleable#View_scrollbarThumbVertical
606 * @attr ref android.R.styleable#View_scrollbarTrackVertical
607 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
608 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700609 * @attr ref android.R.styleable#View_soundEffectsEnabled
610 * @attr ref android.R.styleable#View_tag
611 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 *
613 * @see android.view.ViewGroup
614 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700615public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 private static final boolean DBG = false;
617
618 /**
619 * The logging tag used by this class with android.util.Log.
620 */
621 protected static final String VIEW_LOG_TAG = "View";
622
623 /**
624 * Used to mark a View that has no ID.
625 */
626 public static final int NO_ID = -1;
627
628 /**
629 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
630 * calling setFlags.
631 */
632 private static final int NOT_FOCUSABLE = 0x00000000;
633
634 /**
635 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
636 * setFlags.
637 */
638 private static final int FOCUSABLE = 0x00000001;
639
640 /**
641 * Mask for use with setFlags indicating bits used for focus.
642 */
643 private static final int FOCUSABLE_MASK = 0x00000001;
644
645 /**
646 * This view will adjust its padding to fit sytem windows (e.g. status bar)
647 */
648 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
649
650 /**
651 * This view is visible. Use with {@link #setVisibility}.
652 */
653 public static final int VISIBLE = 0x00000000;
654
655 /**
656 * This view is invisible, but it still takes up space for layout purposes.
657 * Use with {@link #setVisibility}.
658 */
659 public static final int INVISIBLE = 0x00000004;
660
661 /**
662 * This view is invisible, and it doesn't take any space for layout
663 * purposes. Use with {@link #setVisibility}.
664 */
665 public static final int GONE = 0x00000008;
666
667 /**
668 * Mask for use with setFlags indicating bits used for visibility.
669 * {@hide}
670 */
671 static final int VISIBILITY_MASK = 0x0000000C;
672
673 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
674
675 /**
676 * This view is enabled. Intrepretation varies by subclass.
677 * Use with ENABLED_MASK when calling setFlags.
678 * {@hide}
679 */
680 static final int ENABLED = 0x00000000;
681
682 /**
683 * This view is disabled. Intrepretation varies by subclass.
684 * Use with ENABLED_MASK when calling setFlags.
685 * {@hide}
686 */
687 static final int DISABLED = 0x00000020;
688
689 /**
690 * Mask for use with setFlags indicating bits used for indicating whether
691 * this view is enabled
692 * {@hide}
693 */
694 static final int ENABLED_MASK = 0x00000020;
695
696 /**
697 * This view won't draw. {@link #onDraw} won't be called and further
698 * optimizations
699 * will be performed. It is okay to have this flag set and a background.
700 * Use with DRAW_MASK when calling setFlags.
701 * {@hide}
702 */
703 static final int WILL_NOT_DRAW = 0x00000080;
704
705 /**
706 * Mask for use with setFlags indicating bits used for indicating whether
707 * this view is will draw
708 * {@hide}
709 */
710 static final int DRAW_MASK = 0x00000080;
711
712 /**
713 * <p>This view doesn't show scrollbars.</p>
714 * {@hide}
715 */
716 static final int SCROLLBARS_NONE = 0x00000000;
717
718 /**
719 * <p>This view shows horizontal scrollbars.</p>
720 * {@hide}
721 */
722 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
723
724 /**
725 * <p>This view shows vertical scrollbars.</p>
726 * {@hide}
727 */
728 static final int SCROLLBARS_VERTICAL = 0x00000200;
729
730 /**
731 * <p>Mask for use with setFlags indicating bits used for indicating which
732 * scrollbars are enabled.</p>
733 * {@hide}
734 */
735 static final int SCROLLBARS_MASK = 0x00000300;
736
Jeff Brown85a31762010-09-01 17:01:00 -0700737 /**
738 * Indicates that the view should filter touches when its window is obscured.
739 * Refer to the class comments for more information about this security feature.
740 * {@hide}
741 */
742 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
743
744 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745
746 /**
747 * <p>This view doesn't show fading edges.</p>
748 * {@hide}
749 */
750 static final int FADING_EDGE_NONE = 0x00000000;
751
752 /**
753 * <p>This view shows horizontal fading edges.</p>
754 * {@hide}
755 */
756 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
757
758 /**
759 * <p>This view shows vertical fading edges.</p>
760 * {@hide}
761 */
762 static final int FADING_EDGE_VERTICAL = 0x00002000;
763
764 /**
765 * <p>Mask for use with setFlags indicating bits used for indicating which
766 * fading edges are enabled.</p>
767 * {@hide}
768 */
769 static final int FADING_EDGE_MASK = 0x00003000;
770
771 /**
772 * <p>Indicates this view can be clicked. When clickable, a View reacts
773 * to clicks by notifying the OnClickListener.<p>
774 * {@hide}
775 */
776 static final int CLICKABLE = 0x00004000;
777
778 /**
779 * <p>Indicates this view is caching its drawing into a bitmap.</p>
780 * {@hide}
781 */
782 static final int DRAWING_CACHE_ENABLED = 0x00008000;
783
784 /**
785 * <p>Indicates that no icicle should be saved for this view.<p>
786 * {@hide}
787 */
788 static final int SAVE_DISABLED = 0x000010000;
789
790 /**
791 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
792 * property.</p>
793 * {@hide}
794 */
795 static final int SAVE_DISABLED_MASK = 0x000010000;
796
797 /**
798 * <p>Indicates that no drawing cache should ever be created for this view.<p>
799 * {@hide}
800 */
801 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
802
803 /**
804 * <p>Indicates this view can take / keep focus when int touch mode.</p>
805 * {@hide}
806 */
807 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
808
809 /**
810 * <p>Enables low quality mode for the drawing cache.</p>
811 */
812 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
813
814 /**
815 * <p>Enables high quality mode for the drawing cache.</p>
816 */
817 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
818
819 /**
820 * <p>Enables automatic quality mode for the drawing cache.</p>
821 */
822 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
823
824 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
825 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
826 };
827
828 /**
829 * <p>Mask for use with setFlags indicating bits used for the cache
830 * quality property.</p>
831 * {@hide}
832 */
833 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
834
835 /**
836 * <p>
837 * Indicates this view can be long clicked. When long clickable, a View
838 * reacts to long clicks by notifying the OnLongClickListener or showing a
839 * context menu.
840 * </p>
841 * {@hide}
842 */
843 static final int LONG_CLICKABLE = 0x00200000;
844
845 /**
846 * <p>Indicates that this view gets its drawable states from its direct parent
847 * and ignores its original internal states.</p>
848 *
849 * @hide
850 */
851 static final int DUPLICATE_PARENT_STATE = 0x00400000;
852
853 /**
854 * The scrollbar style to display the scrollbars inside the content area,
855 * without increasing the padding. The scrollbars will be overlaid with
856 * translucency on the view's content.
857 */
858 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
859
860 /**
861 * The scrollbar style to display the scrollbars inside the padded area,
862 * increasing the padding of the view. The scrollbars will not overlap the
863 * content area of the view.
864 */
865 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
866
867 /**
868 * The scrollbar style to display the scrollbars at the edge of the view,
869 * without increasing the padding. The scrollbars will be overlaid with
870 * translucency.
871 */
872 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
873
874 /**
875 * The scrollbar style to display the scrollbars at the edge of the view,
876 * increasing the padding of the view. The scrollbars will only overlap the
877 * background, if any.
878 */
879 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
880
881 /**
882 * Mask to check if the scrollbar style is overlay or inset.
883 * {@hide}
884 */
885 static final int SCROLLBARS_INSET_MASK = 0x01000000;
886
887 /**
888 * Mask to check if the scrollbar style is inside or outside.
889 * {@hide}
890 */
891 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
892
893 /**
894 * Mask for scrollbar style.
895 * {@hide}
896 */
897 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
898
899 /**
900 * View flag indicating that the screen should remain on while the
901 * window containing this view is visible to the user. This effectively
902 * takes care of automatically setting the WindowManager's
903 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
904 */
905 public static final int KEEP_SCREEN_ON = 0x04000000;
906
907 /**
908 * View flag indicating whether this view should have sound effects enabled
909 * for events such as clicking and touching.
910 */
911 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
912
913 /**
914 * View flag indicating whether this view should have haptic feedback
915 * enabled for events such as long presses.
916 */
917 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
918
919 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700920 * <p>Indicates that the view hierarchy should stop saving state when
921 * it reaches this view. If state saving is initiated immediately at
922 * the view, it will be allowed.
923 * {@hide}
924 */
925 static final int PARENT_SAVE_DISABLED = 0x20000000;
926
927 /**
928 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
929 * {@hide}
930 */
931 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
932
933 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700934 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
935 * should add all focusable Views regardless if they are focusable in touch mode.
936 */
937 public static final int FOCUSABLES_ALL = 0x00000000;
938
939 /**
940 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
941 * should add only Views focusable in touch mode.
942 */
943 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
944
945 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 * Use with {@link #focusSearch}. Move focus to the previous selectable
947 * item.
948 */
949 public static final int FOCUS_BACKWARD = 0x00000001;
950
951 /**
952 * Use with {@link #focusSearch}. Move focus to the next selectable
953 * item.
954 */
955 public static final int FOCUS_FORWARD = 0x00000002;
956
957 /**
958 * Use with {@link #focusSearch}. Move focus to the left.
959 */
960 public static final int FOCUS_LEFT = 0x00000011;
961
962 /**
963 * Use with {@link #focusSearch}. Move focus up.
964 */
965 public static final int FOCUS_UP = 0x00000021;
966
967 /**
968 * Use with {@link #focusSearch}. Move focus to the right.
969 */
970 public static final int FOCUS_RIGHT = 0x00000042;
971
972 /**
973 * Use with {@link #focusSearch}. Move focus down.
974 */
975 public static final int FOCUS_DOWN = 0x00000082;
976
977 /**
978 * Base View state sets
979 */
980 // Singles
981 /**
982 * Indicates the view has no states set. States are used with
983 * {@link android.graphics.drawable.Drawable} to change the drawing of the
984 * view depending on its state.
985 *
986 * @see android.graphics.drawable.Drawable
987 * @see #getDrawableState()
988 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -0700989 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 /**
991 * Indicates the view is enabled. States are used with
992 * {@link android.graphics.drawable.Drawable} to change the drawing of the
993 * view depending on its state.
994 *
995 * @see android.graphics.drawable.Drawable
996 * @see #getDrawableState()
997 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -0700998 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 /**
1000 * Indicates the view is focused. 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 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001007 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 /**
1009 * Indicates the view is selected. States are used with
1010 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1011 * view depending on its state.
1012 *
1013 * @see android.graphics.drawable.Drawable
1014 * @see #getDrawableState()
1015 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001016 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 /**
1018 * Indicates the view is pressed. States are used with
1019 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1020 * view depending on its state.
1021 *
1022 * @see android.graphics.drawable.Drawable
1023 * @see #getDrawableState()
1024 * @hide
1025 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001026 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 /**
1028 * Indicates the view's window has focus. States are used with
1029 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1030 * view depending on its state.
1031 *
1032 * @see android.graphics.drawable.Drawable
1033 * @see #getDrawableState()
1034 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001035 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 // Doubles
1037 /**
1038 * Indicates the view is enabled and has the focus.
1039 *
1040 * @see #ENABLED_STATE_SET
1041 * @see #FOCUSED_STATE_SET
1042 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001043 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 /**
1045 * Indicates the view is enabled and selected.
1046 *
1047 * @see #ENABLED_STATE_SET
1048 * @see #SELECTED_STATE_SET
1049 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001050 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 /**
1052 * Indicates the view is enabled and that its window has focus.
1053 *
1054 * @see #ENABLED_STATE_SET
1055 * @see #WINDOW_FOCUSED_STATE_SET
1056 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001057 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 /**
1059 * Indicates the view is focused and selected.
1060 *
1061 * @see #FOCUSED_STATE_SET
1062 * @see #SELECTED_STATE_SET
1063 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001064 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 /**
1066 * Indicates the view has the focus and that its window has the focus.
1067 *
1068 * @see #FOCUSED_STATE_SET
1069 * @see #WINDOW_FOCUSED_STATE_SET
1070 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001071 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 /**
1073 * Indicates the view is selected and that its window has the focus.
1074 *
1075 * @see #SELECTED_STATE_SET
1076 * @see #WINDOW_FOCUSED_STATE_SET
1077 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001078 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 // Triples
1080 /**
1081 * Indicates the view is enabled, focused and selected.
1082 *
1083 * @see #ENABLED_STATE_SET
1084 * @see #FOCUSED_STATE_SET
1085 * @see #SELECTED_STATE_SET
1086 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001087 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 /**
1089 * Indicates the view is enabled, focused and its window has the focus.
1090 *
1091 * @see #ENABLED_STATE_SET
1092 * @see #FOCUSED_STATE_SET
1093 * @see #WINDOW_FOCUSED_STATE_SET
1094 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001095 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 /**
1097 * Indicates the view is enabled, selected and its window has the focus.
1098 *
1099 * @see #ENABLED_STATE_SET
1100 * @see #SELECTED_STATE_SET
1101 * @see #WINDOW_FOCUSED_STATE_SET
1102 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001103 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 /**
1105 * Indicates the view is focused, selected and its window has the focus.
1106 *
1107 * @see #FOCUSED_STATE_SET
1108 * @see #SELECTED_STATE_SET
1109 * @see #WINDOW_FOCUSED_STATE_SET
1110 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001111 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 /**
1113 * Indicates the view is enabled, focused, selected and its window
1114 * has the focus.
1115 *
1116 * @see #ENABLED_STATE_SET
1117 * @see #FOCUSED_STATE_SET
1118 * @see #SELECTED_STATE_SET
1119 * @see #WINDOW_FOCUSED_STATE_SET
1120 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001121 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 /**
1123 * Indicates the view is pressed and its window has the focus.
1124 *
1125 * @see #PRESSED_STATE_SET
1126 * @see #WINDOW_FOCUSED_STATE_SET
1127 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001128 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 /**
1130 * Indicates the view is pressed and selected.
1131 *
1132 * @see #PRESSED_STATE_SET
1133 * @see #SELECTED_STATE_SET
1134 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001135 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 /**
1137 * Indicates the view is pressed, selected and its window has the focus.
1138 *
1139 * @see #PRESSED_STATE_SET
1140 * @see #SELECTED_STATE_SET
1141 * @see #WINDOW_FOCUSED_STATE_SET
1142 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001143 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 /**
1145 * Indicates the view is pressed and focused.
1146 *
1147 * @see #PRESSED_STATE_SET
1148 * @see #FOCUSED_STATE_SET
1149 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001150 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 /**
1152 * Indicates the view is pressed, focused and its window has the focus.
1153 *
1154 * @see #PRESSED_STATE_SET
1155 * @see #FOCUSED_STATE_SET
1156 * @see #WINDOW_FOCUSED_STATE_SET
1157 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001158 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 /**
1160 * Indicates the view is pressed, focused and selected.
1161 *
1162 * @see #PRESSED_STATE_SET
1163 * @see #SELECTED_STATE_SET
1164 * @see #FOCUSED_STATE_SET
1165 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001166 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 /**
1168 * Indicates the view is pressed, focused, selected and its window has the focus.
1169 *
1170 * @see #PRESSED_STATE_SET
1171 * @see #FOCUSED_STATE_SET
1172 * @see #SELECTED_STATE_SET
1173 * @see #WINDOW_FOCUSED_STATE_SET
1174 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001175 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 /**
1177 * Indicates the view is pressed and enabled.
1178 *
1179 * @see #PRESSED_STATE_SET
1180 * @see #ENABLED_STATE_SET
1181 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001182 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 /**
1184 * Indicates the view is pressed, enabled and its window has the focus.
1185 *
1186 * @see #PRESSED_STATE_SET
1187 * @see #ENABLED_STATE_SET
1188 * @see #WINDOW_FOCUSED_STATE_SET
1189 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001190 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 /**
1192 * Indicates the view is pressed, enabled and selected.
1193 *
1194 * @see #PRESSED_STATE_SET
1195 * @see #ENABLED_STATE_SET
1196 * @see #SELECTED_STATE_SET
1197 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001198 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 /**
1200 * Indicates the view is pressed, enabled, selected and its window has the
1201 * focus.
1202 *
1203 * @see #PRESSED_STATE_SET
1204 * @see #ENABLED_STATE_SET
1205 * @see #SELECTED_STATE_SET
1206 * @see #WINDOW_FOCUSED_STATE_SET
1207 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001208 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 /**
1210 * Indicates the view is pressed, enabled and focused.
1211 *
1212 * @see #PRESSED_STATE_SET
1213 * @see #ENABLED_STATE_SET
1214 * @see #FOCUSED_STATE_SET
1215 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001216 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 /**
1218 * Indicates the view is pressed, enabled, focused and its window has the
1219 * focus.
1220 *
1221 * @see #PRESSED_STATE_SET
1222 * @see #ENABLED_STATE_SET
1223 * @see #FOCUSED_STATE_SET
1224 * @see #WINDOW_FOCUSED_STATE_SET
1225 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001226 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 /**
1228 * Indicates the view is pressed, enabled, focused and selected.
1229 *
1230 * @see #PRESSED_STATE_SET
1231 * @see #ENABLED_STATE_SET
1232 * @see #SELECTED_STATE_SET
1233 * @see #FOCUSED_STATE_SET
1234 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001235 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 /**
1237 * Indicates the view is pressed, enabled, focused, selected and its window
1238 * has the focus.
1239 *
1240 * @see #PRESSED_STATE_SET
1241 * @see #ENABLED_STATE_SET
1242 * @see #SELECTED_STATE_SET
1243 * @see #FOCUSED_STATE_SET
1244 * @see #WINDOW_FOCUSED_STATE_SET
1245 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001246 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247
1248 /**
1249 * The order here is very important to {@link #getDrawableState()}
1250 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001251 private static final int[][] VIEW_STATE_SETS;
1252
1253 static final int VIEW_STATE_WINDOW_FOCUSED = 1<<0;
1254 static final int VIEW_STATE_SELECTED = 1<<1;
1255 static final int VIEW_STATE_FOCUSED = 1<<2;
1256 static final int VIEW_STATE_ENABLED = 1<<3;
1257 static final int VIEW_STATE_PRESSED = 1<<4;
1258 static final int VIEW_STATE_ACTIVATED = 1<<5;
1259
1260 static final int[] VIEW_STATE_IDS = new int[] {
1261 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1262 R.attr.state_selected, VIEW_STATE_SELECTED,
1263 R.attr.state_focused, VIEW_STATE_FOCUSED,
1264 R.attr.state_enabled, VIEW_STATE_ENABLED,
1265 R.attr.state_pressed, VIEW_STATE_PRESSED,
1266 R.attr.state_activated, VIEW_STATE_ACTIVATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 };
1268
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001269 static {
1270 int[] orderedIds = new int[VIEW_STATE_IDS.length];
1271 for (int i=0; i<R.styleable.ViewDrawableStates.length; i++) {
1272 int viewState = R.styleable.ViewDrawableStates[i];
1273 for (int j=0; j<VIEW_STATE_IDS.length; j+=2) {
1274 if (VIEW_STATE_IDS[j] == viewState) {
1275 orderedIds[i*2] = viewState;
1276 orderedIds[i*2+1] = VIEW_STATE_IDS[j+1];
1277 }
1278 }
1279 }
1280 final int NUM_BITS = VIEW_STATE_IDS.length/2;
1281 VIEW_STATE_SETS = new int[1<<NUM_BITS][];
1282 for (int i=0; i<VIEW_STATE_SETS.length; i++) {
1283 int numBits = Integer.bitCount(i);
1284 int[] set = new int[numBits];
1285 int pos = 0;
1286 for (int j=0; j<orderedIds.length; j+=2) {
1287 if ((i&orderedIds[j+1]) != 0) {
1288 if (false) {
1289 Log.i("View", "Index #" + i + " @ ordered #" + j
1290 + " resid=0x" + Integer.toHexString(orderedIds[j])
1291 + " mask " + orderedIds[j+1]);
1292 }
1293 set[pos++] = orderedIds[j];
1294 }
1295 }
1296 VIEW_STATE_SETS[i] = set;
1297 }
1298
1299 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1300 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1301 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1302 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1303 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1304 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1305 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1306 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1307 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1308 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1309 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1310 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1311 | VIEW_STATE_FOCUSED];
1312 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1313 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1314 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1315 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1316 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1317 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1318 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1319 | VIEW_STATE_ENABLED];
1320 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1321 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1322 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1323 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1324 | VIEW_STATE_ENABLED];
1325 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1326 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1327 | VIEW_STATE_ENABLED];
1328 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1329 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1330 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1331
1332 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1333 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1334 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1335 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1336 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1337 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1338 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1339 | VIEW_STATE_PRESSED];
1340 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1341 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1342 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1343 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1344 | VIEW_STATE_PRESSED];
1345 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1346 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1347 | VIEW_STATE_PRESSED];
1348 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1349 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1350 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1351 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1352 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1353 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1354 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1355 | VIEW_STATE_PRESSED];
1356 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1357 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1358 | VIEW_STATE_PRESSED];
1359 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1360 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1361 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1362 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1363 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1364 | VIEW_STATE_PRESSED];
1365 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1366 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1367 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1368 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1369 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1370 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1371 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1372 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1373 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1374 | VIEW_STATE_PRESSED];
1375 }
1376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 /**
1378 * Used by views that contain lists of items. This state indicates that
1379 * the view is showing the last item.
1380 * @hide
1381 */
1382 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1383 /**
1384 * Used by views that contain lists of items. This state indicates that
1385 * the view is showing the first item.
1386 * @hide
1387 */
1388 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1389 /**
1390 * Used by views that contain lists of items. This state indicates that
1391 * the view is showing the middle item.
1392 * @hide
1393 */
1394 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1395 /**
1396 * Used by views that contain lists of items. This state indicates that
1397 * the view is showing only one item.
1398 * @hide
1399 */
1400 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1401 /**
1402 * Used by views that contain lists of items. This state indicates that
1403 * the view is pressed and showing the last item.
1404 * @hide
1405 */
1406 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1407 /**
1408 * Used by views that contain lists of items. This state indicates that
1409 * the view is pressed and showing the first item.
1410 * @hide
1411 */
1412 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1413 /**
1414 * Used by views that contain lists of items. This state indicates that
1415 * the view is pressed and showing the middle item.
1416 * @hide
1417 */
1418 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1419 /**
1420 * Used by views that contain lists of items. This state indicates that
1421 * the view is pressed and showing only one item.
1422 * @hide
1423 */
1424 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1425
1426 /**
1427 * Temporary Rect currently for use in setBackground(). This will probably
1428 * be extended in the future to hold our own class with more than just
1429 * a Rect. :)
1430 */
1431 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001432
1433 /**
1434 * Map used to store views' tags.
1435 */
1436 private static WeakHashMap<View, SparseArray<Object>> sTags;
1437
1438 /**
1439 * Lock used to access sTags.
1440 */
1441 private static final Object sTagsLock = new Object();
1442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 /**
1444 * The animation currently associated with this view.
1445 * @hide
1446 */
1447 protected Animation mCurrentAnimation = null;
1448
1449 /**
1450 * Width as measured during measure pass.
1451 * {@hide}
1452 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001453 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 protected int mMeasuredWidth;
1455
1456 /**
1457 * Height as measured during measure pass.
1458 * {@hide}
1459 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001460 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 protected int mMeasuredHeight;
1462
1463 /**
1464 * The view's identifier.
1465 * {@hide}
1466 *
1467 * @see #setId(int)
1468 * @see #getId()
1469 */
1470 @ViewDebug.ExportedProperty(resolveId = true)
1471 int mID = NO_ID;
1472
1473 /**
1474 * The view's tag.
1475 * {@hide}
1476 *
1477 * @see #setTag(Object)
1478 * @see #getTag()
1479 */
1480 protected Object mTag;
1481
1482 // for mPrivateFlags:
1483 /** {@hide} */
1484 static final int WANTS_FOCUS = 0x00000001;
1485 /** {@hide} */
1486 static final int FOCUSED = 0x00000002;
1487 /** {@hide} */
1488 static final int SELECTED = 0x00000004;
1489 /** {@hide} */
1490 static final int IS_ROOT_NAMESPACE = 0x00000008;
1491 /** {@hide} */
1492 static final int HAS_BOUNDS = 0x00000010;
1493 /** {@hide} */
1494 static final int DRAWN = 0x00000020;
1495 /**
1496 * When this flag is set, this view is running an animation on behalf of its
1497 * children and should therefore not cancel invalidate requests, even if they
1498 * lie outside of this view's bounds.
1499 *
1500 * {@hide}
1501 */
1502 static final int DRAW_ANIMATION = 0x00000040;
1503 /** {@hide} */
1504 static final int SKIP_DRAW = 0x00000080;
1505 /** {@hide} */
1506 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1507 /** {@hide} */
1508 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1509 /** {@hide} */
1510 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1511 /** {@hide} */
1512 static final int MEASURED_DIMENSION_SET = 0x00000800;
1513 /** {@hide} */
1514 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001515 /** {@hide} */
1516 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517
1518 private static final int PRESSED = 0x00004000;
1519
1520 /** {@hide} */
1521 static final int DRAWING_CACHE_VALID = 0x00008000;
1522 /**
1523 * Flag used to indicate that this view should be drawn once more (and only once
1524 * more) after its animation has completed.
1525 * {@hide}
1526 */
1527 static final int ANIMATION_STARTED = 0x00010000;
1528
1529 private static final int SAVE_STATE_CALLED = 0x00020000;
1530
1531 /**
1532 * Indicates that the View returned true when onSetAlpha() was called and that
1533 * the alpha must be restored.
1534 * {@hide}
1535 */
1536 static final int ALPHA_SET = 0x00040000;
1537
1538 /**
1539 * Set by {@link #setScrollContainer(boolean)}.
1540 */
1541 static final int SCROLL_CONTAINER = 0x00080000;
1542
1543 /**
1544 * Set by {@link #setScrollContainer(boolean)}.
1545 */
1546 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1547
1548 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001549 * View flag indicating whether this view was invalidated (fully or partially.)
1550 *
1551 * @hide
1552 */
1553 static final int DIRTY = 0x00200000;
1554
1555 /**
1556 * View flag indicating whether this view was invalidated by an opaque
1557 * invalidate request.
1558 *
1559 * @hide
1560 */
1561 static final int DIRTY_OPAQUE = 0x00400000;
1562
1563 /**
1564 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1565 *
1566 * @hide
1567 */
1568 static final int DIRTY_MASK = 0x00600000;
1569
1570 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001571 * Indicates whether the background is opaque.
1572 *
1573 * @hide
1574 */
1575 static final int OPAQUE_BACKGROUND = 0x00800000;
1576
1577 /**
1578 * Indicates whether the scrollbars are opaque.
1579 *
1580 * @hide
1581 */
1582 static final int OPAQUE_SCROLLBARS = 0x01000000;
1583
1584 /**
1585 * Indicates whether the view is opaque.
1586 *
1587 * @hide
1588 */
1589 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001590
1591 /**
1592 * Indicates a prepressed state;
1593 * the short time between ACTION_DOWN and recognizing
1594 * a 'real' press. Prepressed is used to recognize quick taps
1595 * even when they are shorter than ViewConfiguration.getTapTimeout().
1596 *
1597 * @hide
1598 */
1599 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001600
1601 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001602 * Indicates whether the view is temporarily detached.
1603 *
1604 * @hide
1605 */
1606 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001607
1608 /**
1609 * Indicates that we should awaken scroll bars once attached
1610 *
1611 * @hide
1612 */
1613 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001614
1615 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001616 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1617 * for transform operations
1618 *
1619 * @hide
1620 */
1621 private static final int PIVOT_EXPLICITLY_SET = 0x10000000;
1622
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001623 /** {@hide} */
1624 static final int ACTIVATED = 0x20000000;
1625
Chet Haasefd2b0022010-08-06 13:08:56 -07001626 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 * The parent this view is attached to.
1628 * {@hide}
1629 *
1630 * @see #getParent()
1631 */
1632 protected ViewParent mParent;
1633
1634 /**
1635 * {@hide}
1636 */
1637 AttachInfo mAttachInfo;
1638
1639 /**
1640 * {@hide}
1641 */
Romain Guy809a7f62009-05-14 15:44:42 -07001642 @ViewDebug.ExportedProperty(flagMapping = {
1643 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1644 name = "FORCE_LAYOUT"),
1645 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1646 name = "LAYOUT_REQUIRED"),
1647 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001648 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001649 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1650 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1651 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1652 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1653 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 int mPrivateFlags;
1655
1656 /**
1657 * Count of how many windows this view has been attached to.
1658 */
1659 int mWindowAttachCount;
1660
1661 /**
1662 * The layout parameters associated with this view and used by the parent
1663 * {@link android.view.ViewGroup} to determine how this view should be
1664 * laid out.
1665 * {@hide}
1666 */
1667 protected ViewGroup.LayoutParams mLayoutParams;
1668
1669 /**
1670 * The view flags hold various views states.
1671 * {@hide}
1672 */
1673 @ViewDebug.ExportedProperty
1674 int mViewFlags;
1675
1676 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001677 * The transform matrix for the View. This transform is calculated internally
1678 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1679 * is used by default. Do *not* use this variable directly; instead call
1680 * getMatrix(), which will automatically recalculate the matrix if necessary
1681 * to get the correct matrix based on the latest rotation and scale properties.
1682 */
1683 private final Matrix mMatrix = new Matrix();
1684
1685 /**
1686 * The transform matrix for the View. This transform is calculated internally
1687 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1688 * is used by default. Do *not* use this variable directly; instead call
1689 * getMatrix(), which will automatically recalculate the matrix if necessary
1690 * to get the correct matrix based on the latest rotation and scale properties.
1691 */
1692 private Matrix mInverseMatrix;
1693
1694 /**
1695 * An internal variable that tracks whether we need to recalculate the
1696 * transform matrix, based on whether the rotation or scaleX/Y properties
1697 * have changed since the matrix was last calculated.
1698 */
1699 private boolean mMatrixDirty = false;
1700
1701 /**
1702 * An internal variable that tracks whether we need to recalculate the
1703 * transform matrix, based on whether the rotation or scaleX/Y properties
1704 * have changed since the matrix was last calculated.
1705 */
1706 private boolean mInverseMatrixDirty = true;
1707
1708 /**
1709 * A variable that tracks whether we need to recalculate the
1710 * transform matrix, based on whether the rotation or scaleX/Y properties
1711 * have changed since the matrix was last calculated. This variable
1712 * is only valid after a call to getMatrix().
1713 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001714 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001715
1716 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001717 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1718 */
1719 private Camera mCamera = null;
1720
1721 /**
1722 * This matrix is used when computing the matrix for 3D rotations.
1723 */
1724 private Matrix matrix3D = null;
1725
1726 /**
1727 * These prev values are used to recalculate a centered pivot point when necessary. The
1728 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1729 * set), so thes values are only used then as well.
1730 */
1731 private int mPrevWidth = -1;
1732 private int mPrevHeight = -1;
1733
1734 /**
1735 * Convenience value to check for float values that are close enough to zero to be considered
1736 * zero.
1737 */
Romain Guy2542d192010-08-18 11:47:12 -07001738 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001739
1740 /**
1741 * The degrees rotation around the vertical axis through the pivot point.
1742 */
1743 @ViewDebug.ExportedProperty
1744 private float mRotationY = 0f;
1745
1746 /**
1747 * The degrees rotation around the horizontal axis through the pivot point.
1748 */
1749 @ViewDebug.ExportedProperty
1750 private float mRotationX = 0f;
1751
1752 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001753 * The degrees rotation around the pivot point.
1754 */
1755 @ViewDebug.ExportedProperty
1756 private float mRotation = 0f;
1757
1758 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001759 * The amount of translation of the object away from its left property (post-layout).
1760 */
1761 @ViewDebug.ExportedProperty
1762 private float mTranslationX = 0f;
1763
1764 /**
1765 * The amount of translation of the object away from its top property (post-layout).
1766 */
1767 @ViewDebug.ExportedProperty
1768 private float mTranslationY = 0f;
1769
1770 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001771 * The amount of scale in the x direction around the pivot point. A
1772 * value of 1 means no scaling is applied.
1773 */
1774 @ViewDebug.ExportedProperty
1775 private float mScaleX = 1f;
1776
1777 /**
1778 * The amount of scale in the y direction around the pivot point. A
1779 * value of 1 means no scaling is applied.
1780 */
1781 @ViewDebug.ExportedProperty
1782 private float mScaleY = 1f;
1783
1784 /**
1785 * The amount of scale in the x direction around the pivot point. A
1786 * value of 1 means no scaling is applied.
1787 */
1788 @ViewDebug.ExportedProperty
1789 private float mPivotX = 0f;
1790
1791 /**
1792 * The amount of scale in the y direction around the pivot point. A
1793 * value of 1 means no scaling is applied.
1794 */
1795 @ViewDebug.ExportedProperty
1796 private float mPivotY = 0f;
1797
1798 /**
1799 * The opacity of the View. This is a value from 0 to 1, where 0 means
1800 * completely transparent and 1 means completely opaque.
1801 */
1802 @ViewDebug.ExportedProperty
1803 private float mAlpha = 1f;
1804
1805 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 * The distance in pixels from the left edge of this view's parent
1807 * to the left edge of this view.
1808 * {@hide}
1809 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001810 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 protected int mLeft;
1812 /**
1813 * The distance in pixels from the left edge of this view's parent
1814 * to the right edge of this view.
1815 * {@hide}
1816 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001817 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 protected int mRight;
1819 /**
1820 * The distance in pixels from the top edge of this view's parent
1821 * to the top edge of this view.
1822 * {@hide}
1823 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001824 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 protected int mTop;
1826 /**
1827 * The distance in pixels from the top edge of this view's parent
1828 * to the bottom edge of this view.
1829 * {@hide}
1830 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001831 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 protected int mBottom;
1833
1834 /**
1835 * The offset, in pixels, by which the content of this view is scrolled
1836 * horizontally.
1837 * {@hide}
1838 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001839 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 protected int mScrollX;
1841 /**
1842 * The offset, in pixels, by which the content of this view is scrolled
1843 * vertically.
1844 * {@hide}
1845 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001846 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 protected int mScrollY;
1848
1849 /**
1850 * The left padding in pixels, that is the distance in pixels between the
1851 * left edge of this view and the left edge of its content.
1852 * {@hide}
1853 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001854 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 protected int mPaddingLeft;
1856 /**
1857 * The right padding in pixels, that is the distance in pixels between the
1858 * right edge of this view and the right edge of its content.
1859 * {@hide}
1860 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001861 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 protected int mPaddingRight;
1863 /**
1864 * The top padding in pixels, that is the distance in pixels between the
1865 * top edge of this view and the top edge of its content.
1866 * {@hide}
1867 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001868 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 protected int mPaddingTop;
1870 /**
1871 * The bottom padding in pixels, that is the distance in pixels between the
1872 * bottom edge of this view and the bottom edge of its content.
1873 * {@hide}
1874 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001875 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 protected int mPaddingBottom;
1877
1878 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001879 * Briefly describes the view and is primarily used for accessibility support.
1880 */
1881 private CharSequence mContentDescription;
1882
1883 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 * Cache the paddingRight set by the user to append to the scrollbar's size.
1885 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001886 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 int mUserPaddingRight;
1888
1889 /**
1890 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1891 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001892 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 int mUserPaddingBottom;
1894
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001895 /**
1896 * @hide
1897 */
1898 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1899 /**
1900 * @hide
1901 */
1902 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903
1904 private Resources mResources = null;
1905
1906 private Drawable mBGDrawable;
1907
1908 private int mBackgroundResource;
1909 private boolean mBackgroundSizeChanged;
1910
1911 /**
1912 * Listener used to dispatch focus change events.
1913 * This field should be made private, so it is hidden from the SDK.
1914 * {@hide}
1915 */
1916 protected OnFocusChangeListener mOnFocusChangeListener;
1917
1918 /**
Chet Haase21cd1382010-09-01 17:42:29 -07001919 * Listeners for layout change events.
1920 */
1921 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
1922
1923 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 * Listener used to dispatch click events.
1925 * This field should be made private, so it is hidden from the SDK.
1926 * {@hide}
1927 */
1928 protected OnClickListener mOnClickListener;
1929
1930 /**
1931 * Listener used to dispatch long click events.
1932 * This field should be made private, so it is hidden from the SDK.
1933 * {@hide}
1934 */
1935 protected OnLongClickListener mOnLongClickListener;
1936
1937 /**
1938 * Listener used to build the context menu.
1939 * This field should be made private, so it is hidden from the SDK.
1940 * {@hide}
1941 */
1942 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
1943
1944 private OnKeyListener mOnKeyListener;
1945
1946 private OnTouchListener mOnTouchListener;
1947
1948 /**
1949 * The application environment this view lives in.
1950 * This field should be made private, so it is hidden from the SDK.
1951 * {@hide}
1952 */
1953 protected Context mContext;
1954
1955 private ScrollabilityCache mScrollCache;
1956
1957 private int[] mDrawableState = null;
1958
Romain Guy02890fd2010-08-06 17:58:44 -07001959 private Bitmap mDrawingCache;
1960 private Bitmap mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961
1962 /**
1963 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
1964 * the user may specify which view to go to next.
1965 */
1966 private int mNextFocusLeftId = View.NO_ID;
1967
1968 /**
1969 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
1970 * the user may specify which view to go to next.
1971 */
1972 private int mNextFocusRightId = View.NO_ID;
1973
1974 /**
1975 * When this view has focus and the next focus is {@link #FOCUS_UP},
1976 * the user may specify which view to go to next.
1977 */
1978 private int mNextFocusUpId = View.NO_ID;
1979
1980 /**
1981 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
1982 * the user may specify which view to go to next.
1983 */
1984 private int mNextFocusDownId = View.NO_ID;
1985
1986 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08001987 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08001988 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08001989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 private UnsetPressedState mUnsetPressedState;
1991
1992 /**
1993 * Whether the long press's action has been invoked. The tap's action is invoked on the
1994 * up event while a long press is invoked as soon as the long press duration is reached, so
1995 * a long press could be performed before the tap is checked, in which case the tap's action
1996 * should not be invoked.
1997 */
1998 private boolean mHasPerformedLongPress;
1999
2000 /**
2001 * The minimum height of the view. We'll try our best to have the height
2002 * of this view to at least this amount.
2003 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002004 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 private int mMinHeight;
2006
2007 /**
2008 * The minimum width of the view. We'll try our best to have the width
2009 * of this view to at least this amount.
2010 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002011 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 private int mMinWidth;
2013
2014 /**
2015 * The delegate to handle touch events that are physically in this view
2016 * but should be handled by another view.
2017 */
2018 private TouchDelegate mTouchDelegate = null;
2019
2020 /**
2021 * Solid color to use as a background when creating the drawing cache. Enables
2022 * the cache to use 16 bit bitmaps instead of 32 bit.
2023 */
2024 private int mDrawingCacheBackgroundColor = 0;
2025
2026 /**
2027 * Special tree observer used when mAttachInfo is null.
2028 */
2029 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002030
2031 /**
2032 * Cache the touch slop from the context that created the view.
2033 */
2034 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 /**
2037 * Simple constructor to use when creating a view from code.
2038 *
2039 * @param context The Context the view is running in, through which it can
2040 * access the current theme, resources, etc.
2041 */
2042 public View(Context context) {
2043 mContext = context;
2044 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002045 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002046 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 }
2048
2049 /**
2050 * Constructor that is called when inflating a view from XML. This is called
2051 * when a view is being constructed from an XML file, supplying attributes
2052 * that were specified in the XML file. This version uses a default style of
2053 * 0, so the only attribute values applied are those in the Context's Theme
2054 * and the given AttributeSet.
2055 *
2056 * <p>
2057 * The method onFinishInflate() will be called after all children have been
2058 * added.
2059 *
2060 * @param context The Context the view is running in, through which it can
2061 * access the current theme, resources, etc.
2062 * @param attrs The attributes of the XML tag that is inflating the view.
2063 * @see #View(Context, AttributeSet, int)
2064 */
2065 public View(Context context, AttributeSet attrs) {
2066 this(context, attrs, 0);
2067 }
2068
2069 /**
2070 * Perform inflation from XML and apply a class-specific base style. This
2071 * constructor of View allows subclasses to use their own base style when
2072 * they are inflating. For example, a Button class's constructor would call
2073 * this version of the super class constructor and supply
2074 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2075 * the theme's button style to modify all of the base view attributes (in
2076 * particular its background) as well as the Button class's attributes.
2077 *
2078 * @param context The Context the view is running in, through which it can
2079 * access the current theme, resources, etc.
2080 * @param attrs The attributes of the XML tag that is inflating the view.
2081 * @param defStyle The default style to apply to this view. If 0, no style
2082 * will be applied (beyond what is included in the theme). This may
2083 * either be an attribute resource, whose value will be retrieved
2084 * from the current theme, or an explicit style resource.
2085 * @see #View(Context, AttributeSet)
2086 */
2087 public View(Context context, AttributeSet attrs, int defStyle) {
2088 this(context);
2089
2090 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2091 defStyle, 0);
2092
2093 Drawable background = null;
2094
2095 int leftPadding = -1;
2096 int topPadding = -1;
2097 int rightPadding = -1;
2098 int bottomPadding = -1;
2099
2100 int padding = -1;
2101
2102 int viewFlagValues = 0;
2103 int viewFlagMasks = 0;
2104
2105 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 int x = 0;
2108 int y = 0;
2109
2110 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2111
2112 final int N = a.getIndexCount();
2113 for (int i = 0; i < N; i++) {
2114 int attr = a.getIndex(i);
2115 switch (attr) {
2116 case com.android.internal.R.styleable.View_background:
2117 background = a.getDrawable(attr);
2118 break;
2119 case com.android.internal.R.styleable.View_padding:
2120 padding = a.getDimensionPixelSize(attr, -1);
2121 break;
2122 case com.android.internal.R.styleable.View_paddingLeft:
2123 leftPadding = a.getDimensionPixelSize(attr, -1);
2124 break;
2125 case com.android.internal.R.styleable.View_paddingTop:
2126 topPadding = a.getDimensionPixelSize(attr, -1);
2127 break;
2128 case com.android.internal.R.styleable.View_paddingRight:
2129 rightPadding = a.getDimensionPixelSize(attr, -1);
2130 break;
2131 case com.android.internal.R.styleable.View_paddingBottom:
2132 bottomPadding = a.getDimensionPixelSize(attr, -1);
2133 break;
2134 case com.android.internal.R.styleable.View_scrollX:
2135 x = a.getDimensionPixelOffset(attr, 0);
2136 break;
2137 case com.android.internal.R.styleable.View_scrollY:
2138 y = a.getDimensionPixelOffset(attr, 0);
2139 break;
2140 case com.android.internal.R.styleable.View_id:
2141 mID = a.getResourceId(attr, NO_ID);
2142 break;
2143 case com.android.internal.R.styleable.View_tag:
2144 mTag = a.getText(attr);
2145 break;
2146 case com.android.internal.R.styleable.View_fitsSystemWindows:
2147 if (a.getBoolean(attr, false)) {
2148 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2149 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2150 }
2151 break;
2152 case com.android.internal.R.styleable.View_focusable:
2153 if (a.getBoolean(attr, false)) {
2154 viewFlagValues |= FOCUSABLE;
2155 viewFlagMasks |= FOCUSABLE_MASK;
2156 }
2157 break;
2158 case com.android.internal.R.styleable.View_focusableInTouchMode:
2159 if (a.getBoolean(attr, false)) {
2160 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2161 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2162 }
2163 break;
2164 case com.android.internal.R.styleable.View_clickable:
2165 if (a.getBoolean(attr, false)) {
2166 viewFlagValues |= CLICKABLE;
2167 viewFlagMasks |= CLICKABLE;
2168 }
2169 break;
2170 case com.android.internal.R.styleable.View_longClickable:
2171 if (a.getBoolean(attr, false)) {
2172 viewFlagValues |= LONG_CLICKABLE;
2173 viewFlagMasks |= LONG_CLICKABLE;
2174 }
2175 break;
2176 case com.android.internal.R.styleable.View_saveEnabled:
2177 if (!a.getBoolean(attr, true)) {
2178 viewFlagValues |= SAVE_DISABLED;
2179 viewFlagMasks |= SAVE_DISABLED_MASK;
2180 }
2181 break;
2182 case com.android.internal.R.styleable.View_duplicateParentState:
2183 if (a.getBoolean(attr, false)) {
2184 viewFlagValues |= DUPLICATE_PARENT_STATE;
2185 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2186 }
2187 break;
2188 case com.android.internal.R.styleable.View_visibility:
2189 final int visibility = a.getInt(attr, 0);
2190 if (visibility != 0) {
2191 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2192 viewFlagMasks |= VISIBILITY_MASK;
2193 }
2194 break;
2195 case com.android.internal.R.styleable.View_drawingCacheQuality:
2196 final int cacheQuality = a.getInt(attr, 0);
2197 if (cacheQuality != 0) {
2198 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2199 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2200 }
2201 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002202 case com.android.internal.R.styleable.View_contentDescription:
2203 mContentDescription = a.getString(attr);
2204 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2206 if (!a.getBoolean(attr, true)) {
2207 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2208 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2209 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002210 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2212 if (!a.getBoolean(attr, true)) {
2213 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2214 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2215 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002216 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 case R.styleable.View_scrollbars:
2218 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2219 if (scrollbars != SCROLLBARS_NONE) {
2220 viewFlagValues |= scrollbars;
2221 viewFlagMasks |= SCROLLBARS_MASK;
2222 initializeScrollbars(a);
2223 }
2224 break;
2225 case R.styleable.View_fadingEdge:
2226 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2227 if (fadingEdge != FADING_EDGE_NONE) {
2228 viewFlagValues |= fadingEdge;
2229 viewFlagMasks |= FADING_EDGE_MASK;
2230 initializeFadingEdge(a);
2231 }
2232 break;
2233 case R.styleable.View_scrollbarStyle:
2234 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2235 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2236 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2237 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2238 }
2239 break;
2240 case R.styleable.View_isScrollContainer:
2241 setScrollContainer = true;
2242 if (a.getBoolean(attr, false)) {
2243 setScrollContainer(true);
2244 }
2245 break;
2246 case com.android.internal.R.styleable.View_keepScreenOn:
2247 if (a.getBoolean(attr, false)) {
2248 viewFlagValues |= KEEP_SCREEN_ON;
2249 viewFlagMasks |= KEEP_SCREEN_ON;
2250 }
2251 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002252 case R.styleable.View_filterTouchesWhenObscured:
2253 if (a.getBoolean(attr, false)) {
2254 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2255 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2256 }
2257 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 case R.styleable.View_nextFocusLeft:
2259 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2260 break;
2261 case R.styleable.View_nextFocusRight:
2262 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2263 break;
2264 case R.styleable.View_nextFocusUp:
2265 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2266 break;
2267 case R.styleable.View_nextFocusDown:
2268 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2269 break;
2270 case R.styleable.View_minWidth:
2271 mMinWidth = a.getDimensionPixelSize(attr, 0);
2272 break;
2273 case R.styleable.View_minHeight:
2274 mMinHeight = a.getDimensionPixelSize(attr, 0);
2275 break;
Romain Guy9a817362009-05-01 10:57:14 -07002276 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002277 if (context.isRestricted()) {
2278 throw new IllegalStateException("The android:onClick attribute cannot "
2279 + "be used within a restricted context");
2280 }
2281
Romain Guy9a817362009-05-01 10:57:14 -07002282 final String handlerName = a.getString(attr);
2283 if (handlerName != null) {
2284 setOnClickListener(new OnClickListener() {
2285 private Method mHandler;
2286
2287 public void onClick(View v) {
2288 if (mHandler == null) {
2289 try {
2290 mHandler = getContext().getClass().getMethod(handlerName,
2291 View.class);
2292 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002293 int id = getId();
2294 String idText = id == NO_ID ? "" : " with id '"
2295 + getContext().getResources().getResourceEntryName(
2296 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002297 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002298 handlerName + "(View) in the activity "
2299 + getContext().getClass() + " for onClick handler"
2300 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002301 }
2302 }
2303
2304 try {
2305 mHandler.invoke(getContext(), View.this);
2306 } catch (IllegalAccessException e) {
2307 throw new IllegalStateException("Could not execute non "
2308 + "public method of the activity", e);
2309 } catch (InvocationTargetException e) {
2310 throw new IllegalStateException("Could not execute "
2311 + "method of the activity", e);
2312 }
2313 }
2314 });
2315 }
2316 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 }
2318 }
2319
2320 if (background != null) {
2321 setBackgroundDrawable(background);
2322 }
2323
2324 if (padding >= 0) {
2325 leftPadding = padding;
2326 topPadding = padding;
2327 rightPadding = padding;
2328 bottomPadding = padding;
2329 }
2330
2331 // If the user specified the padding (either with android:padding or
2332 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2333 // use the default padding or the padding from the background drawable
2334 // (stored at this point in mPadding*)
2335 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2336 topPadding >= 0 ? topPadding : mPaddingTop,
2337 rightPadding >= 0 ? rightPadding : mPaddingRight,
2338 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2339
2340 if (viewFlagMasks != 0) {
2341 setFlags(viewFlagValues, viewFlagMasks);
2342 }
2343
2344 // Needs to be called after mViewFlags is set
2345 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2346 recomputePadding();
2347 }
2348
2349 if (x != 0 || y != 0) {
2350 scrollTo(x, y);
2351 }
2352
2353 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2354 setScrollContainer(true);
2355 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002356
2357 computeOpaqueFlags();
2358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 a.recycle();
2360 }
2361
2362 /**
2363 * Non-public constructor for use in testing
2364 */
2365 View() {
2366 }
2367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 /**
2369 * <p>
2370 * Initializes the fading edges from a given set of styled attributes. This
2371 * method should be called by subclasses that need fading edges and when an
2372 * instance of these subclasses is created programmatically rather than
2373 * being inflated from XML. This method is automatically called when the XML
2374 * is inflated.
2375 * </p>
2376 *
2377 * @param a the styled attributes set to initialize the fading edges from
2378 */
2379 protected void initializeFadingEdge(TypedArray a) {
2380 initScrollCache();
2381
2382 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2383 R.styleable.View_fadingEdgeLength,
2384 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2385 }
2386
2387 /**
2388 * Returns the size of the vertical faded edges used to indicate that more
2389 * content in this view is visible.
2390 *
2391 * @return The size in pixels of the vertical faded edge or 0 if vertical
2392 * faded edges are not enabled for this view.
2393 * @attr ref android.R.styleable#View_fadingEdgeLength
2394 */
2395 public int getVerticalFadingEdgeLength() {
2396 if (isVerticalFadingEdgeEnabled()) {
2397 ScrollabilityCache cache = mScrollCache;
2398 if (cache != null) {
2399 return cache.fadingEdgeLength;
2400 }
2401 }
2402 return 0;
2403 }
2404
2405 /**
2406 * Set the size of the faded edge used to indicate that more content in this
2407 * view is available. Will not change whether the fading edge is enabled; use
2408 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2409 * to enable the fading edge for the vertical or horizontal fading edges.
2410 *
2411 * @param length The size in pixels of the faded edge used to indicate that more
2412 * content in this view is visible.
2413 */
2414 public void setFadingEdgeLength(int length) {
2415 initScrollCache();
2416 mScrollCache.fadingEdgeLength = length;
2417 }
2418
2419 /**
2420 * Returns the size of the horizontal faded edges used to indicate that more
2421 * content in this view is visible.
2422 *
2423 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2424 * faded edges are not enabled for this view.
2425 * @attr ref android.R.styleable#View_fadingEdgeLength
2426 */
2427 public int getHorizontalFadingEdgeLength() {
2428 if (isHorizontalFadingEdgeEnabled()) {
2429 ScrollabilityCache cache = mScrollCache;
2430 if (cache != null) {
2431 return cache.fadingEdgeLength;
2432 }
2433 }
2434 return 0;
2435 }
2436
2437 /**
2438 * Returns the width of the vertical scrollbar.
2439 *
2440 * @return The width in pixels of the vertical scrollbar or 0 if there
2441 * is no vertical scrollbar.
2442 */
2443 public int getVerticalScrollbarWidth() {
2444 ScrollabilityCache cache = mScrollCache;
2445 if (cache != null) {
2446 ScrollBarDrawable scrollBar = cache.scrollBar;
2447 if (scrollBar != null) {
2448 int size = scrollBar.getSize(true);
2449 if (size <= 0) {
2450 size = cache.scrollBarSize;
2451 }
2452 return size;
2453 }
2454 return 0;
2455 }
2456 return 0;
2457 }
2458
2459 /**
2460 * Returns the height of the horizontal scrollbar.
2461 *
2462 * @return The height in pixels of the horizontal scrollbar or 0 if
2463 * there is no horizontal scrollbar.
2464 */
2465 protected int getHorizontalScrollbarHeight() {
2466 ScrollabilityCache cache = mScrollCache;
2467 if (cache != null) {
2468 ScrollBarDrawable scrollBar = cache.scrollBar;
2469 if (scrollBar != null) {
2470 int size = scrollBar.getSize(false);
2471 if (size <= 0) {
2472 size = cache.scrollBarSize;
2473 }
2474 return size;
2475 }
2476 return 0;
2477 }
2478 return 0;
2479 }
2480
2481 /**
2482 * <p>
2483 * Initializes the scrollbars from a given set of styled attributes. This
2484 * method should be called by subclasses that need scrollbars and when an
2485 * instance of these subclasses is created programmatically rather than
2486 * being inflated from XML. This method is automatically called when the XML
2487 * is inflated.
2488 * </p>
2489 *
2490 * @param a the styled attributes set to initialize the scrollbars from
2491 */
2492 protected void initializeScrollbars(TypedArray a) {
2493 initScrollCache();
2494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002496
2497 if (scrollabilityCache.scrollBar == null) {
2498 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2499 }
2500
Romain Guy8bda2482010-03-02 11:42:11 -08002501 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502
Mike Cleronf116bf82009-09-27 19:14:12 -07002503 if (!fadeScrollbars) {
2504 scrollabilityCache.state = ScrollabilityCache.ON;
2505 }
2506 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2507
2508
2509 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2510 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2511 .getScrollBarFadeDuration());
2512 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2513 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2514 ViewConfiguration.getScrollDefaultDelay());
2515
2516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2518 com.android.internal.R.styleable.View_scrollbarSize,
2519 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2520
2521 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2522 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2523
2524 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2525 if (thumb != null) {
2526 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2527 }
2528
2529 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2530 false);
2531 if (alwaysDraw) {
2532 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2533 }
2534
2535 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2536 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2537
2538 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2539 if (thumb != null) {
2540 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2541 }
2542
2543 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2544 false);
2545 if (alwaysDraw) {
2546 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2547 }
2548
2549 // Re-apply user/background padding so that scrollbar(s) get added
2550 recomputePadding();
2551 }
2552
2553 /**
2554 * <p>
2555 * Initalizes the scrollability cache if necessary.
2556 * </p>
2557 */
2558 private void initScrollCache() {
2559 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002560 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 }
2562 }
2563
2564 /**
2565 * Register a callback to be invoked when focus of this view changed.
2566 *
2567 * @param l The callback that will run.
2568 */
2569 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2570 mOnFocusChangeListener = l;
2571 }
2572
2573 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002574 * Add a listener that will be called when the bounds of the view change due to
2575 * layout processing.
2576 *
2577 * @param listener The listener that will be called when layout bounds change.
2578 */
2579 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2580 if (mOnLayoutChangeListeners == null) {
2581 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2582 }
2583 mOnLayoutChangeListeners.add(listener);
2584 }
2585
2586 /**
2587 * Remove a listener for layout changes.
2588 *
2589 * @param listener The listener for layout bounds change.
2590 */
2591 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2592 if (mOnLayoutChangeListeners == null) {
2593 return;
2594 }
2595 mOnLayoutChangeListeners.remove(listener);
2596 }
2597
2598 /**
2599 * Gets the current list of listeners for layout changes.
2600 * @return
2601 */
2602 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2603 return mOnLayoutChangeListeners;
2604 }
2605
2606 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 * Returns the focus-change callback registered for this view.
2608 *
2609 * @return The callback, or null if one is not registered.
2610 */
2611 public OnFocusChangeListener getOnFocusChangeListener() {
2612 return mOnFocusChangeListener;
2613 }
2614
2615 /**
2616 * Register a callback to be invoked when this view is clicked. If this view is not
2617 * clickable, it becomes clickable.
2618 *
2619 * @param l The callback that will run
2620 *
2621 * @see #setClickable(boolean)
2622 */
2623 public void setOnClickListener(OnClickListener l) {
2624 if (!isClickable()) {
2625 setClickable(true);
2626 }
2627 mOnClickListener = l;
2628 }
2629
2630 /**
2631 * Register a callback to be invoked when this view is clicked and held. If this view is not
2632 * long clickable, it becomes long clickable.
2633 *
2634 * @param l The callback that will run
2635 *
2636 * @see #setLongClickable(boolean)
2637 */
2638 public void setOnLongClickListener(OnLongClickListener l) {
2639 if (!isLongClickable()) {
2640 setLongClickable(true);
2641 }
2642 mOnLongClickListener = l;
2643 }
2644
2645 /**
2646 * Register a callback to be invoked when the context menu for this view is
2647 * being built. If this view is not long clickable, it becomes long clickable.
2648 *
2649 * @param l The callback that will run
2650 *
2651 */
2652 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2653 if (!isLongClickable()) {
2654 setLongClickable(true);
2655 }
2656 mOnCreateContextMenuListener = l;
2657 }
2658
2659 /**
2660 * Call this view's OnClickListener, if it is defined.
2661 *
2662 * @return True there was an assigned OnClickListener that was called, false
2663 * otherwise is returned.
2664 */
2665 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002666 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 if (mOnClickListener != null) {
2669 playSoundEffect(SoundEffectConstants.CLICK);
2670 mOnClickListener.onClick(this);
2671 return true;
2672 }
2673
2674 return false;
2675 }
2676
2677 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002678 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2679 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002681 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 */
2683 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002684 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 boolean handled = false;
2687 if (mOnLongClickListener != null) {
2688 handled = mOnLongClickListener.onLongClick(View.this);
2689 }
2690 if (!handled) {
2691 handled = showContextMenu();
2692 }
2693 if (handled) {
2694 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2695 }
2696 return handled;
2697 }
2698
2699 /**
2700 * Bring up the context menu for this view.
2701 *
2702 * @return Whether a context menu was displayed.
2703 */
2704 public boolean showContextMenu() {
2705 return getParent().showContextMenuForChild(this);
2706 }
2707
2708 /**
Adam Powell6e346362010-07-23 10:18:23 -07002709 * Start an action mode.
2710 *
2711 * @param callback Callback that will control the lifecycle of the action mode
2712 * @return The new action mode if it is started, null otherwise
2713 *
2714 * @see ActionMode
2715 */
2716 public ActionMode startActionMode(ActionMode.Callback callback) {
2717 return getParent().startActionModeForChild(this, callback);
2718 }
2719
2720 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 * Register a callback to be invoked when a key is pressed in this view.
2722 * @param l the key listener to attach to this view
2723 */
2724 public void setOnKeyListener(OnKeyListener l) {
2725 mOnKeyListener = l;
2726 }
2727
2728 /**
2729 * Register a callback to be invoked when a touch event is sent to this view.
2730 * @param l the touch listener to attach to this view
2731 */
2732 public void setOnTouchListener(OnTouchListener l) {
2733 mOnTouchListener = l;
2734 }
2735
2736 /**
2737 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2738 *
2739 * Note: this does not check whether this {@link View} should get focus, it just
2740 * gives it focus no matter what. It should only be called internally by framework
2741 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2742 *
2743 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2744 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2745 * focus moved when requestFocus() is called. It may not always
2746 * apply, in which case use the default View.FOCUS_DOWN.
2747 * @param previouslyFocusedRect The rectangle of the view that had focus
2748 * prior in this View's coordinate system.
2749 */
2750 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2751 if (DBG) {
2752 System.out.println(this + " requestFocus()");
2753 }
2754
2755 if ((mPrivateFlags & FOCUSED) == 0) {
2756 mPrivateFlags |= FOCUSED;
2757
2758 if (mParent != null) {
2759 mParent.requestChildFocus(this, this);
2760 }
2761
2762 onFocusChanged(true, direction, previouslyFocusedRect);
2763 refreshDrawableState();
2764 }
2765 }
2766
2767 /**
2768 * Request that a rectangle of this view be visible on the screen,
2769 * scrolling if necessary just enough.
2770 *
2771 * <p>A View should call this if it maintains some notion of which part
2772 * of its content is interesting. For example, a text editing view
2773 * should call this when its cursor moves.
2774 *
2775 * @param rectangle The rectangle.
2776 * @return Whether any parent scrolled.
2777 */
2778 public boolean requestRectangleOnScreen(Rect rectangle) {
2779 return requestRectangleOnScreen(rectangle, false);
2780 }
2781
2782 /**
2783 * Request that a rectangle of this view be visible on the screen,
2784 * scrolling if necessary just enough.
2785 *
2786 * <p>A View should call this if it maintains some notion of which part
2787 * of its content is interesting. For example, a text editing view
2788 * should call this when its cursor moves.
2789 *
2790 * <p>When <code>immediate</code> is set to true, scrolling will not be
2791 * animated.
2792 *
2793 * @param rectangle The rectangle.
2794 * @param immediate True to forbid animated scrolling, false otherwise
2795 * @return Whether any parent scrolled.
2796 */
2797 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
2798 View child = this;
2799 ViewParent parent = mParent;
2800 boolean scrolled = false;
2801 while (parent != null) {
2802 scrolled |= parent.requestChildRectangleOnScreen(child,
2803 rectangle, immediate);
2804
2805 // offset rect so next call has the rectangle in the
2806 // coordinate system of its direct child.
2807 rectangle.offset(child.getLeft(), child.getTop());
2808 rectangle.offset(-child.getScrollX(), -child.getScrollY());
2809
2810 if (!(parent instanceof View)) {
2811 break;
2812 }
Romain Guy8506ab42009-06-11 17:35:47 -07002813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 child = (View) parent;
2815 parent = child.getParent();
2816 }
2817 return scrolled;
2818 }
2819
2820 /**
2821 * Called when this view wants to give up focus. This will cause
2822 * {@link #onFocusChanged} to be called.
2823 */
2824 public void clearFocus() {
2825 if (DBG) {
2826 System.out.println(this + " clearFocus()");
2827 }
2828
2829 if ((mPrivateFlags & FOCUSED) != 0) {
2830 mPrivateFlags &= ~FOCUSED;
2831
2832 if (mParent != null) {
2833 mParent.clearChildFocus(this);
2834 }
2835
2836 onFocusChanged(false, 0, null);
2837 refreshDrawableState();
2838 }
2839 }
2840
2841 /**
2842 * Called to clear the focus of a view that is about to be removed.
2843 * Doesn't call clearChildFocus, which prevents this view from taking
2844 * focus again before it has been removed from the parent
2845 */
2846 void clearFocusForRemoval() {
2847 if ((mPrivateFlags & FOCUSED) != 0) {
2848 mPrivateFlags &= ~FOCUSED;
2849
2850 onFocusChanged(false, 0, null);
2851 refreshDrawableState();
2852 }
2853 }
2854
2855 /**
2856 * Called internally by the view system when a new view is getting focus.
2857 * This is what clears the old focus.
2858 */
2859 void unFocus() {
2860 if (DBG) {
2861 System.out.println(this + " unFocus()");
2862 }
2863
2864 if ((mPrivateFlags & FOCUSED) != 0) {
2865 mPrivateFlags &= ~FOCUSED;
2866
2867 onFocusChanged(false, 0, null);
2868 refreshDrawableState();
2869 }
2870 }
2871
2872 /**
2873 * Returns true if this view has focus iteself, or is the ancestor of the
2874 * view that has focus.
2875 *
2876 * @return True if this view has or contains focus, false otherwise.
2877 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002878 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 public boolean hasFocus() {
2880 return (mPrivateFlags & FOCUSED) != 0;
2881 }
2882
2883 /**
2884 * Returns true if this view is focusable or if it contains a reachable View
2885 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
2886 * is a View whose parents do not block descendants focus.
2887 *
2888 * Only {@link #VISIBLE} views are considered focusable.
2889 *
2890 * @return True if the view is focusable or if the view contains a focusable
2891 * View, false otherwise.
2892 *
2893 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
2894 */
2895 public boolean hasFocusable() {
2896 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
2897 }
2898
2899 /**
2900 * Called by the view system when the focus state of this view changes.
2901 * When the focus change event is caused by directional navigation, direction
2902 * and previouslyFocusedRect provide insight into where the focus is coming from.
2903 * When overriding, be sure to call up through to the super class so that
2904 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07002905 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 * @param gainFocus True if the View has focus; false otherwise.
2907 * @param direction The direction focus has moved when requestFocus()
2908 * is called to give this view focus. Values are
Romain Guyea4823c2009-12-08 15:03:39 -08002909 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT} or
2910 * {@link #FOCUS_RIGHT}. It may not always apply, in which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 * case use the default.
2912 * @param previouslyFocusedRect The rectangle, in this view's coordinate
2913 * system, of the previously focused view. If applicable, this will be
2914 * passed in as finer grained information about where the focus is coming
2915 * from (in addition to direction). Will be <code>null</code> otherwise.
2916 */
2917 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07002918 if (gainFocus) {
2919 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2920 }
2921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 InputMethodManager imm = InputMethodManager.peekInstance();
2923 if (!gainFocus) {
2924 if (isPressed()) {
2925 setPressed(false);
2926 }
2927 if (imm != null && mAttachInfo != null
2928 && mAttachInfo.mHasWindowFocus) {
2929 imm.focusOut(this);
2930 }
Romain Guya2431d02009-04-30 16:30:00 -07002931 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 } else if (imm != null && mAttachInfo != null
2933 && mAttachInfo.mHasWindowFocus) {
2934 imm.focusIn(this);
2935 }
Romain Guy8506ab42009-06-11 17:35:47 -07002936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 invalidate();
2938 if (mOnFocusChangeListener != null) {
2939 mOnFocusChangeListener.onFocusChange(this, gainFocus);
2940 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002941
2942 if (mAttachInfo != null) {
2943 mAttachInfo.mKeyDispatchState.reset(this);
2944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 }
2946
2947 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002948 * {@inheritDoc}
2949 */
2950 public void sendAccessibilityEvent(int eventType) {
2951 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2952 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
2953 }
2954 }
2955
2956 /**
2957 * {@inheritDoc}
2958 */
2959 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
2960 event.setClassName(getClass().getName());
2961 event.setPackageName(getContext().getPackageName());
2962 event.setEnabled(isEnabled());
2963 event.setContentDescription(mContentDescription);
2964
2965 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
2966 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
2967 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
2968 event.setItemCount(focusablesTempList.size());
2969 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
2970 focusablesTempList.clear();
2971 }
2972
2973 dispatchPopulateAccessibilityEvent(event);
2974
2975 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
2976 }
2977
2978 /**
2979 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
2980 * to be populated.
2981 *
2982 * @param event The event.
2983 *
2984 * @return True if the event population was completed.
2985 */
2986 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2987 return false;
2988 }
2989
2990 /**
2991 * Gets the {@link View} description. It briefly describes the view and is
2992 * primarily used for accessibility support. Set this property to enable
2993 * better accessibility support for your application. This is especially
2994 * true for views that do not have textual representation (For example,
2995 * ImageButton).
2996 *
2997 * @return The content descriptiopn.
2998 *
2999 * @attr ref android.R.styleable#View_contentDescription
3000 */
3001 public CharSequence getContentDescription() {
3002 return mContentDescription;
3003 }
3004
3005 /**
3006 * Sets the {@link View} description. It briefly describes the view and is
3007 * primarily used for accessibility support. Set this property to enable
3008 * better accessibility support for your application. This is especially
3009 * true for views that do not have textual representation (For example,
3010 * ImageButton).
3011 *
3012 * @param contentDescription The content description.
3013 *
3014 * @attr ref android.R.styleable#View_contentDescription
3015 */
3016 public void setContentDescription(CharSequence contentDescription) {
3017 mContentDescription = contentDescription;
3018 }
3019
3020 /**
Romain Guya2431d02009-04-30 16:30:00 -07003021 * Invoked whenever this view loses focus, either by losing window focus or by losing
3022 * focus within its window. This method can be used to clear any state tied to the
3023 * focus. For instance, if a button is held pressed with the trackball and the window
3024 * loses focus, this method can be used to cancel the press.
3025 *
3026 * Subclasses of View overriding this method should always call super.onFocusLost().
3027 *
3028 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003029 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003030 *
3031 * @hide pending API council approval
3032 */
3033 protected void onFocusLost() {
3034 resetPressedState();
3035 }
3036
3037 private void resetPressedState() {
3038 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3039 return;
3040 }
3041
3042 if (isPressed()) {
3043 setPressed(false);
3044
3045 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003046 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003047 }
3048 }
3049 }
3050
3051 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 * Returns true if this view has focus
3053 *
3054 * @return True if this view has focus, false otherwise.
3055 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003056 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 public boolean isFocused() {
3058 return (mPrivateFlags & FOCUSED) != 0;
3059 }
3060
3061 /**
3062 * Find the view in the hierarchy rooted at this view that currently has
3063 * focus.
3064 *
3065 * @return The view that currently has focus, or null if no focused view can
3066 * be found.
3067 */
3068 public View findFocus() {
3069 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3070 }
3071
3072 /**
3073 * Change whether this view is one of the set of scrollable containers in
3074 * its window. This will be used to determine whether the window can
3075 * resize or must pan when a soft input area is open -- scrollable
3076 * containers allow the window to use resize mode since the container
3077 * will appropriately shrink.
3078 */
3079 public void setScrollContainer(boolean isScrollContainer) {
3080 if (isScrollContainer) {
3081 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3082 mAttachInfo.mScrollContainers.add(this);
3083 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3084 }
3085 mPrivateFlags |= SCROLL_CONTAINER;
3086 } else {
3087 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3088 mAttachInfo.mScrollContainers.remove(this);
3089 }
3090 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3091 }
3092 }
3093
3094 /**
3095 * Returns the quality of the drawing cache.
3096 *
3097 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3098 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3099 *
3100 * @see #setDrawingCacheQuality(int)
3101 * @see #setDrawingCacheEnabled(boolean)
3102 * @see #isDrawingCacheEnabled()
3103 *
3104 * @attr ref android.R.styleable#View_drawingCacheQuality
3105 */
3106 public int getDrawingCacheQuality() {
3107 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3108 }
3109
3110 /**
3111 * Set the drawing cache quality of this view. This value is used only when the
3112 * drawing cache is enabled
3113 *
3114 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3115 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3116 *
3117 * @see #getDrawingCacheQuality()
3118 * @see #setDrawingCacheEnabled(boolean)
3119 * @see #isDrawingCacheEnabled()
3120 *
3121 * @attr ref android.R.styleable#View_drawingCacheQuality
3122 */
3123 public void setDrawingCacheQuality(int quality) {
3124 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3125 }
3126
3127 /**
3128 * Returns whether the screen should remain on, corresponding to the current
3129 * value of {@link #KEEP_SCREEN_ON}.
3130 *
3131 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3132 *
3133 * @see #setKeepScreenOn(boolean)
3134 *
3135 * @attr ref android.R.styleable#View_keepScreenOn
3136 */
3137 public boolean getKeepScreenOn() {
3138 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3139 }
3140
3141 /**
3142 * Controls whether the screen should remain on, modifying the
3143 * value of {@link #KEEP_SCREEN_ON}.
3144 *
3145 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3146 *
3147 * @see #getKeepScreenOn()
3148 *
3149 * @attr ref android.R.styleable#View_keepScreenOn
3150 */
3151 public void setKeepScreenOn(boolean keepScreenOn) {
3152 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3153 }
3154
3155 /**
3156 * @return The user specified next focus ID.
3157 *
3158 * @attr ref android.R.styleable#View_nextFocusLeft
3159 */
3160 public int getNextFocusLeftId() {
3161 return mNextFocusLeftId;
3162 }
3163
3164 /**
3165 * Set the id of the view to use for the next focus
3166 *
3167 * @param nextFocusLeftId
3168 *
3169 * @attr ref android.R.styleable#View_nextFocusLeft
3170 */
3171 public void setNextFocusLeftId(int nextFocusLeftId) {
3172 mNextFocusLeftId = nextFocusLeftId;
3173 }
3174
3175 /**
3176 * @return The user specified next focus ID.
3177 *
3178 * @attr ref android.R.styleable#View_nextFocusRight
3179 */
3180 public int getNextFocusRightId() {
3181 return mNextFocusRightId;
3182 }
3183
3184 /**
3185 * Set the id of the view to use for the next focus
3186 *
3187 * @param nextFocusRightId
3188 *
3189 * @attr ref android.R.styleable#View_nextFocusRight
3190 */
3191 public void setNextFocusRightId(int nextFocusRightId) {
3192 mNextFocusRightId = nextFocusRightId;
3193 }
3194
3195 /**
3196 * @return The user specified next focus ID.
3197 *
3198 * @attr ref android.R.styleable#View_nextFocusUp
3199 */
3200 public int getNextFocusUpId() {
3201 return mNextFocusUpId;
3202 }
3203
3204 /**
3205 * Set the id of the view to use for the next focus
3206 *
3207 * @param nextFocusUpId
3208 *
3209 * @attr ref android.R.styleable#View_nextFocusUp
3210 */
3211 public void setNextFocusUpId(int nextFocusUpId) {
3212 mNextFocusUpId = nextFocusUpId;
3213 }
3214
3215 /**
3216 * @return The user specified next focus ID.
3217 *
3218 * @attr ref android.R.styleable#View_nextFocusDown
3219 */
3220 public int getNextFocusDownId() {
3221 return mNextFocusDownId;
3222 }
3223
3224 /**
3225 * Set the id of the view to use for the next focus
3226 *
3227 * @param nextFocusDownId
3228 *
3229 * @attr ref android.R.styleable#View_nextFocusDown
3230 */
3231 public void setNextFocusDownId(int nextFocusDownId) {
3232 mNextFocusDownId = nextFocusDownId;
3233 }
3234
3235 /**
3236 * Returns the visibility of this view and all of its ancestors
3237 *
3238 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3239 */
3240 public boolean isShown() {
3241 View current = this;
3242 //noinspection ConstantConditions
3243 do {
3244 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3245 return false;
3246 }
3247 ViewParent parent = current.mParent;
3248 if (parent == null) {
3249 return false; // We are not attached to the view root
3250 }
3251 if (!(parent instanceof View)) {
3252 return true;
3253 }
3254 current = (View) parent;
3255 } while (current != null);
3256
3257 return false;
3258 }
3259
3260 /**
3261 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3262 * is set
3263 *
3264 * @param insets Insets for system windows
3265 *
3266 * @return True if this view applied the insets, false otherwise
3267 */
3268 protected boolean fitSystemWindows(Rect insets) {
3269 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3270 mPaddingLeft = insets.left;
3271 mPaddingTop = insets.top;
3272 mPaddingRight = insets.right;
3273 mPaddingBottom = insets.bottom;
3274 requestLayout();
3275 return true;
3276 }
3277 return false;
3278 }
3279
3280 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003281 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3282 * @return True if window has FITS_SYSTEM_WINDOWS set
3283 *
3284 * @hide
3285 */
3286 public boolean isFitsSystemWindowsFlagSet() {
3287 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3288 }
3289
3290 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 * Returns the visibility status for this view.
3292 *
3293 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3294 * @attr ref android.R.styleable#View_visibility
3295 */
3296 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003297 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3298 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3299 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 })
3301 public int getVisibility() {
3302 return mViewFlags & VISIBILITY_MASK;
3303 }
3304
3305 /**
3306 * Set the enabled state of this view.
3307 *
3308 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3309 * @attr ref android.R.styleable#View_visibility
3310 */
3311 @RemotableViewMethod
3312 public void setVisibility(int visibility) {
3313 setFlags(visibility, VISIBILITY_MASK);
3314 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3315 }
3316
3317 /**
3318 * Returns the enabled status for this view. The interpretation of the
3319 * enabled state varies by subclass.
3320 *
3321 * @return True if this view is enabled, false otherwise.
3322 */
3323 @ViewDebug.ExportedProperty
3324 public boolean isEnabled() {
3325 return (mViewFlags & ENABLED_MASK) == ENABLED;
3326 }
3327
3328 /**
3329 * Set the enabled state of this view. The interpretation of the enabled
3330 * state varies by subclass.
3331 *
3332 * @param enabled True if this view is enabled, false otherwise.
3333 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003334 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003336 if (enabled == isEnabled()) return;
3337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3339
3340 /*
3341 * The View most likely has to change its appearance, so refresh
3342 * the drawable state.
3343 */
3344 refreshDrawableState();
3345
3346 // Invalidate too, since the default behavior for views is to be
3347 // be drawn at 50% alpha rather than to change the drawable.
3348 invalidate();
3349 }
3350
3351 /**
3352 * Set whether this view can receive the focus.
3353 *
3354 * Setting this to false will also ensure that this view is not focusable
3355 * in touch mode.
3356 *
3357 * @param focusable If true, this view can receive the focus.
3358 *
3359 * @see #setFocusableInTouchMode(boolean)
3360 * @attr ref android.R.styleable#View_focusable
3361 */
3362 public void setFocusable(boolean focusable) {
3363 if (!focusable) {
3364 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3365 }
3366 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3367 }
3368
3369 /**
3370 * Set whether this view can receive focus while in touch mode.
3371 *
3372 * Setting this to true will also ensure that this view is focusable.
3373 *
3374 * @param focusableInTouchMode If true, this view can receive the focus while
3375 * in touch mode.
3376 *
3377 * @see #setFocusable(boolean)
3378 * @attr ref android.R.styleable#View_focusableInTouchMode
3379 */
3380 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3381 // Focusable in touch mode should always be set before the focusable flag
3382 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3383 // which, in touch mode, will not successfully request focus on this view
3384 // because the focusable in touch mode flag is not set
3385 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3386 if (focusableInTouchMode) {
3387 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3388 }
3389 }
3390
3391 /**
3392 * Set whether this view should have sound effects enabled for events such as
3393 * clicking and touching.
3394 *
3395 * <p>You may wish to disable sound effects for a view if you already play sounds,
3396 * for instance, a dial key that plays dtmf tones.
3397 *
3398 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3399 * @see #isSoundEffectsEnabled()
3400 * @see #playSoundEffect(int)
3401 * @attr ref android.R.styleable#View_soundEffectsEnabled
3402 */
3403 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3404 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3405 }
3406
3407 /**
3408 * @return whether this view should have sound effects enabled for events such as
3409 * clicking and touching.
3410 *
3411 * @see #setSoundEffectsEnabled(boolean)
3412 * @see #playSoundEffect(int)
3413 * @attr ref android.R.styleable#View_soundEffectsEnabled
3414 */
3415 @ViewDebug.ExportedProperty
3416 public boolean isSoundEffectsEnabled() {
3417 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3418 }
3419
3420 /**
3421 * Set whether this view should have haptic feedback for events such as
3422 * long presses.
3423 *
3424 * <p>You may wish to disable haptic feedback if your view already controls
3425 * its own haptic feedback.
3426 *
3427 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3428 * @see #isHapticFeedbackEnabled()
3429 * @see #performHapticFeedback(int)
3430 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3431 */
3432 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3433 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3434 }
3435
3436 /**
3437 * @return whether this view should have haptic feedback enabled for events
3438 * long presses.
3439 *
3440 * @see #setHapticFeedbackEnabled(boolean)
3441 * @see #performHapticFeedback(int)
3442 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3443 */
3444 @ViewDebug.ExportedProperty
3445 public boolean isHapticFeedbackEnabled() {
3446 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3447 }
3448
3449 /**
3450 * If this view doesn't do any drawing on its own, set this flag to
3451 * allow further optimizations. By default, this flag is not set on
3452 * View, but could be set on some View subclasses such as ViewGroup.
3453 *
3454 * Typically, if you override {@link #onDraw} you should clear this flag.
3455 *
3456 * @param willNotDraw whether or not this View draw on its own
3457 */
3458 public void setWillNotDraw(boolean willNotDraw) {
3459 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3460 }
3461
3462 /**
3463 * Returns whether or not this View draws on its own.
3464 *
3465 * @return true if this view has nothing to draw, false otherwise
3466 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003467 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 public boolean willNotDraw() {
3469 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3470 }
3471
3472 /**
3473 * When a View's drawing cache is enabled, drawing is redirected to an
3474 * offscreen bitmap. Some views, like an ImageView, must be able to
3475 * bypass this mechanism if they already draw a single bitmap, to avoid
3476 * unnecessary usage of the memory.
3477 *
3478 * @param willNotCacheDrawing true if this view does not cache its
3479 * drawing, false otherwise
3480 */
3481 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3482 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3483 }
3484
3485 /**
3486 * Returns whether or not this View can cache its drawing or not.
3487 *
3488 * @return true if this view does not cache its drawing, false otherwise
3489 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003490 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 public boolean willNotCacheDrawing() {
3492 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3493 }
3494
3495 /**
3496 * Indicates whether this view reacts to click events or not.
3497 *
3498 * @return true if the view is clickable, false otherwise
3499 *
3500 * @see #setClickable(boolean)
3501 * @attr ref android.R.styleable#View_clickable
3502 */
3503 @ViewDebug.ExportedProperty
3504 public boolean isClickable() {
3505 return (mViewFlags & CLICKABLE) == CLICKABLE;
3506 }
3507
3508 /**
3509 * Enables or disables click events for this view. When a view
3510 * is clickable it will change its state to "pressed" on every click.
3511 * Subclasses should set the view clickable to visually react to
3512 * user's clicks.
3513 *
3514 * @param clickable true to make the view clickable, false otherwise
3515 *
3516 * @see #isClickable()
3517 * @attr ref android.R.styleable#View_clickable
3518 */
3519 public void setClickable(boolean clickable) {
3520 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3521 }
3522
3523 /**
3524 * Indicates whether this view reacts to long click events or not.
3525 *
3526 * @return true if the view is long clickable, false otherwise
3527 *
3528 * @see #setLongClickable(boolean)
3529 * @attr ref android.R.styleable#View_longClickable
3530 */
3531 public boolean isLongClickable() {
3532 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3533 }
3534
3535 /**
3536 * Enables or disables long click events for this view. When a view is long
3537 * clickable it reacts to the user holding down the button for a longer
3538 * duration than a tap. This event can either launch the listener or a
3539 * context menu.
3540 *
3541 * @param longClickable true to make the view long clickable, false otherwise
3542 * @see #isLongClickable()
3543 * @attr ref android.R.styleable#View_longClickable
3544 */
3545 public void setLongClickable(boolean longClickable) {
3546 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3547 }
3548
3549 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003550 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 *
3552 * @see #isClickable()
3553 * @see #setClickable(boolean)
3554 *
3555 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3556 * the View's internal state from a previously set "pressed" state.
3557 */
3558 public void setPressed(boolean pressed) {
3559 if (pressed) {
3560 mPrivateFlags |= PRESSED;
3561 } else {
3562 mPrivateFlags &= ~PRESSED;
3563 }
3564 refreshDrawableState();
3565 dispatchSetPressed(pressed);
3566 }
3567
3568 /**
3569 * Dispatch setPressed to all of this View's children.
3570 *
3571 * @see #setPressed(boolean)
3572 *
3573 * @param pressed The new pressed state
3574 */
3575 protected void dispatchSetPressed(boolean pressed) {
3576 }
3577
3578 /**
3579 * Indicates whether the view is currently in pressed state. Unless
3580 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3581 * the pressed state.
3582 *
3583 * @see #setPressed
3584 * @see #isClickable()
3585 * @see #setClickable(boolean)
3586 *
3587 * @return true if the view is currently pressed, false otherwise
3588 */
3589 public boolean isPressed() {
3590 return (mPrivateFlags & PRESSED) == PRESSED;
3591 }
3592
3593 /**
3594 * Indicates whether this view will save its state (that is,
3595 * whether its {@link #onSaveInstanceState} method will be called).
3596 *
3597 * @return Returns true if the view state saving is enabled, else false.
3598 *
3599 * @see #setSaveEnabled(boolean)
3600 * @attr ref android.R.styleable#View_saveEnabled
3601 */
3602 public boolean isSaveEnabled() {
3603 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3604 }
3605
3606 /**
3607 * Controls whether the saving of this view's state is
3608 * enabled (that is, whether its {@link #onSaveInstanceState} method
3609 * will be called). Note that even if freezing is enabled, the
3610 * view still must have an id assigned to it (via {@link #setId setId()})
3611 * for its state to be saved. This flag can only disable the
3612 * saving of this view; any child views may still have their state saved.
3613 *
3614 * @param enabled Set to false to <em>disable</em> state saving, or true
3615 * (the default) to allow it.
3616 *
3617 * @see #isSaveEnabled()
3618 * @see #setId(int)
3619 * @see #onSaveInstanceState()
3620 * @attr ref android.R.styleable#View_saveEnabled
3621 */
3622 public void setSaveEnabled(boolean enabled) {
3623 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3624 }
3625
Jeff Brown85a31762010-09-01 17:01:00 -07003626 /**
3627 * Gets whether the framework should discard touches when the view's
3628 * window is obscured by another visible window.
3629 * Refer to the {@link View} security documentation for more details.
3630 *
3631 * @return True if touch filtering is enabled.
3632 *
3633 * @see #setFilterTouchesWhenObscured(boolean)
3634 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3635 */
3636 @ViewDebug.ExportedProperty
3637 public boolean getFilterTouchesWhenObscured() {
3638 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3639 }
3640
3641 /**
3642 * Sets whether the framework should discard touches when the view's
3643 * window is obscured by another visible window.
3644 * Refer to the {@link View} security documentation for more details.
3645 *
3646 * @param enabled True if touch filtering should be enabled.
3647 *
3648 * @see #getFilterTouchesWhenObscured
3649 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3650 */
3651 public void setFilterTouchesWhenObscured(boolean enabled) {
3652 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3653 FILTER_TOUCHES_WHEN_OBSCURED);
3654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655
3656 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003657 * Indicates whether the entire hierarchy under this view will save its
3658 * state when a state saving traversal occurs from its parent. The default
3659 * is true; if false, these views will not be saved unless
3660 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3661 *
3662 * @return Returns true if the view state saving from parent is enabled, else false.
3663 *
3664 * @see #setSaveFromParentEnabled(boolean)
3665 */
3666 public boolean isSaveFromParentEnabled() {
3667 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3668 }
3669
3670 /**
3671 * Controls whether the entire hierarchy under this view will save its
3672 * state when a state saving traversal occurs from its parent. The default
3673 * is true; if false, these views will not be saved unless
3674 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3675 *
3676 * @param enabled Set to false to <em>disable</em> state saving, or true
3677 * (the default) to allow it.
3678 *
3679 * @see #isSaveFromParentEnabled()
3680 * @see #setId(int)
3681 * @see #onSaveInstanceState()
3682 */
3683 public void setSaveFromParentEnabled(boolean enabled) {
3684 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
3685 }
3686
3687
3688 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 * Returns whether this View is able to take focus.
3690 *
3691 * @return True if this view can take focus, or false otherwise.
3692 * @attr ref android.R.styleable#View_focusable
3693 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003694 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695 public final boolean isFocusable() {
3696 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3697 }
3698
3699 /**
3700 * When a view is focusable, it may not want to take focus when in touch mode.
3701 * For example, a button would like focus when the user is navigating via a D-pad
3702 * so that the user can click on it, but once the user starts touching the screen,
3703 * the button shouldn't take focus
3704 * @return Whether the view is focusable in touch mode.
3705 * @attr ref android.R.styleable#View_focusableInTouchMode
3706 */
3707 @ViewDebug.ExportedProperty
3708 public final boolean isFocusableInTouchMode() {
3709 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3710 }
3711
3712 /**
3713 * Find the nearest view in the specified direction that can take focus.
3714 * This does not actually give focus to that view.
3715 *
3716 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3717 *
3718 * @return The nearest focusable in the specified direction, or null if none
3719 * can be found.
3720 */
3721 public View focusSearch(int direction) {
3722 if (mParent != null) {
3723 return mParent.focusSearch(this, direction);
3724 } else {
3725 return null;
3726 }
3727 }
3728
3729 /**
3730 * This method is the last chance for the focused view and its ancestors to
3731 * respond to an arrow key. This is called when the focused view did not
3732 * consume the key internally, nor could the view system find a new view in
3733 * the requested direction to give focus to.
3734 *
3735 * @param focused The currently focused view.
3736 * @param direction The direction focus wants to move. One of FOCUS_UP,
3737 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3738 * @return True if the this view consumed this unhandled move.
3739 */
3740 public boolean dispatchUnhandledMove(View focused, int direction) {
3741 return false;
3742 }
3743
3744 /**
3745 * If a user manually specified the next view id for a particular direction,
3746 * use the root to look up the view. Once a view is found, it is cached
3747 * for future lookups.
3748 * @param root The root view of the hierarchy containing this view.
3749 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3750 * @return The user specified next view, or null if there is none.
3751 */
3752 View findUserSetNextFocus(View root, int direction) {
3753 switch (direction) {
3754 case FOCUS_LEFT:
3755 if (mNextFocusLeftId == View.NO_ID) return null;
3756 return findViewShouldExist(root, mNextFocusLeftId);
3757 case FOCUS_RIGHT:
3758 if (mNextFocusRightId == View.NO_ID) return null;
3759 return findViewShouldExist(root, mNextFocusRightId);
3760 case FOCUS_UP:
3761 if (mNextFocusUpId == View.NO_ID) return null;
3762 return findViewShouldExist(root, mNextFocusUpId);
3763 case FOCUS_DOWN:
3764 if (mNextFocusDownId == View.NO_ID) return null;
3765 return findViewShouldExist(root, mNextFocusDownId);
3766 }
3767 return null;
3768 }
3769
3770 private static View findViewShouldExist(View root, int childViewId) {
3771 View result = root.findViewById(childViewId);
3772 if (result == null) {
3773 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3774 + "by user for id " + childViewId);
3775 }
3776 return result;
3777 }
3778
3779 /**
3780 * Find and return all focusable views that are descendants of this view,
3781 * possibly including this view if it is focusable itself.
3782 *
3783 * @param direction The direction of the focus
3784 * @return A list of focusable views
3785 */
3786 public ArrayList<View> getFocusables(int direction) {
3787 ArrayList<View> result = new ArrayList<View>(24);
3788 addFocusables(result, direction);
3789 return result;
3790 }
3791
3792 /**
3793 * Add any focusable views that are descendants of this view (possibly
3794 * including this view if it is focusable itself) to views. If we are in touch mode,
3795 * only add views that are also focusable in touch mode.
3796 *
3797 * @param views Focusable views found so far
3798 * @param direction The direction of the focus
3799 */
3800 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003801 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003803
svetoslavganov75986cf2009-05-14 22:28:01 -07003804 /**
3805 * Adds any focusable views that are descendants of this view (possibly
3806 * including this view if it is focusable itself) to views. This method
3807 * adds all focusable views regardless if we are in touch mode or
3808 * only views focusable in touch mode if we are in touch mode depending on
3809 * the focusable mode paramater.
3810 *
3811 * @param views Focusable views found so far or null if all we are interested is
3812 * the number of focusables.
3813 * @param direction The direction of the focus.
3814 * @param focusableMode The type of focusables to be added.
3815 *
3816 * @see #FOCUSABLES_ALL
3817 * @see #FOCUSABLES_TOUCH_MODE
3818 */
3819 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3820 if (!isFocusable()) {
3821 return;
3822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823
svetoslavganov75986cf2009-05-14 22:28:01 -07003824 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3825 isInTouchMode() && !isFocusableInTouchMode()) {
3826 return;
3827 }
3828
3829 if (views != null) {
3830 views.add(this);
3831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 }
3833
3834 /**
3835 * Find and return all touchable views that are descendants of this view,
3836 * possibly including this view if it is touchable itself.
3837 *
3838 * @return A list of touchable views
3839 */
3840 public ArrayList<View> getTouchables() {
3841 ArrayList<View> result = new ArrayList<View>();
3842 addTouchables(result);
3843 return result;
3844 }
3845
3846 /**
3847 * Add any touchable views that are descendants of this view (possibly
3848 * including this view if it is touchable itself) to views.
3849 *
3850 * @param views Touchable views found so far
3851 */
3852 public void addTouchables(ArrayList<View> views) {
3853 final int viewFlags = mViewFlags;
3854
3855 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
3856 && (viewFlags & ENABLED_MASK) == ENABLED) {
3857 views.add(this);
3858 }
3859 }
3860
3861 /**
3862 * Call this to try to give focus to a specific view or to one of its
3863 * descendants.
3864 *
3865 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3866 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3867 * while the device is in touch mode.
3868 *
3869 * See also {@link #focusSearch}, which is what you call to say that you
3870 * have focus, and you want your parent to look for the next one.
3871 *
3872 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
3873 * {@link #FOCUS_DOWN} and <code>null</code>.
3874 *
3875 * @return Whether this view or one of its descendants actually took focus.
3876 */
3877 public final boolean requestFocus() {
3878 return requestFocus(View.FOCUS_DOWN);
3879 }
3880
3881
3882 /**
3883 * Call this to try to give focus to a specific view or to one of its
3884 * descendants and give it a hint about what direction focus is heading.
3885 *
3886 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3887 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3888 * while the device is in touch mode.
3889 *
3890 * See also {@link #focusSearch}, which is what you call to say that you
3891 * have focus, and you want your parent to look for the next one.
3892 *
3893 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
3894 * <code>null</code> set for the previously focused rectangle.
3895 *
3896 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3897 * @return Whether this view or one of its descendants actually took focus.
3898 */
3899 public final boolean requestFocus(int direction) {
3900 return requestFocus(direction, null);
3901 }
3902
3903 /**
3904 * Call this to try to give focus to a specific view or to one of its descendants
3905 * and give it hints about the direction and a specific rectangle that the focus
3906 * is coming from. The rectangle can help give larger views a finer grained hint
3907 * about where focus is coming from, and therefore, where to show selection, or
3908 * forward focus change internally.
3909 *
3910 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3911 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3912 * while the device is in touch mode.
3913 *
3914 * A View will not take focus if it is not visible.
3915 *
3916 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
3917 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
3918 *
3919 * See also {@link #focusSearch}, which is what you call to say that you
3920 * have focus, and you want your parent to look for the next one.
3921 *
3922 * You may wish to override this method if your custom {@link View} has an internal
3923 * {@link View} that it wishes to forward the request to.
3924 *
3925 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3926 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
3927 * to give a finer grained hint about where focus is coming from. May be null
3928 * if there is no hint.
3929 * @return Whether this view or one of its descendants actually took focus.
3930 */
3931 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
3932 // need to be focusable
3933 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
3934 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3935 return false;
3936 }
3937
3938 // need to be focusable in touch mode if in touch mode
3939 if (isInTouchMode() &&
3940 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
3941 return false;
3942 }
3943
3944 // need to not have any parents blocking us
3945 if (hasAncestorThatBlocksDescendantFocus()) {
3946 return false;
3947 }
3948
3949 handleFocusGainInternal(direction, previouslyFocusedRect);
3950 return true;
3951 }
3952
3953 /**
3954 * Call this to try to give focus to a specific view or to one of its descendants. This is a
3955 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
3956 * touch mode to request focus when they are touched.
3957 *
3958 * @return Whether this view or one of its descendants actually took focus.
3959 *
3960 * @see #isInTouchMode()
3961 *
3962 */
3963 public final boolean requestFocusFromTouch() {
3964 // Leave touch mode if we need to
3965 if (isInTouchMode()) {
3966 View root = getRootView();
3967 if (root != null) {
3968 ViewRoot viewRoot = (ViewRoot)root.getParent();
3969 if (viewRoot != null) {
3970 viewRoot.ensureTouchMode(false);
3971 }
3972 }
3973 }
3974 return requestFocus(View.FOCUS_DOWN);
3975 }
3976
3977 /**
3978 * @return Whether any ancestor of this view blocks descendant focus.
3979 */
3980 private boolean hasAncestorThatBlocksDescendantFocus() {
3981 ViewParent ancestor = mParent;
3982 while (ancestor instanceof ViewGroup) {
3983 final ViewGroup vgAncestor = (ViewGroup) ancestor;
3984 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
3985 return true;
3986 } else {
3987 ancestor = vgAncestor.getParent();
3988 }
3989 }
3990 return false;
3991 }
3992
3993 /**
Romain Guya440b002010-02-24 15:57:54 -08003994 * @hide
3995 */
3996 public void dispatchStartTemporaryDetach() {
3997 onStartTemporaryDetach();
3998 }
3999
4000 /**
4001 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4003 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004004 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 */
4006 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004007 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004008 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004009 }
4010
4011 /**
4012 * @hide
4013 */
4014 public void dispatchFinishTemporaryDetach() {
4015 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 }
Romain Guy8506ab42009-06-11 17:35:47 -07004017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 /**
4019 * Called after {@link #onStartTemporaryDetach} when the container is done
4020 * changing the view.
4021 */
4022 public void onFinishTemporaryDetach() {
4023 }
Romain Guy8506ab42009-06-11 17:35:47 -07004024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 /**
4026 * capture information of this view for later analysis: developement only
4027 * check dynamic switch to make sure we only dump view
4028 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4029 */
4030 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004031 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 return;
4033 }
4034 ViewDebug.dumpCapturedView(subTag, v);
4035 }
4036
4037 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004038 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4039 * for this view's window. Returns null if the view is not currently attached
4040 * to the window. Normally you will not need to use this directly, but
4041 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4042 */
4043 public KeyEvent.DispatcherState getKeyDispatcherState() {
4044 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4045 }
4046
4047 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 * Dispatch a key event before it is processed by any input method
4049 * associated with the view hierarchy. This can be used to intercept
4050 * key events in special situations before the IME consumes them; a
4051 * typical example would be handling the BACK key to update the application's
4052 * UI instead of allowing the IME to see it and close itself.
4053 *
4054 * @param event The key event to be dispatched.
4055 * @return True if the event was handled, false otherwise.
4056 */
4057 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4058 return onKeyPreIme(event.getKeyCode(), event);
4059 }
4060
4061 /**
4062 * Dispatch a key event to the next view on the focus path. This path runs
4063 * from the top of the view tree down to the currently focused view. If this
4064 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4065 * the next node down the focus path. This method also fires any key
4066 * listeners.
4067 *
4068 * @param event The key event to be dispatched.
4069 * @return True if the event was handled, false otherwise.
4070 */
4071 public boolean dispatchKeyEvent(KeyEvent event) {
4072 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073
Romain Guyf607bdc2010-09-10 19:20:06 -07004074 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 if (android.util.Config.LOGV) {
4076 captureViewInfo("captureViewKeyEvent", this);
4077 }
4078
Romain Guyf607bdc2010-09-10 19:20:06 -07004079 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4081 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4082 return true;
4083 }
4084
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004085 return event.dispatch(this, mAttachInfo != null
4086 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 }
4088
4089 /**
4090 * Dispatches a key shortcut event.
4091 *
4092 * @param event The key event to be dispatched.
4093 * @return True if the event was handled by the view, false otherwise.
4094 */
4095 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4096 return onKeyShortcut(event.getKeyCode(), event);
4097 }
4098
4099 /**
4100 * Pass the touch screen motion event down to the target view, or this
4101 * view if it is the target.
4102 *
4103 * @param event The motion event to be dispatched.
4104 * @return True if the event was handled by the view, false otherwise.
4105 */
4106 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004107 if (!onFilterTouchEventForSecurity(event)) {
4108 return false;
4109 }
4110
Romain Guyf607bdc2010-09-10 19:20:06 -07004111 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4113 mOnTouchListener.onTouch(this, event)) {
4114 return true;
4115 }
4116 return onTouchEvent(event);
4117 }
4118
4119 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004120 * Filter the touch event to apply security policies.
4121 *
4122 * @param event The motion event to be filtered.
4123 * @return True if the event should be dispatched, false if the event should be dropped.
4124 *
4125 * @see #getFilterTouchesWhenObscured
4126 */
4127 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004128 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004129 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4130 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4131 // Window is obscured, drop this touch.
4132 return false;
4133 }
4134 return true;
4135 }
4136
4137 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 * Pass a trackball motion event down to the focused view.
4139 *
4140 * @param event The motion event to be dispatched.
4141 * @return True if the event was handled by the view, false otherwise.
4142 */
4143 public boolean dispatchTrackballEvent(MotionEvent event) {
4144 //Log.i("view", "view=" + this + ", " + event.toString());
4145 return onTrackballEvent(event);
4146 }
4147
4148 /**
4149 * Called when the window containing this view gains or loses window focus.
4150 * ViewGroups should override to route to their children.
4151 *
4152 * @param hasFocus True if the window containing this view now has focus,
4153 * false otherwise.
4154 */
4155 public void dispatchWindowFocusChanged(boolean hasFocus) {
4156 onWindowFocusChanged(hasFocus);
4157 }
4158
4159 /**
4160 * Called when the window containing this view gains or loses focus. Note
4161 * that this is separate from view focus: to receive key events, both
4162 * your view and its window must have focus. If a window is displayed
4163 * on top of yours that takes input focus, then your own window will lose
4164 * focus but the view focus will remain unchanged.
4165 *
4166 * @param hasWindowFocus True if the window containing this view now has
4167 * focus, false otherwise.
4168 */
4169 public void onWindowFocusChanged(boolean hasWindowFocus) {
4170 InputMethodManager imm = InputMethodManager.peekInstance();
4171 if (!hasWindowFocus) {
4172 if (isPressed()) {
4173 setPressed(false);
4174 }
4175 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4176 imm.focusOut(this);
4177 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004178 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004179 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4181 imm.focusIn(this);
4182 }
4183 refreshDrawableState();
4184 }
4185
4186 /**
4187 * Returns true if this view is in a window that currently has window focus.
4188 * Note that this is not the same as the view itself having focus.
4189 *
4190 * @return True if this view is in a window that currently has window focus.
4191 */
4192 public boolean hasWindowFocus() {
4193 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4194 }
4195
4196 /**
Adam Powell326d8082009-12-09 15:10:07 -08004197 * Dispatch a view visibility change down the view hierarchy.
4198 * ViewGroups should override to route to their children.
4199 * @param changedView The view whose visibility changed. Could be 'this' or
4200 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004201 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4202 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004203 */
4204 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4205 onVisibilityChanged(changedView, visibility);
4206 }
4207
4208 /**
4209 * Called when the visibility of the view or an ancestor of the view is changed.
4210 * @param changedView The view whose visibility changed. Could be 'this' or
4211 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004212 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4213 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004214 */
4215 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004216 if (visibility == VISIBLE) {
4217 if (mAttachInfo != null) {
4218 initialAwakenScrollBars();
4219 } else {
4220 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4221 }
4222 }
Adam Powell326d8082009-12-09 15:10:07 -08004223 }
4224
4225 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004226 * Dispatch a hint about whether this view is displayed. For instance, when
4227 * a View moves out of the screen, it might receives a display hint indicating
4228 * the view is not displayed. Applications should not <em>rely</em> on this hint
4229 * as there is no guarantee that they will receive one.
4230 *
4231 * @param hint A hint about whether or not this view is displayed:
4232 * {@link #VISIBLE} or {@link #INVISIBLE}.
4233 */
4234 public void dispatchDisplayHint(int hint) {
4235 onDisplayHint(hint);
4236 }
4237
4238 /**
4239 * Gives this view a hint about whether is displayed or not. For instance, when
4240 * a View moves out of the screen, it might receives a display hint indicating
4241 * the view is not displayed. Applications should not <em>rely</em> on this hint
4242 * as there is no guarantee that they will receive one.
4243 *
4244 * @param hint A hint about whether or not this view is displayed:
4245 * {@link #VISIBLE} or {@link #INVISIBLE}.
4246 */
4247 protected void onDisplayHint(int hint) {
4248 }
4249
4250 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251 * Dispatch a window visibility change down the view hierarchy.
4252 * ViewGroups should override to route to their children.
4253 *
4254 * @param visibility The new visibility of the window.
4255 *
4256 * @see #onWindowVisibilityChanged
4257 */
4258 public void dispatchWindowVisibilityChanged(int visibility) {
4259 onWindowVisibilityChanged(visibility);
4260 }
4261
4262 /**
4263 * Called when the window containing has change its visibility
4264 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4265 * that this tells you whether or not your window is being made visible
4266 * to the window manager; this does <em>not</em> tell you whether or not
4267 * your window is obscured by other windows on the screen, even if it
4268 * is itself visible.
4269 *
4270 * @param visibility The new visibility of the window.
4271 */
4272 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004273 if (visibility == VISIBLE) {
4274 initialAwakenScrollBars();
4275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 }
4277
4278 /**
4279 * Returns the current visibility of the window this view is attached to
4280 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4281 *
4282 * @return Returns the current visibility of the view's window.
4283 */
4284 public int getWindowVisibility() {
4285 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4286 }
4287
4288 /**
4289 * Retrieve the overall visible display size in which the window this view is
4290 * attached to has been positioned in. This takes into account screen
4291 * decorations above the window, for both cases where the window itself
4292 * is being position inside of them or the window is being placed under
4293 * then and covered insets are used for the window to position its content
4294 * inside. In effect, this tells you the available area where content can
4295 * be placed and remain visible to users.
4296 *
4297 * <p>This function requires an IPC back to the window manager to retrieve
4298 * the requested information, so should not be used in performance critical
4299 * code like drawing.
4300 *
4301 * @param outRect Filled in with the visible display frame. If the view
4302 * is not attached to a window, this is simply the raw display size.
4303 */
4304 public void getWindowVisibleDisplayFrame(Rect outRect) {
4305 if (mAttachInfo != null) {
4306 try {
4307 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4308 } catch (RemoteException e) {
4309 return;
4310 }
4311 // XXX This is really broken, and probably all needs to be done
4312 // in the window manager, and we need to know more about whether
4313 // we want the area behind or in front of the IME.
4314 final Rect insets = mAttachInfo.mVisibleInsets;
4315 outRect.left += insets.left;
4316 outRect.top += insets.top;
4317 outRect.right -= insets.right;
4318 outRect.bottom -= insets.bottom;
4319 return;
4320 }
4321 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4322 outRect.set(0, 0, d.getWidth(), d.getHeight());
4323 }
4324
4325 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004326 * Dispatch a notification about a resource configuration change down
4327 * the view hierarchy.
4328 * ViewGroups should override to route to their children.
4329 *
4330 * @param newConfig The new resource configuration.
4331 *
4332 * @see #onConfigurationChanged
4333 */
4334 public void dispatchConfigurationChanged(Configuration newConfig) {
4335 onConfigurationChanged(newConfig);
4336 }
4337
4338 /**
4339 * Called when the current configuration of the resources being used
4340 * by the application have changed. You can use this to decide when
4341 * to reload resources that can changed based on orientation and other
4342 * configuration characterstics. You only need to use this if you are
4343 * not relying on the normal {@link android.app.Activity} mechanism of
4344 * recreating the activity instance upon a configuration change.
4345 *
4346 * @param newConfig The new resource configuration.
4347 */
4348 protected void onConfigurationChanged(Configuration newConfig) {
4349 }
4350
4351 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004352 * Private function to aggregate all per-view attributes in to the view
4353 * root.
4354 */
4355 void dispatchCollectViewAttributes(int visibility) {
4356 performCollectViewAttributes(visibility);
4357 }
4358
4359 void performCollectViewAttributes(int visibility) {
4360 //noinspection PointlessBitwiseExpression
4361 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4362 == (VISIBLE | KEEP_SCREEN_ON)) {
4363 mAttachInfo.mKeepScreenOn = true;
4364 }
4365 }
4366
4367 void needGlobalAttributesUpdate(boolean force) {
4368 AttachInfo ai = mAttachInfo;
4369 if (ai != null) {
4370 if (ai.mKeepScreenOn || force) {
4371 ai.mRecomputeGlobalAttributes = true;
4372 }
4373 }
4374 }
4375
4376 /**
4377 * Returns whether the device is currently in touch mode. Touch mode is entered
4378 * once the user begins interacting with the device by touch, and affects various
4379 * things like whether focus is always visible to the user.
4380 *
4381 * @return Whether the device is in touch mode.
4382 */
4383 @ViewDebug.ExportedProperty
4384 public boolean isInTouchMode() {
4385 if (mAttachInfo != null) {
4386 return mAttachInfo.mInTouchMode;
4387 } else {
4388 return ViewRoot.isInTouchMode();
4389 }
4390 }
4391
4392 /**
4393 * Returns the context the view is running in, through which it can
4394 * access the current theme, resources, etc.
4395 *
4396 * @return The view's Context.
4397 */
4398 @ViewDebug.CapturedViewProperty
4399 public final Context getContext() {
4400 return mContext;
4401 }
4402
4403 /**
4404 * Handle a key event before it is processed by any input method
4405 * associated with the view hierarchy. This can be used to intercept
4406 * key events in special situations before the IME consumes them; a
4407 * typical example would be handling the BACK key to update the application's
4408 * UI instead of allowing the IME to see it and close itself.
4409 *
4410 * @param keyCode The value in event.getKeyCode().
4411 * @param event Description of the key event.
4412 * @return If you handled the event, return true. If you want to allow the
4413 * event to be handled by the next receiver, return false.
4414 */
4415 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4416 return false;
4417 }
4418
4419 /**
4420 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4421 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4422 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4423 * is released, if the view is enabled and clickable.
4424 *
4425 * @param keyCode A key code that represents the button pressed, from
4426 * {@link android.view.KeyEvent}.
4427 * @param event The KeyEvent object that defines the button action.
4428 */
4429 public boolean onKeyDown(int keyCode, KeyEvent event) {
4430 boolean result = false;
4431
4432 switch (keyCode) {
4433 case KeyEvent.KEYCODE_DPAD_CENTER:
4434 case KeyEvent.KEYCODE_ENTER: {
4435 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4436 return true;
4437 }
4438 // Long clickable items don't necessarily have to be clickable
4439 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4440 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4441 (event.getRepeatCount() == 0)) {
4442 setPressed(true);
4443 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004444 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 }
4446 return true;
4447 }
4448 break;
4449 }
4450 }
4451 return result;
4452 }
4453
4454 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004455 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4456 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4457 * the event).
4458 */
4459 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4460 return false;
4461 }
4462
4463 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4465 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4466 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4467 * {@link KeyEvent#KEYCODE_ENTER} is released.
4468 *
4469 * @param keyCode A key code that represents the button pressed, from
4470 * {@link android.view.KeyEvent}.
4471 * @param event The KeyEvent object that defines the button action.
4472 */
4473 public boolean onKeyUp(int keyCode, KeyEvent event) {
4474 boolean result = false;
4475
4476 switch (keyCode) {
4477 case KeyEvent.KEYCODE_DPAD_CENTER:
4478 case KeyEvent.KEYCODE_ENTER: {
4479 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4480 return true;
4481 }
4482 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4483 setPressed(false);
4484
4485 if (!mHasPerformedLongPress) {
4486 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004487 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488
4489 result = performClick();
4490 }
4491 }
4492 break;
4493 }
4494 }
4495 return result;
4496 }
4497
4498 /**
4499 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4500 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4501 * the event).
4502 *
4503 * @param keyCode A key code that represents the button pressed, from
4504 * {@link android.view.KeyEvent}.
4505 * @param repeatCount The number of times the action was made.
4506 * @param event The KeyEvent object that defines the button action.
4507 */
4508 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4509 return false;
4510 }
4511
4512 /**
4513 * Called when an unhandled key shortcut event occurs.
4514 *
4515 * @param keyCode The value in event.getKeyCode().
4516 * @param event Description of the key event.
4517 * @return If you handled the event, return true. If you want to allow the
4518 * event to be handled by the next receiver, return false.
4519 */
4520 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4521 return false;
4522 }
4523
4524 /**
4525 * Check whether the called view is a text editor, in which case it
4526 * would make sense to automatically display a soft input window for
4527 * it. Subclasses should override this if they implement
4528 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004529 * a call on that method would return a non-null InputConnection, and
4530 * they are really a first-class editor that the user would normally
4531 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004532 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004533 * <p>The default implementation always returns false. This does
4534 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4535 * will not be called or the user can not otherwise perform edits on your
4536 * view; it is just a hint to the system that this is not the primary
4537 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004538 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 * @return Returns true if this view is a text editor, else false.
4540 */
4541 public boolean onCheckIsTextEditor() {
4542 return false;
4543 }
Romain Guy8506ab42009-06-11 17:35:47 -07004544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 /**
4546 * Create a new InputConnection for an InputMethod to interact
4547 * with the view. The default implementation returns null, since it doesn't
4548 * support input methods. You can override this to implement such support.
4549 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004550 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 * <p>When implementing this, you probably also want to implement
4552 * {@link #onCheckIsTextEditor()} to indicate you will return a
4553 * non-null InputConnection.
4554 *
4555 * @param outAttrs Fill in with attribute information about the connection.
4556 */
4557 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4558 return null;
4559 }
4560
4561 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004562 * Called by the {@link android.view.inputmethod.InputMethodManager}
4563 * when a view who is not the current
4564 * input connection target is trying to make a call on the manager. The
4565 * default implementation returns false; you can override this to return
4566 * true for certain views if you are performing InputConnection proxying
4567 * to them.
4568 * @param view The View that is making the InputMethodManager call.
4569 * @return Return true to allow the call, false to reject.
4570 */
4571 public boolean checkInputConnectionProxy(View view) {
4572 return false;
4573 }
Romain Guy8506ab42009-06-11 17:35:47 -07004574
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004575 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 * Show the context menu for this view. It is not safe to hold on to the
4577 * menu after returning from this method.
4578 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004579 * You should normally not overload this method. Overload
4580 * {@link #onCreateContextMenu(ContextMenu)} or define an
4581 * {@link OnCreateContextMenuListener} to add items to the context menu.
4582 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 * @param menu The context menu to populate
4584 */
4585 public void createContextMenu(ContextMenu menu) {
4586 ContextMenuInfo menuInfo = getContextMenuInfo();
4587
4588 // Sets the current menu info so all items added to menu will have
4589 // my extra info set.
4590 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4591
4592 onCreateContextMenu(menu);
4593 if (mOnCreateContextMenuListener != null) {
4594 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4595 }
4596
4597 // Clear the extra information so subsequent items that aren't mine don't
4598 // have my extra info.
4599 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4600
4601 if (mParent != null) {
4602 mParent.createContextMenu(menu);
4603 }
4604 }
4605
4606 /**
4607 * Views should implement this if they have extra information to associate
4608 * with the context menu. The return result is supplied as a parameter to
4609 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4610 * callback.
4611 *
4612 * @return Extra information about the item for which the context menu
4613 * should be shown. This information will vary across different
4614 * subclasses of View.
4615 */
4616 protected ContextMenuInfo getContextMenuInfo() {
4617 return null;
4618 }
4619
4620 /**
4621 * Views should implement this if the view itself is going to add items to
4622 * the context menu.
4623 *
4624 * @param menu the context menu to populate
4625 */
4626 protected void onCreateContextMenu(ContextMenu menu) {
4627 }
4628
4629 /**
4630 * Implement this method to handle trackball motion events. The
4631 * <em>relative</em> movement of the trackball since the last event
4632 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4633 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4634 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4635 * they will often be fractional values, representing the more fine-grained
4636 * movement information available from a trackball).
4637 *
4638 * @param event The motion event.
4639 * @return True if the event was handled, false otherwise.
4640 */
4641 public boolean onTrackballEvent(MotionEvent event) {
4642 return false;
4643 }
4644
4645 /**
4646 * Implement this method to handle touch screen motion events.
4647 *
4648 * @param event The motion event.
4649 * @return True if the event was handled, false otherwise.
4650 */
4651 public boolean onTouchEvent(MotionEvent event) {
4652 final int viewFlags = mViewFlags;
4653
4654 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4655 // A disabled view that is clickable still consumes the touch
4656 // events, it just doesn't respond to them.
4657 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4658 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4659 }
4660
4661 if (mTouchDelegate != null) {
4662 if (mTouchDelegate.onTouchEvent(event)) {
4663 return true;
4664 }
4665 }
4666
4667 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4668 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4669 switch (event.getAction()) {
4670 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004671 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4672 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004673 // take focus if we don't have it already and we should in
4674 // touch mode.
4675 boolean focusTaken = false;
4676 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4677 focusTaken = requestFocus();
4678 }
4679
4680 if (!mHasPerformedLongPress) {
4681 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004682 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004683
4684 // Only perform take click actions if we were in the pressed state
4685 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004686 // Use a Runnable and post this rather than calling
4687 // performClick directly. This lets other visual state
4688 // of the view update before click actions start.
4689 if (mPerformClick == null) {
4690 mPerformClick = new PerformClick();
4691 }
4692 if (!post(mPerformClick)) {
4693 performClick();
4694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004695 }
4696 }
4697
4698 if (mUnsetPressedState == null) {
4699 mUnsetPressedState = new UnsetPressedState();
4700 }
4701
Adam Powelle14579b2009-12-16 18:39:52 -08004702 if (prepressed) {
4703 mPrivateFlags |= PRESSED;
4704 refreshDrawableState();
4705 postDelayed(mUnsetPressedState,
4706 ViewConfiguration.getPressedStateDuration());
4707 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004708 // If the post failed, unpress right now
4709 mUnsetPressedState.run();
4710 }
Adam Powelle14579b2009-12-16 18:39:52 -08004711 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004712 }
4713 break;
4714
4715 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004716 if (mPendingCheckForTap == null) {
4717 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004718 }
Adam Powelle14579b2009-12-16 18:39:52 -08004719 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004720 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004721 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004722 break;
4723
4724 case MotionEvent.ACTION_CANCEL:
4725 mPrivateFlags &= ~PRESSED;
4726 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004727 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004728 break;
4729
4730 case MotionEvent.ACTION_MOVE:
4731 final int x = (int) event.getX();
4732 final int y = (int) event.getY();
4733
4734 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004735 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004736 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004737 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004738 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004739 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004740 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004741
4742 // Need to switch from pressed to not pressed
4743 mPrivateFlags &= ~PRESSED;
4744 refreshDrawableState();
4745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004746 }
4747 break;
4748 }
4749 return true;
4750 }
4751
4752 return false;
4753 }
4754
4755 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004756 * Remove the longpress detection timer.
4757 */
4758 private void removeLongPressCallback() {
4759 if (mPendingCheckForLongPress != null) {
4760 removeCallbacks(mPendingCheckForLongPress);
4761 }
4762 }
Adam Powelle14579b2009-12-16 18:39:52 -08004763
4764 /**
Romain Guya440b002010-02-24 15:57:54 -08004765 * Remove the prepress detection timer.
4766 */
4767 private void removeUnsetPressCallback() {
4768 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4769 setPressed(false);
4770 removeCallbacks(mUnsetPressedState);
4771 }
4772 }
4773
4774 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004775 * Remove the tap detection timer.
4776 */
4777 private void removeTapCallback() {
4778 if (mPendingCheckForTap != null) {
4779 mPrivateFlags &= ~PREPRESSED;
4780 removeCallbacks(mPendingCheckForTap);
4781 }
4782 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004783
4784 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004785 * Cancels a pending long press. Your subclass can use this if you
4786 * want the context menu to come up if the user presses and holds
4787 * at the same place, but you don't want it to come up if they press
4788 * and then move around enough to cause scrolling.
4789 */
4790 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004791 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004792
4793 /*
4794 * The prepressed state handled by the tap callback is a display
4795 * construct, but the tap callback will post a long press callback
4796 * less its own timeout. Remove it here.
4797 */
4798 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004799 }
4800
4801 /**
4802 * Sets the TouchDelegate for this View.
4803 */
4804 public void setTouchDelegate(TouchDelegate delegate) {
4805 mTouchDelegate = delegate;
4806 }
4807
4808 /**
4809 * Gets the TouchDelegate for this View.
4810 */
4811 public TouchDelegate getTouchDelegate() {
4812 return mTouchDelegate;
4813 }
4814
4815 /**
4816 * Set flags controlling behavior of this view.
4817 *
4818 * @param flags Constant indicating the value which should be set
4819 * @param mask Constant indicating the bit range that should be changed
4820 */
4821 void setFlags(int flags, int mask) {
4822 int old = mViewFlags;
4823 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4824
4825 int changed = mViewFlags ^ old;
4826 if (changed == 0) {
4827 return;
4828 }
4829 int privateFlags = mPrivateFlags;
4830
4831 /* Check if the FOCUSABLE bit has changed */
4832 if (((changed & FOCUSABLE_MASK) != 0) &&
4833 ((privateFlags & HAS_BOUNDS) !=0)) {
4834 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4835 && ((privateFlags & FOCUSED) != 0)) {
4836 /* Give up focus if we are no longer focusable */
4837 clearFocus();
4838 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4839 && ((privateFlags & FOCUSED) == 0)) {
4840 /*
4841 * Tell the view system that we are now available to take focus
4842 * if no one else already has it.
4843 */
4844 if (mParent != null) mParent.focusableViewAvailable(this);
4845 }
4846 }
4847
4848 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4849 if ((changed & VISIBILITY_MASK) != 0) {
4850 /*
4851 * If this view is becoming visible, set the DRAWN flag so that
4852 * the next invalidate() will not be skipped.
4853 */
4854 mPrivateFlags |= DRAWN;
4855
4856 needGlobalAttributesUpdate(true);
4857
4858 // a view becoming visible is worth notifying the parent
4859 // about in case nothing has focus. even if this specific view
4860 // isn't focusable, it may contain something that is, so let
4861 // the root view try to give this focus if nothing else does.
4862 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4863 mParent.focusableViewAvailable(this);
4864 }
4865 }
4866 }
4867
4868 /* Check if the GONE bit has changed */
4869 if ((changed & GONE) != 0) {
4870 needGlobalAttributesUpdate(false);
4871 requestLayout();
4872 invalidate();
4873
Romain Guyecd80ee2009-12-03 17:13:02 -08004874 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
4875 if (hasFocus()) clearFocus();
4876 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004877 }
4878 if (mAttachInfo != null) {
4879 mAttachInfo.mViewVisibilityChanged = true;
4880 }
4881 }
4882
4883 /* Check if the VISIBLE bit has changed */
4884 if ((changed & INVISIBLE) != 0) {
4885 needGlobalAttributesUpdate(false);
4886 invalidate();
4887
4888 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4889 // root view becoming invisible shouldn't clear focus
4890 if (getRootView() != this) {
4891 clearFocus();
4892 }
4893 }
4894 if (mAttachInfo != null) {
4895 mAttachInfo.mViewVisibilityChanged = true;
4896 }
4897 }
4898
Adam Powell326d8082009-12-09 15:10:07 -08004899 if ((changed & VISIBILITY_MASK) != 0) {
4900 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
4901 }
4902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004903 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4904 destroyDrawingCache();
4905 }
4906
4907 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4908 destroyDrawingCache();
4909 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4910 }
4911
4912 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4913 destroyDrawingCache();
4914 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4915 }
4916
4917 if ((changed & DRAW_MASK) != 0) {
4918 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4919 if (mBGDrawable != null) {
4920 mPrivateFlags &= ~SKIP_DRAW;
4921 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4922 } else {
4923 mPrivateFlags |= SKIP_DRAW;
4924 }
4925 } else {
4926 mPrivateFlags &= ~SKIP_DRAW;
4927 }
4928 requestLayout();
4929 invalidate();
4930 }
4931
4932 if ((changed & KEEP_SCREEN_ON) != 0) {
4933 if (mParent != null) {
4934 mParent.recomputeViewAttributes(this);
4935 }
4936 }
4937 }
4938
4939 /**
4940 * Change the view's z order in the tree, so it's on top of other sibling
4941 * views
4942 */
4943 public void bringToFront() {
4944 if (mParent != null) {
4945 mParent.bringChildToFront(this);
4946 }
4947 }
4948
4949 /**
4950 * This is called in response to an internal scroll in this view (i.e., the
4951 * view scrolled its own contents). This is typically as a result of
4952 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4953 * called.
4954 *
4955 * @param l Current horizontal scroll origin.
4956 * @param t Current vertical scroll origin.
4957 * @param oldl Previous horizontal scroll origin.
4958 * @param oldt Previous vertical scroll origin.
4959 */
4960 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4961 mBackgroundSizeChanged = true;
4962
4963 final AttachInfo ai = mAttachInfo;
4964 if (ai != null) {
4965 ai.mViewScrollChanged = true;
4966 }
4967 }
4968
4969 /**
Chet Haase21cd1382010-09-01 17:42:29 -07004970 * Interface definition for a callback to be invoked when the layout bounds of a view
4971 * changes due to layout processing.
4972 */
4973 public interface OnLayoutChangeListener {
4974 /**
4975 * Called when the focus state of a view has changed.
4976 *
4977 * @param v The view whose state has changed.
4978 * @param left The new value of the view's left property.
4979 * @param top The new value of the view's top property.
4980 * @param right The new value of the view's right property.
4981 * @param bottom The new value of the view's bottom property.
4982 * @param oldLeft The previous value of the view's left property.
4983 * @param oldTop The previous value of the view's top property.
4984 * @param oldRight The previous value of the view's right property.
4985 * @param oldBottom The previous value of the view's bottom property.
4986 */
4987 void onLayoutChange(View v, int left, int top, int right, int bottom,
4988 int oldLeft, int oldTop, int oldRight, int oldBottom);
4989 }
4990
4991 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004992 * This is called during layout when the size of this view has changed. If
4993 * you were just added to the view hierarchy, you're called with the old
4994 * values of 0.
4995 *
4996 * @param w Current width of this view.
4997 * @param h Current height of this view.
4998 * @param oldw Old width of this view.
4999 * @param oldh Old height of this view.
5000 */
5001 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5002 }
5003
5004 /**
5005 * Called by draw to draw the child views. This may be overridden
5006 * by derived classes to gain control just before its children are drawn
5007 * (but after its own view has been drawn).
5008 * @param canvas the canvas on which to draw the view
5009 */
5010 protected void dispatchDraw(Canvas canvas) {
5011 }
5012
5013 /**
5014 * Gets the parent of this view. Note that the parent is a
5015 * ViewParent and not necessarily a View.
5016 *
5017 * @return Parent of this view.
5018 */
5019 public final ViewParent getParent() {
5020 return mParent;
5021 }
5022
5023 /**
5024 * Return the scrolled left position of this view. This is the left edge of
5025 * the displayed part of your view. You do not need to draw any pixels
5026 * farther left, since those are outside of the frame of your view on
5027 * screen.
5028 *
5029 * @return The left edge of the displayed part of your view, in pixels.
5030 */
5031 public final int getScrollX() {
5032 return mScrollX;
5033 }
5034
5035 /**
5036 * Return the scrolled top position of this view. This is the top edge of
5037 * the displayed part of your view. You do not need to draw any pixels above
5038 * it, since those are outside of the frame of your view on screen.
5039 *
5040 * @return The top edge of the displayed part of your view, in pixels.
5041 */
5042 public final int getScrollY() {
5043 return mScrollY;
5044 }
5045
5046 /**
5047 * Return the width of the your view.
5048 *
5049 * @return The width of your view, in pixels.
5050 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005051 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005052 public final int getWidth() {
5053 return mRight - mLeft;
5054 }
5055
5056 /**
5057 * Return the height of your view.
5058 *
5059 * @return The height of your view, in pixels.
5060 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005061 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 public final int getHeight() {
5063 return mBottom - mTop;
5064 }
5065
5066 /**
5067 * Return the visible drawing bounds of your view. Fills in the output
5068 * rectangle with the values from getScrollX(), getScrollY(),
5069 * getWidth(), and getHeight().
5070 *
5071 * @param outRect The (scrolled) drawing bounds of the view.
5072 */
5073 public void getDrawingRect(Rect outRect) {
5074 outRect.left = mScrollX;
5075 outRect.top = mScrollY;
5076 outRect.right = mScrollX + (mRight - mLeft);
5077 outRect.bottom = mScrollY + (mBottom - mTop);
5078 }
5079
5080 /**
5081 * The width of this view as measured in the most recent call to measure().
5082 * This should be used during measurement and layout calculations only. Use
5083 * {@link #getWidth()} to see how wide a view is after layout.
5084 *
5085 * @return The measured width of this view.
5086 */
5087 public final int getMeasuredWidth() {
5088 return mMeasuredWidth;
5089 }
5090
5091 /**
5092 * The height of this view as measured in the most recent call to measure().
5093 * This should be used during measurement and layout calculations only. Use
5094 * {@link #getHeight()} to see how tall a view is after layout.
5095 *
5096 * @return The measured height of this view.
5097 */
5098 public final int getMeasuredHeight() {
5099 return mMeasuredHeight;
5100 }
5101
5102 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005103 * The transform matrix of this view, which is calculated based on the current
5104 * roation, scale, and pivot properties.
5105 *
5106 * @see #getRotation()
5107 * @see #getScaleX()
5108 * @see #getScaleY()
5109 * @see #getPivotX()
5110 * @see #getPivotY()
5111 * @return The current transform matrix for the view
5112 */
5113 public Matrix getMatrix() {
Romain Guy33e72ae2010-07-17 12:40:29 -07005114 hasIdentityMatrix();
5115 return mMatrix;
5116 }
5117
5118 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005119 * Utility function to determine if the value is far enough away from zero to be
5120 * considered non-zero.
5121 * @param value A floating point value to check for zero-ness
5122 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5123 */
5124 private static boolean nonzero(float value) {
5125 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5126 }
5127
5128 /**
Romain Guy33e72ae2010-07-17 12:40:29 -07005129 * Recomputes the transform matrix if necessary.
5130 *
5131 * @return True if the transform matrix is the identity matrix, false otherwise.
5132 */
5133 boolean hasIdentityMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005134 if (mMatrixDirty) {
5135 // transform-related properties have changed since the last time someone
5136 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005137
5138 // Figure out if we need to update the pivot point
5139 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5140 if ((mRight - mLeft) != mPrevWidth && (mBottom - mTop) != mPrevHeight) {
5141 mPrevWidth = mRight - mLeft;
5142 mPrevHeight = mBottom - mTop;
5143 mPivotX = (float) mPrevWidth / 2f;
5144 mPivotY = (float) mPrevHeight / 2f;
5145 }
5146 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005147 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005148 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5149 mMatrix.setTranslate(mTranslationX, mTranslationY);
5150 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5151 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5152 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005153 if (mCamera == null) {
5154 mCamera = new Camera();
5155 matrix3D = new Matrix();
5156 }
5157 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005158 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005159 mCamera.rotateX(mRotationX);
5160 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005161 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005162 mCamera.getMatrix(matrix3D);
5163 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005164 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005165 mMatrix.postConcat(matrix3D);
5166 mCamera.restore();
5167 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005168 mMatrixDirty = false;
5169 mMatrixIsIdentity = mMatrix.isIdentity();
5170 mInverseMatrixDirty = true;
5171 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005172 return mMatrixIsIdentity;
Chet Haasec3aa3612010-06-17 08:50:37 -07005173 }
5174
5175 /**
5176 * Utility method to retrieve the inverse of the current mMatrix property.
5177 * We cache the matrix to avoid recalculating it when transform properties
5178 * have not changed.
5179 *
5180 * @return The inverse of the current matrix of this view.
5181 */
5182 Matrix getInverseMatrix() {
5183 if (mInverseMatrixDirty) {
5184 if (mInverseMatrix == null) {
5185 mInverseMatrix = new Matrix();
5186 }
5187 mMatrix.invert(mInverseMatrix);
5188 mInverseMatrixDirty = false;
5189 }
5190 return mInverseMatrix;
5191 }
5192
5193 /**
5194 * The degrees that the view is rotated around the pivot point.
5195 *
5196 * @see #getPivotX()
5197 * @see #getPivotY()
5198 * @return The degrees of rotation.
5199 */
5200 public float getRotation() {
5201 return mRotation;
5202 }
5203
5204 /**
Chet Haase897247b2010-09-09 14:54:47 -07005205 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5206 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005207 *
5208 * @param rotation The degrees of rotation.
5209 * @see #getPivotX()
5210 * @see #getPivotY()
5211 */
5212 public void setRotation(float rotation) {
5213 if (mRotation != rotation) {
5214 // Double-invalidation is necessary to capture view's old and new areas
5215 invalidate();
5216 mRotation = rotation;
5217 mMatrixDirty = true;
5218 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5219 invalidate();
5220 }
5221 }
5222
5223 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005224 * The degrees that the view is rotated around the vertical axis through the pivot point.
5225 *
5226 * @see #getPivotX()
5227 * @see #getPivotY()
5228 * @return The degrees of Y rotation.
5229 */
5230 public float getRotationY() {
5231 return mRotationY;
5232 }
5233
5234 /**
Chet Haase897247b2010-09-09 14:54:47 -07005235 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5236 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5237 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005238 *
5239 * @param rotationY The degrees of Y rotation.
5240 * @see #getPivotX()
5241 * @see #getPivotY()
5242 */
5243 public void setRotationY(float rotationY) {
5244 if (mRotationY != rotationY) {
5245 // Double-invalidation is necessary to capture view's old and new areas
5246 invalidate();
5247 mRotationY = rotationY;
5248 mMatrixDirty = true;
5249 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5250 invalidate();
5251 }
5252 }
5253
5254 /**
5255 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5256 *
5257 * @see #getPivotX()
5258 * @see #getPivotY()
5259 * @return The degrees of X rotation.
5260 */
5261 public float getRotationX() {
5262 return mRotationX;
5263 }
5264
5265 /**
Chet Haase897247b2010-09-09 14:54:47 -07005266 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5267 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5268 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005269 *
5270 * @param rotationX The degrees of X rotation.
5271 * @see #getPivotX()
5272 * @see #getPivotY()
5273 */
5274 public void setRotationX(float rotationX) {
5275 if (mRotationX != rotationX) {
5276 // Double-invalidation is necessary to capture view's old and new areas
5277 invalidate();
5278 mRotationX = rotationX;
5279 mMatrixDirty = true;
5280 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5281 invalidate();
5282 }
5283 }
5284
5285 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005286 * The amount that the view is scaled in x around the pivot point, as a proportion of
5287 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5288 *
Joe Onorato93162322010-09-16 15:42:01 -04005289 * <p>By default, this is 1.0f.
5290 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005291 * @see #getPivotX()
5292 * @see #getPivotY()
5293 * @return The scaling factor.
5294 */
5295 public float getScaleX() {
5296 return mScaleX;
5297 }
5298
5299 /**
5300 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5301 * the view's unscaled width. A value of 1 means that no scaling is applied.
5302 *
5303 * @param scaleX The scaling factor.
5304 * @see #getPivotX()
5305 * @see #getPivotY()
5306 */
5307 public void setScaleX(float scaleX) {
5308 if (mScaleX != scaleX) {
5309 // Double-invalidation is necessary to capture view's old and new areas
5310 invalidate();
5311 mScaleX = scaleX;
5312 mMatrixDirty = true;
5313 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5314 invalidate();
5315 }
5316 }
5317
5318 /**
5319 * The amount that the view is scaled in y around the pivot point, as a proportion of
5320 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5321 *
Joe Onorato93162322010-09-16 15:42:01 -04005322 * <p>By default, this is 1.0f.
5323 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005324 * @see #getPivotX()
5325 * @see #getPivotY()
5326 * @return The scaling factor.
5327 */
5328 public float getScaleY() {
5329 return mScaleY;
5330 }
5331
5332 /**
5333 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5334 * the view's unscaled width. A value of 1 means that no scaling is applied.
5335 *
5336 * @param scaleY The scaling factor.
5337 * @see #getPivotX()
5338 * @see #getPivotY()
5339 */
5340 public void setScaleY(float scaleY) {
5341 if (mScaleY != scaleY) {
5342 // Double-invalidation is necessary to capture view's old and new areas
5343 invalidate();
5344 mScaleY = scaleY;
5345 mMatrixDirty = true;
5346 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5347 invalidate();
5348 }
5349 }
5350
5351 /**
5352 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5353 * and {@link #setScaleX(float) scaled}.
5354 *
5355 * @see #getRotation()
5356 * @see #getScaleX()
5357 * @see #getScaleY()
5358 * @see #getPivotY()
5359 * @return The x location of the pivot point.
5360 */
5361 public float getPivotX() {
5362 return mPivotX;
5363 }
5364
5365 /**
5366 * Sets the x location of the point around which the view is
5367 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005368 * By default, the pivot point is centered on the object.
5369 * Setting this property disables this behavior and causes the view to use only the
5370 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005371 *
5372 * @param pivotX The x location of the pivot point.
5373 * @see #getRotation()
5374 * @see #getScaleX()
5375 * @see #getScaleY()
5376 * @see #getPivotY()
5377 */
5378 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005379 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005380 if (mPivotX != pivotX) {
5381 // Double-invalidation is necessary to capture view's old and new areas
5382 invalidate();
5383 mPivotX = pivotX;
5384 mMatrixDirty = true;
5385 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5386 invalidate();
5387 }
5388 }
5389
5390 /**
5391 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5392 * and {@link #setScaleY(float) scaled}.
5393 *
5394 * @see #getRotation()
5395 * @see #getScaleX()
5396 * @see #getScaleY()
5397 * @see #getPivotY()
5398 * @return The y location of the pivot point.
5399 */
5400 public float getPivotY() {
5401 return mPivotY;
5402 }
5403
5404 /**
5405 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005406 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5407 * Setting this property disables this behavior and causes the view to use only the
5408 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005409 *
5410 * @param pivotY The y location of the pivot point.
5411 * @see #getRotation()
5412 * @see #getScaleX()
5413 * @see #getScaleY()
5414 * @see #getPivotY()
5415 */
5416 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005417 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005418 if (mPivotY != pivotY) {
5419 // Double-invalidation is necessary to capture view's old and new areas
5420 invalidate();
5421 mPivotY = pivotY;
5422 mMatrixDirty = true;
5423 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5424 invalidate();
5425 }
5426 }
5427
5428 /**
5429 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5430 * completely transparent and 1 means the view is completely opaque.
5431 *
Joe Onorato93162322010-09-16 15:42:01 -04005432 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005433 * @return The opacity of the view.
5434 */
5435 public float getAlpha() {
5436 return mAlpha;
5437 }
5438
5439 /**
5440 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5441 * completely transparent and 1 means the view is completely opaque.
5442 *
5443 * @param alpha The opacity of the view.
5444 */
5445 public void setAlpha(float alpha) {
5446 mAlpha = alpha;
Romain Guy9b34d452010-09-02 11:45:04 -07005447 onSetAlpha((int) (alpha * 255));
Chet Haasec3aa3612010-06-17 08:50:37 -07005448 invalidate();
5449 }
5450
5451 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 * Top position of this view relative to its parent.
5453 *
5454 * @return The top of this view, in pixels.
5455 */
5456 @ViewDebug.CapturedViewProperty
5457 public final int getTop() {
5458 return mTop;
5459 }
5460
5461 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005462 * Sets the top position of this view relative to its parent. This method is meant to be called
5463 * by the layout system and should not generally be called otherwise, because the property
5464 * may be changed at any time by the layout.
5465 *
5466 * @param top The top of this view, in pixels.
5467 */
5468 public final void setTop(int top) {
5469 if (top != mTop) {
5470 if (hasIdentityMatrix()) {
5471 final ViewParent p = mParent;
5472 if (p != null && mAttachInfo != null) {
5473 final Rect r = mAttachInfo.mTmpInvalRect;
5474 int minTop;
5475 int yLoc;
5476 if (top < mTop) {
5477 minTop = top;
5478 yLoc = top - mTop;
5479 } else {
5480 minTop = mTop;
5481 yLoc = 0;
5482 }
5483 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5484 p.invalidateChild(this, r);
5485 }
5486 } else {
5487 // Double-invalidation is necessary to capture view's old and new areas
5488 invalidate();
5489 }
5490
5491 mTop = top;
5492
5493 if (!mMatrixIsIdentity) {
5494 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5495 invalidate();
5496 }
5497 }
5498 }
5499
5500 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 * Bottom position of this view relative to its parent.
5502 *
5503 * @return The bottom of this view, in pixels.
5504 */
5505 @ViewDebug.CapturedViewProperty
5506 public final int getBottom() {
5507 return mBottom;
5508 }
5509
5510 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005511 * Sets the bottom position of this view relative to its parent. This method is meant to be
5512 * called by the layout system and should not generally be called otherwise, because the
5513 * property may be changed at any time by the layout.
5514 *
5515 * @param bottom The bottom of this view, in pixels.
5516 */
5517 public final void setBottom(int bottom) {
5518 if (bottom != mBottom) {
5519 if (hasIdentityMatrix()) {
5520 final ViewParent p = mParent;
5521 if (p != null && mAttachInfo != null) {
5522 final Rect r = mAttachInfo.mTmpInvalRect;
5523 int maxBottom;
5524 if (bottom < mBottom) {
5525 maxBottom = mBottom;
5526 } else {
5527 maxBottom = bottom;
5528 }
5529 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5530 p.invalidateChild(this, r);
5531 }
5532 } else {
5533 // Double-invalidation is necessary to capture view's old and new areas
5534 invalidate();
5535 }
5536
5537 mBottom = bottom;
5538
5539 if (!mMatrixIsIdentity) {
5540 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5541 invalidate();
5542 }
5543 }
5544 }
5545
5546 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005547 * Left position of this view relative to its parent.
5548 *
5549 * @return The left edge of this view, in pixels.
5550 */
5551 @ViewDebug.CapturedViewProperty
5552 public final int getLeft() {
5553 return mLeft;
5554 }
5555
5556 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005557 * Sets the left position of this view relative to its parent. This method is meant to be called
5558 * by the layout system and should not generally be called otherwise, because the property
5559 * may be changed at any time by the layout.
5560 *
5561 * @param left The bottom of this view, in pixels.
5562 */
5563 public final void setLeft(int left) {
5564 if (left != mLeft) {
5565 System.out.println("view " + this + " left = " + left);
5566 if (hasIdentityMatrix()) {
5567 final ViewParent p = mParent;
5568 if (p != null && mAttachInfo != null) {
5569 final Rect r = mAttachInfo.mTmpInvalRect;
5570 int minLeft;
5571 int xLoc;
5572 if (left < mLeft) {
5573 minLeft = left;
5574 xLoc = left - mLeft;
5575 } else {
5576 minLeft = mLeft;
5577 xLoc = 0;
5578 }
5579 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
5580 p.invalidateChild(this, r);
5581 }
5582 } else {
5583 // Double-invalidation is necessary to capture view's old and new areas
5584 invalidate();
5585 }
5586
5587 mLeft = left;
5588
5589 if (!mMatrixIsIdentity) {
5590 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5591 invalidate();
5592 }
5593 }
5594 }
5595
5596 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597 * Right position of this view relative to its parent.
5598 *
5599 * @return The right edge of this view, in pixels.
5600 */
5601 @ViewDebug.CapturedViewProperty
5602 public final int getRight() {
5603 return mRight;
5604 }
5605
5606 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005607 * Sets the right position of this view relative to its parent. This method is meant to be called
5608 * by the layout system and should not generally be called otherwise, because the property
5609 * may be changed at any time by the layout.
5610 *
5611 * @param right The bottom of this view, in pixels.
5612 */
5613 public final void setRight(int right) {
5614 if (right != mRight) {
5615 if (hasIdentityMatrix()) {
5616 final ViewParent p = mParent;
5617 if (p != null && mAttachInfo != null) {
5618 final Rect r = mAttachInfo.mTmpInvalRect;
5619 int maxRight;
5620 if (right < mRight) {
5621 maxRight = mRight;
5622 } else {
5623 maxRight = right;
5624 }
5625 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
5626 p.invalidateChild(this, r);
5627 }
5628 } else {
5629 // Double-invalidation is necessary to capture view's old and new areas
5630 invalidate();
5631 }
5632
5633 mRight = right;
5634
5635 if (!mMatrixIsIdentity) {
5636 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5637 invalidate();
5638 }
5639 }
5640 }
5641
5642 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005643 * The visual x position of this view, in pixels. This is equivalent to the
5644 * {@link #setTranslationX(float) translationX} property plus the current
5645 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07005646 *
Chet Haasedf030d22010-07-30 17:22:38 -07005647 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005648 */
Chet Haasedf030d22010-07-30 17:22:38 -07005649 public float getX() {
5650 return mLeft + mTranslationX;
5651 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005652
Chet Haasedf030d22010-07-30 17:22:38 -07005653 /**
5654 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
5655 * {@link #setTranslationX(float) translationX} property to be the difference between
5656 * the x value passed in and the current {@link #getLeft() left} property.
5657 *
5658 * @param x The visual x position of this view, in pixels.
5659 */
5660 public void setX(float x) {
5661 setTranslationX(x - mLeft);
5662 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005663
Chet Haasedf030d22010-07-30 17:22:38 -07005664 /**
5665 * The visual y position of this view, in pixels. This is equivalent to the
5666 * {@link #setTranslationY(float) translationY} property plus the current
5667 * {@link #getTop() top} property.
5668 *
5669 * @return The visual y position of this view, in pixels.
5670 */
5671 public float getY() {
5672 return mTop + mTranslationY;
5673 }
5674
5675 /**
5676 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
5677 * {@link #setTranslationY(float) translationY} property to be the difference between
5678 * the y value passed in and the current {@link #getTop() top} property.
5679 *
5680 * @param y The visual y position of this view, in pixels.
5681 */
5682 public void setY(float y) {
5683 setTranslationY(y - mTop);
5684 }
5685
5686
5687 /**
5688 * The horizontal location of this view relative to its {@link #getLeft() left} position.
5689 * This position is post-layout, in addition to wherever the object's
5690 * layout placed it.
5691 *
5692 * @return The horizontal position of this view relative to its left position, in pixels.
5693 */
5694 public float getTranslationX() {
5695 return mTranslationX;
5696 }
5697
5698 /**
5699 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
5700 * This effectively positions the object post-layout, in addition to wherever the object's
5701 * layout placed it.
5702 *
5703 * @param translationX The horizontal position of this view relative to its left position,
5704 * in pixels.
5705 */
5706 public void setTranslationX(float translationX) {
5707 if (mTranslationX != translationX) {
5708 // Double-invalidation is necessary to capture view's old and new areas
5709 invalidate();
5710 mTranslationX = translationX;
5711 mMatrixDirty = true;
5712 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5713 invalidate();
Chet Haasec3aa3612010-06-17 08:50:37 -07005714 }
5715 }
5716
5717 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005718 * The horizontal location of this view relative to its {@link #getTop() top} position.
5719 * This position is post-layout, in addition to wherever the object's
5720 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005721 *
Chet Haasedf030d22010-07-30 17:22:38 -07005722 * @return The vertical position of this view relative to its top position,
5723 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005724 */
Chet Haasedf030d22010-07-30 17:22:38 -07005725 public float getTranslationY() {
5726 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07005727 }
5728
5729 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005730 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
5731 * This effectively positions the object post-layout, in addition to wherever the object's
5732 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005733 *
Chet Haasedf030d22010-07-30 17:22:38 -07005734 * @param translationY The vertical position of this view relative to its top position,
5735 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005736 */
Chet Haasedf030d22010-07-30 17:22:38 -07005737 public void setTranslationY(float translationY) {
5738 if (mTranslationY != translationY) {
5739 // Double-invalidation is necessary to capture view's old and new areas
5740 invalidate();
5741 mTranslationY = translationY;
5742 mMatrixDirty = true;
5743 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5744 invalidate();
5745 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005746 }
5747
5748 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 * Hit rectangle in parent's coordinates
5750 *
5751 * @param outRect The hit rectangle of the view.
5752 */
5753 public void getHitRect(Rect outRect) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005754 if (hasIdentityMatrix() || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005755 outRect.set(mLeft, mTop, mRight, mBottom);
5756 } else {
Adam Powellb5de9f32010-07-17 01:00:53 -07005757 Matrix m = getMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005758 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07005759 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Chet Haasec3aa3612010-06-17 08:50:37 -07005760 m.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07005761 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
5762 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07005763 }
5764 }
5765
5766 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005767 * Utility method to determine whether the given point, in local coordinates,
5768 * is inside the view, where the area of the view is expanded by the slop factor.
5769 * This method is called while processing touch-move events to determine if the event
5770 * is still within the view.
5771 */
5772 private boolean pointInView(float localX, float localY, float slop) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005773 return localX > -slop && localY > -slop && localX < ((mRight - mLeft) + slop) &&
5774 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775 }
5776
5777 /**
5778 * When a view has focus and the user navigates away from it, the next view is searched for
5779 * starting from the rectangle filled in by this method.
5780 *
5781 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
5782 * view maintains some idea of internal selection, such as a cursor, or a selected row
5783 * or column, you should override this method and fill in a more specific rectangle.
5784 *
5785 * @param r The rectangle to fill in, in this view's coordinates.
5786 */
5787 public void getFocusedRect(Rect r) {
5788 getDrawingRect(r);
5789 }
5790
5791 /**
5792 * If some part of this view is not clipped by any of its parents, then
5793 * return that area in r in global (root) coordinates. To convert r to local
5794 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
5795 * -globalOffset.y)) If the view is completely clipped or translated out,
5796 * return false.
5797 *
5798 * @param r If true is returned, r holds the global coordinates of the
5799 * visible portion of this view.
5800 * @param globalOffset If true is returned, globalOffset holds the dx,dy
5801 * between this view and its root. globalOffet may be null.
5802 * @return true if r is non-empty (i.e. part of the view is visible at the
5803 * root level.
5804 */
5805 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
5806 int width = mRight - mLeft;
5807 int height = mBottom - mTop;
5808 if (width > 0 && height > 0) {
5809 r.set(0, 0, width, height);
5810 if (globalOffset != null) {
5811 globalOffset.set(-mScrollX, -mScrollY);
5812 }
5813 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
5814 }
5815 return false;
5816 }
5817
5818 public final boolean getGlobalVisibleRect(Rect r) {
5819 return getGlobalVisibleRect(r, null);
5820 }
5821
5822 public final boolean getLocalVisibleRect(Rect r) {
5823 Point offset = new Point();
5824 if (getGlobalVisibleRect(r, offset)) {
5825 r.offset(-offset.x, -offset.y); // make r local
5826 return true;
5827 }
5828 return false;
5829 }
5830
5831 /**
5832 * Offset this view's vertical location by the specified number of pixels.
5833 *
5834 * @param offset the number of pixels to offset the view by
5835 */
5836 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005837 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005838 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005839 final ViewParent p = mParent;
5840 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005841 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005842 int minTop;
5843 int maxBottom;
5844 int yLoc;
5845 if (offset < 0) {
5846 minTop = mTop + offset;
5847 maxBottom = mBottom;
5848 yLoc = offset;
5849 } else {
5850 minTop = mTop;
5851 maxBottom = mBottom + offset;
5852 yLoc = 0;
5853 }
5854 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
5855 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005856 }
5857 } else {
5858 invalidate();
5859 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005860
Chet Haasec3aa3612010-06-17 08:50:37 -07005861 mTop += offset;
5862 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005863
Chet Haasec3aa3612010-06-17 08:50:37 -07005864 if (!mMatrixIsIdentity) {
5865 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5866 invalidate();
5867 }
5868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 }
5870
5871 /**
5872 * Offset this view's horizontal location by the specified amount of pixels.
5873 *
5874 * @param offset the numer of pixels to offset the view by
5875 */
5876 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005877 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005878 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005879 final ViewParent p = mParent;
5880 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005881 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005882 int minLeft;
5883 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005884 if (offset < 0) {
5885 minLeft = mLeft + offset;
5886 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005887 } else {
5888 minLeft = mLeft;
5889 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005890 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005891 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07005892 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005893 }
5894 } else {
5895 invalidate();
5896 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005897
Chet Haasec3aa3612010-06-17 08:50:37 -07005898 mLeft += offset;
5899 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005900
Chet Haasec3aa3612010-06-17 08:50:37 -07005901 if (!mMatrixIsIdentity) {
5902 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5903 invalidate();
5904 }
5905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906 }
5907
5908 /**
5909 * Get the LayoutParams associated with this view. All views should have
5910 * layout parameters. These supply parameters to the <i>parent</i> of this
5911 * view specifying how it should be arranged. There are many subclasses of
5912 * ViewGroup.LayoutParams, and these correspond to the different subclasses
5913 * of ViewGroup that are responsible for arranging their children.
5914 * @return The LayoutParams associated with this view
5915 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07005916 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 public ViewGroup.LayoutParams getLayoutParams() {
5918 return mLayoutParams;
5919 }
5920
5921 /**
5922 * Set the layout parameters associated with this view. These supply
5923 * parameters to the <i>parent</i> of this view specifying how it should be
5924 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
5925 * correspond to the different subclasses of ViewGroup that are responsible
5926 * for arranging their children.
5927 *
5928 * @param params the layout parameters for this view
5929 */
5930 public void setLayoutParams(ViewGroup.LayoutParams params) {
5931 if (params == null) {
5932 throw new NullPointerException("params == null");
5933 }
5934 mLayoutParams = params;
5935 requestLayout();
5936 }
5937
5938 /**
5939 * Set the scrolled position of your view. This will cause a call to
5940 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5941 * invalidated.
5942 * @param x the x position to scroll to
5943 * @param y the y position to scroll to
5944 */
5945 public void scrollTo(int x, int y) {
5946 if (mScrollX != x || mScrollY != y) {
5947 int oldX = mScrollX;
5948 int oldY = mScrollY;
5949 mScrollX = x;
5950 mScrollY = y;
5951 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07005952 if (!awakenScrollBars()) {
5953 invalidate();
5954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005955 }
5956 }
5957
5958 /**
5959 * Move the scrolled position of your view. This will cause a call to
5960 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5961 * invalidated.
5962 * @param x the amount of pixels to scroll by horizontally
5963 * @param y the amount of pixels to scroll by vertically
5964 */
5965 public void scrollBy(int x, int y) {
5966 scrollTo(mScrollX + x, mScrollY + y);
5967 }
5968
5969 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07005970 * <p>Trigger the scrollbars to draw. When invoked this method starts an
5971 * animation to fade the scrollbars out after a default delay. If a subclass
5972 * provides animated scrolling, the start delay should equal the duration
5973 * of the scrolling animation.</p>
5974 *
5975 * <p>The animation starts only if at least one of the scrollbars is
5976 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
5977 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5978 * this method returns true, and false otherwise. If the animation is
5979 * started, this method calls {@link #invalidate()}; in that case the
5980 * caller should not call {@link #invalidate()}.</p>
5981 *
5982 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07005983 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07005984 *
5985 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
5986 * and {@link #scrollTo(int, int)}.</p>
5987 *
5988 * @return true if the animation is played, false otherwise
5989 *
5990 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07005991 * @see #scrollBy(int, int)
5992 * @see #scrollTo(int, int)
5993 * @see #isHorizontalScrollBarEnabled()
5994 * @see #isVerticalScrollBarEnabled()
5995 * @see #setHorizontalScrollBarEnabled(boolean)
5996 * @see #setVerticalScrollBarEnabled(boolean)
5997 */
5998 protected boolean awakenScrollBars() {
5999 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006000 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006001 }
6002
6003 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006004 * Trigger the scrollbars to draw.
6005 * This method differs from awakenScrollBars() only in its default duration.
6006 * initialAwakenScrollBars() will show the scroll bars for longer than
6007 * usual to give the user more of a chance to notice them.
6008 *
6009 * @return true if the animation is played, false otherwise.
6010 */
6011 private boolean initialAwakenScrollBars() {
6012 return mScrollCache != null &&
6013 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6014 }
6015
6016 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006017 * <p>
6018 * Trigger the scrollbars to draw. When invoked this method starts an
6019 * animation to fade the scrollbars out after a fixed delay. If a subclass
6020 * provides animated scrolling, the start delay should equal the duration of
6021 * the scrolling animation.
6022 * </p>
6023 *
6024 * <p>
6025 * The animation starts only if at least one of the scrollbars is enabled,
6026 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6027 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6028 * this method returns true, and false otherwise. If the animation is
6029 * started, this method calls {@link #invalidate()}; in that case the caller
6030 * should not call {@link #invalidate()}.
6031 * </p>
6032 *
6033 * <p>
6034 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006035 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006036 * </p>
6037 *
6038 * @param startDelay the delay, in milliseconds, after which the animation
6039 * should start; when the delay is 0, the animation starts
6040 * immediately
6041 * @return true if the animation is played, false otherwise
6042 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006043 * @see #scrollBy(int, int)
6044 * @see #scrollTo(int, int)
6045 * @see #isHorizontalScrollBarEnabled()
6046 * @see #isVerticalScrollBarEnabled()
6047 * @see #setHorizontalScrollBarEnabled(boolean)
6048 * @see #setVerticalScrollBarEnabled(boolean)
6049 */
6050 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006051 return awakenScrollBars(startDelay, true);
6052 }
6053
6054 /**
6055 * <p>
6056 * Trigger the scrollbars to draw. When invoked this method starts an
6057 * animation to fade the scrollbars out after a fixed delay. If a subclass
6058 * provides animated scrolling, the start delay should equal the duration of
6059 * the scrolling animation.
6060 * </p>
6061 *
6062 * <p>
6063 * The animation starts only if at least one of the scrollbars is enabled,
6064 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6065 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6066 * this method returns true, and false otherwise. If the animation is
6067 * started, this method calls {@link #invalidate()} if the invalidate parameter
6068 * is set to true; in that case the caller
6069 * should not call {@link #invalidate()}.
6070 * </p>
6071 *
6072 * <p>
6073 * This method should be invoked everytime a subclass directly updates the
6074 * scroll parameters.
6075 * </p>
6076 *
6077 * @param startDelay the delay, in milliseconds, after which the animation
6078 * should start; when the delay is 0, the animation starts
6079 * immediately
6080 *
6081 * @param invalidate Wheter this method should call invalidate
6082 *
6083 * @return true if the animation is played, false otherwise
6084 *
6085 * @see #scrollBy(int, int)
6086 * @see #scrollTo(int, int)
6087 * @see #isHorizontalScrollBarEnabled()
6088 * @see #isVerticalScrollBarEnabled()
6089 * @see #setHorizontalScrollBarEnabled(boolean)
6090 * @see #setVerticalScrollBarEnabled(boolean)
6091 */
6092 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006093 final ScrollabilityCache scrollCache = mScrollCache;
6094
6095 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6096 return false;
6097 }
6098
6099 if (scrollCache.scrollBar == null) {
6100 scrollCache.scrollBar = new ScrollBarDrawable();
6101 }
6102
6103 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6104
Mike Cleron290947b2009-09-29 18:34:32 -07006105 if (invalidate) {
6106 // Invalidate to show the scrollbars
6107 invalidate();
6108 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006109
6110 if (scrollCache.state == ScrollabilityCache.OFF) {
6111 // FIXME: this is copied from WindowManagerService.
6112 // We should get this value from the system when it
6113 // is possible to do so.
6114 final int KEY_REPEAT_FIRST_DELAY = 750;
6115 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6116 }
6117
6118 // Tell mScrollCache when we should start fading. This may
6119 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006120 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006121 scrollCache.fadeStartTime = fadeStartTime;
6122 scrollCache.state = ScrollabilityCache.ON;
6123
6124 // Schedule our fader to run, unscheduling any old ones first
6125 if (mAttachInfo != null) {
6126 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6127 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6128 }
6129
6130 return true;
6131 }
6132
6133 return false;
6134 }
6135
6136 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 * Mark the the area defined by dirty as needing to be drawn. If the view is
6138 * visible, {@link #onDraw} will be called at some point in the future.
6139 * This must be called from a UI thread. To call from a non-UI thread, call
6140 * {@link #postInvalidate()}.
6141 *
6142 * WARNING: This method is destructive to dirty.
6143 * @param dirty the rectangle representing the bounds of the dirty region
6144 */
6145 public void invalidate(Rect dirty) {
6146 if (ViewDebug.TRACE_HIERARCHY) {
6147 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6148 }
6149
6150 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6151 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6152 final ViewParent p = mParent;
6153 final AttachInfo ai = mAttachInfo;
6154 if (p != null && ai != null) {
6155 final int scrollX = mScrollX;
6156 final int scrollY = mScrollY;
6157 final Rect r = ai.mTmpInvalRect;
6158 r.set(dirty.left - scrollX, dirty.top - scrollY,
6159 dirty.right - scrollX, dirty.bottom - scrollY);
6160 mParent.invalidateChild(this, r);
6161 }
6162 }
6163 }
6164
6165 /**
6166 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6167 * The coordinates of the dirty rect are relative to the view.
6168 * If the view is visible, {@link #onDraw} will be called at some point
6169 * in the future. This must be called from a UI thread. To call
6170 * from a non-UI thread, call {@link #postInvalidate()}.
6171 * @param l the left position of the dirty region
6172 * @param t the top position of the dirty region
6173 * @param r the right position of the dirty region
6174 * @param b the bottom position of the dirty region
6175 */
6176 public void invalidate(int l, int t, int r, int b) {
6177 if (ViewDebug.TRACE_HIERARCHY) {
6178 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6179 }
6180
6181 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6182 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6183 final ViewParent p = mParent;
6184 final AttachInfo ai = mAttachInfo;
6185 if (p != null && ai != null && l < r && t < b) {
6186 final int scrollX = mScrollX;
6187 final int scrollY = mScrollY;
6188 final Rect tmpr = ai.mTmpInvalRect;
6189 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6190 p.invalidateChild(this, tmpr);
6191 }
6192 }
6193 }
6194
6195 /**
6196 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6197 * be called at some point in the future. This must be called from a
6198 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6199 */
6200 public void invalidate() {
6201 if (ViewDebug.TRACE_HIERARCHY) {
6202 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6203 }
6204
6205 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6206 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
6207 final ViewParent p = mParent;
6208 final AttachInfo ai = mAttachInfo;
6209 if (p != null && ai != null) {
6210 final Rect r = ai.mTmpInvalRect;
6211 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6212 // Don't call invalidate -- we don't want to internally scroll
6213 // our own bounds
6214 p.invalidateChild(this, r);
6215 }
6216 }
6217 }
6218
6219 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006220 * Indicates whether this View is opaque. An opaque View guarantees that it will
6221 * draw all the pixels overlapping its bounds using a fully opaque color.
6222 *
6223 * Subclasses of View should override this method whenever possible to indicate
6224 * whether an instance is opaque. Opaque Views are treated in a special way by
6225 * the View hierarchy, possibly allowing it to perform optimizations during
6226 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006227 *
Romain Guy24443ea2009-05-11 11:56:30 -07006228 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006229 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006230 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006231 public boolean isOpaque() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006232 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
6233 }
6234
6235 private void computeOpaqueFlags() {
6236 // Opaque if:
6237 // - Has a background
6238 // - Background is opaque
6239 // - Doesn't have scrollbars or scrollbars are inside overlay
6240
6241 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6242 mPrivateFlags |= OPAQUE_BACKGROUND;
6243 } else {
6244 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6245 }
6246
6247 final int flags = mViewFlags;
6248 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6249 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6250 mPrivateFlags |= OPAQUE_SCROLLBARS;
6251 } else {
6252 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6253 }
6254 }
6255
6256 /**
6257 * @hide
6258 */
6259 protected boolean hasOpaqueScrollbars() {
6260 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006261 }
6262
6263 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 * @return A handler associated with the thread running the View. This
6265 * handler can be used to pump events in the UI events queue.
6266 */
6267 public Handler getHandler() {
6268 if (mAttachInfo != null) {
6269 return mAttachInfo.mHandler;
6270 }
6271 return null;
6272 }
6273
6274 /**
6275 * Causes the Runnable to be added to the message queue.
6276 * The runnable will be run on the user interface thread.
6277 *
6278 * @param action The Runnable that will be executed.
6279 *
6280 * @return Returns true if the Runnable was successfully placed in to the
6281 * message queue. Returns false on failure, usually because the
6282 * looper processing the message queue is exiting.
6283 */
6284 public boolean post(Runnable action) {
6285 Handler handler;
6286 if (mAttachInfo != null) {
6287 handler = mAttachInfo.mHandler;
6288 } else {
6289 // Assume that post will succeed later
6290 ViewRoot.getRunQueue().post(action);
6291 return true;
6292 }
6293
6294 return handler.post(action);
6295 }
6296
6297 /**
6298 * Causes the Runnable to be added to the message queue, to be run
6299 * after the specified amount of time elapses.
6300 * The runnable will be run on the user interface thread.
6301 *
6302 * @param action The Runnable that will be executed.
6303 * @param delayMillis The delay (in milliseconds) until the Runnable
6304 * will be executed.
6305 *
6306 * @return true if the Runnable was successfully placed in to the
6307 * message queue. Returns false on failure, usually because the
6308 * looper processing the message queue is exiting. Note that a
6309 * result of true does not mean the Runnable will be processed --
6310 * if the looper is quit before the delivery time of the message
6311 * occurs then the message will be dropped.
6312 */
6313 public boolean postDelayed(Runnable action, long delayMillis) {
6314 Handler handler;
6315 if (mAttachInfo != null) {
6316 handler = mAttachInfo.mHandler;
6317 } else {
6318 // Assume that post will succeed later
6319 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6320 return true;
6321 }
6322
6323 return handler.postDelayed(action, delayMillis);
6324 }
6325
6326 /**
6327 * Removes the specified Runnable from the message queue.
6328 *
6329 * @param action The Runnable to remove from the message handling queue
6330 *
6331 * @return true if this view could ask the Handler to remove the Runnable,
6332 * false otherwise. When the returned value is true, the Runnable
6333 * may or may not have been actually removed from the message queue
6334 * (for instance, if the Runnable was not in the queue already.)
6335 */
6336 public boolean removeCallbacks(Runnable action) {
6337 Handler handler;
6338 if (mAttachInfo != null) {
6339 handler = mAttachInfo.mHandler;
6340 } else {
6341 // Assume that post will succeed later
6342 ViewRoot.getRunQueue().removeCallbacks(action);
6343 return true;
6344 }
6345
6346 handler.removeCallbacks(action);
6347 return true;
6348 }
6349
6350 /**
6351 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6352 * Use this to invalidate the View from a non-UI thread.
6353 *
6354 * @see #invalidate()
6355 */
6356 public void postInvalidate() {
6357 postInvalidateDelayed(0);
6358 }
6359
6360 /**
6361 * Cause an invalidate of the specified area to happen on a subsequent cycle
6362 * through the event loop. Use this to invalidate the View from a non-UI thread.
6363 *
6364 * @param left The left coordinate of the rectangle to invalidate.
6365 * @param top The top coordinate of the rectangle to invalidate.
6366 * @param right The right coordinate of the rectangle to invalidate.
6367 * @param bottom The bottom coordinate of the rectangle to invalidate.
6368 *
6369 * @see #invalidate(int, int, int, int)
6370 * @see #invalidate(Rect)
6371 */
6372 public void postInvalidate(int left, int top, int right, int bottom) {
6373 postInvalidateDelayed(0, left, top, right, bottom);
6374 }
6375
6376 /**
6377 * Cause an invalidate to happen on a subsequent cycle through the event
6378 * loop. Waits for the specified amount of time.
6379 *
6380 * @param delayMilliseconds the duration in milliseconds to delay the
6381 * invalidation by
6382 */
6383 public void postInvalidateDelayed(long delayMilliseconds) {
6384 // We try only with the AttachInfo because there's no point in invalidating
6385 // if we are not attached to our window
6386 if (mAttachInfo != null) {
6387 Message msg = Message.obtain();
6388 msg.what = AttachInfo.INVALIDATE_MSG;
6389 msg.obj = this;
6390 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6391 }
6392 }
6393
6394 /**
6395 * Cause an invalidate of the specified area to happen on a subsequent cycle
6396 * through the event loop. Waits for the specified amount of time.
6397 *
6398 * @param delayMilliseconds the duration in milliseconds to delay the
6399 * invalidation by
6400 * @param left The left coordinate of the rectangle to invalidate.
6401 * @param top The top coordinate of the rectangle to invalidate.
6402 * @param right The right coordinate of the rectangle to invalidate.
6403 * @param bottom The bottom coordinate of the rectangle to invalidate.
6404 */
6405 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6406 int right, int bottom) {
6407
6408 // We try only with the AttachInfo because there's no point in invalidating
6409 // if we are not attached to our window
6410 if (mAttachInfo != null) {
6411 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6412 info.target = this;
6413 info.left = left;
6414 info.top = top;
6415 info.right = right;
6416 info.bottom = bottom;
6417
6418 final Message msg = Message.obtain();
6419 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6420 msg.obj = info;
6421 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6422 }
6423 }
6424
6425 /**
6426 * Called by a parent to request that a child update its values for mScrollX
6427 * and mScrollY if necessary. This will typically be done if the child is
6428 * animating a scroll using a {@link android.widget.Scroller Scroller}
6429 * object.
6430 */
6431 public void computeScroll() {
6432 }
6433
6434 /**
6435 * <p>Indicate whether the horizontal edges are faded when the view is
6436 * scrolled horizontally.</p>
6437 *
6438 * @return true if the horizontal edges should are faded on scroll, false
6439 * otherwise
6440 *
6441 * @see #setHorizontalFadingEdgeEnabled(boolean)
6442 * @attr ref android.R.styleable#View_fadingEdge
6443 */
6444 public boolean isHorizontalFadingEdgeEnabled() {
6445 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6446 }
6447
6448 /**
6449 * <p>Define whether the horizontal edges should be faded when this view
6450 * is scrolled horizontally.</p>
6451 *
6452 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6453 * be faded when the view is scrolled
6454 * horizontally
6455 *
6456 * @see #isHorizontalFadingEdgeEnabled()
6457 * @attr ref android.R.styleable#View_fadingEdge
6458 */
6459 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6460 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6461 if (horizontalFadingEdgeEnabled) {
6462 initScrollCache();
6463 }
6464
6465 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6466 }
6467 }
6468
6469 /**
6470 * <p>Indicate whether the vertical edges are faded when the view is
6471 * scrolled horizontally.</p>
6472 *
6473 * @return true if the vertical edges should are faded on scroll, false
6474 * otherwise
6475 *
6476 * @see #setVerticalFadingEdgeEnabled(boolean)
6477 * @attr ref android.R.styleable#View_fadingEdge
6478 */
6479 public boolean isVerticalFadingEdgeEnabled() {
6480 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6481 }
6482
6483 /**
6484 * <p>Define whether the vertical edges should be faded when this view
6485 * is scrolled vertically.</p>
6486 *
6487 * @param verticalFadingEdgeEnabled true if the vertical edges should
6488 * be faded when the view is scrolled
6489 * vertically
6490 *
6491 * @see #isVerticalFadingEdgeEnabled()
6492 * @attr ref android.R.styleable#View_fadingEdge
6493 */
6494 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6495 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6496 if (verticalFadingEdgeEnabled) {
6497 initScrollCache();
6498 }
6499
6500 mViewFlags ^= FADING_EDGE_VERTICAL;
6501 }
6502 }
6503
6504 /**
6505 * Returns the strength, or intensity, of the top faded edge. The strength is
6506 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6507 * returns 0.0 or 1.0 but no value in between.
6508 *
6509 * Subclasses should override this method to provide a smoother fade transition
6510 * when scrolling occurs.
6511 *
6512 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6513 */
6514 protected float getTopFadingEdgeStrength() {
6515 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6516 }
6517
6518 /**
6519 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6520 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6521 * returns 0.0 or 1.0 but no value in between.
6522 *
6523 * Subclasses should override this method to provide a smoother fade transition
6524 * when scrolling occurs.
6525 *
6526 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6527 */
6528 protected float getBottomFadingEdgeStrength() {
6529 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6530 computeVerticalScrollRange() ? 1.0f : 0.0f;
6531 }
6532
6533 /**
6534 * Returns the strength, or intensity, of the left faded edge. The strength is
6535 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6536 * returns 0.0 or 1.0 but no value in between.
6537 *
6538 * Subclasses should override this method to provide a smoother fade transition
6539 * when scrolling occurs.
6540 *
6541 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6542 */
6543 protected float getLeftFadingEdgeStrength() {
6544 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6545 }
6546
6547 /**
6548 * Returns the strength, or intensity, of the right faded edge. The strength is
6549 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6550 * returns 0.0 or 1.0 but no value in between.
6551 *
6552 * Subclasses should override this method to provide a smoother fade transition
6553 * when scrolling occurs.
6554 *
6555 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6556 */
6557 protected float getRightFadingEdgeStrength() {
6558 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6559 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6560 }
6561
6562 /**
6563 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6564 * scrollbar is not drawn by default.</p>
6565 *
6566 * @return true if the horizontal scrollbar should be painted, false
6567 * otherwise
6568 *
6569 * @see #setHorizontalScrollBarEnabled(boolean)
6570 */
6571 public boolean isHorizontalScrollBarEnabled() {
6572 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6573 }
6574
6575 /**
6576 * <p>Define whether the horizontal scrollbar should be drawn or not. The
6577 * scrollbar is not drawn by default.</p>
6578 *
6579 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
6580 * be painted
6581 *
6582 * @see #isHorizontalScrollBarEnabled()
6583 */
6584 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
6585 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
6586 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006587 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 recomputePadding();
6589 }
6590 }
6591
6592 /**
6593 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
6594 * scrollbar is not drawn by default.</p>
6595 *
6596 * @return true if the vertical scrollbar should be painted, false
6597 * otherwise
6598 *
6599 * @see #setVerticalScrollBarEnabled(boolean)
6600 */
6601 public boolean isVerticalScrollBarEnabled() {
6602 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
6603 }
6604
6605 /**
6606 * <p>Define whether the vertical scrollbar should be drawn or not. The
6607 * scrollbar is not drawn by default.</p>
6608 *
6609 * @param verticalScrollBarEnabled true if the vertical scrollbar should
6610 * be painted
6611 *
6612 * @see #isVerticalScrollBarEnabled()
6613 */
6614 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
6615 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
6616 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006617 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 recomputePadding();
6619 }
6620 }
6621
6622 private void recomputePadding() {
6623 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
6624 }
Mike Cleronfe81d382009-09-28 14:22:16 -07006625
6626 /**
6627 * Define whether scrollbars will fade when the view is not scrolling.
6628 *
6629 * @param fadeScrollbars wheter to enable fading
6630 *
6631 */
6632 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
6633 initScrollCache();
6634 final ScrollabilityCache scrollabilityCache = mScrollCache;
6635 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07006636 if (fadeScrollbars) {
6637 scrollabilityCache.state = ScrollabilityCache.OFF;
6638 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07006639 scrollabilityCache.state = ScrollabilityCache.ON;
6640 }
6641 }
6642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006643 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07006644 *
6645 * Returns true if scrollbars will fade when this view is not scrolling
6646 *
6647 * @return true if scrollbar fading is enabled
6648 */
6649 public boolean isScrollbarFadingEnabled() {
6650 return mScrollCache != null && mScrollCache.fadeScrollBars;
6651 }
6652
6653 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006654 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
6655 * inset. When inset, they add to the padding of the view. And the scrollbars
6656 * can be drawn inside the padding area or on the edge of the view. For example,
6657 * if a view has a background drawable and you want to draw the scrollbars
6658 * inside the padding specified by the drawable, you can use
6659 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
6660 * appear at the edge of the view, ignoring the padding, then you can use
6661 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
6662 * @param style the style of the scrollbars. Should be one of
6663 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
6664 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
6665 * @see #SCROLLBARS_INSIDE_OVERLAY
6666 * @see #SCROLLBARS_INSIDE_INSET
6667 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6668 * @see #SCROLLBARS_OUTSIDE_INSET
6669 */
6670 public void setScrollBarStyle(int style) {
6671 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
6672 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07006673 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 recomputePadding();
6675 }
6676 }
6677
6678 /**
6679 * <p>Returns the current scrollbar style.</p>
6680 * @return the current scrollbar style
6681 * @see #SCROLLBARS_INSIDE_OVERLAY
6682 * @see #SCROLLBARS_INSIDE_INSET
6683 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6684 * @see #SCROLLBARS_OUTSIDE_INSET
6685 */
6686 public int getScrollBarStyle() {
6687 return mViewFlags & SCROLLBARS_STYLE_MASK;
6688 }
6689
6690 /**
6691 * <p>Compute the horizontal range that the horizontal scrollbar
6692 * represents.</p>
6693 *
6694 * <p>The range is expressed in arbitrary units that must be the same as the
6695 * units used by {@link #computeHorizontalScrollExtent()} and
6696 * {@link #computeHorizontalScrollOffset()}.</p>
6697 *
6698 * <p>The default range is the drawing width of this view.</p>
6699 *
6700 * @return the total horizontal range represented by the horizontal
6701 * scrollbar
6702 *
6703 * @see #computeHorizontalScrollExtent()
6704 * @see #computeHorizontalScrollOffset()
6705 * @see android.widget.ScrollBarDrawable
6706 */
6707 protected int computeHorizontalScrollRange() {
6708 return getWidth();
6709 }
6710
6711 /**
6712 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
6713 * within the horizontal range. This value is used to compute the position
6714 * of the thumb within the scrollbar's track.</p>
6715 *
6716 * <p>The range is expressed in arbitrary units that must be the same as the
6717 * units used by {@link #computeHorizontalScrollRange()} and
6718 * {@link #computeHorizontalScrollExtent()}.</p>
6719 *
6720 * <p>The default offset is the scroll offset of this view.</p>
6721 *
6722 * @return the horizontal offset of the scrollbar's thumb
6723 *
6724 * @see #computeHorizontalScrollRange()
6725 * @see #computeHorizontalScrollExtent()
6726 * @see android.widget.ScrollBarDrawable
6727 */
6728 protected int computeHorizontalScrollOffset() {
6729 return mScrollX;
6730 }
6731
6732 /**
6733 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
6734 * within the horizontal range. This value is used to compute the length
6735 * of the thumb within the scrollbar's track.</p>
6736 *
6737 * <p>The range is expressed in arbitrary units that must be the same as the
6738 * units used by {@link #computeHorizontalScrollRange()} and
6739 * {@link #computeHorizontalScrollOffset()}.</p>
6740 *
6741 * <p>The default extent is the drawing width of this view.</p>
6742 *
6743 * @return the horizontal extent of the scrollbar's thumb
6744 *
6745 * @see #computeHorizontalScrollRange()
6746 * @see #computeHorizontalScrollOffset()
6747 * @see android.widget.ScrollBarDrawable
6748 */
6749 protected int computeHorizontalScrollExtent() {
6750 return getWidth();
6751 }
6752
6753 /**
6754 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
6755 *
6756 * <p>The range is expressed in arbitrary units that must be the same as the
6757 * units used by {@link #computeVerticalScrollExtent()} and
6758 * {@link #computeVerticalScrollOffset()}.</p>
6759 *
6760 * @return the total vertical range represented by the vertical scrollbar
6761 *
6762 * <p>The default range is the drawing height of this view.</p>
6763 *
6764 * @see #computeVerticalScrollExtent()
6765 * @see #computeVerticalScrollOffset()
6766 * @see android.widget.ScrollBarDrawable
6767 */
6768 protected int computeVerticalScrollRange() {
6769 return getHeight();
6770 }
6771
6772 /**
6773 * <p>Compute the vertical offset of the vertical scrollbar's thumb
6774 * within the horizontal range. This value is used to compute the position
6775 * of the thumb within the scrollbar's track.</p>
6776 *
6777 * <p>The range is expressed in arbitrary units that must be the same as the
6778 * units used by {@link #computeVerticalScrollRange()} and
6779 * {@link #computeVerticalScrollExtent()}.</p>
6780 *
6781 * <p>The default offset is the scroll offset of this view.</p>
6782 *
6783 * @return the vertical offset of the scrollbar's thumb
6784 *
6785 * @see #computeVerticalScrollRange()
6786 * @see #computeVerticalScrollExtent()
6787 * @see android.widget.ScrollBarDrawable
6788 */
6789 protected int computeVerticalScrollOffset() {
6790 return mScrollY;
6791 }
6792
6793 /**
6794 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
6795 * within the vertical range. This value is used to compute the length
6796 * of the thumb within the scrollbar's track.</p>
6797 *
6798 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08006799 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006800 * {@link #computeVerticalScrollOffset()}.</p>
6801 *
6802 * <p>The default extent is the drawing height of this view.</p>
6803 *
6804 * @return the vertical extent of the scrollbar's thumb
6805 *
6806 * @see #computeVerticalScrollRange()
6807 * @see #computeVerticalScrollOffset()
6808 * @see android.widget.ScrollBarDrawable
6809 */
6810 protected int computeVerticalScrollExtent() {
6811 return getHeight();
6812 }
6813
6814 /**
6815 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
6816 * scrollbars are painted only if they have been awakened first.</p>
6817 *
6818 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07006819 *
6820 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006821 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08006822 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006823 // scrollbars are drawn only when the animation is running
6824 final ScrollabilityCache cache = mScrollCache;
6825 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006826
6827 int state = cache.state;
6828
6829 if (state == ScrollabilityCache.OFF) {
6830 return;
6831 }
6832
6833 boolean invalidate = false;
6834
6835 if (state == ScrollabilityCache.FADING) {
6836 // We're fading -- get our fade interpolation
6837 if (cache.interpolatorValues == null) {
6838 cache.interpolatorValues = new float[1];
6839 }
6840
6841 float[] values = cache.interpolatorValues;
6842
6843 // Stops the animation if we're done
6844 if (cache.scrollBarInterpolator.timeToValues(values) ==
6845 Interpolator.Result.FREEZE_END) {
6846 cache.state = ScrollabilityCache.OFF;
6847 } else {
6848 cache.scrollBar.setAlpha(Math.round(values[0]));
6849 }
6850
6851 // This will make the scroll bars inval themselves after
6852 // drawing. We only want this when we're fading so that
6853 // we prevent excessive redraws
6854 invalidate = true;
6855 } else {
6856 // We're just on -- but we may have been fading before so
6857 // reset alpha
6858 cache.scrollBar.setAlpha(255);
6859 }
6860
6861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 final int viewFlags = mViewFlags;
6863
6864 final boolean drawHorizontalScrollBar =
6865 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6866 final boolean drawVerticalScrollBar =
6867 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
6868 && !isVerticalScrollBarHidden();
6869
6870 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
6871 final int width = mRight - mLeft;
6872 final int height = mBottom - mTop;
6873
6874 final ScrollBarDrawable scrollBar = cache.scrollBar;
6875 int size = scrollBar.getSize(false);
6876 if (size <= 0) {
6877 size = cache.scrollBarSize;
6878 }
6879
Mike Reede8853fc2009-09-04 14:01:48 -04006880 final int scrollX = mScrollX;
6881 final int scrollY = mScrollY;
6882 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
6883
Mike Cleronf116bf82009-09-27 19:14:12 -07006884 int left, top, right, bottom;
6885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006887 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04006888 computeHorizontalScrollOffset(),
6889 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04006890 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07006891 getVerticalScrollbarWidth() : 0;
6892 top = scrollY + height - size - (mUserPaddingBottom & inside);
6893 left = scrollX + (mPaddingLeft & inside);
6894 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
6895 bottom = top + size;
6896 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
6897 if (invalidate) {
6898 invalidate(left, top, right, bottom);
6899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006900 }
6901
6902 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04006903 scrollBar.setParameters(computeVerticalScrollRange(),
6904 computeVerticalScrollOffset(),
6905 computeVerticalScrollExtent(), true);
6906 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07006907 left = scrollX + width - size - (mUserPaddingRight & inside);
6908 top = scrollY + (mPaddingTop & inside);
6909 right = left + size;
6910 bottom = scrollY + height - (mUserPaddingBottom & inside);
6911 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
6912 if (invalidate) {
6913 invalidate(left, top, right, bottom);
6914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006915 }
6916 }
6917 }
6918 }
Romain Guy8506ab42009-06-11 17:35:47 -07006919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006920 /**
Romain Guy8506ab42009-06-11 17:35:47 -07006921 * 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 -08006922 * FastScroller is visible.
6923 * @return whether to temporarily hide the vertical scrollbar
6924 * @hide
6925 */
6926 protected boolean isVerticalScrollBarHidden() {
6927 return false;
6928 }
6929
6930 /**
6931 * <p>Draw the horizontal scrollbar if
6932 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
6933 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006934 * @param canvas the canvas on which to draw the scrollbar
6935 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006936 *
6937 * @see #isHorizontalScrollBarEnabled()
6938 * @see #computeHorizontalScrollRange()
6939 * @see #computeHorizontalScrollExtent()
6940 * @see #computeHorizontalScrollOffset()
6941 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07006942 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006943 */
Romain Guy8fb95422010-08-17 18:38:51 -07006944 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
6945 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006946 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006947 scrollBar.draw(canvas);
6948 }
Mike Reede8853fc2009-09-04 14:01:48 -04006949
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006950 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
6952 * returns true.</p>
6953 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006954 * @param canvas the canvas on which to draw the scrollbar
6955 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006956 *
6957 * @see #isVerticalScrollBarEnabled()
6958 * @see #computeVerticalScrollRange()
6959 * @see #computeVerticalScrollExtent()
6960 * @see #computeVerticalScrollOffset()
6961 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04006962 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006963 */
Romain Guy8fb95422010-08-17 18:38:51 -07006964 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
6965 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04006966 scrollBar.setBounds(l, t, r, b);
6967 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006968 }
6969
6970 /**
6971 * Implement this to do your drawing.
6972 *
6973 * @param canvas the canvas on which the background will be drawn
6974 */
6975 protected void onDraw(Canvas canvas) {
6976 }
6977
6978 /*
6979 * Caller is responsible for calling requestLayout if necessary.
6980 * (This allows addViewInLayout to not request a new layout.)
6981 */
6982 void assignParent(ViewParent parent) {
6983 if (mParent == null) {
6984 mParent = parent;
6985 } else if (parent == null) {
6986 mParent = null;
6987 } else {
6988 throw new RuntimeException("view " + this + " being added, but"
6989 + " it already has a parent");
6990 }
6991 }
6992
6993 /**
6994 * This is called when the view is attached to a window. At this point it
6995 * has a Surface and will start drawing. Note that this function is
6996 * guaranteed to be called before {@link #onDraw}, however it may be called
6997 * any time before the first onDraw -- including before or after
6998 * {@link #onMeasure}.
6999 *
7000 * @see #onDetachedFromWindow()
7001 */
7002 protected void onAttachedToWindow() {
7003 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7004 mParent.requestTransparentRegion(this);
7005 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007006 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7007 initialAwakenScrollBars();
7008 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007010 }
7011
7012 /**
7013 * This is called when the view is detached from a window. At this point it
7014 * no longer has a surface for drawing.
7015 *
7016 * @see #onAttachedToWindow()
7017 */
7018 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007019 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08007020 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007021 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 destroyDrawingCache();
7023 }
7024
7025 /**
7026 * @return The number of times this view has been attached to a window
7027 */
7028 protected int getWindowAttachCount() {
7029 return mWindowAttachCount;
7030 }
7031
7032 /**
7033 * Retrieve a unique token identifying the window this view is attached to.
7034 * @return Return the window's token for use in
7035 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7036 */
7037 public IBinder getWindowToken() {
7038 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7039 }
7040
7041 /**
7042 * Retrieve a unique token identifying the top-level "real" window of
7043 * the window that this view is attached to. That is, this is like
7044 * {@link #getWindowToken}, except if the window this view in is a panel
7045 * window (attached to another containing window), then the token of
7046 * the containing window is returned instead.
7047 *
7048 * @return Returns the associated window token, either
7049 * {@link #getWindowToken()} or the containing window's token.
7050 */
7051 public IBinder getApplicationWindowToken() {
7052 AttachInfo ai = mAttachInfo;
7053 if (ai != null) {
7054 IBinder appWindowToken = ai.mPanelParentWindowToken;
7055 if (appWindowToken == null) {
7056 appWindowToken = ai.mWindowToken;
7057 }
7058 return appWindowToken;
7059 }
7060 return null;
7061 }
7062
7063 /**
7064 * Retrieve private session object this view hierarchy is using to
7065 * communicate with the window manager.
7066 * @return the session object to communicate with the window manager
7067 */
7068 /*package*/ IWindowSession getWindowSession() {
7069 return mAttachInfo != null ? mAttachInfo.mSession : null;
7070 }
7071
7072 /**
7073 * @param info the {@link android.view.View.AttachInfo} to associated with
7074 * this view
7075 */
7076 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7077 //System.out.println("Attached! " + this);
7078 mAttachInfo = info;
7079 mWindowAttachCount++;
7080 if (mFloatingTreeObserver != null) {
7081 info.mTreeObserver.merge(mFloatingTreeObserver);
7082 mFloatingTreeObserver = null;
7083 }
7084 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7085 mAttachInfo.mScrollContainers.add(this);
7086 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7087 }
7088 performCollectViewAttributes(visibility);
7089 onAttachedToWindow();
7090 int vis = info.mWindowVisibility;
7091 if (vis != GONE) {
7092 onWindowVisibilityChanged(vis);
7093 }
7094 }
7095
7096 void dispatchDetachedFromWindow() {
7097 //System.out.println("Detached! " + this);
7098 AttachInfo info = mAttachInfo;
7099 if (info != null) {
7100 int vis = info.mWindowVisibility;
7101 if (vis != GONE) {
7102 onWindowVisibilityChanged(GONE);
7103 }
7104 }
7105
7106 onDetachedFromWindow();
7107 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7108 mAttachInfo.mScrollContainers.remove(this);
7109 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7110 }
7111 mAttachInfo = null;
7112 }
7113
7114 /**
7115 * Store this view hierarchy's frozen state into the given container.
7116 *
7117 * @param container The SparseArray in which to save the view's state.
7118 *
7119 * @see #restoreHierarchyState
7120 * @see #dispatchSaveInstanceState
7121 * @see #onSaveInstanceState
7122 */
7123 public void saveHierarchyState(SparseArray<Parcelable> container) {
7124 dispatchSaveInstanceState(container);
7125 }
7126
7127 /**
7128 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7129 * May be overridden to modify how freezing happens to a view's children; for example, some
7130 * views may want to not store state for their children.
7131 *
7132 * @param container The SparseArray in which to save the view's state.
7133 *
7134 * @see #dispatchRestoreInstanceState
7135 * @see #saveHierarchyState
7136 * @see #onSaveInstanceState
7137 */
7138 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7139 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7140 mPrivateFlags &= ~SAVE_STATE_CALLED;
7141 Parcelable state = onSaveInstanceState();
7142 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7143 throw new IllegalStateException(
7144 "Derived class did not call super.onSaveInstanceState()");
7145 }
7146 if (state != null) {
7147 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7148 // + ": " + state);
7149 container.put(mID, state);
7150 }
7151 }
7152 }
7153
7154 /**
7155 * Hook allowing a view to generate a representation of its internal state
7156 * that can later be used to create a new instance with that same state.
7157 * This state should only contain information that is not persistent or can
7158 * not be reconstructed later. For example, you will never store your
7159 * current position on screen because that will be computed again when a
7160 * new instance of the view is placed in its view hierarchy.
7161 * <p>
7162 * Some examples of things you may store here: the current cursor position
7163 * in a text view (but usually not the text itself since that is stored in a
7164 * content provider or other persistent storage), the currently selected
7165 * item in a list view.
7166 *
7167 * @return Returns a Parcelable object containing the view's current dynamic
7168 * state, or null if there is nothing interesting to save. The
7169 * default implementation returns null.
7170 * @see #onRestoreInstanceState
7171 * @see #saveHierarchyState
7172 * @see #dispatchSaveInstanceState
7173 * @see #setSaveEnabled(boolean)
7174 */
7175 protected Parcelable onSaveInstanceState() {
7176 mPrivateFlags |= SAVE_STATE_CALLED;
7177 return BaseSavedState.EMPTY_STATE;
7178 }
7179
7180 /**
7181 * Restore this view hierarchy's frozen state from the given container.
7182 *
7183 * @param container The SparseArray which holds previously frozen states.
7184 *
7185 * @see #saveHierarchyState
7186 * @see #dispatchRestoreInstanceState
7187 * @see #onRestoreInstanceState
7188 */
7189 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7190 dispatchRestoreInstanceState(container);
7191 }
7192
7193 /**
7194 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7195 * children. May be overridden to modify how restoreing happens to a view's children; for
7196 * example, some views may want to not store state for their children.
7197 *
7198 * @param container The SparseArray which holds previously saved state.
7199 *
7200 * @see #dispatchSaveInstanceState
7201 * @see #restoreHierarchyState
7202 * @see #onRestoreInstanceState
7203 */
7204 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7205 if (mID != NO_ID) {
7206 Parcelable state = container.get(mID);
7207 if (state != null) {
7208 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7209 // + ": " + state);
7210 mPrivateFlags &= ~SAVE_STATE_CALLED;
7211 onRestoreInstanceState(state);
7212 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7213 throw new IllegalStateException(
7214 "Derived class did not call super.onRestoreInstanceState()");
7215 }
7216 }
7217 }
7218 }
7219
7220 /**
7221 * Hook allowing a view to re-apply a representation of its internal state that had previously
7222 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7223 * null state.
7224 *
7225 * @param state The frozen state that had previously been returned by
7226 * {@link #onSaveInstanceState}.
7227 *
7228 * @see #onSaveInstanceState
7229 * @see #restoreHierarchyState
7230 * @see #dispatchRestoreInstanceState
7231 */
7232 protected void onRestoreInstanceState(Parcelable state) {
7233 mPrivateFlags |= SAVE_STATE_CALLED;
7234 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007235 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7236 + "received " + state.getClass().toString() + " instead. This usually happens "
7237 + "when two views of different type have the same id in the same hierarchy. "
7238 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7239 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007240 }
7241 }
7242
7243 /**
7244 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7245 *
7246 * @return the drawing start time in milliseconds
7247 */
7248 public long getDrawingTime() {
7249 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7250 }
7251
7252 /**
7253 * <p>Enables or disables the duplication of the parent's state into this view. When
7254 * duplication is enabled, this view gets its drawable state from its parent rather
7255 * than from its own internal properties.</p>
7256 *
7257 * <p>Note: in the current implementation, setting this property to true after the
7258 * view was added to a ViewGroup might have no effect at all. This property should
7259 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7260 *
7261 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7262 * property is enabled, an exception will be thrown.</p>
7263 *
7264 * @param enabled True to enable duplication of the parent's drawable state, false
7265 * to disable it.
7266 *
7267 * @see #getDrawableState()
7268 * @see #isDuplicateParentStateEnabled()
7269 */
7270 public void setDuplicateParentStateEnabled(boolean enabled) {
7271 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7272 }
7273
7274 /**
7275 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7276 *
7277 * @return True if this view's drawable state is duplicated from the parent,
7278 * false otherwise
7279 *
7280 * @see #getDrawableState()
7281 * @see #setDuplicateParentStateEnabled(boolean)
7282 */
7283 public boolean isDuplicateParentStateEnabled() {
7284 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7285 }
7286
7287 /**
7288 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
7289 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
7290 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
7291 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
7292 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
7293 * null.</p>
7294 *
7295 * @param enabled true to enable the drawing cache, false otherwise
7296 *
7297 * @see #isDrawingCacheEnabled()
7298 * @see #getDrawingCache()
7299 * @see #buildDrawingCache()
7300 */
7301 public void setDrawingCacheEnabled(boolean enabled) {
7302 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
7303 }
7304
7305 /**
7306 * <p>Indicates whether the drawing cache is enabled for this view.</p>
7307 *
7308 * @return true if the drawing cache is enabled
7309 *
7310 * @see #setDrawingCacheEnabled(boolean)
7311 * @see #getDrawingCache()
7312 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07007313 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 public boolean isDrawingCacheEnabled() {
7315 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
7316 }
7317
7318 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007319 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
7320 *
7321 * @return A non-scaled bitmap representing this view or null if cache is disabled.
7322 *
7323 * @see #getDrawingCache(boolean)
7324 */
7325 public Bitmap getDrawingCache() {
7326 return getDrawingCache(false);
7327 }
7328
7329 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
7331 * is null when caching is disabled. If caching is enabled and the cache is not ready,
7332 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
7333 * draw from the cache when the cache is enabled. To benefit from the cache, you must
7334 * request the drawing cache by calling this method and draw it on screen if the
7335 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007336 *
7337 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7338 * this method will create a bitmap of the same size as this view. Because this bitmap
7339 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7340 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7341 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7342 * size than the view. This implies that your application must be able to handle this
7343 * size.</p>
7344 *
7345 * @param autoScale Indicates whether the generated bitmap should be scaled based on
7346 * the current density of the screen when the application is in compatibility
7347 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007348 *
Romain Guyfbd8f692009-06-26 14:51:58 -07007349 * @return A bitmap representing this view or null if cache is disabled.
7350 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 * @see #setDrawingCacheEnabled(boolean)
7352 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07007353 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007354 * @see #destroyDrawingCache()
7355 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007356 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007357 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7358 return null;
7359 }
7360 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007361 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007362 }
Romain Guy02890fd2010-08-06 17:58:44 -07007363 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007364 }
7365
7366 /**
7367 * <p>Frees the resources used by the drawing cache. If you call
7368 * {@link #buildDrawingCache()} manually without calling
7369 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7370 * should cleanup the cache with this method afterwards.</p>
7371 *
7372 * @see #setDrawingCacheEnabled(boolean)
7373 * @see #buildDrawingCache()
7374 * @see #getDrawingCache()
7375 */
7376 public void destroyDrawingCache() {
7377 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007378 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007379 mDrawingCache = null;
7380 }
Romain Guyfbd8f692009-06-26 14:51:58 -07007381 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007382 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07007383 mUnscaledDrawingCache = null;
7384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007385 }
7386
7387 /**
7388 * Setting a solid background color for the drawing cache's bitmaps will improve
7389 * perfromance and memory usage. Note, though that this should only be used if this
7390 * view will always be drawn on top of a solid color.
7391 *
7392 * @param color The background color to use for the drawing cache's bitmap
7393 *
7394 * @see #setDrawingCacheEnabled(boolean)
7395 * @see #buildDrawingCache()
7396 * @see #getDrawingCache()
7397 */
7398 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08007399 if (color != mDrawingCacheBackgroundColor) {
7400 mDrawingCacheBackgroundColor = color;
7401 mPrivateFlags &= ~DRAWING_CACHE_VALID;
7402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007403 }
7404
7405 /**
7406 * @see #setDrawingCacheBackgroundColor(int)
7407 *
7408 * @return The background color to used for the drawing cache's bitmap
7409 */
7410 public int getDrawingCacheBackgroundColor() {
7411 return mDrawingCacheBackgroundColor;
7412 }
7413
7414 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007415 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
7416 *
7417 * @see #buildDrawingCache(boolean)
7418 */
7419 public void buildDrawingCache() {
7420 buildDrawingCache(false);
7421 }
7422
7423 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007424 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
7425 *
7426 * <p>If you call {@link #buildDrawingCache()} manually without calling
7427 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7428 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007429 *
7430 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7431 * this method will create a bitmap of the same size as this view. Because this bitmap
7432 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7433 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7434 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7435 * size than the view. This implies that your application must be able to handle this
7436 * size.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007437 *
7438 * @see #getDrawingCache()
7439 * @see #destroyDrawingCache()
7440 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007441 public void buildDrawingCache(boolean autoScale) {
7442 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07007443 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007444
7445 if (ViewDebug.TRACE_HIERARCHY) {
7446 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007448
Romain Guy8506ab42009-06-11 17:35:47 -07007449 int width = mRight - mLeft;
7450 int height = mBottom - mTop;
7451
7452 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007453 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007454
Romain Guye1123222009-06-29 14:24:56 -07007455 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007456 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7457 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007459
7460 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007461 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Romain Guya62e4702009-10-08 10:48:54 -07007462 final boolean translucentWindow = attachInfo != null && attachInfo.mTranslucentWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007463
7464 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007465 // Projected bitmap size in bytes
7466 (width * height * (opaque && !translucentWindow ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007467 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7468 destroyDrawingCache();
7469 return;
7470 }
7471
7472 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07007473 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474
7475 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007476 Bitmap.Config quality;
7477 if (!opaque) {
7478 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7479 case DRAWING_CACHE_QUALITY_AUTO:
7480 quality = Bitmap.Config.ARGB_8888;
7481 break;
7482 case DRAWING_CACHE_QUALITY_LOW:
7483 quality = Bitmap.Config.ARGB_4444;
7484 break;
7485 case DRAWING_CACHE_QUALITY_HIGH:
7486 quality = Bitmap.Config.ARGB_8888;
7487 break;
7488 default:
7489 quality = Bitmap.Config.ARGB_8888;
7490 break;
7491 }
7492 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07007493 // Optimization for translucent windows
7494 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
7495 quality = translucentWindow ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007496 }
7497
7498 // Try to cleanup memory
7499 if (bitmap != null) bitmap.recycle();
7500
7501 try {
7502 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07007503 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07007504 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07007505 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007506 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07007507 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007508 }
Romain Guy35b38ce2009-10-07 13:38:55 -07007509 if (opaque && translucentWindow) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007510 } catch (OutOfMemoryError e) {
7511 // If there is not enough memory to create the bitmap cache, just
7512 // ignore the issue as bitmap caches are not required to draw the
7513 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07007514 if (autoScale) {
7515 mDrawingCache = null;
7516 } else {
7517 mUnscaledDrawingCache = null;
7518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007519 return;
7520 }
7521
7522 clear = drawingCacheBackgroundColor != 0;
7523 }
7524
7525 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007526 if (attachInfo != null) {
7527 canvas = attachInfo.mCanvas;
7528 if (canvas == null) {
7529 canvas = new Canvas();
7530 }
7531 canvas.setBitmap(bitmap);
7532 // Temporarily clobber the cached Canvas in case one of our children
7533 // is also using a drawing cache. Without this, the children would
7534 // steal the canvas by attaching their own bitmap to it and bad, bad
7535 // thing would happen (invisible views, corrupted drawings, etc.)
7536 attachInfo.mCanvas = null;
7537 } else {
7538 // This case should hopefully never or seldom happen
7539 canvas = new Canvas(bitmap);
7540 }
7541
7542 if (clear) {
7543 bitmap.eraseColor(drawingCacheBackgroundColor);
7544 }
7545
7546 computeScroll();
7547 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07007548
Romain Guye1123222009-06-29 14:24:56 -07007549 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007550 final float scale = attachInfo.mApplicationScale;
7551 canvas.scale(scale, scale);
7552 }
7553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554 canvas.translate(-mScrollX, -mScrollY);
7555
Romain Guy5bcdff42009-05-14 21:27:18 -07007556 mPrivateFlags |= DRAWN;
Romain Guyecd80ee2009-12-03 17:13:02 -08007557 mPrivateFlags |= DRAWING_CACHE_VALID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007558
7559 // Fast path for layouts with no backgrounds
7560 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7561 if (ViewDebug.TRACE_HIERARCHY) {
7562 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7563 }
Romain Guy5bcdff42009-05-14 21:27:18 -07007564 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007565 dispatchDraw(canvas);
7566 } else {
7567 draw(canvas);
7568 }
7569
7570 canvas.restoreToCount(restoreCount);
7571
7572 if (attachInfo != null) {
7573 // Restore the cached Canvas for our siblings
7574 attachInfo.mCanvas = canvas;
7575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007576 }
7577 }
7578
7579 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007580 * Create a snapshot of the view into a bitmap. We should probably make
7581 * some form of this public, but should think about the API.
7582 */
Romain Guy223ff5c2010-03-02 17:07:47 -08007583 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007584 int width = mRight - mLeft;
7585 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007586
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007587 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07007588 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007589 width = (int) ((width * scale) + 0.5f);
7590 height = (int) ((height * scale) + 0.5f);
7591
Romain Guy8c11e312009-09-14 15:15:30 -07007592 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007593 if (bitmap == null) {
7594 throw new OutOfMemoryError();
7595 }
7596
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007597 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
7598
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007599 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007600 if (attachInfo != null) {
7601 canvas = attachInfo.mCanvas;
7602 if (canvas == null) {
7603 canvas = new Canvas();
7604 }
7605 canvas.setBitmap(bitmap);
7606 // Temporarily clobber the cached Canvas in case one of our children
7607 // is also using a drawing cache. Without this, the children would
7608 // steal the canvas by attaching their own bitmap to it and bad, bad
7609 // things would happen (invisible views, corrupted drawings, etc.)
7610 attachInfo.mCanvas = null;
7611 } else {
7612 // This case should hopefully never or seldom happen
7613 canvas = new Canvas(bitmap);
7614 }
7615
Romain Guy5bcdff42009-05-14 21:27:18 -07007616 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007617 bitmap.eraseColor(backgroundColor);
7618 }
7619
7620 computeScroll();
7621 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007622 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007623 canvas.translate(-mScrollX, -mScrollY);
7624
Romain Guy5bcdff42009-05-14 21:27:18 -07007625 // Temporarily remove the dirty mask
7626 int flags = mPrivateFlags;
7627 mPrivateFlags &= ~DIRTY_MASK;
7628
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007629 // Fast path for layouts with no backgrounds
7630 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7631 dispatchDraw(canvas);
7632 } else {
7633 draw(canvas);
7634 }
7635
Romain Guy5bcdff42009-05-14 21:27:18 -07007636 mPrivateFlags = flags;
7637
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007638 canvas.restoreToCount(restoreCount);
7639
7640 if (attachInfo != null) {
7641 // Restore the cached Canvas for our siblings
7642 attachInfo.mCanvas = canvas;
7643 }
Romain Guy8506ab42009-06-11 17:35:47 -07007644
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007645 return bitmap;
7646 }
7647
7648 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 * Indicates whether this View is currently in edit mode. A View is usually
7650 * in edit mode when displayed within a developer tool. For instance, if
7651 * this View is being drawn by a visual user interface builder, this method
7652 * should return true.
7653 *
7654 * Subclasses should check the return value of this method to provide
7655 * different behaviors if their normal behavior might interfere with the
7656 * host environment. For instance: the class spawns a thread in its
7657 * constructor, the drawing code relies on device-specific features, etc.
7658 *
7659 * This method is usually checked in the drawing code of custom widgets.
7660 *
7661 * @return True if this View is in edit mode, false otherwise.
7662 */
7663 public boolean isInEditMode() {
7664 return false;
7665 }
7666
7667 /**
7668 * If the View draws content inside its padding and enables fading edges,
7669 * it needs to support padding offsets. Padding offsets are added to the
7670 * fading edges to extend the length of the fade so that it covers pixels
7671 * drawn inside the padding.
7672 *
7673 * Subclasses of this class should override this method if they need
7674 * to draw content inside the padding.
7675 *
7676 * @return True if padding offset must be applied, false otherwise.
7677 *
7678 * @see #getLeftPaddingOffset()
7679 * @see #getRightPaddingOffset()
7680 * @see #getTopPaddingOffset()
7681 * @see #getBottomPaddingOffset()
7682 *
7683 * @since CURRENT
7684 */
7685 protected boolean isPaddingOffsetRequired() {
7686 return false;
7687 }
7688
7689 /**
7690 * Amount by which to extend the left fading region. Called only when
7691 * {@link #isPaddingOffsetRequired()} returns true.
7692 *
7693 * @return The left padding offset in pixels.
7694 *
7695 * @see #isPaddingOffsetRequired()
7696 *
7697 * @since CURRENT
7698 */
7699 protected int getLeftPaddingOffset() {
7700 return 0;
7701 }
7702
7703 /**
7704 * Amount by which to extend the right fading region. Called only when
7705 * {@link #isPaddingOffsetRequired()} returns true.
7706 *
7707 * @return The right padding offset in pixels.
7708 *
7709 * @see #isPaddingOffsetRequired()
7710 *
7711 * @since CURRENT
7712 */
7713 protected int getRightPaddingOffset() {
7714 return 0;
7715 }
7716
7717 /**
7718 * Amount by which to extend the top fading region. Called only when
7719 * {@link #isPaddingOffsetRequired()} returns true.
7720 *
7721 * @return The top padding offset in pixels.
7722 *
7723 * @see #isPaddingOffsetRequired()
7724 *
7725 * @since CURRENT
7726 */
7727 protected int getTopPaddingOffset() {
7728 return 0;
7729 }
7730
7731 /**
7732 * Amount by which to extend the bottom fading region. Called only when
7733 * {@link #isPaddingOffsetRequired()} returns true.
7734 *
7735 * @return The bottom padding offset in pixels.
7736 *
7737 * @see #isPaddingOffsetRequired()
7738 *
7739 * @since CURRENT
7740 */
7741 protected int getBottomPaddingOffset() {
7742 return 0;
7743 }
7744
7745 /**
Romain Guy2bffd262010-09-12 17:40:02 -07007746 * <p>Indicates whether this view is attached to an hardware accelerated
7747 * window or not.</p>
7748 *
7749 * <p>Even if this method returns true, it does not mean that every call
7750 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
7751 * accelerated {@link android.graphics.Canvas}. For instance, if this view
7752 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
7753 * window is hardware accelerated,
7754 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
7755 * return false, and this method will return true.</p>
7756 *
7757 * @return True if the view is attached to a window and the window is
7758 * hardware accelerated; false in any other case.
7759 */
7760 public boolean isHardwareAccelerated() {
7761 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
7762 }
7763
7764 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007765 * Manually render this view (and all of its children) to the given Canvas.
7766 * The view must have already done a full layout before this function is
7767 * called. When implementing a view, do not override this method; instead,
7768 * you should implement {@link #onDraw}.
7769 *
7770 * @param canvas The Canvas to which the View is rendered.
7771 */
7772 public void draw(Canvas canvas) {
7773 if (ViewDebug.TRACE_HIERARCHY) {
7774 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7775 }
7776
Romain Guy5bcdff42009-05-14 21:27:18 -07007777 final int privateFlags = mPrivateFlags;
7778 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
7779 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
7780 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07007781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007782 /*
7783 * Draw traversal performs several drawing steps which must be executed
7784 * in the appropriate order:
7785 *
7786 * 1. Draw the background
7787 * 2. If necessary, save the canvas' layers to prepare for fading
7788 * 3. Draw view's content
7789 * 4. Draw children
7790 * 5. If necessary, draw the fading edges and restore layers
7791 * 6. Draw decorations (scrollbars for instance)
7792 */
7793
7794 // Step 1, draw the background, if needed
7795 int saveCount;
7796
Romain Guy24443ea2009-05-11 11:56:30 -07007797 if (!dirtyOpaque) {
7798 final Drawable background = mBGDrawable;
7799 if (background != null) {
7800 final int scrollX = mScrollX;
7801 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802
Romain Guy24443ea2009-05-11 11:56:30 -07007803 if (mBackgroundSizeChanged) {
7804 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
7805 mBackgroundSizeChanged = false;
7806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807
Romain Guy24443ea2009-05-11 11:56:30 -07007808 if ((scrollX | scrollY) == 0) {
7809 background.draw(canvas);
7810 } else {
7811 canvas.translate(scrollX, scrollY);
7812 background.draw(canvas);
7813 canvas.translate(-scrollX, -scrollY);
7814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 }
7816 }
7817
7818 // skip step 2 & 5 if possible (common case)
7819 final int viewFlags = mViewFlags;
7820 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
7821 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
7822 if (!verticalEdges && !horizontalEdges) {
7823 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007824 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007825
7826 // Step 4, draw the children
7827 dispatchDraw(canvas);
7828
7829 // Step 6, draw decorations (scrollbars)
7830 onDrawScrollBars(canvas);
7831
7832 // we're done...
7833 return;
7834 }
7835
7836 /*
7837 * Here we do the full fledged routine...
7838 * (this is an uncommon case where speed matters less,
7839 * this is why we repeat some of the tests that have been
7840 * done above)
7841 */
7842
7843 boolean drawTop = false;
7844 boolean drawBottom = false;
7845 boolean drawLeft = false;
7846 boolean drawRight = false;
7847
7848 float topFadeStrength = 0.0f;
7849 float bottomFadeStrength = 0.0f;
7850 float leftFadeStrength = 0.0f;
7851 float rightFadeStrength = 0.0f;
7852
7853 // Step 2, save the canvas' layers
7854 int paddingLeft = mPaddingLeft;
7855 int paddingTop = mPaddingTop;
7856
7857 final boolean offsetRequired = isPaddingOffsetRequired();
7858 if (offsetRequired) {
7859 paddingLeft += getLeftPaddingOffset();
7860 paddingTop += getTopPaddingOffset();
7861 }
7862
7863 int left = mScrollX + paddingLeft;
7864 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
7865 int top = mScrollY + paddingTop;
7866 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
7867
7868 if (offsetRequired) {
7869 right += getRightPaddingOffset();
7870 bottom += getBottomPaddingOffset();
7871 }
7872
7873 final ScrollabilityCache scrollabilityCache = mScrollCache;
7874 int length = scrollabilityCache.fadingEdgeLength;
7875
7876 // clip the fade length if top and bottom fades overlap
7877 // overlapping fades produce odd-looking artifacts
7878 if (verticalEdges && (top + length > bottom - length)) {
7879 length = (bottom - top) / 2;
7880 }
7881
7882 // also clip horizontal fades if necessary
7883 if (horizontalEdges && (left + length > right - length)) {
7884 length = (right - left) / 2;
7885 }
7886
7887 if (verticalEdges) {
7888 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007889 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007890 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007891 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 }
7893
7894 if (horizontalEdges) {
7895 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007896 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007897 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007898 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 }
7900
7901 saveCount = canvas.getSaveCount();
7902
7903 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07007904 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
7906
7907 if (drawTop) {
7908 canvas.saveLayer(left, top, right, top + length, null, flags);
7909 }
7910
7911 if (drawBottom) {
7912 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
7913 }
7914
7915 if (drawLeft) {
7916 canvas.saveLayer(left, top, left + length, bottom, null, flags);
7917 }
7918
7919 if (drawRight) {
7920 canvas.saveLayer(right - length, top, right, bottom, null, flags);
7921 }
7922 } else {
7923 scrollabilityCache.setFadeColor(solidColor);
7924 }
7925
7926 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007927 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007928
7929 // Step 4, draw the children
7930 dispatchDraw(canvas);
7931
7932 // Step 5, draw the fade effect and restore layers
7933 final Paint p = scrollabilityCache.paint;
7934 final Matrix matrix = scrollabilityCache.matrix;
7935 final Shader fade = scrollabilityCache.shader;
7936 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
7937
7938 if (drawTop) {
7939 matrix.setScale(1, fadeHeight * topFadeStrength);
7940 matrix.postTranslate(left, top);
7941 fade.setLocalMatrix(matrix);
7942 canvas.drawRect(left, top, right, top + length, p);
7943 }
7944
7945 if (drawBottom) {
7946 matrix.setScale(1, fadeHeight * bottomFadeStrength);
7947 matrix.postRotate(180);
7948 matrix.postTranslate(left, bottom);
7949 fade.setLocalMatrix(matrix);
7950 canvas.drawRect(left, bottom - length, right, bottom, p);
7951 }
7952
7953 if (drawLeft) {
7954 matrix.setScale(1, fadeHeight * leftFadeStrength);
7955 matrix.postRotate(-90);
7956 matrix.postTranslate(left, top);
7957 fade.setLocalMatrix(matrix);
7958 canvas.drawRect(left, top, left + length, bottom, p);
7959 }
7960
7961 if (drawRight) {
7962 matrix.setScale(1, fadeHeight * rightFadeStrength);
7963 matrix.postRotate(90);
7964 matrix.postTranslate(right, top);
7965 fade.setLocalMatrix(matrix);
7966 canvas.drawRect(right - length, top, right, bottom, p);
7967 }
7968
7969 canvas.restoreToCount(saveCount);
7970
7971 // Step 6, draw decorations (scrollbars)
7972 onDrawScrollBars(canvas);
7973 }
7974
7975 /**
7976 * Override this if your view is known to always be drawn on top of a solid color background,
7977 * and needs to draw fading edges. Returning a non-zero color enables the view system to
7978 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
7979 * should be set to 0xFF.
7980 *
7981 * @see #setVerticalFadingEdgeEnabled
7982 * @see #setHorizontalFadingEdgeEnabled
7983 *
7984 * @return The known solid color background for this view, or 0 if the color may vary
7985 */
7986 public int getSolidColor() {
7987 return 0;
7988 }
7989
7990 /**
7991 * Build a human readable string representation of the specified view flags.
7992 *
7993 * @param flags the view flags to convert to a string
7994 * @return a String representing the supplied flags
7995 */
7996 private static String printFlags(int flags) {
7997 String output = "";
7998 int numFlags = 0;
7999 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8000 output += "TAKES_FOCUS";
8001 numFlags++;
8002 }
8003
8004 switch (flags & VISIBILITY_MASK) {
8005 case INVISIBLE:
8006 if (numFlags > 0) {
8007 output += " ";
8008 }
8009 output += "INVISIBLE";
8010 // USELESS HERE numFlags++;
8011 break;
8012 case GONE:
8013 if (numFlags > 0) {
8014 output += " ";
8015 }
8016 output += "GONE";
8017 // USELESS HERE numFlags++;
8018 break;
8019 default:
8020 break;
8021 }
8022 return output;
8023 }
8024
8025 /**
8026 * Build a human readable string representation of the specified private
8027 * view flags.
8028 *
8029 * @param privateFlags the private view flags to convert to a string
8030 * @return a String representing the supplied flags
8031 */
8032 private static String printPrivateFlags(int privateFlags) {
8033 String output = "";
8034 int numFlags = 0;
8035
8036 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8037 output += "WANTS_FOCUS";
8038 numFlags++;
8039 }
8040
8041 if ((privateFlags & FOCUSED) == FOCUSED) {
8042 if (numFlags > 0) {
8043 output += " ";
8044 }
8045 output += "FOCUSED";
8046 numFlags++;
8047 }
8048
8049 if ((privateFlags & SELECTED) == SELECTED) {
8050 if (numFlags > 0) {
8051 output += " ";
8052 }
8053 output += "SELECTED";
8054 numFlags++;
8055 }
8056
8057 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8058 if (numFlags > 0) {
8059 output += " ";
8060 }
8061 output += "IS_ROOT_NAMESPACE";
8062 numFlags++;
8063 }
8064
8065 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8066 if (numFlags > 0) {
8067 output += " ";
8068 }
8069 output += "HAS_BOUNDS";
8070 numFlags++;
8071 }
8072
8073 if ((privateFlags & DRAWN) == DRAWN) {
8074 if (numFlags > 0) {
8075 output += " ";
8076 }
8077 output += "DRAWN";
8078 // USELESS HERE numFlags++;
8079 }
8080 return output;
8081 }
8082
8083 /**
8084 * <p>Indicates whether or not this view's layout will be requested during
8085 * the next hierarchy layout pass.</p>
8086 *
8087 * @return true if the layout will be forced during next layout pass
8088 */
8089 public boolean isLayoutRequested() {
8090 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8091 }
8092
8093 /**
8094 * Assign a size and position to a view and all of its
8095 * descendants
8096 *
8097 * <p>This is the second phase of the layout mechanism.
8098 * (The first is measuring). In this phase, each parent calls
8099 * layout on all of its children to position them.
8100 * This is typically done using the child measurements
8101 * that were stored in the measure pass().
8102 *
8103 * Derived classes with children should override
8104 * onLayout. In that method, they should
Chet Haase21cd1382010-09-01 17:42:29 -07008105 * call layout on each of their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008106 *
8107 * @param l Left position, relative to parent
8108 * @param t Top position, relative to parent
8109 * @param r Right position, relative to parent
8110 * @param b Bottom position, relative to parent
8111 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008112 @SuppressWarnings({"unchecked"})
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113 public final void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008114 int oldL = mLeft;
8115 int oldT = mTop;
8116 int oldB = mBottom;
8117 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118 boolean changed = setFrame(l, t, r, b);
8119 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8120 if (ViewDebug.TRACE_HIERARCHY) {
8121 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8122 }
8123
8124 onLayout(changed, l, t, r, b);
8125 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008126
8127 if (mOnLayoutChangeListeners != null) {
8128 ArrayList<OnLayoutChangeListener> listenersCopy =
8129 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8130 int numListeners = listenersCopy.size();
8131 for (int i = 0; i < numListeners; ++i) {
8132 listenersCopy.get(i).onLayoutChange(this, l, r, t, b, oldL, oldT, oldR, oldB);
8133 }
8134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 }
8136 mPrivateFlags &= ~FORCE_LAYOUT;
8137 }
8138
8139 /**
8140 * Called from layout when this view should
8141 * assign a size and position to each of its children.
8142 *
8143 * Derived classes with children should override
8144 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008145 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008146 * @param changed This is a new size or position for this view
8147 * @param left Left position, relative to parent
8148 * @param top Top position, relative to parent
8149 * @param right Right position, relative to parent
8150 * @param bottom Bottom position, relative to parent
8151 */
8152 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8153 }
8154
8155 /**
8156 * Assign a size and position to this view.
8157 *
8158 * This is called from layout.
8159 *
8160 * @param left Left position, relative to parent
8161 * @param top Top position, relative to parent
8162 * @param right Right position, relative to parent
8163 * @param bottom Bottom position, relative to parent
8164 * @return true if the new size and position are different than the
8165 * previous ones
8166 * {@hide}
8167 */
8168 protected boolean setFrame(int left, int top, int right, int bottom) {
8169 boolean changed = false;
8170
8171 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008172 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 + right + "," + bottom + ")");
8174 }
8175
8176 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8177 changed = true;
8178
8179 // Remember our drawn bit
8180 int drawn = mPrivateFlags & DRAWN;
8181
8182 // Invalidate our old position
8183 invalidate();
8184
8185
8186 int oldWidth = mRight - mLeft;
8187 int oldHeight = mBottom - mTop;
8188
8189 mLeft = left;
8190 mTop = top;
8191 mRight = right;
8192 mBottom = bottom;
8193
8194 mPrivateFlags |= HAS_BOUNDS;
8195
8196 int newWidth = right - left;
8197 int newHeight = bottom - top;
8198
8199 if (newWidth != oldWidth || newHeight != oldHeight) {
8200 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8201 }
8202
8203 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8204 // If we are visible, force the DRAWN bit to on so that
8205 // this invalidate will go through (at least to our parent).
8206 // This is because someone may have invalidated this view
8207 // before this call to setFrame came in, therby clearing
8208 // the DRAWN bit.
8209 mPrivateFlags |= DRAWN;
8210 invalidate();
8211 }
8212
8213 // Reset drawn bit to original value (invalidate turns it off)
8214 mPrivateFlags |= drawn;
8215
8216 mBackgroundSizeChanged = true;
8217 }
8218 return changed;
8219 }
8220
8221 /**
8222 * Finalize inflating a view from XML. This is called as the last phase
8223 * of inflation, after all child views have been added.
8224 *
8225 * <p>Even if the subclass overrides onFinishInflate, they should always be
8226 * sure to call the super method, so that we get called.
8227 */
8228 protected void onFinishInflate() {
8229 }
8230
8231 /**
8232 * Returns the resources associated with this view.
8233 *
8234 * @return Resources object.
8235 */
8236 public Resources getResources() {
8237 return mResources;
8238 }
8239
8240 /**
8241 * Invalidates the specified Drawable.
8242 *
8243 * @param drawable the drawable to invalidate
8244 */
8245 public void invalidateDrawable(Drawable drawable) {
8246 if (verifyDrawable(drawable)) {
8247 final Rect dirty = drawable.getBounds();
8248 final int scrollX = mScrollX;
8249 final int scrollY = mScrollY;
8250
8251 invalidate(dirty.left + scrollX, dirty.top + scrollY,
8252 dirty.right + scrollX, dirty.bottom + scrollY);
8253 }
8254 }
8255
8256 /**
8257 * Schedules an action on a drawable to occur at a specified time.
8258 *
8259 * @param who the recipient of the action
8260 * @param what the action to run on the drawable
8261 * @param when the time at which the action must occur. Uses the
8262 * {@link SystemClock#uptimeMillis} timebase.
8263 */
8264 public void scheduleDrawable(Drawable who, Runnable what, long when) {
8265 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8266 mAttachInfo.mHandler.postAtTime(what, who, when);
8267 }
8268 }
8269
8270 /**
8271 * Cancels a scheduled action on a drawable.
8272 *
8273 * @param who the recipient of the action
8274 * @param what the action to cancel
8275 */
8276 public void unscheduleDrawable(Drawable who, Runnable what) {
8277 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8278 mAttachInfo.mHandler.removeCallbacks(what, who);
8279 }
8280 }
8281
8282 /**
8283 * Unschedule any events associated with the given Drawable. This can be
8284 * used when selecting a new Drawable into a view, so that the previous
8285 * one is completely unscheduled.
8286 *
8287 * @param who The Drawable to unschedule.
8288 *
8289 * @see #drawableStateChanged
8290 */
8291 public void unscheduleDrawable(Drawable who) {
8292 if (mAttachInfo != null) {
8293 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
8294 }
8295 }
8296
8297 /**
8298 * If your view subclass is displaying its own Drawable objects, it should
8299 * override this function and return true for any Drawable it is
8300 * displaying. This allows animations for those drawables to be
8301 * scheduled.
8302 *
8303 * <p>Be sure to call through to the super class when overriding this
8304 * function.
8305 *
8306 * @param who The Drawable to verify. Return true if it is one you are
8307 * displaying, else return the result of calling through to the
8308 * super class.
8309 *
8310 * @return boolean If true than the Drawable is being displayed in the
8311 * view; else false and it is not allowed to animate.
8312 *
8313 * @see #unscheduleDrawable
8314 * @see #drawableStateChanged
8315 */
8316 protected boolean verifyDrawable(Drawable who) {
8317 return who == mBGDrawable;
8318 }
8319
8320 /**
8321 * This function is called whenever the state of the view changes in such
8322 * a way that it impacts the state of drawables being shown.
8323 *
8324 * <p>Be sure to call through to the superclass when overriding this
8325 * function.
8326 *
8327 * @see Drawable#setState
8328 */
8329 protected void drawableStateChanged() {
8330 Drawable d = mBGDrawable;
8331 if (d != null && d.isStateful()) {
8332 d.setState(getDrawableState());
8333 }
8334 }
8335
8336 /**
8337 * Call this to force a view to update its drawable state. This will cause
8338 * drawableStateChanged to be called on this view. Views that are interested
8339 * in the new state should call getDrawableState.
8340 *
8341 * @see #drawableStateChanged
8342 * @see #getDrawableState
8343 */
8344 public void refreshDrawableState() {
8345 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
8346 drawableStateChanged();
8347
8348 ViewParent parent = mParent;
8349 if (parent != null) {
8350 parent.childDrawableStateChanged(this);
8351 }
8352 }
8353
8354 /**
8355 * Return an array of resource IDs of the drawable states representing the
8356 * current state of the view.
8357 *
8358 * @return The current drawable state
8359 *
8360 * @see Drawable#setState
8361 * @see #drawableStateChanged
8362 * @see #onCreateDrawableState
8363 */
8364 public final int[] getDrawableState() {
8365 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
8366 return mDrawableState;
8367 } else {
8368 mDrawableState = onCreateDrawableState(0);
8369 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
8370 return mDrawableState;
8371 }
8372 }
8373
8374 /**
8375 * Generate the new {@link android.graphics.drawable.Drawable} state for
8376 * this view. This is called by the view
8377 * system when the cached Drawable state is determined to be invalid. To
8378 * retrieve the current state, you should use {@link #getDrawableState}.
8379 *
8380 * @param extraSpace if non-zero, this is the number of extra entries you
8381 * would like in the returned array in which you can place your own
8382 * states.
8383 *
8384 * @return Returns an array holding the current {@link Drawable} state of
8385 * the view.
8386 *
8387 * @see #mergeDrawableStates
8388 */
8389 protected int[] onCreateDrawableState(int extraSpace) {
8390 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
8391 mParent instanceof View) {
8392 return ((View) mParent).onCreateDrawableState(extraSpace);
8393 }
8394
8395 int[] drawableState;
8396
8397 int privateFlags = mPrivateFlags;
8398
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008399 int viewStateIndex = 0;
8400 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
8401 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
8402 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
8403 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
8404 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
8405 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008406
8407 drawableState = VIEW_STATE_SETS[viewStateIndex];
8408
8409 //noinspection ConstantIfStatement
8410 if (false) {
8411 Log.i("View", "drawableStateIndex=" + viewStateIndex);
8412 Log.i("View", toString()
8413 + " pressed=" + ((privateFlags & PRESSED) != 0)
8414 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
8415 + " fo=" + hasFocus()
8416 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008417 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008418 + ": " + Arrays.toString(drawableState));
8419 }
8420
8421 if (extraSpace == 0) {
8422 return drawableState;
8423 }
8424
8425 final int[] fullState;
8426 if (drawableState != null) {
8427 fullState = new int[drawableState.length + extraSpace];
8428 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
8429 } else {
8430 fullState = new int[extraSpace];
8431 }
8432
8433 return fullState;
8434 }
8435
8436 /**
8437 * Merge your own state values in <var>additionalState</var> into the base
8438 * state values <var>baseState</var> that were returned by
8439 * {@link #onCreateDrawableState}.
8440 *
8441 * @param baseState The base state values returned by
8442 * {@link #onCreateDrawableState}, which will be modified to also hold your
8443 * own additional state values.
8444 *
8445 * @param additionalState The additional state values you would like
8446 * added to <var>baseState</var>; this array is not modified.
8447 *
8448 * @return As a convenience, the <var>baseState</var> array you originally
8449 * passed into the function is returned.
8450 *
8451 * @see #onCreateDrawableState
8452 */
8453 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
8454 final int N = baseState.length;
8455 int i = N - 1;
8456 while (i >= 0 && baseState[i] == 0) {
8457 i--;
8458 }
8459 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
8460 return baseState;
8461 }
8462
8463 /**
8464 * Sets the background color for this view.
8465 * @param color the color of the background
8466 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008467 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008468 public void setBackgroundColor(int color) {
8469 setBackgroundDrawable(new ColorDrawable(color));
8470 }
8471
8472 /**
8473 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07008474 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 * @param resid The identifier of the resource.
8476 * @attr ref android.R.styleable#View_background
8477 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008478 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008479 public void setBackgroundResource(int resid) {
8480 if (resid != 0 && resid == mBackgroundResource) {
8481 return;
8482 }
8483
8484 Drawable d= null;
8485 if (resid != 0) {
8486 d = mResources.getDrawable(resid);
8487 }
8488 setBackgroundDrawable(d);
8489
8490 mBackgroundResource = resid;
8491 }
8492
8493 /**
8494 * Set the background to a given Drawable, or remove the background. If the
8495 * background has padding, this View's padding is set to the background's
8496 * padding. However, when a background is removed, this View's padding isn't
8497 * touched. If setting the padding is desired, please use
8498 * {@link #setPadding(int, int, int, int)}.
8499 *
8500 * @param d The Drawable to use as the background, or null to remove the
8501 * background
8502 */
8503 public void setBackgroundDrawable(Drawable d) {
8504 boolean requestLayout = false;
8505
8506 mBackgroundResource = 0;
8507
8508 /*
8509 * Regardless of whether we're setting a new background or not, we want
8510 * to clear the previous drawable.
8511 */
8512 if (mBGDrawable != null) {
8513 mBGDrawable.setCallback(null);
8514 unscheduleDrawable(mBGDrawable);
8515 }
8516
8517 if (d != null) {
8518 Rect padding = sThreadLocal.get();
8519 if (padding == null) {
8520 padding = new Rect();
8521 sThreadLocal.set(padding);
8522 }
8523 if (d.getPadding(padding)) {
8524 setPadding(padding.left, padding.top, padding.right, padding.bottom);
8525 }
8526
8527 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
8528 // if it has a different minimum size, we should layout again
8529 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
8530 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
8531 requestLayout = true;
8532 }
8533
8534 d.setCallback(this);
8535 if (d.isStateful()) {
8536 d.setState(getDrawableState());
8537 }
8538 d.setVisible(getVisibility() == VISIBLE, false);
8539 mBGDrawable = d;
8540
8541 if ((mPrivateFlags & SKIP_DRAW) != 0) {
8542 mPrivateFlags &= ~SKIP_DRAW;
8543 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8544 requestLayout = true;
8545 }
8546 } else {
8547 /* Remove the background */
8548 mBGDrawable = null;
8549
8550 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
8551 /*
8552 * This view ONLY drew the background before and we're removing
8553 * the background, so now it won't draw anything
8554 * (hence we SKIP_DRAW)
8555 */
8556 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
8557 mPrivateFlags |= SKIP_DRAW;
8558 }
8559
8560 /*
8561 * When the background is set, we try to apply its padding to this
8562 * View. When the background is removed, we don't touch this View's
8563 * padding. This is noted in the Javadocs. Hence, we don't need to
8564 * requestLayout(), the invalidate() below is sufficient.
8565 */
8566
8567 // The old background's minimum size could have affected this
8568 // View's layout, so let's requestLayout
8569 requestLayout = true;
8570 }
8571
Romain Guy8f1344f52009-05-15 16:03:59 -07008572 computeOpaqueFlags();
8573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 if (requestLayout) {
8575 requestLayout();
8576 }
8577
8578 mBackgroundSizeChanged = true;
8579 invalidate();
8580 }
8581
8582 /**
8583 * Gets the background drawable
8584 * @return The drawable used as the background for this view, if any.
8585 */
8586 public Drawable getBackground() {
8587 return mBGDrawable;
8588 }
8589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 /**
8591 * Sets the padding. The view may add on the space required to display
8592 * the scrollbars, depending on the style and visibility of the scrollbars.
8593 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
8594 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
8595 * from the values set in this call.
8596 *
8597 * @attr ref android.R.styleable#View_padding
8598 * @attr ref android.R.styleable#View_paddingBottom
8599 * @attr ref android.R.styleable#View_paddingLeft
8600 * @attr ref android.R.styleable#View_paddingRight
8601 * @attr ref android.R.styleable#View_paddingTop
8602 * @param left the left padding in pixels
8603 * @param top the top padding in pixels
8604 * @param right the right padding in pixels
8605 * @param bottom the bottom padding in pixels
8606 */
8607 public void setPadding(int left, int top, int right, int bottom) {
8608 boolean changed = false;
8609
8610 mUserPaddingRight = right;
8611 mUserPaddingBottom = bottom;
8612
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008613 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07008614
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008615 // Common case is there are no scroll bars.
8616 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
8617 // TODO: Deal with RTL languages to adjust left padding instead of right.
8618 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
8619 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8620 ? 0 : getVerticalScrollbarWidth();
8621 }
8622 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
8623 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8624 ? 0 : getHorizontalScrollbarHeight();
8625 }
8626 }
Romain Guy8506ab42009-06-11 17:35:47 -07008627
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008628 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 changed = true;
8630 mPaddingLeft = left;
8631 }
8632 if (mPaddingTop != top) {
8633 changed = true;
8634 mPaddingTop = top;
8635 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008636 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008637 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008638 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008639 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008640 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008642 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643 }
8644
8645 if (changed) {
8646 requestLayout();
8647 }
8648 }
8649
8650 /**
8651 * Returns the top padding of this view.
8652 *
8653 * @return the top padding in pixels
8654 */
8655 public int getPaddingTop() {
8656 return mPaddingTop;
8657 }
8658
8659 /**
8660 * Returns the bottom padding of this view. If there are inset and enabled
8661 * scrollbars, this value may include the space required to display the
8662 * scrollbars as well.
8663 *
8664 * @return the bottom padding in pixels
8665 */
8666 public int getPaddingBottom() {
8667 return mPaddingBottom;
8668 }
8669
8670 /**
8671 * Returns the left padding of this view. If there are inset and enabled
8672 * scrollbars, this value may include the space required to display the
8673 * scrollbars as well.
8674 *
8675 * @return the left padding in pixels
8676 */
8677 public int getPaddingLeft() {
8678 return mPaddingLeft;
8679 }
8680
8681 /**
8682 * Returns the right padding of this view. If there are inset and enabled
8683 * scrollbars, this value may include the space required to display the
8684 * scrollbars as well.
8685 *
8686 * @return the right padding in pixels
8687 */
8688 public int getPaddingRight() {
8689 return mPaddingRight;
8690 }
8691
8692 /**
8693 * Changes the selection state of this view. A view can be selected or not.
8694 * Note that selection is not the same as focus. Views are typically
8695 * selected in the context of an AdapterView like ListView or GridView;
8696 * the selected view is the view that is highlighted.
8697 *
8698 * @param selected true if the view must be selected, false otherwise
8699 */
8700 public void setSelected(boolean selected) {
8701 if (((mPrivateFlags & SELECTED) != 0) != selected) {
8702 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07008703 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008704 invalidate();
8705 refreshDrawableState();
8706 dispatchSetSelected(selected);
8707 }
8708 }
8709
8710 /**
8711 * Dispatch setSelected to all of this View's children.
8712 *
8713 * @see #setSelected(boolean)
8714 *
8715 * @param selected The new selected state
8716 */
8717 protected void dispatchSetSelected(boolean selected) {
8718 }
8719
8720 /**
8721 * Indicates the selection state of this view.
8722 *
8723 * @return true if the view is selected, false otherwise
8724 */
8725 @ViewDebug.ExportedProperty
8726 public boolean isSelected() {
8727 return (mPrivateFlags & SELECTED) != 0;
8728 }
8729
8730 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008731 * Changes the activated state of this view. A view can be activated or not.
8732 * Note that activation is not the same as selection. Selection is
8733 * a transient property, representing the view (hierarchy) the user is
8734 * currently interacting with. Activation is a longer-term state that the
8735 * user can move views in and out of. For example, in a list view with
8736 * single or multiple selection enabled, the views in the current selection
8737 * set are activated. (Um, yeah, we are deeply sorry about the terminology
8738 * here.) The activated state is propagated down to children of the view it
8739 * is set on.
8740 *
8741 * @param activated true if the view must be activated, false otherwise
8742 */
8743 public void setActivated(boolean activated) {
8744 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
8745 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
8746 invalidate();
8747 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07008748 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008749 }
8750 }
8751
8752 /**
8753 * Dispatch setActivated to all of this View's children.
8754 *
8755 * @see #setActivated(boolean)
8756 *
8757 * @param activated The new activated state
8758 */
8759 protected void dispatchSetActivated(boolean activated) {
8760 }
8761
8762 /**
8763 * Indicates the activation state of this view.
8764 *
8765 * @return true if the view is activated, false otherwise
8766 */
8767 @ViewDebug.ExportedProperty
8768 public boolean isActivated() {
8769 return (mPrivateFlags & ACTIVATED) != 0;
8770 }
8771
8772 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
8774 * observer can be used to get notifications when global events, like
8775 * layout, happen.
8776 *
8777 * The returned ViewTreeObserver observer is not guaranteed to remain
8778 * valid for the lifetime of this View. If the caller of this method keeps
8779 * a long-lived reference to ViewTreeObserver, it should always check for
8780 * the return value of {@link ViewTreeObserver#isAlive()}.
8781 *
8782 * @return The ViewTreeObserver for this view's hierarchy.
8783 */
8784 public ViewTreeObserver getViewTreeObserver() {
8785 if (mAttachInfo != null) {
8786 return mAttachInfo.mTreeObserver;
8787 }
8788 if (mFloatingTreeObserver == null) {
8789 mFloatingTreeObserver = new ViewTreeObserver();
8790 }
8791 return mFloatingTreeObserver;
8792 }
8793
8794 /**
8795 * <p>Finds the topmost view in the current view hierarchy.</p>
8796 *
8797 * @return the topmost view containing this view
8798 */
8799 public View getRootView() {
8800 if (mAttachInfo != null) {
8801 final View v = mAttachInfo.mRootView;
8802 if (v != null) {
8803 return v;
8804 }
8805 }
Romain Guy8506ab42009-06-11 17:35:47 -07008806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008807 View parent = this;
8808
8809 while (parent.mParent != null && parent.mParent instanceof View) {
8810 parent = (View) parent.mParent;
8811 }
8812
8813 return parent;
8814 }
8815
8816 /**
8817 * <p>Computes the coordinates of this view on the screen. The argument
8818 * must be an array of two integers. After the method returns, the array
8819 * contains the x and y location in that order.</p>
8820 *
8821 * @param location an array of two integers in which to hold the coordinates
8822 */
8823 public void getLocationOnScreen(int[] location) {
8824 getLocationInWindow(location);
8825
8826 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07008827 if (info != null) {
8828 location[0] += info.mWindowLeft;
8829 location[1] += info.mWindowTop;
8830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831 }
8832
8833 /**
8834 * <p>Computes the coordinates of this view in its window. The argument
8835 * must be an array of two integers. After the method returns, the array
8836 * contains the x and y location in that order.</p>
8837 *
8838 * @param location an array of two integers in which to hold the coordinates
8839 */
8840 public void getLocationInWindow(int[] location) {
8841 if (location == null || location.length < 2) {
8842 throw new IllegalArgumentException("location must be an array of "
8843 + "two integers");
8844 }
8845
8846 location[0] = mLeft;
8847 location[1] = mTop;
8848
8849 ViewParent viewParent = mParent;
8850 while (viewParent instanceof View) {
8851 final View view = (View)viewParent;
8852 location[0] += view.mLeft - view.mScrollX;
8853 location[1] += view.mTop - view.mScrollY;
8854 viewParent = view.mParent;
8855 }
Romain Guy8506ab42009-06-11 17:35:47 -07008856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008857 if (viewParent instanceof ViewRoot) {
8858 // *cough*
8859 final ViewRoot vr = (ViewRoot)viewParent;
8860 location[1] -= vr.mCurScrollY;
8861 }
8862 }
8863
8864 /**
8865 * {@hide}
8866 * @param id the id of the view to be found
8867 * @return the view of the specified id, null if cannot be found
8868 */
8869 protected View findViewTraversal(int id) {
8870 if (id == mID) {
8871 return this;
8872 }
8873 return null;
8874 }
8875
8876 /**
8877 * {@hide}
8878 * @param tag the tag of the view to be found
8879 * @return the view of specified tag, null if cannot be found
8880 */
8881 protected View findViewWithTagTraversal(Object tag) {
8882 if (tag != null && tag.equals(mTag)) {
8883 return this;
8884 }
8885 return null;
8886 }
8887
8888 /**
8889 * Look for a child view with the given id. If this view has the given
8890 * id, return this view.
8891 *
8892 * @param id The id to search for.
8893 * @return The view that has the given id in the hierarchy or null
8894 */
8895 public final View findViewById(int id) {
8896 if (id < 0) {
8897 return null;
8898 }
8899 return findViewTraversal(id);
8900 }
8901
8902 /**
8903 * Look for a child view with the given tag. If this view has the given
8904 * tag, return this view.
8905 *
8906 * @param tag The tag to search for, using "tag.equals(getTag())".
8907 * @return The View that has the given tag in the hierarchy or null
8908 */
8909 public final View findViewWithTag(Object tag) {
8910 if (tag == null) {
8911 return null;
8912 }
8913 return findViewWithTagTraversal(tag);
8914 }
8915
8916 /**
8917 * Sets the identifier for this view. The identifier does not have to be
8918 * unique in this view's hierarchy. The identifier should be a positive
8919 * number.
8920 *
8921 * @see #NO_ID
8922 * @see #getId
8923 * @see #findViewById
8924 *
8925 * @param id a number used to identify the view
8926 *
8927 * @attr ref android.R.styleable#View_id
8928 */
8929 public void setId(int id) {
8930 mID = id;
8931 }
8932
8933 /**
8934 * {@hide}
8935 *
8936 * @param isRoot true if the view belongs to the root namespace, false
8937 * otherwise
8938 */
8939 public void setIsRootNamespace(boolean isRoot) {
8940 if (isRoot) {
8941 mPrivateFlags |= IS_ROOT_NAMESPACE;
8942 } else {
8943 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
8944 }
8945 }
8946
8947 /**
8948 * {@hide}
8949 *
8950 * @return true if the view belongs to the root namespace, false otherwise
8951 */
8952 public boolean isRootNamespace() {
8953 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
8954 }
8955
8956 /**
8957 * Returns this view's identifier.
8958 *
8959 * @return a positive integer used to identify the view or {@link #NO_ID}
8960 * if the view has no ID
8961 *
8962 * @see #setId
8963 * @see #findViewById
8964 * @attr ref android.R.styleable#View_id
8965 */
8966 @ViewDebug.CapturedViewProperty
8967 public int getId() {
8968 return mID;
8969 }
8970
8971 /**
8972 * Returns this view's tag.
8973 *
8974 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07008975 *
8976 * @see #setTag(Object)
8977 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008978 */
8979 @ViewDebug.ExportedProperty
8980 public Object getTag() {
8981 return mTag;
8982 }
8983
8984 /**
8985 * Sets the tag associated with this view. A tag can be used to mark
8986 * a view in its hierarchy and does not have to be unique within the
8987 * hierarchy. Tags can also be used to store data within a view without
8988 * resorting to another data structure.
8989 *
8990 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07008991 *
8992 * @see #getTag()
8993 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008994 */
8995 public void setTag(final Object tag) {
8996 mTag = tag;
8997 }
8998
8999 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009000 * Returns the tag associated with this view and the specified key.
9001 *
9002 * @param key The key identifying the tag
9003 *
9004 * @return the Object stored in this view as a tag
9005 *
9006 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009007 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009008 */
9009 public Object getTag(int key) {
9010 SparseArray<Object> tags = null;
9011 synchronized (sTagsLock) {
9012 if (sTags != null) {
9013 tags = sTags.get(this);
9014 }
9015 }
9016
9017 if (tags != null) return tags.get(key);
9018 return null;
9019 }
9020
9021 /**
9022 * Sets a tag associated with this view and a key. A tag can be used
9023 * to mark a view in its hierarchy and does not have to be unique within
9024 * the hierarchy. Tags can also be used to store data within a view
9025 * without resorting to another data structure.
9026 *
9027 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009028 * application to ensure it is unique (see the <a
9029 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9030 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009031 * the Android framework or not associated with any package will cause
9032 * an {@link IllegalArgumentException} to be thrown.
9033 *
9034 * @param key The key identifying the tag
9035 * @param tag An Object to tag the view with
9036 *
9037 * @throws IllegalArgumentException If they specified key is not valid
9038 *
9039 * @see #setTag(Object)
9040 * @see #getTag(int)
9041 */
9042 public void setTag(int key, final Object tag) {
9043 // If the package id is 0x00 or 0x01, it's either an undefined package
9044 // or a framework id
9045 if ((key >>> 24) < 2) {
9046 throw new IllegalArgumentException("The key must be an application-specific "
9047 + "resource id.");
9048 }
9049
9050 setTagInternal(this, key, tag);
9051 }
9052
9053 /**
9054 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9055 * framework id.
9056 *
9057 * @hide
9058 */
9059 public void setTagInternal(int key, Object tag) {
9060 if ((key >>> 24) != 0x1) {
9061 throw new IllegalArgumentException("The key must be a framework-specific "
9062 + "resource id.");
9063 }
9064
Romain Guy8506ab42009-06-11 17:35:47 -07009065 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009066 }
9067
9068 private static void setTagInternal(View view, int key, Object tag) {
9069 SparseArray<Object> tags = null;
9070 synchronized (sTagsLock) {
9071 if (sTags == null) {
9072 sTags = new WeakHashMap<View, SparseArray<Object>>();
9073 } else {
9074 tags = sTags.get(view);
9075 }
9076 }
9077
9078 if (tags == null) {
9079 tags = new SparseArray<Object>(2);
9080 synchronized (sTagsLock) {
9081 sTags.put(view, tags);
9082 }
9083 }
9084
9085 tags.put(key, tag);
9086 }
9087
9088 /**
Romain Guy13922e02009-05-12 17:56:14 -07009089 * @param consistency The type of consistency. See ViewDebug for more information.
9090 *
9091 * @hide
9092 */
9093 protected boolean dispatchConsistencyCheck(int consistency) {
9094 return onConsistencyCheck(consistency);
9095 }
9096
9097 /**
9098 * Method that subclasses should implement to check their consistency. The type of
9099 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009100 *
Romain Guy13922e02009-05-12 17:56:14 -07009101 * @param consistency The type of consistency. See ViewDebug for more information.
9102 *
9103 * @throws IllegalStateException if the view is in an inconsistent state.
9104 *
9105 * @hide
9106 */
9107 protected boolean onConsistencyCheck(int consistency) {
9108 boolean result = true;
9109
9110 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9111 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9112
9113 if (checkLayout) {
9114 if (getParent() == null) {
9115 result = false;
9116 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9117 "View " + this + " does not have a parent.");
9118 }
9119
9120 if (mAttachInfo == null) {
9121 result = false;
9122 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9123 "View " + this + " is not attached to a window.");
9124 }
9125 }
9126
9127 if (checkDrawing) {
9128 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9129 // from their draw() method
9130
9131 if ((mPrivateFlags & DRAWN) != DRAWN &&
9132 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9133 result = false;
9134 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9135 "View " + this + " was invalidated but its drawing cache is valid.");
9136 }
9137 }
9138
9139 return result;
9140 }
9141
9142 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009143 * Prints information about this view in the log output, with the tag
9144 * {@link #VIEW_LOG_TAG}.
9145 *
9146 * @hide
9147 */
9148 public void debug() {
9149 debug(0);
9150 }
9151
9152 /**
9153 * Prints information about this view in the log output, with the tag
9154 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
9155 * indentation defined by the <code>depth</code>.
9156 *
9157 * @param depth the indentation level
9158 *
9159 * @hide
9160 */
9161 protected void debug(int depth) {
9162 String output = debugIndent(depth - 1);
9163
9164 output += "+ " + this;
9165 int id = getId();
9166 if (id != -1) {
9167 output += " (id=" + id + ")";
9168 }
9169 Object tag = getTag();
9170 if (tag != null) {
9171 output += " (tag=" + tag + ")";
9172 }
9173 Log.d(VIEW_LOG_TAG, output);
9174
9175 if ((mPrivateFlags & FOCUSED) != 0) {
9176 output = debugIndent(depth) + " FOCUSED";
9177 Log.d(VIEW_LOG_TAG, output);
9178 }
9179
9180 output = debugIndent(depth);
9181 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
9182 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
9183 + "} ";
9184 Log.d(VIEW_LOG_TAG, output);
9185
9186 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
9187 || mPaddingBottom != 0) {
9188 output = debugIndent(depth);
9189 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
9190 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
9191 Log.d(VIEW_LOG_TAG, output);
9192 }
9193
9194 output = debugIndent(depth);
9195 output += "mMeasureWidth=" + mMeasuredWidth +
9196 " mMeasureHeight=" + mMeasuredHeight;
9197 Log.d(VIEW_LOG_TAG, output);
9198
9199 output = debugIndent(depth);
9200 if (mLayoutParams == null) {
9201 output += "BAD! no layout params";
9202 } else {
9203 output = mLayoutParams.debug(output);
9204 }
9205 Log.d(VIEW_LOG_TAG, output);
9206
9207 output = debugIndent(depth);
9208 output += "flags={";
9209 output += View.printFlags(mViewFlags);
9210 output += "}";
9211 Log.d(VIEW_LOG_TAG, output);
9212
9213 output = debugIndent(depth);
9214 output += "privateFlags={";
9215 output += View.printPrivateFlags(mPrivateFlags);
9216 output += "}";
9217 Log.d(VIEW_LOG_TAG, output);
9218 }
9219
9220 /**
9221 * Creates an string of whitespaces used for indentation.
9222 *
9223 * @param depth the indentation level
9224 * @return a String containing (depth * 2 + 3) * 2 white spaces
9225 *
9226 * @hide
9227 */
9228 protected static String debugIndent(int depth) {
9229 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
9230 for (int i = 0; i < (depth * 2) + 3; i++) {
9231 spaces.append(' ').append(' ');
9232 }
9233 return spaces.toString();
9234 }
9235
9236 /**
9237 * <p>Return the offset of the widget's text baseline from the widget's top
9238 * boundary. If this widget does not support baseline alignment, this
9239 * method returns -1. </p>
9240 *
9241 * @return the offset of the baseline within the widget's bounds or -1
9242 * if baseline alignment is not supported
9243 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07009244 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009245 public int getBaseline() {
9246 return -1;
9247 }
9248
9249 /**
9250 * Call this when something has changed which has invalidated the
9251 * layout of this view. This will schedule a layout pass of the view
9252 * tree.
9253 */
9254 public void requestLayout() {
9255 if (ViewDebug.TRACE_HIERARCHY) {
9256 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
9257 }
9258
9259 mPrivateFlags |= FORCE_LAYOUT;
9260
9261 if (mParent != null && !mParent.isLayoutRequested()) {
9262 mParent.requestLayout();
9263 }
9264 }
9265
9266 /**
9267 * Forces this view to be laid out during the next layout pass.
9268 * This method does not call requestLayout() or forceLayout()
9269 * on the parent.
9270 */
9271 public void forceLayout() {
9272 mPrivateFlags |= FORCE_LAYOUT;
9273 }
9274
9275 /**
9276 * <p>
9277 * This is called to find out how big a view should be. The parent
9278 * supplies constraint information in the width and height parameters.
9279 * </p>
9280 *
9281 * <p>
9282 * The actual mesurement work of a view is performed in
9283 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
9284 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
9285 * </p>
9286 *
9287 *
9288 * @param widthMeasureSpec Horizontal space requirements as imposed by the
9289 * parent
9290 * @param heightMeasureSpec Vertical space requirements as imposed by the
9291 * parent
9292 *
9293 * @see #onMeasure(int, int)
9294 */
9295 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
9296 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
9297 widthMeasureSpec != mOldWidthMeasureSpec ||
9298 heightMeasureSpec != mOldHeightMeasureSpec) {
9299
9300 // first clears the measured dimension flag
9301 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9302
9303 if (ViewDebug.TRACE_HIERARCHY) {
9304 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
9305 }
9306
9307 // measure ourselves, this should set the measured dimension flag back
9308 onMeasure(widthMeasureSpec, heightMeasureSpec);
9309
9310 // flag not set, setMeasuredDimension() was not invoked, we raise
9311 // an exception to warn the developer
9312 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9313 throw new IllegalStateException("onMeasure() did not set the"
9314 + " measured dimension by calling"
9315 + " setMeasuredDimension()");
9316 }
9317
9318 mPrivateFlags |= LAYOUT_REQUIRED;
9319 }
9320
9321 mOldWidthMeasureSpec = widthMeasureSpec;
9322 mOldHeightMeasureSpec = heightMeasureSpec;
9323 }
9324
9325 /**
9326 * <p>
9327 * Measure the view and its content to determine the measured width and the
9328 * measured height. This method is invoked by {@link #measure(int, int)} and
9329 * should be overriden by subclasses to provide accurate and efficient
9330 * measurement of their contents.
9331 * </p>
9332 *
9333 * <p>
9334 * <strong>CONTRACT:</strong> When overriding this method, you
9335 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
9336 * measured width and height of this view. Failure to do so will trigger an
9337 * <code>IllegalStateException</code>, thrown by
9338 * {@link #measure(int, int)}. Calling the superclass'
9339 * {@link #onMeasure(int, int)} is a valid use.
9340 * </p>
9341 *
9342 * <p>
9343 * The base class implementation of measure defaults to the background size,
9344 * unless a larger size is allowed by the MeasureSpec. Subclasses should
9345 * override {@link #onMeasure(int, int)} to provide better measurements of
9346 * their content.
9347 * </p>
9348 *
9349 * <p>
9350 * If this method is overridden, it is the subclass's responsibility to make
9351 * sure the measured height and width are at least the view's minimum height
9352 * and width ({@link #getSuggestedMinimumHeight()} and
9353 * {@link #getSuggestedMinimumWidth()}).
9354 * </p>
9355 *
9356 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
9357 * The requirements are encoded with
9358 * {@link android.view.View.MeasureSpec}.
9359 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
9360 * The requirements are encoded with
9361 * {@link android.view.View.MeasureSpec}.
9362 *
9363 * @see #getMeasuredWidth()
9364 * @see #getMeasuredHeight()
9365 * @see #setMeasuredDimension(int, int)
9366 * @see #getSuggestedMinimumHeight()
9367 * @see #getSuggestedMinimumWidth()
9368 * @see android.view.View.MeasureSpec#getMode(int)
9369 * @see android.view.View.MeasureSpec#getSize(int)
9370 */
9371 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9372 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
9373 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
9374 }
9375
9376 /**
9377 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
9378 * measured width and measured height. Failing to do so will trigger an
9379 * exception at measurement time.</p>
9380 *
9381 * @param measuredWidth the measured width of this view
9382 * @param measuredHeight the measured height of this view
9383 */
9384 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
9385 mMeasuredWidth = measuredWidth;
9386 mMeasuredHeight = measuredHeight;
9387
9388 mPrivateFlags |= MEASURED_DIMENSION_SET;
9389 }
9390
9391 /**
9392 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
9393 * Will take the desired size, unless a different size is imposed by the constraints.
9394 *
9395 * @param size How big the view wants to be
9396 * @param measureSpec Constraints imposed by the parent
9397 * @return The size this view should be.
9398 */
9399 public static int resolveSize(int size, int measureSpec) {
9400 int result = size;
9401 int specMode = MeasureSpec.getMode(measureSpec);
9402 int specSize = MeasureSpec.getSize(measureSpec);
9403 switch (specMode) {
9404 case MeasureSpec.UNSPECIFIED:
9405 result = size;
9406 break;
9407 case MeasureSpec.AT_MOST:
9408 result = Math.min(size, specSize);
9409 break;
9410 case MeasureSpec.EXACTLY:
9411 result = specSize;
9412 break;
9413 }
9414 return result;
9415 }
9416
9417 /**
9418 * Utility to return a default size. Uses the supplied size if the
9419 * MeasureSpec imposed no contraints. Will get larger if allowed
9420 * by the MeasureSpec.
9421 *
9422 * @param size Default size for this view
9423 * @param measureSpec Constraints imposed by the parent
9424 * @return The size this view should be.
9425 */
9426 public static int getDefaultSize(int size, int measureSpec) {
9427 int result = size;
9428 int specMode = MeasureSpec.getMode(measureSpec);
9429 int specSize = MeasureSpec.getSize(measureSpec);
9430
9431 switch (specMode) {
9432 case MeasureSpec.UNSPECIFIED:
9433 result = size;
9434 break;
9435 case MeasureSpec.AT_MOST:
9436 case MeasureSpec.EXACTLY:
9437 result = specSize;
9438 break;
9439 }
9440 return result;
9441 }
9442
9443 /**
9444 * Returns the suggested minimum height that the view should use. This
9445 * returns the maximum of the view's minimum height
9446 * and the background's minimum height
9447 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
9448 * <p>
9449 * When being used in {@link #onMeasure(int, int)}, the caller should still
9450 * ensure the returned height is within the requirements of the parent.
9451 *
9452 * @return The suggested minimum height of the view.
9453 */
9454 protected int getSuggestedMinimumHeight() {
9455 int suggestedMinHeight = mMinHeight;
9456
9457 if (mBGDrawable != null) {
9458 final int bgMinHeight = mBGDrawable.getMinimumHeight();
9459 if (suggestedMinHeight < bgMinHeight) {
9460 suggestedMinHeight = bgMinHeight;
9461 }
9462 }
9463
9464 return suggestedMinHeight;
9465 }
9466
9467 /**
9468 * Returns the suggested minimum width that the view should use. This
9469 * returns the maximum of the view's minimum width)
9470 * and the background's minimum width
9471 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
9472 * <p>
9473 * When being used in {@link #onMeasure(int, int)}, the caller should still
9474 * ensure the returned width is within the requirements of the parent.
9475 *
9476 * @return The suggested minimum width of the view.
9477 */
9478 protected int getSuggestedMinimumWidth() {
9479 int suggestedMinWidth = mMinWidth;
9480
9481 if (mBGDrawable != null) {
9482 final int bgMinWidth = mBGDrawable.getMinimumWidth();
9483 if (suggestedMinWidth < bgMinWidth) {
9484 suggestedMinWidth = bgMinWidth;
9485 }
9486 }
9487
9488 return suggestedMinWidth;
9489 }
9490
9491 /**
9492 * Sets the minimum height of the view. It is not guaranteed the view will
9493 * be able to achieve this minimum height (for example, if its parent layout
9494 * constrains it with less available height).
9495 *
9496 * @param minHeight The minimum height the view will try to be.
9497 */
9498 public void setMinimumHeight(int minHeight) {
9499 mMinHeight = minHeight;
9500 }
9501
9502 /**
9503 * Sets the minimum width of the view. It is not guaranteed the view will
9504 * be able to achieve this minimum width (for example, if its parent layout
9505 * constrains it with less available width).
9506 *
9507 * @param minWidth The minimum width the view will try to be.
9508 */
9509 public void setMinimumWidth(int minWidth) {
9510 mMinWidth = minWidth;
9511 }
9512
9513 /**
9514 * Get the animation currently associated with this view.
9515 *
9516 * @return The animation that is currently playing or
9517 * scheduled to play for this view.
9518 */
9519 public Animation getAnimation() {
9520 return mCurrentAnimation;
9521 }
9522
9523 /**
9524 * Start the specified animation now.
9525 *
9526 * @param animation the animation to start now
9527 */
9528 public void startAnimation(Animation animation) {
9529 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
9530 setAnimation(animation);
9531 invalidate();
9532 }
9533
9534 /**
9535 * Cancels any animations for this view.
9536 */
9537 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08009538 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08009539 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08009540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009541 mCurrentAnimation = null;
9542 }
9543
9544 /**
9545 * Sets the next animation to play for this view.
9546 * If you want the animation to play immediately, use
9547 * startAnimation. This method provides allows fine-grained
9548 * control over the start time and invalidation, but you
9549 * must make sure that 1) the animation has a start time set, and
9550 * 2) the view will be invalidated when the animation is supposed to
9551 * start.
9552 *
9553 * @param animation The next animation, or null.
9554 */
9555 public void setAnimation(Animation animation) {
9556 mCurrentAnimation = animation;
9557 if (animation != null) {
9558 animation.reset();
9559 }
9560 }
9561
9562 /**
9563 * Invoked by a parent ViewGroup to notify the start of the animation
9564 * currently associated with this view. If you override this method,
9565 * always call super.onAnimationStart();
9566 *
9567 * @see #setAnimation(android.view.animation.Animation)
9568 * @see #getAnimation()
9569 */
9570 protected void onAnimationStart() {
9571 mPrivateFlags |= ANIMATION_STARTED;
9572 }
9573
9574 /**
9575 * Invoked by a parent ViewGroup to notify the end of the animation
9576 * currently associated with this view. If you override this method,
9577 * always call super.onAnimationEnd();
9578 *
9579 * @see #setAnimation(android.view.animation.Animation)
9580 * @see #getAnimation()
9581 */
9582 protected void onAnimationEnd() {
9583 mPrivateFlags &= ~ANIMATION_STARTED;
9584 }
9585
9586 /**
9587 * Invoked if there is a Transform that involves alpha. Subclass that can
9588 * draw themselves with the specified alpha should return true, and then
9589 * respect that alpha when their onDraw() is called. If this returns false
9590 * then the view may be redirected to draw into an offscreen buffer to
9591 * fulfill the request, which will look fine, but may be slower than if the
9592 * subclass handles it internally. The default implementation returns false.
9593 *
9594 * @param alpha The alpha (0..255) to apply to the view's drawing
9595 * @return true if the view can draw with the specified alpha.
9596 */
9597 protected boolean onSetAlpha(int alpha) {
9598 return false;
9599 }
9600
9601 /**
9602 * This is used by the RootView to perform an optimization when
9603 * the view hierarchy contains one or several SurfaceView.
9604 * SurfaceView is always considered transparent, but its children are not,
9605 * therefore all View objects remove themselves from the global transparent
9606 * region (passed as a parameter to this function).
9607 *
9608 * @param region The transparent region for this ViewRoot (window).
9609 *
9610 * @return Returns true if the effective visibility of the view at this
9611 * point is opaque, regardless of the transparent region; returns false
9612 * if it is possible for underlying windows to be seen behind the view.
9613 *
9614 * {@hide}
9615 */
9616 public boolean gatherTransparentRegion(Region region) {
9617 final AttachInfo attachInfo = mAttachInfo;
9618 if (region != null && attachInfo != null) {
9619 final int pflags = mPrivateFlags;
9620 if ((pflags & SKIP_DRAW) == 0) {
9621 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
9622 // remove it from the transparent region.
9623 final int[] location = attachInfo.mTransparentLocation;
9624 getLocationInWindow(location);
9625 region.op(location[0], location[1], location[0] + mRight - mLeft,
9626 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
9627 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
9628 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
9629 // exists, so we remove the background drawable's non-transparent
9630 // parts from this transparent region.
9631 applyDrawableToTransparentRegion(mBGDrawable, region);
9632 }
9633 }
9634 return true;
9635 }
9636
9637 /**
9638 * Play a sound effect for this view.
9639 *
9640 * <p>The framework will play sound effects for some built in actions, such as
9641 * clicking, but you may wish to play these effects in your widget,
9642 * for instance, for internal navigation.
9643 *
9644 * <p>The sound effect will only be played if sound effects are enabled by the user, and
9645 * {@link #isSoundEffectsEnabled()} is true.
9646 *
9647 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
9648 */
9649 public void playSoundEffect(int soundConstant) {
9650 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
9651 return;
9652 }
9653 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
9654 }
9655
9656 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009657 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009658 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009659 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009660 *
9661 * <p>The framework will provide haptic feedback for some built in actions,
9662 * such as long presses, but you may wish to provide feedback for your
9663 * own widget.
9664 *
9665 * <p>The feedback will only be performed if
9666 * {@link #isHapticFeedbackEnabled()} is true.
9667 *
9668 * @param feedbackConstant One of the constants defined in
9669 * {@link HapticFeedbackConstants}
9670 */
9671 public boolean performHapticFeedback(int feedbackConstant) {
9672 return performHapticFeedback(feedbackConstant, 0);
9673 }
9674
9675 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009676 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009677 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009678 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 *
9680 * @param feedbackConstant One of the constants defined in
9681 * {@link HapticFeedbackConstants}
9682 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
9683 */
9684 public boolean performHapticFeedback(int feedbackConstant, int flags) {
9685 if (mAttachInfo == null) {
9686 return false;
9687 }
Romain Guyf607bdc2010-09-10 19:20:06 -07009688 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -07009689 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009690 && !isHapticFeedbackEnabled()) {
9691 return false;
9692 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009693 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
9694 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009695 }
9696
9697 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -07009698 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
9699 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -07009700 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -07009701 */
9702 public void onCloseSystemDialogs(String reason) {
9703 }
9704
9705 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009706 * Given a Drawable whose bounds have been set to draw into this view,
9707 * update a Region being computed for {@link #gatherTransparentRegion} so
9708 * that any non-transparent parts of the Drawable are removed from the
9709 * given transparent region.
9710 *
9711 * @param dr The Drawable whose transparency is to be applied to the region.
9712 * @param region A Region holding the current transparency information,
9713 * where any parts of the region that are set are considered to be
9714 * transparent. On return, this region will be modified to have the
9715 * transparency information reduced by the corresponding parts of the
9716 * Drawable that are not transparent.
9717 * {@hide}
9718 */
9719 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
9720 if (DBG) {
9721 Log.i("View", "Getting transparent region for: " + this);
9722 }
9723 final Region r = dr.getTransparentRegion();
9724 final Rect db = dr.getBounds();
9725 final AttachInfo attachInfo = mAttachInfo;
9726 if (r != null && attachInfo != null) {
9727 final int w = getRight()-getLeft();
9728 final int h = getBottom()-getTop();
9729 if (db.left > 0) {
9730 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
9731 r.op(0, 0, db.left, h, Region.Op.UNION);
9732 }
9733 if (db.right < w) {
9734 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
9735 r.op(db.right, 0, w, h, Region.Op.UNION);
9736 }
9737 if (db.top > 0) {
9738 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
9739 r.op(0, 0, w, db.top, Region.Op.UNION);
9740 }
9741 if (db.bottom < h) {
9742 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
9743 r.op(0, db.bottom, w, h, Region.Op.UNION);
9744 }
9745 final int[] location = attachInfo.mTransparentLocation;
9746 getLocationInWindow(location);
9747 r.translate(location[0], location[1]);
9748 region.op(r, Region.Op.INTERSECT);
9749 } else {
9750 region.op(db, Region.Op.DIFFERENCE);
9751 }
9752 }
9753
Adam Powelle14579b2009-12-16 18:39:52 -08009754 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009755 mHasPerformedLongPress = false;
9756
9757 if (mPendingCheckForLongPress == null) {
9758 mPendingCheckForLongPress = new CheckForLongPress();
9759 }
9760 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -08009761 postDelayed(mPendingCheckForLongPress,
9762 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009763 }
9764
Romain Guy812ccbe2010-06-01 14:07:24 -07009765 private static int[] stateSetUnion(final int[] stateSet1, final int[] stateSet2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009766 final int stateSet1Length = stateSet1.length;
9767 final int stateSet2Length = stateSet2.length;
9768 final int[] newSet = new int[stateSet1Length + stateSet2Length];
9769 int k = 0;
9770 int i = 0;
9771 int j = 0;
9772 // This is a merge of the two input state sets and assumes that the
9773 // input sets are sorted by the order imposed by ViewDrawableStates.
9774 for (int viewState : R.styleable.ViewDrawableStates) {
9775 if (i < stateSet1Length && stateSet1[i] == viewState) {
9776 newSet[k++] = viewState;
9777 i++;
9778 } else if (j < stateSet2Length && stateSet2[j] == viewState) {
9779 newSet[k++] = viewState;
9780 j++;
9781 }
9782 if (k > 1) {
9783 assert(newSet[k - 1] > newSet[k - 2]);
9784 }
9785 }
9786 return newSet;
9787 }
9788
9789 /**
9790 * Inflate a view from an XML resource. This convenience method wraps the {@link
9791 * LayoutInflater} class, which provides a full range of options for view inflation.
9792 *
9793 * @param context The Context object for your activity or application.
9794 * @param resource The resource ID to inflate
9795 * @param root A view group that will be the parent. Used to properly inflate the
9796 * layout_* parameters.
9797 * @see LayoutInflater
9798 */
9799 public static View inflate(Context context, int resource, ViewGroup root) {
9800 LayoutInflater factory = LayoutInflater.from(context);
9801 return factory.inflate(resource, root);
9802 }
Romain Guy33e72ae2010-07-17 12:40:29 -07009803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009804 /**
9805 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
9806 * Each MeasureSpec represents a requirement for either the width or the height.
9807 * A MeasureSpec is comprised of a size and a mode. There are three possible
9808 * modes:
9809 * <dl>
9810 * <dt>UNSPECIFIED</dt>
9811 * <dd>
9812 * The parent has not imposed any constraint on the child. It can be whatever size
9813 * it wants.
9814 * </dd>
9815 *
9816 * <dt>EXACTLY</dt>
9817 * <dd>
9818 * The parent has determined an exact size for the child. The child is going to be
9819 * given those bounds regardless of how big it wants to be.
9820 * </dd>
9821 *
9822 * <dt>AT_MOST</dt>
9823 * <dd>
9824 * The child can be as large as it wants up to the specified size.
9825 * </dd>
9826 * </dl>
9827 *
9828 * MeasureSpecs are implemented as ints to reduce object allocation. This class
9829 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
9830 */
9831 public static class MeasureSpec {
9832 private static final int MODE_SHIFT = 30;
9833 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
9834
9835 /**
9836 * Measure specification mode: The parent has not imposed any constraint
9837 * on the child. It can be whatever size it wants.
9838 */
9839 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
9840
9841 /**
9842 * Measure specification mode: The parent has determined an exact size
9843 * for the child. The child is going to be given those bounds regardless
9844 * of how big it wants to be.
9845 */
9846 public static final int EXACTLY = 1 << MODE_SHIFT;
9847
9848 /**
9849 * Measure specification mode: The child can be as large as it wants up
9850 * to the specified size.
9851 */
9852 public static final int AT_MOST = 2 << MODE_SHIFT;
9853
9854 /**
9855 * Creates a measure specification based on the supplied size and mode.
9856 *
9857 * The mode must always be one of the following:
9858 * <ul>
9859 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
9860 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
9861 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
9862 * </ul>
9863 *
9864 * @param size the size of the measure specification
9865 * @param mode the mode of the measure specification
9866 * @return the measure specification based on size and mode
9867 */
9868 public static int makeMeasureSpec(int size, int mode) {
9869 return size + mode;
9870 }
9871
9872 /**
9873 * Extracts the mode from the supplied measure specification.
9874 *
9875 * @param measureSpec the measure specification to extract the mode from
9876 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
9877 * {@link android.view.View.MeasureSpec#AT_MOST} or
9878 * {@link android.view.View.MeasureSpec#EXACTLY}
9879 */
9880 public static int getMode(int measureSpec) {
9881 return (measureSpec & MODE_MASK);
9882 }
9883
9884 /**
9885 * Extracts the size from the supplied measure specification.
9886 *
9887 * @param measureSpec the measure specification to extract the size from
9888 * @return the size in pixels defined in the supplied measure specification
9889 */
9890 public static int getSize(int measureSpec) {
9891 return (measureSpec & ~MODE_MASK);
9892 }
9893
9894 /**
9895 * Returns a String representation of the specified measure
9896 * specification.
9897 *
9898 * @param measureSpec the measure specification to convert to a String
9899 * @return a String with the following format: "MeasureSpec: MODE SIZE"
9900 */
9901 public static String toString(int measureSpec) {
9902 int mode = getMode(measureSpec);
9903 int size = getSize(measureSpec);
9904
9905 StringBuilder sb = new StringBuilder("MeasureSpec: ");
9906
9907 if (mode == UNSPECIFIED)
9908 sb.append("UNSPECIFIED ");
9909 else if (mode == EXACTLY)
9910 sb.append("EXACTLY ");
9911 else if (mode == AT_MOST)
9912 sb.append("AT_MOST ");
9913 else
9914 sb.append(mode).append(" ");
9915
9916 sb.append(size);
9917 return sb.toString();
9918 }
9919 }
9920
9921 class CheckForLongPress implements Runnable {
9922
9923 private int mOriginalWindowAttachCount;
9924
9925 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -07009926 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009927 && mOriginalWindowAttachCount == mWindowAttachCount) {
9928 if (performLongClick()) {
9929 mHasPerformedLongPress = true;
9930 }
9931 }
9932 }
9933
9934 public void rememberWindowAttachCount() {
9935 mOriginalWindowAttachCount = mWindowAttachCount;
9936 }
9937 }
Adam Powelle14579b2009-12-16 18:39:52 -08009938
9939 private final class CheckForTap implements Runnable {
9940 public void run() {
9941 mPrivateFlags &= ~PREPRESSED;
9942 mPrivateFlags |= PRESSED;
9943 refreshDrawableState();
9944 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
9945 postCheckForLongClick(ViewConfiguration.getTapTimeout());
9946 }
9947 }
9948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009949
Adam Powella35d7682010-03-12 14:48:13 -08009950 private final class PerformClick implements Runnable {
9951 public void run() {
9952 performClick();
9953 }
9954 }
9955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009956 /**
9957 * Interface definition for a callback to be invoked when a key event is
9958 * dispatched to this view. The callback will be invoked before the key
9959 * event is given to the view.
9960 */
9961 public interface OnKeyListener {
9962 /**
9963 * Called when a key is dispatched to a view. This allows listeners to
9964 * get a chance to respond before the target view.
9965 *
9966 * @param v The view the key has been dispatched to.
9967 * @param keyCode The code for the physical key that was pressed
9968 * @param event The KeyEvent object containing full information about
9969 * the event.
9970 * @return True if the listener has consumed the event, false otherwise.
9971 */
9972 boolean onKey(View v, int keyCode, KeyEvent event);
9973 }
9974
9975 /**
9976 * Interface definition for a callback to be invoked when a touch event is
9977 * dispatched to this view. The callback will be invoked before the touch
9978 * event is given to the view.
9979 */
9980 public interface OnTouchListener {
9981 /**
9982 * Called when a touch event is dispatched to a view. This allows listeners to
9983 * get a chance to respond before the target view.
9984 *
9985 * @param v The view the touch event has been dispatched to.
9986 * @param event The MotionEvent object containing full information about
9987 * the event.
9988 * @return True if the listener has consumed the event, false otherwise.
9989 */
9990 boolean onTouch(View v, MotionEvent event);
9991 }
9992
9993 /**
9994 * Interface definition for a callback to be invoked when a view has been clicked and held.
9995 */
9996 public interface OnLongClickListener {
9997 /**
9998 * Called when a view has been clicked and held.
9999 *
10000 * @param v The view that was clicked and held.
10001 *
10002 * return True if the callback consumed the long click, false otherwise
10003 */
10004 boolean onLongClick(View v);
10005 }
10006
10007 /**
10008 * Interface definition for a callback to be invoked when the focus state of
10009 * a view changed.
10010 */
10011 public interface OnFocusChangeListener {
10012 /**
10013 * Called when the focus state of a view has changed.
10014 *
10015 * @param v The view whose state has changed.
10016 * @param hasFocus The new focus state of v.
10017 */
10018 void onFocusChange(View v, boolean hasFocus);
10019 }
10020
10021 /**
10022 * Interface definition for a callback to be invoked when a view is clicked.
10023 */
10024 public interface OnClickListener {
10025 /**
10026 * Called when a view has been clicked.
10027 *
10028 * @param v The view that was clicked.
10029 */
10030 void onClick(View v);
10031 }
10032
10033 /**
10034 * Interface definition for a callback to be invoked when the context menu
10035 * for this view is being built.
10036 */
10037 public interface OnCreateContextMenuListener {
10038 /**
10039 * Called when the context menu for this view is being built. It is not
10040 * safe to hold onto the menu after this method returns.
10041 *
10042 * @param menu The context menu that is being built
10043 * @param v The view for which the context menu is being built
10044 * @param menuInfo Extra information about the item for which the
10045 * context menu should be shown. This information will vary
10046 * depending on the class of v.
10047 */
10048 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
10049 }
10050
10051 private final class UnsetPressedState implements Runnable {
10052 public void run() {
10053 setPressed(false);
10054 }
10055 }
10056
10057 /**
10058 * Base class for derived classes that want to save and restore their own
10059 * state in {@link android.view.View#onSaveInstanceState()}.
10060 */
10061 public static class BaseSavedState extends AbsSavedState {
10062 /**
10063 * Constructor used when reading from a parcel. Reads the state of the superclass.
10064 *
10065 * @param source
10066 */
10067 public BaseSavedState(Parcel source) {
10068 super(source);
10069 }
10070
10071 /**
10072 * Constructor called by derived classes when creating their SavedState objects
10073 *
10074 * @param superState The state of the superclass of this view
10075 */
10076 public BaseSavedState(Parcelable superState) {
10077 super(superState);
10078 }
10079
10080 public static final Parcelable.Creator<BaseSavedState> CREATOR =
10081 new Parcelable.Creator<BaseSavedState>() {
10082 public BaseSavedState createFromParcel(Parcel in) {
10083 return new BaseSavedState(in);
10084 }
10085
10086 public BaseSavedState[] newArray(int size) {
10087 return new BaseSavedState[size];
10088 }
10089 };
10090 }
10091
10092 /**
10093 * A set of information given to a view when it is attached to its parent
10094 * window.
10095 */
10096 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010097 interface Callbacks {
10098 void playSoundEffect(int effectId);
10099 boolean performHapticFeedback(int effectId, boolean always);
10100 }
10101
10102 /**
10103 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
10104 * to a Handler. This class contains the target (View) to invalidate and
10105 * the coordinates of the dirty rectangle.
10106 *
10107 * For performance purposes, this class also implements a pool of up to
10108 * POOL_LIMIT objects that get reused. This reduces memory allocations
10109 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010110 */
Romain Guyd928d682009-03-31 17:52:16 -070010111 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010112 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070010113 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
10114 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070010115 public InvalidateInfo newInstance() {
10116 return new InvalidateInfo();
10117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010118
Romain Guyd928d682009-03-31 17:52:16 -070010119 public void onAcquired(InvalidateInfo element) {
10120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010121
Romain Guyd928d682009-03-31 17:52:16 -070010122 public void onReleased(InvalidateInfo element) {
10123 }
10124 }, POOL_LIMIT)
10125 );
10126
10127 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010128
10129 View target;
10130
10131 int left;
10132 int top;
10133 int right;
10134 int bottom;
10135
Romain Guyd928d682009-03-31 17:52:16 -070010136 public void setNextPoolable(InvalidateInfo element) {
10137 mNext = element;
10138 }
10139
10140 public InvalidateInfo getNextPoolable() {
10141 return mNext;
10142 }
10143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010144 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070010145 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010146 }
10147
10148 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070010149 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010150 }
10151 }
10152
10153 final IWindowSession mSession;
10154
10155 final IWindow mWindow;
10156
10157 final IBinder mWindowToken;
10158
10159 final Callbacks mRootCallbacks;
10160
10161 /**
10162 * The top view of the hierarchy.
10163 */
10164 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070010165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010166 IBinder mPanelParentWindowToken;
10167 Surface mSurface;
10168
Romain Guy2bffd262010-09-12 17:40:02 -070010169 boolean mHardwareAccelerated;
10170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010171 /**
Romain Guy8506ab42009-06-11 17:35:47 -070010172 * Scale factor used by the compatibility mode
10173 */
10174 float mApplicationScale;
10175
10176 /**
10177 * Indicates whether the application is in compatibility mode
10178 */
10179 boolean mScalingRequired;
10180
10181 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010182 * Left position of this view's window
10183 */
10184 int mWindowLeft;
10185
10186 /**
10187 * Top position of this view's window
10188 */
10189 int mWindowTop;
10190
10191 /**
Romain Guy35b38ce2009-10-07 13:38:55 -070010192 * Indicates whether the window is translucent/transparent
10193 */
10194 boolean mTranslucentWindow;
10195
10196 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010197 * For windows that are full-screen but using insets to layout inside
10198 * of the screen decorations, these are the current insets for the
10199 * content of the window.
10200 */
10201 final Rect mContentInsets = new Rect();
10202
10203 /**
10204 * For windows that are full-screen but using insets to layout inside
10205 * of the screen decorations, these are the current insets for the
10206 * actual visible parts of the window.
10207 */
10208 final Rect mVisibleInsets = new Rect();
10209
10210 /**
10211 * The internal insets given by this window. This value is
10212 * supplied by the client (through
10213 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
10214 * be given to the window manager when changed to be used in laying
10215 * out windows behind it.
10216 */
10217 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
10218 = new ViewTreeObserver.InternalInsetsInfo();
10219
10220 /**
10221 * All views in the window's hierarchy that serve as scroll containers,
10222 * used to determine if the window can be resized or must be panned
10223 * to adjust for a soft input area.
10224 */
10225 final ArrayList<View> mScrollContainers = new ArrayList<View>();
10226
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070010227 final KeyEvent.DispatcherState mKeyDispatchState
10228 = new KeyEvent.DispatcherState();
10229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010230 /**
10231 * Indicates whether the view's window currently has the focus.
10232 */
10233 boolean mHasWindowFocus;
10234
10235 /**
10236 * The current visibility of the window.
10237 */
10238 int mWindowVisibility;
10239
10240 /**
10241 * Indicates the time at which drawing started to occur.
10242 */
10243 long mDrawingTime;
10244
10245 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070010246 * Indicates whether or not ignoring the DIRTY_MASK flags.
10247 */
10248 boolean mIgnoreDirtyState;
10249
10250 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010251 * Indicates whether the view's window is currently in touch mode.
10252 */
10253 boolean mInTouchMode;
10254
10255 /**
10256 * Indicates that ViewRoot should trigger a global layout change
10257 * the next time it performs a traversal
10258 */
10259 boolean mRecomputeGlobalAttributes;
10260
10261 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010262 * Set during a traveral if any views want to keep the screen on.
10263 */
10264 boolean mKeepScreenOn;
10265
10266 /**
10267 * Set if the visibility of any views has changed.
10268 */
10269 boolean mViewVisibilityChanged;
10270
10271 /**
10272 * Set to true if a view has been scrolled.
10273 */
10274 boolean mViewScrollChanged;
10275
10276 /**
10277 * Global to the view hierarchy used as a temporary for dealing with
10278 * x/y points in the transparent region computations.
10279 */
10280 final int[] mTransparentLocation = new int[2];
10281
10282 /**
10283 * Global to the view hierarchy used as a temporary for dealing with
10284 * x/y points in the ViewGroup.invalidateChild implementation.
10285 */
10286 final int[] mInvalidateChildLocation = new int[2];
10287
Chet Haasec3aa3612010-06-17 08:50:37 -070010288
10289 /**
10290 * Global to the view hierarchy used as a temporary for dealing with
10291 * x/y location when view is transformed.
10292 */
10293 final float[] mTmpTransformLocation = new float[2];
10294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010295 /**
10296 * The view tree observer used to dispatch global events like
10297 * layout, pre-draw, touch mode change, etc.
10298 */
10299 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
10300
10301 /**
10302 * A Canvas used by the view hierarchy to perform bitmap caching.
10303 */
10304 Canvas mCanvas;
10305
10306 /**
10307 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
10308 * handler can be used to pump events in the UI events queue.
10309 */
10310 final Handler mHandler;
10311
10312 /**
10313 * Identifier for messages requesting the view to be invalidated.
10314 * Such messages should be sent to {@link #mHandler}.
10315 */
10316 static final int INVALIDATE_MSG = 0x1;
10317
10318 /**
10319 * Identifier for messages requesting the view to invalidate a region.
10320 * Such messages should be sent to {@link #mHandler}.
10321 */
10322 static final int INVALIDATE_RECT_MSG = 0x2;
10323
10324 /**
10325 * Temporary for use in computing invalidate rectangles while
10326 * calling up the hierarchy.
10327 */
10328 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070010329
10330 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070010331 * Temporary for use in computing hit areas with transformed views
10332 */
10333 final RectF mTmpTransformRect = new RectF();
10334
10335 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070010336 * Temporary list for use in collecting focusable descendents of a view.
10337 */
10338 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
10339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010340 /**
10341 * Creates a new set of attachment information with the specified
10342 * events handler and thread.
10343 *
10344 * @param handler the events handler the view must use
10345 */
10346 AttachInfo(IWindowSession session, IWindow window,
10347 Handler handler, Callbacks effectPlayer) {
10348 mSession = session;
10349 mWindow = window;
10350 mWindowToken = window.asBinder();
10351 mHandler = handler;
10352 mRootCallbacks = effectPlayer;
10353 }
10354 }
10355
10356 /**
10357 * <p>ScrollabilityCache holds various fields used by a View when scrolling
10358 * is supported. This avoids keeping too many unused fields in most
10359 * instances of View.</p>
10360 */
Mike Cleronf116bf82009-09-27 19:14:12 -070010361 private static class ScrollabilityCache implements Runnable {
10362
10363 /**
10364 * Scrollbars are not visible
10365 */
10366 public static final int OFF = 0;
10367
10368 /**
10369 * Scrollbars are visible
10370 */
10371 public static final int ON = 1;
10372
10373 /**
10374 * Scrollbars are fading away
10375 */
10376 public static final int FADING = 2;
10377
10378 public boolean fadeScrollBars;
10379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010380 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070010381 public int scrollBarDefaultDelayBeforeFade;
10382 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010383
10384 public int scrollBarSize;
10385 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070010386 public float[] interpolatorValues;
10387 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010388
10389 public final Paint paint;
10390 public final Matrix matrix;
10391 public Shader shader;
10392
Mike Cleronf116bf82009-09-27 19:14:12 -070010393 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
10394
Romain Guy8fb95422010-08-17 18:38:51 -070010395 private final float[] mOpaque = { 255.0f };
10396 private final float[] mTransparent = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070010397
10398 /**
10399 * When fading should start. This time moves into the future every time
10400 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
10401 */
10402 public long fadeStartTime;
10403
10404
10405 /**
10406 * The current state of the scrollbars: ON, OFF, or FADING
10407 */
10408 public int state = OFF;
10409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010410 private int mLastColor;
10411
Mike Cleronf116bf82009-09-27 19:14:12 -070010412 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010413 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
10414 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070010415 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
10416 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010417
10418 paint = new Paint();
10419 matrix = new Matrix();
10420 // use use a height of 1, and then wack the matrix each time we
10421 // actually use it.
10422 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010424 paint.setShader(shader);
10425 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070010426 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010427 }
Romain Guy8506ab42009-06-11 17:35:47 -070010428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010429 public void setFadeColor(int color) {
10430 if (color != 0 && color != mLastColor) {
10431 mLastColor = color;
10432 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070010433
Romain Guye55e1a72009-08-27 10:42:26 -070010434 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
10435 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010437 paint.setShader(shader);
10438 // Restore the default transfer mode (src_over)
10439 paint.setXfermode(null);
10440 }
10441 }
Mike Cleronf116bf82009-09-27 19:14:12 -070010442
10443 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070010444 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070010445 if (now >= fadeStartTime) {
10446
10447 // the animation fades the scrollbars out by changing
10448 // the opacity (alpha) from fully opaque to fully
10449 // transparent
10450 int nextFrame = (int) now;
10451 int framesCount = 0;
10452
10453 Interpolator interpolator = scrollBarInterpolator;
10454
10455 // Start opaque
10456 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
10457
10458 // End transparent
10459 nextFrame += scrollBarFadeDuration;
10460 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
10461
10462 state = FADING;
10463
10464 // Kick off the fade animation
10465 host.invalidate();
10466 }
10467 }
10468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010469 }
10470}