blob: e3a07157dd21f6120fdcb4d56cde8fc27fdf2b22 [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
Christopher Tatea53146c2010-09-07 11:57:52 -070019import android.content.ClipData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080021import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070025import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070027import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.graphics.LinearGradient;
29import android.graphics.Matrix;
30import android.graphics.Paint;
31import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070032import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
35import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070036import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.graphics.Region;
38import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Message;
44import android.os.Parcel;
45import android.os.Parcelable;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.os.SystemProperties;
49import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070051import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070052import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070053import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070054import android.util.Pools;
55import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.view.ContextMenu.ContextMenuInfo;
svetoslavganov75986cf2009-05-14 22:28:01 -070057import android.view.accessibility.AccessibilityEvent;
58import android.view.accessibility.AccessibilityEventSource;
59import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070061import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070062import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.view.inputmethod.InputConnection;
64import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.widget.ScrollBarDrawable;
Romain Guyf607bdc2010-09-10 19:20:06 -070066import com.android.internal.R;
67import com.android.internal.view.menu.MenuBuilder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
Christopher Tatea0374192010-10-05 13:06:41 -070069import java.lang.ref.WeakReference;
svetoslavganov75986cf2009-05-14 22:28:01 -070070import java.lang.reflect.InvocationTargetException;
71import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.util.ArrayList;
73import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070074import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070075import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
77/**
78 * <p>
79 * This class represents the basic building block for user interface components. A View
80 * occupies a rectangular area on the screen and is responsible for drawing and
81 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070082 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
84 * are invisible containers that hold other Views (or other ViewGroups) and define
85 * their layout properties.
86 * </p>
87 *
88 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070089 * <p>For an introduction to using this class to develop your
90 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070092 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
94 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
95 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
101 * </p>
102 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700103 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 * <a name="Using"></a>
105 * <h3>Using Views</h3>
106 * <p>
107 * All of the views in a window are arranged in a single tree. You can add views
108 * either from code or by specifying a tree of views in one or more XML layout
109 * files. There are many specialized subclasses of views that act as controls or
110 * are capable of displaying text, images, or other content.
111 * </p>
112 * <p>
113 * Once you have created a tree of views, there are typically a few types of
114 * common operations you may wish to perform:
115 * <ul>
116 * <li><strong>Set properties:</strong> for example setting the text of a
117 * {@link android.widget.TextView}. The available properties and the methods
118 * that set them will vary among the different subclasses of views. Note that
119 * properties that are known at build time can be set in the XML layout
120 * files.</li>
121 * <li><strong>Set focus:</strong> The framework will handled moving focus in
122 * response to user input. To force focus to a specific view, call
123 * {@link #requestFocus}.</li>
124 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
125 * that will be notified when something interesting happens to the view. For
126 * example, all views will let you set a listener to be notified when the view
127 * gains or loses focus. You can register such a listener using
128 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
129 * specialized listeners. For example, a Button exposes a listener to notify
130 * clients when the button is clicked.</li>
131 * <li><strong>Set visibility:</strong> You can hide or show views using
132 * {@link #setVisibility}.</li>
133 * </ul>
134 * </p>
135 * <p><em>
136 * Note: The Android framework is responsible for measuring, laying out and
137 * drawing views. You should not call methods that perform these actions on
138 * views yourself unless you are actually implementing a
139 * {@link android.view.ViewGroup}.
140 * </em></p>
141 *
142 * <a name="Lifecycle"></a>
143 * <h3>Implementing a Custom View</h3>
144 *
145 * <p>
146 * To implement a custom view, you will usually begin by providing overrides for
147 * some of the standard methods that the framework calls on all views. You do
148 * not need to override all of these methods. In fact, you can start by just
149 * overriding {@link #onDraw(android.graphics.Canvas)}.
150 * <table border="2" width="85%" align="center" cellpadding="5">
151 * <thead>
152 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
153 * </thead>
154 *
155 * <tbody>
156 * <tr>
157 * <td rowspan="2">Creation</td>
158 * <td>Constructors</td>
159 * <td>There is a form of the constructor that are called when the view
160 * is created from code and a form that is called when the view is
161 * inflated from a layout file. The second form should parse and apply
162 * any attributes defined in the layout file.
163 * </td>
164 * </tr>
165 * <tr>
166 * <td><code>{@link #onFinishInflate()}</code></td>
167 * <td>Called after a view and all of its children has been inflated
168 * from XML.</td>
169 * </tr>
170 *
171 * <tr>
172 * <td rowspan="3">Layout</td>
173 * <td><code>{@link #onMeasure}</code></td>
174 * <td>Called to determine the size requirements for this view and all
175 * of its children.
176 * </td>
177 * </tr>
178 * <tr>
179 * <td><code>{@link #onLayout}</code></td>
180 * <td>Called when this view should assign a size and position to all
181 * of its children.
182 * </td>
183 * </tr>
184 * <tr>
185 * <td><code>{@link #onSizeChanged}</code></td>
186 * <td>Called when the size of this view has changed.
187 * </td>
188 * </tr>
189 *
190 * <tr>
191 * <td>Drawing</td>
192 * <td><code>{@link #onDraw}</code></td>
193 * <td>Called when the view should render its content.
194 * </td>
195 * </tr>
196 *
197 * <tr>
198 * <td rowspan="4">Event processing</td>
199 * <td><code>{@link #onKeyDown}</code></td>
200 * <td>Called when a new key event occurs.
201 * </td>
202 * </tr>
203 * <tr>
204 * <td><code>{@link #onKeyUp}</code></td>
205 * <td>Called when a key up event occurs.
206 * </td>
207 * </tr>
208 * <tr>
209 * <td><code>{@link #onTrackballEvent}</code></td>
210 * <td>Called when a trackball motion event occurs.
211 * </td>
212 * </tr>
213 * <tr>
214 * <td><code>{@link #onTouchEvent}</code></td>
215 * <td>Called when a touch screen motion event occurs.
216 * </td>
217 * </tr>
218 *
219 * <tr>
220 * <td rowspan="2">Focus</td>
221 * <td><code>{@link #onFocusChanged}</code></td>
222 * <td>Called when the view gains or loses focus.
223 * </td>
224 * </tr>
225 *
226 * <tr>
227 * <td><code>{@link #onWindowFocusChanged}</code></td>
228 * <td>Called when the window containing the view gains or loses focus.
229 * </td>
230 * </tr>
231 *
232 * <tr>
233 * <td rowspan="3">Attaching</td>
234 * <td><code>{@link #onAttachedToWindow()}</code></td>
235 * <td>Called when the view is attached to a window.
236 * </td>
237 * </tr>
238 *
239 * <tr>
240 * <td><code>{@link #onDetachedFromWindow}</code></td>
241 * <td>Called when the view is detached from its window.
242 * </td>
243 * </tr>
244 *
245 * <tr>
246 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
247 * <td>Called when the visibility of the window containing the view
248 * has changed.
249 * </td>
250 * </tr>
251 * </tbody>
252 *
253 * </table>
254 * </p>
255 *
256 * <a name="IDs"></a>
257 * <h3>IDs</h3>
258 * Views may have an integer id associated with them. These ids are typically
259 * assigned in the layout XML files, and are used to find specific views within
260 * the view tree. A common pattern is to:
261 * <ul>
262 * <li>Define a Button in the layout file and assign it a unique ID.
263 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700264 * &lt;Button
265 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 * android:layout_width="wrap_content"
267 * android:layout_height="wrap_content"
268 * android:text="@string/my_button_text"/&gt;
269 * </pre></li>
270 * <li>From the onCreate method of an Activity, find the Button
271 * <pre class="prettyprint">
272 * Button myButton = (Button) findViewById(R.id.my_button);
273 * </pre></li>
274 * </ul>
275 * <p>
276 * View IDs need not be unique throughout the tree, but it is good practice to
277 * ensure that they are at least unique within the part of the tree you are
278 * searching.
279 * </p>
280 *
281 * <a name="Position"></a>
282 * <h3>Position</h3>
283 * <p>
284 * The geometry of a view is that of a rectangle. A view has a location,
285 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
286 * two dimensions, expressed as a width and a height. The unit for location
287 * and dimensions is the pixel.
288 * </p>
289 *
290 * <p>
291 * It is possible to retrieve the location of a view by invoking the methods
292 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
293 * coordinate of the rectangle representing the view. The latter returns the
294 * top, or Y, coordinate of the rectangle representing the view. These methods
295 * both return the location of the view relative to its parent. For instance,
296 * when getLeft() returns 20, that means the view is located 20 pixels to the
297 * right of the left edge of its direct parent.
298 * </p>
299 *
300 * <p>
301 * In addition, several convenience methods are offered to avoid unnecessary
302 * computations, namely {@link #getRight()} and {@link #getBottom()}.
303 * These methods return the coordinates of the right and bottom edges of the
304 * rectangle representing the view. For instance, calling {@link #getRight()}
305 * is similar to the following computation: <code>getLeft() + getWidth()</code>
306 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
307 * </p>
308 *
309 * <a name="SizePaddingMargins"></a>
310 * <h3>Size, padding and margins</h3>
311 * <p>
312 * The size of a view is expressed with a width and a height. A view actually
313 * possess two pairs of width and height values.
314 * </p>
315 *
316 * <p>
317 * The first pair is known as <em>measured width</em> and
318 * <em>measured height</em>. These dimensions define how big a view wants to be
319 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
320 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
321 * and {@link #getMeasuredHeight()}.
322 * </p>
323 *
324 * <p>
325 * The second pair is simply known as <em>width</em> and <em>height</em>, or
326 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
327 * dimensions define the actual size of the view on screen, at drawing time and
328 * after layout. These values may, but do not have to, be different from the
329 * measured width and height. The width and height can be obtained by calling
330 * {@link #getWidth()} and {@link #getHeight()}.
331 * </p>
332 *
333 * <p>
334 * To measure its dimensions, a view takes into account its padding. The padding
335 * is expressed in pixels for the left, top, right and bottom parts of the view.
336 * Padding can be used to offset the content of the view by a specific amount of
337 * pixels. For instance, a left padding of 2 will push the view's content by
338 * 2 pixels to the right of the left edge. Padding can be set using the
339 * {@link #setPadding(int, int, int, int)} method and queried by calling
340 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
341 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
342 * </p>
343 *
344 * <p>
345 * Even though a view can define a padding, it does not provide any support for
346 * margins. However, view groups provide such a support. Refer to
347 * {@link android.view.ViewGroup} and
348 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
349 * </p>
350 *
351 * <a name="Layout"></a>
352 * <h3>Layout</h3>
353 * <p>
354 * Layout is a two pass process: a measure pass and a layout pass. The measuring
355 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
356 * of the view tree. Each view pushes dimension specifications down the tree
357 * during the recursion. At the end of the measure pass, every view has stored
358 * its measurements. The second pass happens in
359 * {@link #layout(int,int,int,int)} and is also top-down. During
360 * this pass each parent is responsible for positioning all of its children
361 * using the sizes computed in the measure pass.
362 * </p>
363 *
364 * <p>
365 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
366 * {@link #getMeasuredHeight()} values must be set, along with those for all of
367 * that view's descendants. A view's measured width and measured height values
368 * must respect the constraints imposed by the view's parents. This guarantees
369 * that at the end of the measure pass, all parents accept all of their
370 * children's measurements. A parent view may call measure() more than once on
371 * its children. For example, the parent may measure each child once with
372 * unspecified dimensions to find out how big they want to be, then call
373 * measure() on them again with actual numbers if the sum of all the children's
374 * unconstrained sizes is too big or too small.
375 * </p>
376 *
377 * <p>
378 * The measure pass uses two classes to communicate dimensions. The
379 * {@link MeasureSpec} class is used by views to tell their parents how they
380 * want to be measured and positioned. The base LayoutParams class just
381 * describes how big the view wants to be for both width and height. For each
382 * dimension, it can specify one of:
383 * <ul>
384 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800385 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 * (minus padding)
387 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
388 * enclose its content (plus padding).
389 * </ul>
390 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
391 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
392 * an X and Y value.
393 * </p>
394 *
395 * <p>
396 * MeasureSpecs are used to push requirements down the tree from parent to
397 * child. A MeasureSpec can be in one of three modes:
398 * <ul>
399 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
400 * of a child view. For example, a LinearLayout may call measure() on its child
401 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
402 * tall the child view wants to be given a width of 240 pixels.
403 * <li>EXACTLY: This is used by the parent to impose an exact size on the
404 * child. The child must use this size, and guarantee that all of its
405 * descendants will fit within this size.
406 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
407 * child. The child must gurantee that it and all of its descendants will fit
408 * within this size.
409 * </ul>
410 * </p>
411 *
412 * <p>
413 * To intiate a layout, call {@link #requestLayout}. This method is typically
414 * called by a view on itself when it believes that is can no longer fit within
415 * its current bounds.
416 * </p>
417 *
418 * <a name="Drawing"></a>
419 * <h3>Drawing</h3>
420 * <p>
421 * Drawing is handled by walking the tree and rendering each view that
422 * intersects the the invalid region. Because the tree is traversed in-order,
423 * this means that parents will draw before (i.e., behind) their children, with
424 * siblings drawn in the order they appear in the tree.
425 * If you set a background drawable for a View, then the View will draw it for you
426 * before calling back to its <code>onDraw()</code> method.
427 * </p>
428 *
429 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700430 * Note that the framework will not draw views that are not in the invalid region.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 * </p>
432 *
433 * <p>
434 * To force a view to draw, call {@link #invalidate()}.
435 * </p>
436 *
437 * <a name="EventHandlingThreading"></a>
438 * <h3>Event Handling and Threading</h3>
439 * <p>
440 * The basic cycle of a view is as follows:
441 * <ol>
442 * <li>An event comes in and is dispatched to the appropriate view. The view
443 * handles the event and notifies any listeners.</li>
444 * <li>If in the course of processing the event, the view's bounds may need
445 * to be changed, the view will call {@link #requestLayout()}.</li>
446 * <li>Similarly, if in the course of processing the event the view's appearance
447 * may need to be changed, the view will call {@link #invalidate()}.</li>
448 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
449 * the framework will take care of measuring, laying out, and drawing the tree
450 * as appropriate.</li>
451 * </ol>
452 * </p>
453 *
454 * <p><em>Note: The entire view tree is single threaded. You must always be on
455 * the UI thread when calling any method on any view.</em>
456 * If you are doing work on other threads and want to update the state of a view
457 * from that thread, you should use a {@link Handler}.
458 * </p>
459 *
460 * <a name="FocusHandling"></a>
461 * <h3>Focus Handling</h3>
462 * <p>
463 * The framework will handle routine focus movement in response to user input.
464 * This includes changing the focus as views are removed or hidden, or as new
465 * views become available. Views indicate their willingness to take focus
466 * through the {@link #isFocusable} method. To change whether a view can take
467 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
468 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
469 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
470 * </p>
471 * <p>
472 * Focus movement is based on an algorithm which finds the nearest neighbor in a
473 * given direction. In rare cases, the default algorithm may not match the
474 * intended behavior of the developer. In these situations, you can provide
475 * explicit overrides by using these XML attributes in the layout file:
476 * <pre>
477 * nextFocusDown
478 * nextFocusLeft
479 * nextFocusRight
480 * nextFocusUp
481 * </pre>
482 * </p>
483 *
484 *
485 * <p>
486 * To get a particular view to take focus, call {@link #requestFocus()}.
487 * </p>
488 *
489 * <a name="TouchMode"></a>
490 * <h3>Touch Mode</h3>
491 * <p>
492 * When a user is navigating a user interface via directional keys such as a D-pad, it is
493 * necessary to give focus to actionable items such as buttons so the user can see
494 * what will take input. If the device has touch capabilities, however, and the user
495 * begins interacting with the interface by touching it, it is no longer necessary to
496 * always highlight, or give focus to, a particular view. This motivates a mode
497 * for interaction named 'touch mode'.
498 * </p>
499 * <p>
500 * For a touch capable device, once the user touches the screen, the device
501 * will enter touch mode. From this point onward, only views for which
502 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
503 * Other views that are touchable, like buttons, will not take focus when touched; they will
504 * only fire the on click listeners.
505 * </p>
506 * <p>
507 * Any time a user hits a directional key, such as a D-pad direction, the view device will
508 * exit touch mode, and find a view to take focus, so that the user may resume interacting
509 * with the user interface without touching the screen again.
510 * </p>
511 * <p>
512 * The touch mode state is maintained across {@link android.app.Activity}s. Call
513 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
514 * </p>
515 *
516 * <a name="Scrolling"></a>
517 * <h3>Scrolling</h3>
518 * <p>
519 * The framework provides basic support for views that wish to internally
520 * scroll their content. This includes keeping track of the X and Y scroll
521 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700522 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
523 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 * </p>
525 *
526 * <a name="Tags"></a>
527 * <h3>Tags</h3>
528 * <p>
529 * Unlike IDs, tags are not used to identify views. Tags are essentially an
530 * extra piece of information that can be associated with a view. They are most
531 * often used as a convenience to store data related to views in the views
532 * themselves rather than by putting them in a separate structure.
533 * </p>
534 *
535 * <a name="Animation"></a>
536 * <h3>Animation</h3>
537 * <p>
538 * You can attach an {@link Animation} object to a view using
539 * {@link #setAnimation(Animation)} or
540 * {@link #startAnimation(Animation)}. The animation can alter the scale,
541 * rotation, translation and alpha of a view over time. If the animation is
542 * attached to a view that has children, the animation will affect the entire
543 * subtree rooted by that node. When an animation is started, the framework will
544 * take care of redrawing the appropriate views until the animation completes.
545 * </p>
546 *
Jeff Brown85a31762010-09-01 17:01:00 -0700547 * <a name="Security"></a>
548 * <h3>Security</h3>
549 * <p>
550 * Sometimes it is essential that an application be able to verify that an action
551 * is being performed with the full knowledge and consent of the user, such as
552 * granting a permission request, making a purchase or clicking on an advertisement.
553 * Unfortunately, a malicious application could try to spoof the user into
554 * performing these actions, unaware, by concealing the intended purpose of the view.
555 * As a remedy, the framework offers a touch filtering mechanism that can be used to
556 * improve the security of views that provide access to sensitive functionality.
557 * </p><p>
558 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
559 * andoird:filterTouchesWhenObscured attribute to true. When enabled, the framework
560 * will discard touches that are received whenever the view's window is obscured by
561 * another visible window. As a result, the view will not receive touches whenever a
562 * toast, dialog or other window appears above the view's window.
563 * </p><p>
564 * For more fine-grained control over security, consider overriding the
565 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
566 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
567 * </p>
568 *
Romain Guyd6a463a2009-05-21 23:10:10 -0700569 * @attr ref android.R.styleable#View_background
570 * @attr ref android.R.styleable#View_clickable
571 * @attr ref android.R.styleable#View_contentDescription
572 * @attr ref android.R.styleable#View_drawingCacheQuality
573 * @attr ref android.R.styleable#View_duplicateParentState
574 * @attr ref android.R.styleable#View_id
575 * @attr ref android.R.styleable#View_fadingEdge
576 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700577 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700579 * @attr ref android.R.styleable#View_isScrollContainer
580 * @attr ref android.R.styleable#View_focusable
581 * @attr ref android.R.styleable#View_focusableInTouchMode
582 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
583 * @attr ref android.R.styleable#View_keepScreenOn
584 * @attr ref android.R.styleable#View_longClickable
585 * @attr ref android.R.styleable#View_minHeight
586 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 * @attr ref android.R.styleable#View_nextFocusDown
588 * @attr ref android.R.styleable#View_nextFocusLeft
589 * @attr ref android.R.styleable#View_nextFocusRight
590 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700591 * @attr ref android.R.styleable#View_onClick
592 * @attr ref android.R.styleable#View_padding
593 * @attr ref android.R.styleable#View_paddingBottom
594 * @attr ref android.R.styleable#View_paddingLeft
595 * @attr ref android.R.styleable#View_paddingRight
596 * @attr ref android.R.styleable#View_paddingTop
597 * @attr ref android.R.styleable#View_saveEnabled
Chet Haase73066682010-11-29 15:55:32 -0800598 * @attr ref android.R.styleable#View_rotation
599 * @attr ref android.R.styleable#View_rotationX
600 * @attr ref android.R.styleable#View_rotationY
601 * @attr ref android.R.styleable#View_scaleX
602 * @attr ref android.R.styleable#View_scaleY
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 * @attr ref android.R.styleable#View_scrollX
604 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700605 * @attr ref android.R.styleable#View_scrollbarSize
606 * @attr ref android.R.styleable#View_scrollbarStyle
607 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700608 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
609 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
611 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 * @attr ref android.R.styleable#View_scrollbarThumbVertical
613 * @attr ref android.R.styleable#View_scrollbarTrackVertical
614 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
615 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700616 * @attr ref android.R.styleable#View_soundEffectsEnabled
617 * @attr ref android.R.styleable#View_tag
Chet Haase73066682010-11-29 15:55:32 -0800618 * @attr ref android.R.styleable#View_transformPivotX
619 * @attr ref android.R.styleable#View_transformPivotY
620 * @attr ref android.R.styleable#View_translationX
621 * @attr ref android.R.styleable#View_translationY
Romain Guyd6a463a2009-05-21 23:10:10 -0700622 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 *
624 * @see android.view.ViewGroup
625 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700626public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 private static final boolean DBG = false;
628
629 /**
630 * The logging tag used by this class with android.util.Log.
631 */
632 protected static final String VIEW_LOG_TAG = "View";
633
634 /**
635 * Used to mark a View that has no ID.
636 */
637 public static final int NO_ID = -1;
638
639 /**
640 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
641 * calling setFlags.
642 */
643 private static final int NOT_FOCUSABLE = 0x00000000;
644
645 /**
646 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
647 * setFlags.
648 */
649 private static final int FOCUSABLE = 0x00000001;
650
651 /**
652 * Mask for use with setFlags indicating bits used for focus.
653 */
654 private static final int FOCUSABLE_MASK = 0x00000001;
655
656 /**
657 * This view will adjust its padding to fit sytem windows (e.g. status bar)
658 */
659 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
660
661 /**
662 * This view is visible. Use with {@link #setVisibility}.
663 */
664 public static final int VISIBLE = 0x00000000;
665
666 /**
667 * This view is invisible, but it still takes up space for layout purposes.
668 * Use with {@link #setVisibility}.
669 */
670 public static final int INVISIBLE = 0x00000004;
671
672 /**
673 * This view is invisible, and it doesn't take any space for layout
674 * purposes. Use with {@link #setVisibility}.
675 */
676 public static final int GONE = 0x00000008;
677
678 /**
679 * Mask for use with setFlags indicating bits used for visibility.
680 * {@hide}
681 */
682 static final int VISIBILITY_MASK = 0x0000000C;
683
684 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
685
686 /**
687 * This view is enabled. Intrepretation varies by subclass.
688 * Use with ENABLED_MASK when calling setFlags.
689 * {@hide}
690 */
691 static final int ENABLED = 0x00000000;
692
693 /**
694 * This view is disabled. Intrepretation varies by subclass.
695 * Use with ENABLED_MASK when calling setFlags.
696 * {@hide}
697 */
698 static final int DISABLED = 0x00000020;
699
700 /**
701 * Mask for use with setFlags indicating bits used for indicating whether
702 * this view is enabled
703 * {@hide}
704 */
705 static final int ENABLED_MASK = 0x00000020;
706
707 /**
708 * This view won't draw. {@link #onDraw} won't be called and further
709 * optimizations
710 * will be performed. It is okay to have this flag set and a background.
711 * Use with DRAW_MASK when calling setFlags.
712 * {@hide}
713 */
714 static final int WILL_NOT_DRAW = 0x00000080;
715
716 /**
717 * Mask for use with setFlags indicating bits used for indicating whether
718 * this view is will draw
719 * {@hide}
720 */
721 static final int DRAW_MASK = 0x00000080;
722
723 /**
724 * <p>This view doesn't show scrollbars.</p>
725 * {@hide}
726 */
727 static final int SCROLLBARS_NONE = 0x00000000;
728
729 /**
730 * <p>This view shows horizontal scrollbars.</p>
731 * {@hide}
732 */
733 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
734
735 /**
736 * <p>This view shows vertical scrollbars.</p>
737 * {@hide}
738 */
739 static final int SCROLLBARS_VERTICAL = 0x00000200;
740
741 /**
742 * <p>Mask for use with setFlags indicating bits used for indicating which
743 * scrollbars are enabled.</p>
744 * {@hide}
745 */
746 static final int SCROLLBARS_MASK = 0x00000300;
747
Jeff Brown85a31762010-09-01 17:01:00 -0700748 /**
749 * Indicates that the view should filter touches when its window is obscured.
750 * Refer to the class comments for more information about this security feature.
751 * {@hide}
752 */
753 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
754
755 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756
757 /**
758 * <p>This view doesn't show fading edges.</p>
759 * {@hide}
760 */
761 static final int FADING_EDGE_NONE = 0x00000000;
762
763 /**
764 * <p>This view shows horizontal fading edges.</p>
765 * {@hide}
766 */
767 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
768
769 /**
770 * <p>This view shows vertical fading edges.</p>
771 * {@hide}
772 */
773 static final int FADING_EDGE_VERTICAL = 0x00002000;
774
775 /**
776 * <p>Mask for use with setFlags indicating bits used for indicating which
777 * fading edges are enabled.</p>
778 * {@hide}
779 */
780 static final int FADING_EDGE_MASK = 0x00003000;
781
782 /**
783 * <p>Indicates this view can be clicked. When clickable, a View reacts
784 * to clicks by notifying the OnClickListener.<p>
785 * {@hide}
786 */
787 static final int CLICKABLE = 0x00004000;
788
789 /**
790 * <p>Indicates this view is caching its drawing into a bitmap.</p>
791 * {@hide}
792 */
793 static final int DRAWING_CACHE_ENABLED = 0x00008000;
794
795 /**
796 * <p>Indicates that no icicle should be saved for this view.<p>
797 * {@hide}
798 */
799 static final int SAVE_DISABLED = 0x000010000;
800
801 /**
802 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
803 * property.</p>
804 * {@hide}
805 */
806 static final int SAVE_DISABLED_MASK = 0x000010000;
807
808 /**
809 * <p>Indicates that no drawing cache should ever be created for this view.<p>
810 * {@hide}
811 */
812 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
813
814 /**
815 * <p>Indicates this view can take / keep focus when int touch mode.</p>
816 * {@hide}
817 */
818 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
819
820 /**
821 * <p>Enables low quality mode for the drawing cache.</p>
822 */
823 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
824
825 /**
826 * <p>Enables high quality mode for the drawing cache.</p>
827 */
828 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
829
830 /**
831 * <p>Enables automatic quality mode for the drawing cache.</p>
832 */
833 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
834
835 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
836 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
837 };
838
839 /**
840 * <p>Mask for use with setFlags indicating bits used for the cache
841 * quality property.</p>
842 * {@hide}
843 */
844 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
845
846 /**
847 * <p>
848 * Indicates this view can be long clicked. When long clickable, a View
849 * reacts to long clicks by notifying the OnLongClickListener or showing a
850 * context menu.
851 * </p>
852 * {@hide}
853 */
854 static final int LONG_CLICKABLE = 0x00200000;
855
856 /**
857 * <p>Indicates that this view gets its drawable states from its direct parent
858 * and ignores its original internal states.</p>
859 *
860 * @hide
861 */
862 static final int DUPLICATE_PARENT_STATE = 0x00400000;
863
864 /**
865 * The scrollbar style to display the scrollbars inside the content area,
866 * without increasing the padding. The scrollbars will be overlaid with
867 * translucency on the view's content.
868 */
869 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
870
871 /**
872 * The scrollbar style to display the scrollbars inside the padded area,
873 * increasing the padding of the view. The scrollbars will not overlap the
874 * content area of the view.
875 */
876 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
877
878 /**
879 * The scrollbar style to display the scrollbars at the edge of the view,
880 * without increasing the padding. The scrollbars will be overlaid with
881 * translucency.
882 */
883 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
884
885 /**
886 * The scrollbar style to display the scrollbars at the edge of the view,
887 * increasing the padding of the view. The scrollbars will only overlap the
888 * background, if any.
889 */
890 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
891
892 /**
893 * Mask to check if the scrollbar style is overlay or inset.
894 * {@hide}
895 */
896 static final int SCROLLBARS_INSET_MASK = 0x01000000;
897
898 /**
899 * Mask to check if the scrollbar style is inside or outside.
900 * {@hide}
901 */
902 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
903
904 /**
905 * Mask for scrollbar style.
906 * {@hide}
907 */
908 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
909
910 /**
911 * View flag indicating that the screen should remain on while the
912 * window containing this view is visible to the user. This effectively
913 * takes care of automatically setting the WindowManager's
914 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
915 */
916 public static final int KEEP_SCREEN_ON = 0x04000000;
917
918 /**
919 * View flag indicating whether this view should have sound effects enabled
920 * for events such as clicking and touching.
921 */
922 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
923
924 /**
925 * View flag indicating whether this view should have haptic feedback
926 * enabled for events such as long presses.
927 */
928 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
929
930 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700931 * <p>Indicates that the view hierarchy should stop saving state when
932 * it reaches this view. If state saving is initiated immediately at
933 * the view, it will be allowed.
934 * {@hide}
935 */
936 static final int PARENT_SAVE_DISABLED = 0x20000000;
937
938 /**
939 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
940 * {@hide}
941 */
942 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
943
944 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700945 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
946 * should add all focusable Views regardless if they are focusable in touch mode.
947 */
948 public static final int FOCUSABLES_ALL = 0x00000000;
949
950 /**
951 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
952 * should add only Views focusable in touch mode.
953 */
954 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
955
956 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 * Use with {@link #focusSearch}. Move focus to the previous selectable
958 * item.
959 */
960 public static final int FOCUS_BACKWARD = 0x00000001;
961
962 /**
963 * Use with {@link #focusSearch}. Move focus to the next selectable
964 * item.
965 */
966 public static final int FOCUS_FORWARD = 0x00000002;
967
968 /**
969 * Use with {@link #focusSearch}. Move focus to the left.
970 */
971 public static final int FOCUS_LEFT = 0x00000011;
972
973 /**
974 * Use with {@link #focusSearch}. Move focus up.
975 */
976 public static final int FOCUS_UP = 0x00000021;
977
978 /**
979 * Use with {@link #focusSearch}. Move focus to the right.
980 */
981 public static final int FOCUS_RIGHT = 0x00000042;
982
983 /**
984 * Use with {@link #focusSearch}. Move focus down.
985 */
986 public static final int FOCUS_DOWN = 0x00000082;
987
988 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -0800989 * Bits of {@link #getMeasuredWidthAndState()} and
990 * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
991 */
992 public static final int MEASURED_SIZE_MASK = 0x00ffffff;
993
994 /**
995 * Bits of {@link #getMeasuredWidthAndState()} and
996 * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
997 */
998 public static final int MEASURED_STATE_MASK = 0xff000000;
999
1000 /**
1001 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1002 * for functions that combine both width and height into a single int,
1003 * such as {@link #getMeasuredState()} and the childState argument of
1004 * {@link #resolveSizeAndState(int, int, int)}.
1005 */
1006 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1007
1008 /**
1009 * Bit of {@link #getMeasuredWidthAndState()} and
1010 * {@link #getMeasuredWidthAndState()} that indicates the measured size
1011 * is smaller that the space the view would like to have.
1012 */
1013 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1014
1015 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 * Base View state sets
1017 */
1018 // Singles
1019 /**
1020 * Indicates the view has no states set. States are used with
1021 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1022 * view depending on its state.
1023 *
1024 * @see android.graphics.drawable.Drawable
1025 * @see #getDrawableState()
1026 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001027 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 /**
1029 * Indicates the view is enabled. States are used with
1030 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1031 * view depending on its state.
1032 *
1033 * @see android.graphics.drawable.Drawable
1034 * @see #getDrawableState()
1035 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001036 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 /**
1038 * Indicates the view is focused. States are used with
1039 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1040 * view depending on its state.
1041 *
1042 * @see android.graphics.drawable.Drawable
1043 * @see #getDrawableState()
1044 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001045 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 /**
1047 * Indicates the view is selected. States are used with
1048 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1049 * view depending on its state.
1050 *
1051 * @see android.graphics.drawable.Drawable
1052 * @see #getDrawableState()
1053 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001054 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 /**
1056 * Indicates the view is pressed. States are used with
1057 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1058 * view depending on its state.
1059 *
1060 * @see android.graphics.drawable.Drawable
1061 * @see #getDrawableState()
1062 * @hide
1063 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001064 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 /**
1066 * Indicates the view's window has focus. States are used with
1067 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1068 * view depending on its state.
1069 *
1070 * @see android.graphics.drawable.Drawable
1071 * @see #getDrawableState()
1072 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001073 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 // Doubles
1075 /**
1076 * Indicates the view is enabled and has the focus.
1077 *
1078 * @see #ENABLED_STATE_SET
1079 * @see #FOCUSED_STATE_SET
1080 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001081 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 /**
1083 * Indicates the view is enabled and selected.
1084 *
1085 * @see #ENABLED_STATE_SET
1086 * @see #SELECTED_STATE_SET
1087 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001088 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 /**
1090 * Indicates the view is enabled and that its window has focus.
1091 *
1092 * @see #ENABLED_STATE_SET
1093 * @see #WINDOW_FOCUSED_STATE_SET
1094 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001095 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 /**
1097 * Indicates the view is focused and selected.
1098 *
1099 * @see #FOCUSED_STATE_SET
1100 * @see #SELECTED_STATE_SET
1101 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001102 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 /**
1104 * Indicates the view has the focus and that its window has the focus.
1105 *
1106 * @see #FOCUSED_STATE_SET
1107 * @see #WINDOW_FOCUSED_STATE_SET
1108 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001109 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 /**
1111 * Indicates the view is selected and that its window has the focus.
1112 *
1113 * @see #SELECTED_STATE_SET
1114 * @see #WINDOW_FOCUSED_STATE_SET
1115 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001116 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 // Triples
1118 /**
1119 * Indicates the view is enabled, focused and selected.
1120 *
1121 * @see #ENABLED_STATE_SET
1122 * @see #FOCUSED_STATE_SET
1123 * @see #SELECTED_STATE_SET
1124 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001125 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 /**
1127 * Indicates the view is enabled, focused and its window has the focus.
1128 *
1129 * @see #ENABLED_STATE_SET
1130 * @see #FOCUSED_STATE_SET
1131 * @see #WINDOW_FOCUSED_STATE_SET
1132 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001133 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 /**
1135 * Indicates the view is enabled, selected and its window has the focus.
1136 *
1137 * @see #ENABLED_STATE_SET
1138 * @see #SELECTED_STATE_SET
1139 * @see #WINDOW_FOCUSED_STATE_SET
1140 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001141 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 /**
1143 * Indicates the view is focused, selected and its window has the focus.
1144 *
1145 * @see #FOCUSED_STATE_SET
1146 * @see #SELECTED_STATE_SET
1147 * @see #WINDOW_FOCUSED_STATE_SET
1148 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001149 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 /**
1151 * Indicates the view is enabled, focused, selected and its window
1152 * has the focus.
1153 *
1154 * @see #ENABLED_STATE_SET
1155 * @see #FOCUSED_STATE_SET
1156 * @see #SELECTED_STATE_SET
1157 * @see #WINDOW_FOCUSED_STATE_SET
1158 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001159 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 /**
1161 * Indicates the view is pressed and its window has the focus.
1162 *
1163 * @see #PRESSED_STATE_SET
1164 * @see #WINDOW_FOCUSED_STATE_SET
1165 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001166 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 /**
1168 * Indicates the view is pressed and selected.
1169 *
1170 * @see #PRESSED_STATE_SET
1171 * @see #SELECTED_STATE_SET
1172 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001173 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 /**
1175 * Indicates the view is pressed, selected and its window has the focus.
1176 *
1177 * @see #PRESSED_STATE_SET
1178 * @see #SELECTED_STATE_SET
1179 * @see #WINDOW_FOCUSED_STATE_SET
1180 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001181 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 /**
1183 * Indicates the view is pressed and focused.
1184 *
1185 * @see #PRESSED_STATE_SET
1186 * @see #FOCUSED_STATE_SET
1187 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001188 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 /**
1190 * Indicates the view is pressed, focused and its window has the focus.
1191 *
1192 * @see #PRESSED_STATE_SET
1193 * @see #FOCUSED_STATE_SET
1194 * @see #WINDOW_FOCUSED_STATE_SET
1195 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001196 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 /**
1198 * Indicates the view is pressed, focused and selected.
1199 *
1200 * @see #PRESSED_STATE_SET
1201 * @see #SELECTED_STATE_SET
1202 * @see #FOCUSED_STATE_SET
1203 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001204 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 /**
1206 * Indicates the view is pressed, focused, selected and its window has the focus.
1207 *
1208 * @see #PRESSED_STATE_SET
1209 * @see #FOCUSED_STATE_SET
1210 * @see #SELECTED_STATE_SET
1211 * @see #WINDOW_FOCUSED_STATE_SET
1212 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001213 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 /**
1215 * Indicates the view is pressed and enabled.
1216 *
1217 * @see #PRESSED_STATE_SET
1218 * @see #ENABLED_STATE_SET
1219 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001220 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 /**
1222 * Indicates the view is pressed, enabled and its window has the focus.
1223 *
1224 * @see #PRESSED_STATE_SET
1225 * @see #ENABLED_STATE_SET
1226 * @see #WINDOW_FOCUSED_STATE_SET
1227 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001228 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 /**
1230 * Indicates the view is pressed, enabled and selected.
1231 *
1232 * @see #PRESSED_STATE_SET
1233 * @see #ENABLED_STATE_SET
1234 * @see #SELECTED_STATE_SET
1235 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001236 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 /**
1238 * Indicates the view is pressed, enabled, selected and its window has the
1239 * focus.
1240 *
1241 * @see #PRESSED_STATE_SET
1242 * @see #ENABLED_STATE_SET
1243 * @see #SELECTED_STATE_SET
1244 * @see #WINDOW_FOCUSED_STATE_SET
1245 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001246 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 /**
1248 * Indicates the view is pressed, enabled and focused.
1249 *
1250 * @see #PRESSED_STATE_SET
1251 * @see #ENABLED_STATE_SET
1252 * @see #FOCUSED_STATE_SET
1253 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001254 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 /**
1256 * Indicates the view is pressed, enabled, focused and its window has the
1257 * focus.
1258 *
1259 * @see #PRESSED_STATE_SET
1260 * @see #ENABLED_STATE_SET
1261 * @see #FOCUSED_STATE_SET
1262 * @see #WINDOW_FOCUSED_STATE_SET
1263 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001264 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 /**
1266 * Indicates the view is pressed, enabled, focused and selected.
1267 *
1268 * @see #PRESSED_STATE_SET
1269 * @see #ENABLED_STATE_SET
1270 * @see #SELECTED_STATE_SET
1271 * @see #FOCUSED_STATE_SET
1272 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001273 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 /**
1275 * Indicates the view is pressed, enabled, focused, selected and its window
1276 * has the focus.
1277 *
1278 * @see #PRESSED_STATE_SET
1279 * @see #ENABLED_STATE_SET
1280 * @see #SELECTED_STATE_SET
1281 * @see #FOCUSED_STATE_SET
1282 * @see #WINDOW_FOCUSED_STATE_SET
1283 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001284 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285
1286 /**
1287 * The order here is very important to {@link #getDrawableState()}
1288 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001289 private static final int[][] VIEW_STATE_SETS;
1290
Romain Guyb051e892010-09-28 19:09:36 -07001291 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1292 static final int VIEW_STATE_SELECTED = 1 << 1;
1293 static final int VIEW_STATE_FOCUSED = 1 << 2;
1294 static final int VIEW_STATE_ENABLED = 1 << 3;
1295 static final int VIEW_STATE_PRESSED = 1 << 4;
1296 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001297 static final int VIEW_STATE_ACCELERATED = 1 << 6;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001298
1299 static final int[] VIEW_STATE_IDS = new int[] {
1300 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1301 R.attr.state_selected, VIEW_STATE_SELECTED,
1302 R.attr.state_focused, VIEW_STATE_FOCUSED,
1303 R.attr.state_enabled, VIEW_STATE_ENABLED,
1304 R.attr.state_pressed, VIEW_STATE_PRESSED,
1305 R.attr.state_activated, VIEW_STATE_ACTIVATED,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001306 R.attr.state_accelerated, VIEW_STATE_ACCELERATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 };
1308
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001309 static {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001310 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1311 throw new IllegalStateException(
1312 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1313 }
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001314 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001315 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001316 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001317 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001318 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001319 orderedIds[i * 2] = viewState;
1320 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001321 }
1322 }
1323 }
Romain Guyb051e892010-09-28 19:09:36 -07001324 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1325 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1326 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001327 int numBits = Integer.bitCount(i);
1328 int[] set = new int[numBits];
1329 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001330 for (int j = 0; j < orderedIds.length; j += 2) {
1331 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001332 set[pos++] = orderedIds[j];
1333 }
1334 }
1335 VIEW_STATE_SETS[i] = set;
1336 }
1337
1338 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1339 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1340 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1341 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1342 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1343 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1344 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1345 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1346 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1347 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1348 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1349 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1350 | VIEW_STATE_FOCUSED];
1351 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1352 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1353 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1354 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1355 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1356 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1357 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1358 | VIEW_STATE_ENABLED];
1359 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1360 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1361 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1362 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1363 | VIEW_STATE_ENABLED];
1364 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1365 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1366 | VIEW_STATE_ENABLED];
1367 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1368 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1369 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1370
1371 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1372 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1373 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1374 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1375 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1376 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1377 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1378 | VIEW_STATE_PRESSED];
1379 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1380 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1381 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1382 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1383 | VIEW_STATE_PRESSED];
1384 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1385 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1386 | VIEW_STATE_PRESSED];
1387 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1388 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1389 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1390 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1391 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1392 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1393 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1394 | VIEW_STATE_PRESSED];
1395 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1396 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1397 | VIEW_STATE_PRESSED];
1398 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1399 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1400 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1401 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1402 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1403 | VIEW_STATE_PRESSED];
1404 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1405 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1406 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1407 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1408 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1409 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1410 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1411 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1412 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1413 | VIEW_STATE_PRESSED];
1414 }
1415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 /**
1417 * Used by views that contain lists of items. This state indicates that
1418 * the view is showing the last item.
1419 * @hide
1420 */
1421 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1422 /**
1423 * Used by views that contain lists of items. This state indicates that
1424 * the view is showing the first item.
1425 * @hide
1426 */
1427 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1428 /**
1429 * Used by views that contain lists of items. This state indicates that
1430 * the view is showing the middle item.
1431 * @hide
1432 */
1433 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1434 /**
1435 * Used by views that contain lists of items. This state indicates that
1436 * the view is showing only one item.
1437 * @hide
1438 */
1439 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1440 /**
1441 * Used by views that contain lists of items. This state indicates that
1442 * the view is pressed and showing the last item.
1443 * @hide
1444 */
1445 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1446 /**
1447 * Used by views that contain lists of items. This state indicates that
1448 * the view is pressed and showing the first item.
1449 * @hide
1450 */
1451 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1452 /**
1453 * Used by views that contain lists of items. This state indicates that
1454 * the view is pressed and showing the middle item.
1455 * @hide
1456 */
1457 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1458 /**
1459 * Used by views that contain lists of items. This state indicates that
1460 * the view is pressed and showing only one item.
1461 * @hide
1462 */
1463 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1464
1465 /**
1466 * Temporary Rect currently for use in setBackground(). This will probably
1467 * be extended in the future to hold our own class with more than just
1468 * a Rect. :)
1469 */
1470 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001471
1472 /**
1473 * Map used to store views' tags.
1474 */
1475 private static WeakHashMap<View, SparseArray<Object>> sTags;
1476
1477 /**
1478 * Lock used to access sTags.
1479 */
1480 private static final Object sTagsLock = new Object();
1481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 /**
1483 * The animation currently associated with this view.
1484 * @hide
1485 */
1486 protected Animation mCurrentAnimation = null;
1487
1488 /**
1489 * Width as measured during measure pass.
1490 * {@hide}
1491 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001492 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001493 /*package*/ int mMeasuredWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494
1495 /**
1496 * Height as measured during measure pass.
1497 * {@hide}
1498 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001499 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001500 /*package*/ int mMeasuredHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501
1502 /**
1503 * The view's identifier.
1504 * {@hide}
1505 *
1506 * @see #setId(int)
1507 * @see #getId()
1508 */
1509 @ViewDebug.ExportedProperty(resolveId = true)
1510 int mID = NO_ID;
1511
1512 /**
1513 * The view's tag.
1514 * {@hide}
1515 *
1516 * @see #setTag(Object)
1517 * @see #getTag()
1518 */
1519 protected Object mTag;
1520
1521 // for mPrivateFlags:
1522 /** {@hide} */
1523 static final int WANTS_FOCUS = 0x00000001;
1524 /** {@hide} */
1525 static final int FOCUSED = 0x00000002;
1526 /** {@hide} */
1527 static final int SELECTED = 0x00000004;
1528 /** {@hide} */
1529 static final int IS_ROOT_NAMESPACE = 0x00000008;
1530 /** {@hide} */
1531 static final int HAS_BOUNDS = 0x00000010;
1532 /** {@hide} */
1533 static final int DRAWN = 0x00000020;
1534 /**
1535 * When this flag is set, this view is running an animation on behalf of its
1536 * children and should therefore not cancel invalidate requests, even if they
1537 * lie outside of this view's bounds.
1538 *
1539 * {@hide}
1540 */
1541 static final int DRAW_ANIMATION = 0x00000040;
1542 /** {@hide} */
1543 static final int SKIP_DRAW = 0x00000080;
1544 /** {@hide} */
1545 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1546 /** {@hide} */
1547 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1548 /** {@hide} */
1549 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1550 /** {@hide} */
1551 static final int MEASURED_DIMENSION_SET = 0x00000800;
1552 /** {@hide} */
1553 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001554 /** {@hide} */
1555 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556
1557 private static final int PRESSED = 0x00004000;
1558
1559 /** {@hide} */
1560 static final int DRAWING_CACHE_VALID = 0x00008000;
1561 /**
1562 * Flag used to indicate that this view should be drawn once more (and only once
1563 * more) after its animation has completed.
1564 * {@hide}
1565 */
1566 static final int ANIMATION_STARTED = 0x00010000;
1567
1568 private static final int SAVE_STATE_CALLED = 0x00020000;
1569
1570 /**
1571 * Indicates that the View returned true when onSetAlpha() was called and that
1572 * the alpha must be restored.
1573 * {@hide}
1574 */
1575 static final int ALPHA_SET = 0x00040000;
1576
1577 /**
1578 * Set by {@link #setScrollContainer(boolean)}.
1579 */
1580 static final int SCROLL_CONTAINER = 0x00080000;
1581
1582 /**
1583 * Set by {@link #setScrollContainer(boolean)}.
1584 */
1585 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1586
1587 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001588 * View flag indicating whether this view was invalidated (fully or partially.)
1589 *
1590 * @hide
1591 */
1592 static final int DIRTY = 0x00200000;
1593
1594 /**
1595 * View flag indicating whether this view was invalidated by an opaque
1596 * invalidate request.
1597 *
1598 * @hide
1599 */
1600 static final int DIRTY_OPAQUE = 0x00400000;
1601
1602 /**
1603 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1604 *
1605 * @hide
1606 */
1607 static final int DIRTY_MASK = 0x00600000;
1608
1609 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001610 * Indicates whether the background is opaque.
1611 *
1612 * @hide
1613 */
1614 static final int OPAQUE_BACKGROUND = 0x00800000;
1615
1616 /**
1617 * Indicates whether the scrollbars are opaque.
1618 *
1619 * @hide
1620 */
1621 static final int OPAQUE_SCROLLBARS = 0x01000000;
1622
1623 /**
1624 * Indicates whether the view is opaque.
1625 *
1626 * @hide
1627 */
1628 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001629
1630 /**
1631 * Indicates a prepressed state;
1632 * the short time between ACTION_DOWN and recognizing
1633 * a 'real' press. Prepressed is used to recognize quick taps
1634 * even when they are shorter than ViewConfiguration.getTapTimeout().
1635 *
1636 * @hide
1637 */
1638 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001639
1640 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001641 * Indicates whether the view is temporarily detached.
1642 *
1643 * @hide
1644 */
1645 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001646
1647 /**
1648 * Indicates that we should awaken scroll bars once attached
1649 *
1650 * @hide
1651 */
1652 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001653
1654 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001655 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1656 * for transform operations
1657 *
1658 * @hide
1659 */
Adam Powellf37df072010-09-17 16:22:49 -07001660 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001661
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001662 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001663 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001664
Chet Haasefd2b0022010-08-06 13:08:56 -07001665 /**
Adam Powell637d3372010-08-25 14:37:03 -07001666 * Always allow a user to over-scroll this view, provided it is a
1667 * view that can scroll.
1668 *
1669 * @see #getOverScrollMode()
1670 * @see #setOverScrollMode(int)
1671 */
1672 public static final int OVER_SCROLL_ALWAYS = 0;
1673
1674 /**
1675 * Allow a user to over-scroll this view only if the content is large
1676 * enough to meaningfully scroll, provided it is a view that can scroll.
1677 *
1678 * @see #getOverScrollMode()
1679 * @see #setOverScrollMode(int)
1680 */
1681 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1682
1683 /**
1684 * Never allow a user to over-scroll this view.
1685 *
1686 * @see #getOverScrollMode()
1687 * @see #setOverScrollMode(int)
1688 */
1689 public static final int OVER_SCROLL_NEVER = 2;
1690
1691 /**
1692 * Controls the over-scroll mode for this view.
1693 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1694 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1695 * and {@link #OVER_SCROLL_NEVER}.
1696 */
1697 private int mOverScrollMode;
1698
1699 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 * The parent this view is attached to.
1701 * {@hide}
1702 *
1703 * @see #getParent()
1704 */
1705 protected ViewParent mParent;
1706
1707 /**
1708 * {@hide}
1709 */
1710 AttachInfo mAttachInfo;
1711
1712 /**
1713 * {@hide}
1714 */
Romain Guy809a7f62009-05-14 15:44:42 -07001715 @ViewDebug.ExportedProperty(flagMapping = {
1716 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1717 name = "FORCE_LAYOUT"),
1718 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1719 name = "LAYOUT_REQUIRED"),
1720 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001721 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001722 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1723 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1724 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1725 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1726 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 int mPrivateFlags;
1728
1729 /**
1730 * Count of how many windows this view has been attached to.
1731 */
1732 int mWindowAttachCount;
1733
1734 /**
1735 * The layout parameters associated with this view and used by the parent
1736 * {@link android.view.ViewGroup} to determine how this view should be
1737 * laid out.
1738 * {@hide}
1739 */
1740 protected ViewGroup.LayoutParams mLayoutParams;
1741
1742 /**
1743 * The view flags hold various views states.
1744 * {@hide}
1745 */
1746 @ViewDebug.ExportedProperty
1747 int mViewFlags;
1748
1749 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001750 * The transform matrix for the View. This transform is calculated internally
1751 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1752 * is used by default. Do *not* use this variable directly; instead call
1753 * getMatrix(), which will automatically recalculate the matrix if necessary
1754 * to get the correct matrix based on the latest rotation and scale properties.
1755 */
1756 private final Matrix mMatrix = new Matrix();
1757
1758 /**
1759 * The transform matrix for the View. This transform is calculated internally
1760 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1761 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001762 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001763 * to get the correct matrix based on the latest rotation and scale properties.
1764 */
1765 private Matrix mInverseMatrix;
1766
1767 /**
1768 * An internal variable that tracks whether we need to recalculate the
1769 * transform matrix, based on whether the rotation or scaleX/Y properties
1770 * have changed since the matrix was last calculated.
1771 */
1772 private boolean mMatrixDirty = false;
1773
1774 /**
1775 * An internal variable that tracks whether we need to recalculate the
1776 * transform matrix, based on whether the rotation or scaleX/Y properties
1777 * have changed since the matrix was last calculated.
1778 */
1779 private boolean mInverseMatrixDirty = true;
1780
1781 /**
1782 * A variable that tracks whether we need to recalculate the
1783 * transform matrix, based on whether the rotation or scaleX/Y properties
1784 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001785 * is only valid after a call to updateMatrix() or to a function that
1786 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001787 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001788 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001789
1790 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001791 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1792 */
1793 private Camera mCamera = null;
1794
1795 /**
1796 * This matrix is used when computing the matrix for 3D rotations.
1797 */
1798 private Matrix matrix3D = null;
1799
1800 /**
1801 * These prev values are used to recalculate a centered pivot point when necessary. The
1802 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1803 * set), so thes values are only used then as well.
1804 */
1805 private int mPrevWidth = -1;
1806 private int mPrevHeight = -1;
1807
1808 /**
1809 * Convenience value to check for float values that are close enough to zero to be considered
1810 * zero.
1811 */
Romain Guy2542d192010-08-18 11:47:12 -07001812 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001813
1814 /**
1815 * The degrees rotation around the vertical axis through the pivot point.
1816 */
1817 @ViewDebug.ExportedProperty
1818 private float mRotationY = 0f;
1819
1820 /**
1821 * The degrees rotation around the horizontal axis through the pivot point.
1822 */
1823 @ViewDebug.ExportedProperty
1824 private float mRotationX = 0f;
1825
1826 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001827 * The degrees rotation around the pivot point.
1828 */
1829 @ViewDebug.ExportedProperty
1830 private float mRotation = 0f;
1831
1832 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001833 * The amount of translation of the object away from its left property (post-layout).
1834 */
1835 @ViewDebug.ExportedProperty
1836 private float mTranslationX = 0f;
1837
1838 /**
1839 * The amount of translation of the object away from its top property (post-layout).
1840 */
1841 @ViewDebug.ExportedProperty
1842 private float mTranslationY = 0f;
1843
1844 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001845 * The amount of scale in the x direction around the pivot point. A
1846 * value of 1 means no scaling is applied.
1847 */
1848 @ViewDebug.ExportedProperty
1849 private float mScaleX = 1f;
1850
1851 /**
1852 * The amount of scale in the y direction around the pivot point. A
1853 * value of 1 means no scaling is applied.
1854 */
1855 @ViewDebug.ExportedProperty
1856 private float mScaleY = 1f;
1857
1858 /**
1859 * The amount of scale in the x direction around the pivot point. A
1860 * value of 1 means no scaling is applied.
1861 */
1862 @ViewDebug.ExportedProperty
1863 private float mPivotX = 0f;
1864
1865 /**
1866 * The amount of scale in the y direction around the pivot point. A
1867 * value of 1 means no scaling is applied.
1868 */
1869 @ViewDebug.ExportedProperty
1870 private float mPivotY = 0f;
1871
1872 /**
1873 * The opacity of the View. This is a value from 0 to 1, where 0 means
1874 * completely transparent and 1 means completely opaque.
1875 */
1876 @ViewDebug.ExportedProperty
1877 private float mAlpha = 1f;
1878
1879 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 * The distance in pixels from the left edge of this view's parent
1881 * to the left edge of this view.
1882 * {@hide}
1883 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001884 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 protected int mLeft;
1886 /**
1887 * The distance in pixels from the left edge of this view's parent
1888 * to the right edge of this view.
1889 * {@hide}
1890 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001891 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 protected int mRight;
1893 /**
1894 * The distance in pixels from the top edge of this view's parent
1895 * to the top edge of this view.
1896 * {@hide}
1897 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001898 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 protected int mTop;
1900 /**
1901 * The distance in pixels from the top edge of this view's parent
1902 * to the bottom edge of this view.
1903 * {@hide}
1904 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001905 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 protected int mBottom;
1907
1908 /**
1909 * The offset, in pixels, by which the content of this view is scrolled
1910 * horizontally.
1911 * {@hide}
1912 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001913 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 protected int mScrollX;
1915 /**
1916 * The offset, in pixels, by which the content of this view is scrolled
1917 * vertically.
1918 * {@hide}
1919 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001920 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 protected int mScrollY;
1922
1923 /**
1924 * The left padding in pixels, that is the distance in pixels between the
1925 * left edge of this view and the left edge of its content.
1926 * {@hide}
1927 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001928 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 protected int mPaddingLeft;
1930 /**
1931 * The right padding in pixels, that is the distance in pixels between the
1932 * right edge of this view and the right edge of its content.
1933 * {@hide}
1934 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001935 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 protected int mPaddingRight;
1937 /**
1938 * The top padding in pixels, that is the distance in pixels between the
1939 * top edge of this view and the top edge of its content.
1940 * {@hide}
1941 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001942 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 protected int mPaddingTop;
1944 /**
1945 * The bottom padding in pixels, that is the distance in pixels between the
1946 * bottom edge of this view and the bottom edge of its content.
1947 * {@hide}
1948 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001949 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 protected int mPaddingBottom;
1951
1952 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001953 * Briefly describes the view and is primarily used for accessibility support.
1954 */
1955 private CharSequence mContentDescription;
1956
1957 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 * Cache the paddingRight set by the user to append to the scrollbar's size.
1959 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001960 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 int mUserPaddingRight;
1962
1963 /**
1964 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1965 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001966 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 int mUserPaddingBottom;
1968
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001969 /**
1970 * @hide
1971 */
1972 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1973 /**
1974 * @hide
1975 */
1976 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977
1978 private Resources mResources = null;
1979
1980 private Drawable mBGDrawable;
1981
1982 private int mBackgroundResource;
1983 private boolean mBackgroundSizeChanged;
1984
1985 /**
1986 * Listener used to dispatch focus change events.
1987 * This field should be made private, so it is hidden from the SDK.
1988 * {@hide}
1989 */
1990 protected OnFocusChangeListener mOnFocusChangeListener;
1991
1992 /**
Chet Haase21cd1382010-09-01 17:42:29 -07001993 * Listeners for layout change events.
1994 */
1995 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
1996
1997 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 * Listener used to dispatch click events.
1999 * This field should be made private, so it is hidden from the SDK.
2000 * {@hide}
2001 */
2002 protected OnClickListener mOnClickListener;
2003
2004 /**
2005 * Listener used to dispatch long click events.
2006 * This field should be made private, so it is hidden from the SDK.
2007 * {@hide}
2008 */
2009 protected OnLongClickListener mOnLongClickListener;
2010
2011 /**
2012 * Listener used to build the context menu.
2013 * This field should be made private, so it is hidden from the SDK.
2014 * {@hide}
2015 */
2016 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2017
2018 private OnKeyListener mOnKeyListener;
2019
2020 private OnTouchListener mOnTouchListener;
2021
Chris Tate32affef2010-10-18 15:29:21 -07002022 private OnDragListener mOnDragListener;
2023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 /**
2025 * The application environment this view lives in.
2026 * This field should be made private, so it is hidden from the SDK.
2027 * {@hide}
2028 */
2029 protected Context mContext;
2030
2031 private ScrollabilityCache mScrollCache;
2032
2033 private int[] mDrawableState = null;
2034
Romain Guy02890fd2010-08-06 17:58:44 -07002035 private Bitmap mDrawingCache;
2036 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07002037 private DisplayList mDisplayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038
2039 /**
2040 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2041 * the user may specify which view to go to next.
2042 */
2043 private int mNextFocusLeftId = View.NO_ID;
2044
2045 /**
2046 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2047 * the user may specify which view to go to next.
2048 */
2049 private int mNextFocusRightId = View.NO_ID;
2050
2051 /**
2052 * When this view has focus and the next focus is {@link #FOCUS_UP},
2053 * the user may specify which view to go to next.
2054 */
2055 private int mNextFocusUpId = View.NO_ID;
2056
2057 /**
2058 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2059 * the user may specify which view to go to next.
2060 */
2061 private int mNextFocusDownId = View.NO_ID;
2062
2063 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08002064 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08002065 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08002066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 private UnsetPressedState mUnsetPressedState;
2068
2069 /**
2070 * Whether the long press's action has been invoked. The tap's action is invoked on the
2071 * up event while a long press is invoked as soon as the long press duration is reached, so
2072 * a long press could be performed before the tap is checked, in which case the tap's action
2073 * should not be invoked.
2074 */
2075 private boolean mHasPerformedLongPress;
2076
2077 /**
2078 * The minimum height of the view. We'll try our best to have the height
2079 * of this view to at least this amount.
2080 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002081 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 private int mMinHeight;
2083
2084 /**
2085 * The minimum width of the view. We'll try our best to have the width
2086 * of this view to at least this amount.
2087 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002088 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 private int mMinWidth;
2090
2091 /**
2092 * The delegate to handle touch events that are physically in this view
2093 * but should be handled by another view.
2094 */
2095 private TouchDelegate mTouchDelegate = null;
2096
2097 /**
2098 * Solid color to use as a background when creating the drawing cache. Enables
2099 * the cache to use 16 bit bitmaps instead of 32 bit.
2100 */
2101 private int mDrawingCacheBackgroundColor = 0;
2102
2103 /**
2104 * Special tree observer used when mAttachInfo is null.
2105 */
2106 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002107
2108 /**
2109 * Cache the touch slop from the context that created the view.
2110 */
2111 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002114 * Cache drag/drop state
2115 *
2116 */
2117 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002118
2119 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 * Simple constructor to use when creating a view from code.
2121 *
2122 * @param context The Context the view is running in, through which it can
2123 * access the current theme, resources, etc.
2124 */
2125 public View(Context context) {
2126 mContext = context;
2127 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002128 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002129 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Adam Powell637d3372010-08-25 14:37:03 -07002130 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 }
2132
2133 /**
2134 * Constructor that is called when inflating a view from XML. This is called
2135 * when a view is being constructed from an XML file, supplying attributes
2136 * that were specified in the XML file. This version uses a default style of
2137 * 0, so the only attribute values applied are those in the Context's Theme
2138 * and the given AttributeSet.
2139 *
2140 * <p>
2141 * The method onFinishInflate() will be called after all children have been
2142 * added.
2143 *
2144 * @param context The Context the view is running in, through which it can
2145 * access the current theme, resources, etc.
2146 * @param attrs The attributes of the XML tag that is inflating the view.
2147 * @see #View(Context, AttributeSet, int)
2148 */
2149 public View(Context context, AttributeSet attrs) {
2150 this(context, attrs, 0);
2151 }
2152
2153 /**
2154 * Perform inflation from XML and apply a class-specific base style. This
2155 * constructor of View allows subclasses to use their own base style when
2156 * they are inflating. For example, a Button class's constructor would call
2157 * this version of the super class constructor and supply
2158 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2159 * the theme's button style to modify all of the base view attributes (in
2160 * particular its background) as well as the Button class's attributes.
2161 *
2162 * @param context The Context the view is running in, through which it can
2163 * access the current theme, resources, etc.
2164 * @param attrs The attributes of the XML tag that is inflating the view.
2165 * @param defStyle The default style to apply to this view. If 0, no style
2166 * will be applied (beyond what is included in the theme). This may
2167 * either be an attribute resource, whose value will be retrieved
2168 * from the current theme, or an explicit style resource.
2169 * @see #View(Context, AttributeSet)
2170 */
2171 public View(Context context, AttributeSet attrs, int defStyle) {
2172 this(context);
2173
2174 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2175 defStyle, 0);
2176
2177 Drawable background = null;
2178
2179 int leftPadding = -1;
2180 int topPadding = -1;
2181 int rightPadding = -1;
2182 int bottomPadding = -1;
2183
2184 int padding = -1;
2185
2186 int viewFlagValues = 0;
2187 int viewFlagMasks = 0;
2188
2189 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 int x = 0;
2192 int y = 0;
2193
Chet Haase73066682010-11-29 15:55:32 -08002194 float tx = 0;
2195 float ty = 0;
2196 float rotation = 0;
2197 float rotationX = 0;
2198 float rotationY = 0;
2199 float sx = 1f;
2200 float sy = 1f;
2201 boolean transformSet = false;
2202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002203 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2204
Adam Powell637d3372010-08-25 14:37:03 -07002205 int overScrollMode = mOverScrollMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 final int N = a.getIndexCount();
2207 for (int i = 0; i < N; i++) {
2208 int attr = a.getIndex(i);
2209 switch (attr) {
2210 case com.android.internal.R.styleable.View_background:
2211 background = a.getDrawable(attr);
2212 break;
2213 case com.android.internal.R.styleable.View_padding:
2214 padding = a.getDimensionPixelSize(attr, -1);
2215 break;
2216 case com.android.internal.R.styleable.View_paddingLeft:
2217 leftPadding = a.getDimensionPixelSize(attr, -1);
2218 break;
2219 case com.android.internal.R.styleable.View_paddingTop:
2220 topPadding = a.getDimensionPixelSize(attr, -1);
2221 break;
2222 case com.android.internal.R.styleable.View_paddingRight:
2223 rightPadding = a.getDimensionPixelSize(attr, -1);
2224 break;
2225 case com.android.internal.R.styleable.View_paddingBottom:
2226 bottomPadding = a.getDimensionPixelSize(attr, -1);
2227 break;
2228 case com.android.internal.R.styleable.View_scrollX:
2229 x = a.getDimensionPixelOffset(attr, 0);
2230 break;
2231 case com.android.internal.R.styleable.View_scrollY:
2232 y = a.getDimensionPixelOffset(attr, 0);
2233 break;
Chet Haase73066682010-11-29 15:55:32 -08002234 case com.android.internal.R.styleable.View_alpha:
2235 setAlpha(a.getFloat(attr, 1f));
2236 break;
2237 case com.android.internal.R.styleable.View_transformPivotX:
2238 setPivotX(a.getDimensionPixelOffset(attr, 0));
2239 break;
2240 case com.android.internal.R.styleable.View_transformPivotY:
2241 setPivotY(a.getDimensionPixelOffset(attr, 0));
2242 break;
2243 case com.android.internal.R.styleable.View_translationX:
2244 tx = a.getDimensionPixelOffset(attr, 0);
2245 transformSet = true;
2246 break;
2247 case com.android.internal.R.styleable.View_translationY:
2248 ty = a.getDimensionPixelOffset(attr, 0);
2249 transformSet = true;
2250 break;
2251 case com.android.internal.R.styleable.View_rotation:
2252 rotation = a.getFloat(attr, 0);
2253 transformSet = true;
2254 break;
2255 case com.android.internal.R.styleable.View_rotationX:
2256 rotationX = a.getFloat(attr, 0);
2257 transformSet = true;
2258 break;
2259 case com.android.internal.R.styleable.View_rotationY:
2260 rotationY = a.getFloat(attr, 0);
2261 transformSet = true;
2262 break;
2263 case com.android.internal.R.styleable.View_scaleX:
2264 sx = a.getFloat(attr, 1f);
2265 transformSet = true;
2266 break;
2267 case com.android.internal.R.styleable.View_scaleY:
2268 sy = a.getFloat(attr, 1f);
2269 transformSet = true;
2270 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 case com.android.internal.R.styleable.View_id:
2272 mID = a.getResourceId(attr, NO_ID);
2273 break;
2274 case com.android.internal.R.styleable.View_tag:
2275 mTag = a.getText(attr);
2276 break;
2277 case com.android.internal.R.styleable.View_fitsSystemWindows:
2278 if (a.getBoolean(attr, false)) {
2279 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2280 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2281 }
2282 break;
2283 case com.android.internal.R.styleable.View_focusable:
2284 if (a.getBoolean(attr, false)) {
2285 viewFlagValues |= FOCUSABLE;
2286 viewFlagMasks |= FOCUSABLE_MASK;
2287 }
2288 break;
2289 case com.android.internal.R.styleable.View_focusableInTouchMode:
2290 if (a.getBoolean(attr, false)) {
2291 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2292 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2293 }
2294 break;
2295 case com.android.internal.R.styleable.View_clickable:
2296 if (a.getBoolean(attr, false)) {
2297 viewFlagValues |= CLICKABLE;
2298 viewFlagMasks |= CLICKABLE;
2299 }
2300 break;
2301 case com.android.internal.R.styleable.View_longClickable:
2302 if (a.getBoolean(attr, false)) {
2303 viewFlagValues |= LONG_CLICKABLE;
2304 viewFlagMasks |= LONG_CLICKABLE;
2305 }
2306 break;
2307 case com.android.internal.R.styleable.View_saveEnabled:
2308 if (!a.getBoolean(attr, true)) {
2309 viewFlagValues |= SAVE_DISABLED;
2310 viewFlagMasks |= SAVE_DISABLED_MASK;
2311 }
2312 break;
2313 case com.android.internal.R.styleable.View_duplicateParentState:
2314 if (a.getBoolean(attr, false)) {
2315 viewFlagValues |= DUPLICATE_PARENT_STATE;
2316 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2317 }
2318 break;
2319 case com.android.internal.R.styleable.View_visibility:
2320 final int visibility = a.getInt(attr, 0);
2321 if (visibility != 0) {
2322 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2323 viewFlagMasks |= VISIBILITY_MASK;
2324 }
2325 break;
2326 case com.android.internal.R.styleable.View_drawingCacheQuality:
2327 final int cacheQuality = a.getInt(attr, 0);
2328 if (cacheQuality != 0) {
2329 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2330 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2331 }
2332 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002333 case com.android.internal.R.styleable.View_contentDescription:
2334 mContentDescription = a.getString(attr);
2335 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2337 if (!a.getBoolean(attr, true)) {
2338 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2339 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2340 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002341 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2343 if (!a.getBoolean(attr, true)) {
2344 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2345 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2346 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002347 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 case R.styleable.View_scrollbars:
2349 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2350 if (scrollbars != SCROLLBARS_NONE) {
2351 viewFlagValues |= scrollbars;
2352 viewFlagMasks |= SCROLLBARS_MASK;
2353 initializeScrollbars(a);
2354 }
2355 break;
2356 case R.styleable.View_fadingEdge:
2357 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2358 if (fadingEdge != FADING_EDGE_NONE) {
2359 viewFlagValues |= fadingEdge;
2360 viewFlagMasks |= FADING_EDGE_MASK;
2361 initializeFadingEdge(a);
2362 }
2363 break;
2364 case R.styleable.View_scrollbarStyle:
2365 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2366 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2367 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2368 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2369 }
2370 break;
2371 case R.styleable.View_isScrollContainer:
2372 setScrollContainer = true;
2373 if (a.getBoolean(attr, false)) {
2374 setScrollContainer(true);
2375 }
2376 break;
2377 case com.android.internal.R.styleable.View_keepScreenOn:
2378 if (a.getBoolean(attr, false)) {
2379 viewFlagValues |= KEEP_SCREEN_ON;
2380 viewFlagMasks |= KEEP_SCREEN_ON;
2381 }
2382 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002383 case R.styleable.View_filterTouchesWhenObscured:
2384 if (a.getBoolean(attr, false)) {
2385 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2386 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2387 }
2388 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 case R.styleable.View_nextFocusLeft:
2390 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2391 break;
2392 case R.styleable.View_nextFocusRight:
2393 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2394 break;
2395 case R.styleable.View_nextFocusUp:
2396 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2397 break;
2398 case R.styleable.View_nextFocusDown:
2399 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2400 break;
2401 case R.styleable.View_minWidth:
2402 mMinWidth = a.getDimensionPixelSize(attr, 0);
2403 break;
2404 case R.styleable.View_minHeight:
2405 mMinHeight = a.getDimensionPixelSize(attr, 0);
2406 break;
Romain Guy9a817362009-05-01 10:57:14 -07002407 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002408 if (context.isRestricted()) {
2409 throw new IllegalStateException("The android:onClick attribute cannot "
2410 + "be used within a restricted context");
2411 }
2412
Romain Guy9a817362009-05-01 10:57:14 -07002413 final String handlerName = a.getString(attr);
2414 if (handlerName != null) {
2415 setOnClickListener(new OnClickListener() {
2416 private Method mHandler;
2417
2418 public void onClick(View v) {
2419 if (mHandler == null) {
2420 try {
2421 mHandler = getContext().getClass().getMethod(handlerName,
2422 View.class);
2423 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002424 int id = getId();
2425 String idText = id == NO_ID ? "" : " with id '"
2426 + getContext().getResources().getResourceEntryName(
2427 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002428 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002429 handlerName + "(View) in the activity "
2430 + getContext().getClass() + " for onClick handler"
2431 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002432 }
2433 }
2434
2435 try {
2436 mHandler.invoke(getContext(), View.this);
2437 } catch (IllegalAccessException e) {
2438 throw new IllegalStateException("Could not execute non "
2439 + "public method of the activity", e);
2440 } catch (InvocationTargetException e) {
2441 throw new IllegalStateException("Could not execute "
2442 + "method of the activity", e);
2443 }
2444 }
2445 });
2446 }
2447 break;
Adam Powell637d3372010-08-25 14:37:03 -07002448 case R.styleable.View_overScrollMode:
2449 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2450 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 }
2452 }
2453
Adam Powell637d3372010-08-25 14:37:03 -07002454 setOverScrollMode(overScrollMode);
2455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 if (background != null) {
2457 setBackgroundDrawable(background);
2458 }
2459
2460 if (padding >= 0) {
2461 leftPadding = padding;
2462 topPadding = padding;
2463 rightPadding = padding;
2464 bottomPadding = padding;
2465 }
2466
2467 // If the user specified the padding (either with android:padding or
2468 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2469 // use the default padding or the padding from the background drawable
2470 // (stored at this point in mPadding*)
2471 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2472 topPadding >= 0 ? topPadding : mPaddingTop,
2473 rightPadding >= 0 ? rightPadding : mPaddingRight,
2474 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2475
2476 if (viewFlagMasks != 0) {
2477 setFlags(viewFlagValues, viewFlagMasks);
2478 }
2479
2480 // Needs to be called after mViewFlags is set
2481 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2482 recomputePadding();
2483 }
2484
2485 if (x != 0 || y != 0) {
2486 scrollTo(x, y);
2487 }
2488
Chet Haase73066682010-11-29 15:55:32 -08002489 if (transformSet) {
2490 setTranslationX(tx);
2491 setTranslationY(ty);
2492 setRotation(rotation);
2493 setRotationX(rotationX);
2494 setRotationY(rotationY);
2495 setScaleX(sx);
2496 setScaleY(sy);
2497 }
2498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2500 setScrollContainer(true);
2501 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002502
2503 computeOpaqueFlags();
2504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 a.recycle();
2506 }
2507
2508 /**
2509 * Non-public constructor for use in testing
2510 */
2511 View() {
2512 }
2513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 /**
2515 * <p>
2516 * Initializes the fading edges from a given set of styled attributes. This
2517 * method should be called by subclasses that need fading edges and when an
2518 * instance of these subclasses is created programmatically rather than
2519 * being inflated from XML. This method is automatically called when the XML
2520 * is inflated.
2521 * </p>
2522 *
2523 * @param a the styled attributes set to initialize the fading edges from
2524 */
2525 protected void initializeFadingEdge(TypedArray a) {
2526 initScrollCache();
2527
2528 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2529 R.styleable.View_fadingEdgeLength,
2530 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2531 }
2532
2533 /**
2534 * Returns the size of the vertical faded edges used to indicate that more
2535 * content in this view is visible.
2536 *
2537 * @return The size in pixels of the vertical faded edge or 0 if vertical
2538 * faded edges are not enabled for this view.
2539 * @attr ref android.R.styleable#View_fadingEdgeLength
2540 */
2541 public int getVerticalFadingEdgeLength() {
2542 if (isVerticalFadingEdgeEnabled()) {
2543 ScrollabilityCache cache = mScrollCache;
2544 if (cache != null) {
2545 return cache.fadingEdgeLength;
2546 }
2547 }
2548 return 0;
2549 }
2550
2551 /**
2552 * Set the size of the faded edge used to indicate that more content in this
2553 * view is available. Will not change whether the fading edge is enabled; use
2554 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2555 * to enable the fading edge for the vertical or horizontal fading edges.
2556 *
2557 * @param length The size in pixels of the faded edge used to indicate that more
2558 * content in this view is visible.
2559 */
2560 public void setFadingEdgeLength(int length) {
2561 initScrollCache();
2562 mScrollCache.fadingEdgeLength = length;
2563 }
2564
2565 /**
2566 * Returns the size of the horizontal faded edges used to indicate that more
2567 * content in this view is visible.
2568 *
2569 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2570 * faded edges are not enabled for this view.
2571 * @attr ref android.R.styleable#View_fadingEdgeLength
2572 */
2573 public int getHorizontalFadingEdgeLength() {
2574 if (isHorizontalFadingEdgeEnabled()) {
2575 ScrollabilityCache cache = mScrollCache;
2576 if (cache != null) {
2577 return cache.fadingEdgeLength;
2578 }
2579 }
2580 return 0;
2581 }
2582
2583 /**
2584 * Returns the width of the vertical scrollbar.
2585 *
2586 * @return The width in pixels of the vertical scrollbar or 0 if there
2587 * is no vertical scrollbar.
2588 */
2589 public int getVerticalScrollbarWidth() {
2590 ScrollabilityCache cache = mScrollCache;
2591 if (cache != null) {
2592 ScrollBarDrawable scrollBar = cache.scrollBar;
2593 if (scrollBar != null) {
2594 int size = scrollBar.getSize(true);
2595 if (size <= 0) {
2596 size = cache.scrollBarSize;
2597 }
2598 return size;
2599 }
2600 return 0;
2601 }
2602 return 0;
2603 }
2604
2605 /**
2606 * Returns the height of the horizontal scrollbar.
2607 *
2608 * @return The height in pixels of the horizontal scrollbar or 0 if
2609 * there is no horizontal scrollbar.
2610 */
2611 protected int getHorizontalScrollbarHeight() {
2612 ScrollabilityCache cache = mScrollCache;
2613 if (cache != null) {
2614 ScrollBarDrawable scrollBar = cache.scrollBar;
2615 if (scrollBar != null) {
2616 int size = scrollBar.getSize(false);
2617 if (size <= 0) {
2618 size = cache.scrollBarSize;
2619 }
2620 return size;
2621 }
2622 return 0;
2623 }
2624 return 0;
2625 }
2626
2627 /**
2628 * <p>
2629 * Initializes the scrollbars from a given set of styled attributes. This
2630 * method should be called by subclasses that need scrollbars and when an
2631 * instance of these subclasses is created programmatically rather than
2632 * being inflated from XML. This method is automatically called when the XML
2633 * is inflated.
2634 * </p>
2635 *
2636 * @param a the styled attributes set to initialize the scrollbars from
2637 */
2638 protected void initializeScrollbars(TypedArray a) {
2639 initScrollCache();
2640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002642
2643 if (scrollabilityCache.scrollBar == null) {
2644 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2645 }
2646
Romain Guy8bda2482010-03-02 11:42:11 -08002647 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648
Mike Cleronf116bf82009-09-27 19:14:12 -07002649 if (!fadeScrollbars) {
2650 scrollabilityCache.state = ScrollabilityCache.ON;
2651 }
2652 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2653
2654
2655 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2656 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2657 .getScrollBarFadeDuration());
2658 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2659 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2660 ViewConfiguration.getScrollDefaultDelay());
2661
2662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2664 com.android.internal.R.styleable.View_scrollbarSize,
2665 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2666
2667 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2668 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2669
2670 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2671 if (thumb != null) {
2672 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2673 }
2674
2675 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2676 false);
2677 if (alwaysDraw) {
2678 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2679 }
2680
2681 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2682 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2683
2684 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2685 if (thumb != null) {
2686 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2687 }
2688
2689 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2690 false);
2691 if (alwaysDraw) {
2692 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2693 }
2694
2695 // Re-apply user/background padding so that scrollbar(s) get added
2696 recomputePadding();
2697 }
2698
2699 /**
2700 * <p>
2701 * Initalizes the scrollability cache if necessary.
2702 * </p>
2703 */
2704 private void initScrollCache() {
2705 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002706 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 }
2708 }
2709
2710 /**
2711 * Register a callback to be invoked when focus of this view changed.
2712 *
2713 * @param l The callback that will run.
2714 */
2715 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2716 mOnFocusChangeListener = l;
2717 }
2718
2719 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002720 * Add a listener that will be called when the bounds of the view change due to
2721 * layout processing.
2722 *
2723 * @param listener The listener that will be called when layout bounds change.
2724 */
2725 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2726 if (mOnLayoutChangeListeners == null) {
2727 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2728 }
2729 mOnLayoutChangeListeners.add(listener);
2730 }
2731
2732 /**
2733 * Remove a listener for layout changes.
2734 *
2735 * @param listener The listener for layout bounds change.
2736 */
2737 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2738 if (mOnLayoutChangeListeners == null) {
2739 return;
2740 }
2741 mOnLayoutChangeListeners.remove(listener);
2742 }
2743
2744 /**
2745 * Gets the current list of listeners for layout changes.
2746 * @return
2747 */
2748 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2749 return mOnLayoutChangeListeners;
2750 }
2751
2752 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 * Returns the focus-change callback registered for this view.
2754 *
2755 * @return The callback, or null if one is not registered.
2756 */
2757 public OnFocusChangeListener getOnFocusChangeListener() {
2758 return mOnFocusChangeListener;
2759 }
2760
2761 /**
2762 * Register a callback to be invoked when this view is clicked. If this view is not
2763 * clickable, it becomes clickable.
2764 *
2765 * @param l The callback that will run
2766 *
2767 * @see #setClickable(boolean)
2768 */
2769 public void setOnClickListener(OnClickListener l) {
2770 if (!isClickable()) {
2771 setClickable(true);
2772 }
2773 mOnClickListener = l;
2774 }
2775
2776 /**
2777 * Register a callback to be invoked when this view is clicked and held. If this view is not
2778 * long clickable, it becomes long clickable.
2779 *
2780 * @param l The callback that will run
2781 *
2782 * @see #setLongClickable(boolean)
2783 */
2784 public void setOnLongClickListener(OnLongClickListener l) {
2785 if (!isLongClickable()) {
2786 setLongClickable(true);
2787 }
2788 mOnLongClickListener = l;
2789 }
2790
2791 /**
2792 * Register a callback to be invoked when the context menu for this view is
2793 * being built. If this view is not long clickable, it becomes long clickable.
2794 *
2795 * @param l The callback that will run
2796 *
2797 */
2798 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2799 if (!isLongClickable()) {
2800 setLongClickable(true);
2801 }
2802 mOnCreateContextMenuListener = l;
2803 }
2804
2805 /**
2806 * Call this view's OnClickListener, if it is defined.
2807 *
2808 * @return True there was an assigned OnClickListener that was called, false
2809 * otherwise is returned.
2810 */
2811 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002812 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 if (mOnClickListener != null) {
2815 playSoundEffect(SoundEffectConstants.CLICK);
2816 mOnClickListener.onClick(this);
2817 return true;
2818 }
2819
2820 return false;
2821 }
2822
2823 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002824 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2825 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002827 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 */
2829 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002830 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 boolean handled = false;
2833 if (mOnLongClickListener != null) {
2834 handled = mOnLongClickListener.onLongClick(View.this);
2835 }
2836 if (!handled) {
2837 handled = showContextMenu();
2838 }
2839 if (handled) {
2840 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2841 }
2842 return handled;
2843 }
2844
2845 /**
2846 * Bring up the context menu for this view.
2847 *
2848 * @return Whether a context menu was displayed.
2849 */
2850 public boolean showContextMenu() {
2851 return getParent().showContextMenuForChild(this);
2852 }
2853
2854 /**
Adam Powell6e346362010-07-23 10:18:23 -07002855 * Start an action mode.
2856 *
2857 * @param callback Callback that will control the lifecycle of the action mode
2858 * @return The new action mode if it is started, null otherwise
2859 *
2860 * @see ActionMode
2861 */
2862 public ActionMode startActionMode(ActionMode.Callback callback) {
2863 return getParent().startActionModeForChild(this, callback);
2864 }
2865
2866 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 * Register a callback to be invoked when a key is pressed in this view.
2868 * @param l the key listener to attach to this view
2869 */
2870 public void setOnKeyListener(OnKeyListener l) {
2871 mOnKeyListener = l;
2872 }
2873
2874 /**
2875 * Register a callback to be invoked when a touch event is sent to this view.
2876 * @param l the touch listener to attach to this view
2877 */
2878 public void setOnTouchListener(OnTouchListener l) {
2879 mOnTouchListener = l;
2880 }
2881
2882 /**
Chris Tate32affef2010-10-18 15:29:21 -07002883 * Register a callback to be invoked when a drag event is sent to this view.
2884 * @param l The drag listener to attach to this view
2885 */
2886 public void setOnDragListener(OnDragListener l) {
2887 mOnDragListener = l;
2888 }
2889
2890 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2892 *
2893 * Note: this does not check whether this {@link View} should get focus, it just
2894 * gives it focus no matter what. It should only be called internally by framework
2895 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2896 *
2897 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2898 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2899 * focus moved when requestFocus() is called. It may not always
2900 * apply, in which case use the default View.FOCUS_DOWN.
2901 * @param previouslyFocusedRect The rectangle of the view that had focus
2902 * prior in this View's coordinate system.
2903 */
2904 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2905 if (DBG) {
2906 System.out.println(this + " requestFocus()");
2907 }
2908
2909 if ((mPrivateFlags & FOCUSED) == 0) {
2910 mPrivateFlags |= FOCUSED;
2911
2912 if (mParent != null) {
2913 mParent.requestChildFocus(this, this);
2914 }
2915
2916 onFocusChanged(true, direction, previouslyFocusedRect);
2917 refreshDrawableState();
2918 }
2919 }
2920
2921 /**
2922 * Request that a rectangle of this view be visible on the screen,
2923 * scrolling if necessary just enough.
2924 *
2925 * <p>A View should call this if it maintains some notion of which part
2926 * of its content is interesting. For example, a text editing view
2927 * should call this when its cursor moves.
2928 *
2929 * @param rectangle The rectangle.
2930 * @return Whether any parent scrolled.
2931 */
2932 public boolean requestRectangleOnScreen(Rect rectangle) {
2933 return requestRectangleOnScreen(rectangle, false);
2934 }
2935
2936 /**
2937 * Request that a rectangle of this view be visible on the screen,
2938 * scrolling if necessary just enough.
2939 *
2940 * <p>A View should call this if it maintains some notion of which part
2941 * of its content is interesting. For example, a text editing view
2942 * should call this when its cursor moves.
2943 *
2944 * <p>When <code>immediate</code> is set to true, scrolling will not be
2945 * animated.
2946 *
2947 * @param rectangle The rectangle.
2948 * @param immediate True to forbid animated scrolling, false otherwise
2949 * @return Whether any parent scrolled.
2950 */
2951 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
2952 View child = this;
2953 ViewParent parent = mParent;
2954 boolean scrolled = false;
2955 while (parent != null) {
2956 scrolled |= parent.requestChildRectangleOnScreen(child,
2957 rectangle, immediate);
2958
2959 // offset rect so next call has the rectangle in the
2960 // coordinate system of its direct child.
2961 rectangle.offset(child.getLeft(), child.getTop());
2962 rectangle.offset(-child.getScrollX(), -child.getScrollY());
2963
2964 if (!(parent instanceof View)) {
2965 break;
2966 }
Romain Guy8506ab42009-06-11 17:35:47 -07002967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 child = (View) parent;
2969 parent = child.getParent();
2970 }
2971 return scrolled;
2972 }
2973
2974 /**
2975 * Called when this view wants to give up focus. This will cause
2976 * {@link #onFocusChanged} to be called.
2977 */
2978 public void clearFocus() {
2979 if (DBG) {
2980 System.out.println(this + " clearFocus()");
2981 }
2982
2983 if ((mPrivateFlags & FOCUSED) != 0) {
2984 mPrivateFlags &= ~FOCUSED;
2985
2986 if (mParent != null) {
2987 mParent.clearChildFocus(this);
2988 }
2989
2990 onFocusChanged(false, 0, null);
2991 refreshDrawableState();
2992 }
2993 }
2994
2995 /**
2996 * Called to clear the focus of a view that is about to be removed.
2997 * Doesn't call clearChildFocus, which prevents this view from taking
2998 * focus again before it has been removed from the parent
2999 */
3000 void clearFocusForRemoval() {
3001 if ((mPrivateFlags & FOCUSED) != 0) {
3002 mPrivateFlags &= ~FOCUSED;
3003
3004 onFocusChanged(false, 0, null);
3005 refreshDrawableState();
3006 }
3007 }
3008
3009 /**
3010 * Called internally by the view system when a new view is getting focus.
3011 * This is what clears the old focus.
3012 */
3013 void unFocus() {
3014 if (DBG) {
3015 System.out.println(this + " unFocus()");
3016 }
3017
3018 if ((mPrivateFlags & FOCUSED) != 0) {
3019 mPrivateFlags &= ~FOCUSED;
3020
3021 onFocusChanged(false, 0, null);
3022 refreshDrawableState();
3023 }
3024 }
3025
3026 /**
3027 * Returns true if this view has focus iteself, or is the ancestor of the
3028 * view that has focus.
3029 *
3030 * @return True if this view has or contains focus, false otherwise.
3031 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003032 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 public boolean hasFocus() {
3034 return (mPrivateFlags & FOCUSED) != 0;
3035 }
3036
3037 /**
3038 * Returns true if this view is focusable or if it contains a reachable View
3039 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3040 * is a View whose parents do not block descendants focus.
3041 *
3042 * Only {@link #VISIBLE} views are considered focusable.
3043 *
3044 * @return True if the view is focusable or if the view contains a focusable
3045 * View, false otherwise.
3046 *
3047 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3048 */
3049 public boolean hasFocusable() {
3050 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3051 }
3052
3053 /**
3054 * Called by the view system when the focus state of this view changes.
3055 * When the focus change event is caused by directional navigation, direction
3056 * and previouslyFocusedRect provide insight into where the focus is coming from.
3057 * When overriding, be sure to call up through to the super class so that
3058 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07003059 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 * @param gainFocus True if the View has focus; false otherwise.
3061 * @param direction The direction focus has moved when requestFocus()
3062 * is called to give this view focus. Values are
Romain Guyea4823c2009-12-08 15:03:39 -08003063 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT} or
3064 * {@link #FOCUS_RIGHT}. It may not always apply, in which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 * case use the default.
3066 * @param previouslyFocusedRect The rectangle, in this view's coordinate
3067 * system, of the previously focused view. If applicable, this will be
3068 * passed in as finer grained information about where the focus is coming
3069 * from (in addition to direction). Will be <code>null</code> otherwise.
3070 */
3071 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003072 if (gainFocus) {
3073 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3074 }
3075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 InputMethodManager imm = InputMethodManager.peekInstance();
3077 if (!gainFocus) {
3078 if (isPressed()) {
3079 setPressed(false);
3080 }
3081 if (imm != null && mAttachInfo != null
3082 && mAttachInfo.mHasWindowFocus) {
3083 imm.focusOut(this);
3084 }
Romain Guya2431d02009-04-30 16:30:00 -07003085 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086 } else if (imm != null && mAttachInfo != null
3087 && mAttachInfo.mHasWindowFocus) {
3088 imm.focusIn(this);
3089 }
Romain Guy8506ab42009-06-11 17:35:47 -07003090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 invalidate();
3092 if (mOnFocusChangeListener != null) {
3093 mOnFocusChangeListener.onFocusChange(this, gainFocus);
3094 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003095
3096 if (mAttachInfo != null) {
3097 mAttachInfo.mKeyDispatchState.reset(this);
3098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 }
3100
3101 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07003102 * {@inheritDoc}
3103 */
3104 public void sendAccessibilityEvent(int eventType) {
3105 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3106 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3107 }
3108 }
3109
3110 /**
3111 * {@inheritDoc}
3112 */
3113 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3114 event.setClassName(getClass().getName());
3115 event.setPackageName(getContext().getPackageName());
3116 event.setEnabled(isEnabled());
3117 event.setContentDescription(mContentDescription);
3118
3119 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3120 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3121 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3122 event.setItemCount(focusablesTempList.size());
3123 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3124 focusablesTempList.clear();
3125 }
3126
3127 dispatchPopulateAccessibilityEvent(event);
3128
3129 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3130 }
3131
3132 /**
3133 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3134 * to be populated.
3135 *
3136 * @param event The event.
3137 *
3138 * @return True if the event population was completed.
3139 */
3140 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3141 return false;
3142 }
3143
3144 /**
3145 * Gets the {@link View} description. It briefly describes the view and is
3146 * primarily used for accessibility support. Set this property to enable
3147 * better accessibility support for your application. This is especially
3148 * true for views that do not have textual representation (For example,
3149 * ImageButton).
3150 *
3151 * @return The content descriptiopn.
3152 *
3153 * @attr ref android.R.styleable#View_contentDescription
3154 */
3155 public CharSequence getContentDescription() {
3156 return mContentDescription;
3157 }
3158
3159 /**
3160 * Sets the {@link View} description. It briefly describes the view and is
3161 * primarily used for accessibility support. Set this property to enable
3162 * better accessibility support for your application. This is especially
3163 * true for views that do not have textual representation (For example,
3164 * ImageButton).
3165 *
3166 * @param contentDescription The content description.
3167 *
3168 * @attr ref android.R.styleable#View_contentDescription
3169 */
3170 public void setContentDescription(CharSequence contentDescription) {
3171 mContentDescription = contentDescription;
3172 }
3173
3174 /**
Romain Guya2431d02009-04-30 16:30:00 -07003175 * Invoked whenever this view loses focus, either by losing window focus or by losing
3176 * focus within its window. This method can be used to clear any state tied to the
3177 * focus. For instance, if a button is held pressed with the trackball and the window
3178 * loses focus, this method can be used to cancel the press.
3179 *
3180 * Subclasses of View overriding this method should always call super.onFocusLost().
3181 *
3182 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003183 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003184 *
3185 * @hide pending API council approval
3186 */
3187 protected void onFocusLost() {
3188 resetPressedState();
3189 }
3190
3191 private void resetPressedState() {
3192 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3193 return;
3194 }
3195
3196 if (isPressed()) {
3197 setPressed(false);
3198
3199 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003200 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003201 }
3202 }
3203 }
3204
3205 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 * Returns true if this view has focus
3207 *
3208 * @return True if this view has focus, false otherwise.
3209 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003210 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 public boolean isFocused() {
3212 return (mPrivateFlags & FOCUSED) != 0;
3213 }
3214
3215 /**
3216 * Find the view in the hierarchy rooted at this view that currently has
3217 * focus.
3218 *
3219 * @return The view that currently has focus, or null if no focused view can
3220 * be found.
3221 */
3222 public View findFocus() {
3223 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3224 }
3225
3226 /**
3227 * Change whether this view is one of the set of scrollable containers in
3228 * its window. This will be used to determine whether the window can
3229 * resize or must pan when a soft input area is open -- scrollable
3230 * containers allow the window to use resize mode since the container
3231 * will appropriately shrink.
3232 */
3233 public void setScrollContainer(boolean isScrollContainer) {
3234 if (isScrollContainer) {
3235 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3236 mAttachInfo.mScrollContainers.add(this);
3237 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3238 }
3239 mPrivateFlags |= SCROLL_CONTAINER;
3240 } else {
3241 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3242 mAttachInfo.mScrollContainers.remove(this);
3243 }
3244 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3245 }
3246 }
3247
3248 /**
3249 * Returns the quality of the drawing cache.
3250 *
3251 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3252 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3253 *
3254 * @see #setDrawingCacheQuality(int)
3255 * @see #setDrawingCacheEnabled(boolean)
3256 * @see #isDrawingCacheEnabled()
3257 *
3258 * @attr ref android.R.styleable#View_drawingCacheQuality
3259 */
3260 public int getDrawingCacheQuality() {
3261 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3262 }
3263
3264 /**
3265 * Set the drawing cache quality of this view. This value is used only when the
3266 * drawing cache is enabled
3267 *
3268 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3269 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3270 *
3271 * @see #getDrawingCacheQuality()
3272 * @see #setDrawingCacheEnabled(boolean)
3273 * @see #isDrawingCacheEnabled()
3274 *
3275 * @attr ref android.R.styleable#View_drawingCacheQuality
3276 */
3277 public void setDrawingCacheQuality(int quality) {
3278 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3279 }
3280
3281 /**
3282 * Returns whether the screen should remain on, corresponding to the current
3283 * value of {@link #KEEP_SCREEN_ON}.
3284 *
3285 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3286 *
3287 * @see #setKeepScreenOn(boolean)
3288 *
3289 * @attr ref android.R.styleable#View_keepScreenOn
3290 */
3291 public boolean getKeepScreenOn() {
3292 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3293 }
3294
3295 /**
3296 * Controls whether the screen should remain on, modifying the
3297 * value of {@link #KEEP_SCREEN_ON}.
3298 *
3299 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3300 *
3301 * @see #getKeepScreenOn()
3302 *
3303 * @attr ref android.R.styleable#View_keepScreenOn
3304 */
3305 public void setKeepScreenOn(boolean keepScreenOn) {
3306 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3307 }
3308
3309 /**
3310 * @return The user specified next focus ID.
3311 *
3312 * @attr ref android.R.styleable#View_nextFocusLeft
3313 */
3314 public int getNextFocusLeftId() {
3315 return mNextFocusLeftId;
3316 }
3317
3318 /**
3319 * Set the id of the view to use for the next focus
3320 *
3321 * @param nextFocusLeftId
3322 *
3323 * @attr ref android.R.styleable#View_nextFocusLeft
3324 */
3325 public void setNextFocusLeftId(int nextFocusLeftId) {
3326 mNextFocusLeftId = nextFocusLeftId;
3327 }
3328
3329 /**
3330 * @return The user specified next focus ID.
3331 *
3332 * @attr ref android.R.styleable#View_nextFocusRight
3333 */
3334 public int getNextFocusRightId() {
3335 return mNextFocusRightId;
3336 }
3337
3338 /**
3339 * Set the id of the view to use for the next focus
3340 *
3341 * @param nextFocusRightId
3342 *
3343 * @attr ref android.R.styleable#View_nextFocusRight
3344 */
3345 public void setNextFocusRightId(int nextFocusRightId) {
3346 mNextFocusRightId = nextFocusRightId;
3347 }
3348
3349 /**
3350 * @return The user specified next focus ID.
3351 *
3352 * @attr ref android.R.styleable#View_nextFocusUp
3353 */
3354 public int getNextFocusUpId() {
3355 return mNextFocusUpId;
3356 }
3357
3358 /**
3359 * Set the id of the view to use for the next focus
3360 *
3361 * @param nextFocusUpId
3362 *
3363 * @attr ref android.R.styleable#View_nextFocusUp
3364 */
3365 public void setNextFocusUpId(int nextFocusUpId) {
3366 mNextFocusUpId = nextFocusUpId;
3367 }
3368
3369 /**
3370 * @return The user specified next focus ID.
3371 *
3372 * @attr ref android.R.styleable#View_nextFocusDown
3373 */
3374 public int getNextFocusDownId() {
3375 return mNextFocusDownId;
3376 }
3377
3378 /**
3379 * Set the id of the view to use for the next focus
3380 *
3381 * @param nextFocusDownId
3382 *
3383 * @attr ref android.R.styleable#View_nextFocusDown
3384 */
3385 public void setNextFocusDownId(int nextFocusDownId) {
3386 mNextFocusDownId = nextFocusDownId;
3387 }
3388
3389 /**
3390 * Returns the visibility of this view and all of its ancestors
3391 *
3392 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3393 */
3394 public boolean isShown() {
3395 View current = this;
3396 //noinspection ConstantConditions
3397 do {
3398 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3399 return false;
3400 }
3401 ViewParent parent = current.mParent;
3402 if (parent == null) {
3403 return false; // We are not attached to the view root
3404 }
3405 if (!(parent instanceof View)) {
3406 return true;
3407 }
3408 current = (View) parent;
3409 } while (current != null);
3410
3411 return false;
3412 }
3413
3414 /**
3415 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3416 * is set
3417 *
3418 * @param insets Insets for system windows
3419 *
3420 * @return True if this view applied the insets, false otherwise
3421 */
3422 protected boolean fitSystemWindows(Rect insets) {
3423 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3424 mPaddingLeft = insets.left;
3425 mPaddingTop = insets.top;
3426 mPaddingRight = insets.right;
3427 mPaddingBottom = insets.bottom;
3428 requestLayout();
3429 return true;
3430 }
3431 return false;
3432 }
3433
3434 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003435 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3436 * @return True if window has FITS_SYSTEM_WINDOWS set
3437 *
3438 * @hide
3439 */
3440 public boolean isFitsSystemWindowsFlagSet() {
3441 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3442 }
3443
3444 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 * Returns the visibility status for this view.
3446 *
3447 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3448 * @attr ref android.R.styleable#View_visibility
3449 */
3450 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003451 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3452 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3453 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 })
3455 public int getVisibility() {
3456 return mViewFlags & VISIBILITY_MASK;
3457 }
3458
3459 /**
3460 * Set the enabled state of this view.
3461 *
3462 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3463 * @attr ref android.R.styleable#View_visibility
3464 */
3465 @RemotableViewMethod
3466 public void setVisibility(int visibility) {
3467 setFlags(visibility, VISIBILITY_MASK);
3468 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3469 }
3470
3471 /**
3472 * Returns the enabled status for this view. The interpretation of the
3473 * enabled state varies by subclass.
3474 *
3475 * @return True if this view is enabled, false otherwise.
3476 */
3477 @ViewDebug.ExportedProperty
3478 public boolean isEnabled() {
3479 return (mViewFlags & ENABLED_MASK) == ENABLED;
3480 }
3481
3482 /**
3483 * Set the enabled state of this view. The interpretation of the enabled
3484 * state varies by subclass.
3485 *
3486 * @param enabled True if this view is enabled, false otherwise.
3487 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003488 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003490 if (enabled == isEnabled()) return;
3491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3493
3494 /*
3495 * The View most likely has to change its appearance, so refresh
3496 * the drawable state.
3497 */
3498 refreshDrawableState();
3499
3500 // Invalidate too, since the default behavior for views is to be
3501 // be drawn at 50% alpha rather than to change the drawable.
3502 invalidate();
3503 }
3504
3505 /**
3506 * Set whether this view can receive the focus.
3507 *
3508 * Setting this to false will also ensure that this view is not focusable
3509 * in touch mode.
3510 *
3511 * @param focusable If true, this view can receive the focus.
3512 *
3513 * @see #setFocusableInTouchMode(boolean)
3514 * @attr ref android.R.styleable#View_focusable
3515 */
3516 public void setFocusable(boolean focusable) {
3517 if (!focusable) {
3518 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3519 }
3520 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3521 }
3522
3523 /**
3524 * Set whether this view can receive focus while in touch mode.
3525 *
3526 * Setting this to true will also ensure that this view is focusable.
3527 *
3528 * @param focusableInTouchMode If true, this view can receive the focus while
3529 * in touch mode.
3530 *
3531 * @see #setFocusable(boolean)
3532 * @attr ref android.R.styleable#View_focusableInTouchMode
3533 */
3534 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3535 // Focusable in touch mode should always be set before the focusable flag
3536 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3537 // which, in touch mode, will not successfully request focus on this view
3538 // because the focusable in touch mode flag is not set
3539 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3540 if (focusableInTouchMode) {
3541 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3542 }
3543 }
3544
3545 /**
3546 * Set whether this view should have sound effects enabled for events such as
3547 * clicking and touching.
3548 *
3549 * <p>You may wish to disable sound effects for a view if you already play sounds,
3550 * for instance, a dial key that plays dtmf tones.
3551 *
3552 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3553 * @see #isSoundEffectsEnabled()
3554 * @see #playSoundEffect(int)
3555 * @attr ref android.R.styleable#View_soundEffectsEnabled
3556 */
3557 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3558 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3559 }
3560
3561 /**
3562 * @return whether this view should have sound effects enabled for events such as
3563 * clicking and touching.
3564 *
3565 * @see #setSoundEffectsEnabled(boolean)
3566 * @see #playSoundEffect(int)
3567 * @attr ref android.R.styleable#View_soundEffectsEnabled
3568 */
3569 @ViewDebug.ExportedProperty
3570 public boolean isSoundEffectsEnabled() {
3571 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3572 }
3573
3574 /**
3575 * Set whether this view should have haptic feedback for events such as
3576 * long presses.
3577 *
3578 * <p>You may wish to disable haptic feedback if your view already controls
3579 * its own haptic feedback.
3580 *
3581 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3582 * @see #isHapticFeedbackEnabled()
3583 * @see #performHapticFeedback(int)
3584 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3585 */
3586 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3587 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3588 }
3589
3590 /**
3591 * @return whether this view should have haptic feedback enabled for events
3592 * long presses.
3593 *
3594 * @see #setHapticFeedbackEnabled(boolean)
3595 * @see #performHapticFeedback(int)
3596 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3597 */
3598 @ViewDebug.ExportedProperty
3599 public boolean isHapticFeedbackEnabled() {
3600 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3601 }
3602
3603 /**
3604 * If this view doesn't do any drawing on its own, set this flag to
3605 * allow further optimizations. By default, this flag is not set on
3606 * View, but could be set on some View subclasses such as ViewGroup.
3607 *
3608 * Typically, if you override {@link #onDraw} you should clear this flag.
3609 *
3610 * @param willNotDraw whether or not this View draw on its own
3611 */
3612 public void setWillNotDraw(boolean willNotDraw) {
3613 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3614 }
3615
3616 /**
3617 * Returns whether or not this View draws on its own.
3618 *
3619 * @return true if this view has nothing to draw, false otherwise
3620 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003621 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 public boolean willNotDraw() {
3623 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3624 }
3625
3626 /**
3627 * When a View's drawing cache is enabled, drawing is redirected to an
3628 * offscreen bitmap. Some views, like an ImageView, must be able to
3629 * bypass this mechanism if they already draw a single bitmap, to avoid
3630 * unnecessary usage of the memory.
3631 *
3632 * @param willNotCacheDrawing true if this view does not cache its
3633 * drawing, false otherwise
3634 */
3635 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3636 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3637 }
3638
3639 /**
3640 * Returns whether or not this View can cache its drawing or not.
3641 *
3642 * @return true if this view does not cache its drawing, false otherwise
3643 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003644 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 public boolean willNotCacheDrawing() {
3646 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3647 }
3648
3649 /**
3650 * Indicates whether this view reacts to click events or not.
3651 *
3652 * @return true if the view is clickable, false otherwise
3653 *
3654 * @see #setClickable(boolean)
3655 * @attr ref android.R.styleable#View_clickable
3656 */
3657 @ViewDebug.ExportedProperty
3658 public boolean isClickable() {
3659 return (mViewFlags & CLICKABLE) == CLICKABLE;
3660 }
3661
3662 /**
3663 * Enables or disables click events for this view. When a view
3664 * is clickable it will change its state to "pressed" on every click.
3665 * Subclasses should set the view clickable to visually react to
3666 * user's clicks.
3667 *
3668 * @param clickable true to make the view clickable, false otherwise
3669 *
3670 * @see #isClickable()
3671 * @attr ref android.R.styleable#View_clickable
3672 */
3673 public void setClickable(boolean clickable) {
3674 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3675 }
3676
3677 /**
3678 * Indicates whether this view reacts to long click events or not.
3679 *
3680 * @return true if the view is long clickable, false otherwise
3681 *
3682 * @see #setLongClickable(boolean)
3683 * @attr ref android.R.styleable#View_longClickable
3684 */
3685 public boolean isLongClickable() {
3686 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3687 }
3688
3689 /**
3690 * Enables or disables long click events for this view. When a view is long
3691 * clickable it reacts to the user holding down the button for a longer
3692 * duration than a tap. This event can either launch the listener or a
3693 * context menu.
3694 *
3695 * @param longClickable true to make the view long clickable, false otherwise
3696 * @see #isLongClickable()
3697 * @attr ref android.R.styleable#View_longClickable
3698 */
3699 public void setLongClickable(boolean longClickable) {
3700 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3701 }
3702
3703 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003704 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 *
3706 * @see #isClickable()
3707 * @see #setClickable(boolean)
3708 *
3709 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3710 * the View's internal state from a previously set "pressed" state.
3711 */
3712 public void setPressed(boolean pressed) {
3713 if (pressed) {
3714 mPrivateFlags |= PRESSED;
3715 } else {
3716 mPrivateFlags &= ~PRESSED;
3717 }
3718 refreshDrawableState();
3719 dispatchSetPressed(pressed);
3720 }
3721
3722 /**
3723 * Dispatch setPressed to all of this View's children.
3724 *
3725 * @see #setPressed(boolean)
3726 *
3727 * @param pressed The new pressed state
3728 */
3729 protected void dispatchSetPressed(boolean pressed) {
3730 }
3731
3732 /**
3733 * Indicates whether the view is currently in pressed state. Unless
3734 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3735 * the pressed state.
3736 *
3737 * @see #setPressed
3738 * @see #isClickable()
3739 * @see #setClickable(boolean)
3740 *
3741 * @return true if the view is currently pressed, false otherwise
3742 */
3743 public boolean isPressed() {
3744 return (mPrivateFlags & PRESSED) == PRESSED;
3745 }
3746
3747 /**
3748 * Indicates whether this view will save its state (that is,
3749 * whether its {@link #onSaveInstanceState} method will be called).
3750 *
3751 * @return Returns true if the view state saving is enabled, else false.
3752 *
3753 * @see #setSaveEnabled(boolean)
3754 * @attr ref android.R.styleable#View_saveEnabled
3755 */
3756 public boolean isSaveEnabled() {
3757 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3758 }
3759
3760 /**
3761 * Controls whether the saving of this view's state is
3762 * enabled (that is, whether its {@link #onSaveInstanceState} method
3763 * will be called). Note that even if freezing is enabled, the
3764 * view still must have an id assigned to it (via {@link #setId setId()})
3765 * for its state to be saved. This flag can only disable the
3766 * saving of this view; any child views may still have their state saved.
3767 *
3768 * @param enabled Set to false to <em>disable</em> state saving, or true
3769 * (the default) to allow it.
3770 *
3771 * @see #isSaveEnabled()
3772 * @see #setId(int)
3773 * @see #onSaveInstanceState()
3774 * @attr ref android.R.styleable#View_saveEnabled
3775 */
3776 public void setSaveEnabled(boolean enabled) {
3777 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3778 }
3779
Jeff Brown85a31762010-09-01 17:01:00 -07003780 /**
3781 * Gets whether the framework should discard touches when the view's
3782 * window is obscured by another visible window.
3783 * Refer to the {@link View} security documentation for more details.
3784 *
3785 * @return True if touch filtering is enabled.
3786 *
3787 * @see #setFilterTouchesWhenObscured(boolean)
3788 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3789 */
3790 @ViewDebug.ExportedProperty
3791 public boolean getFilterTouchesWhenObscured() {
3792 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3793 }
3794
3795 /**
3796 * Sets whether the framework should discard touches when the view's
3797 * window is obscured by another visible window.
3798 * Refer to the {@link View} security documentation for more details.
3799 *
3800 * @param enabled True if touch filtering should be enabled.
3801 *
3802 * @see #getFilterTouchesWhenObscured
3803 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3804 */
3805 public void setFilterTouchesWhenObscured(boolean enabled) {
3806 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3807 FILTER_TOUCHES_WHEN_OBSCURED);
3808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809
3810 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003811 * Indicates whether the entire hierarchy under this view will save its
3812 * state when a state saving traversal occurs from its parent. The default
3813 * is true; if false, these views will not be saved unless
3814 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3815 *
3816 * @return Returns true if the view state saving from parent is enabled, else false.
3817 *
3818 * @see #setSaveFromParentEnabled(boolean)
3819 */
3820 public boolean isSaveFromParentEnabled() {
3821 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3822 }
3823
3824 /**
3825 * Controls whether the entire hierarchy under this view will save its
3826 * state when a state saving traversal occurs from its parent. The default
3827 * is true; if false, these views will not be saved unless
3828 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3829 *
3830 * @param enabled Set to false to <em>disable</em> state saving, or true
3831 * (the default) to allow it.
3832 *
3833 * @see #isSaveFromParentEnabled()
3834 * @see #setId(int)
3835 * @see #onSaveInstanceState()
3836 */
3837 public void setSaveFromParentEnabled(boolean enabled) {
3838 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
3839 }
3840
3841
3842 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 * Returns whether this View is able to take focus.
3844 *
3845 * @return True if this view can take focus, or false otherwise.
3846 * @attr ref android.R.styleable#View_focusable
3847 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003848 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 public final boolean isFocusable() {
3850 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3851 }
3852
3853 /**
3854 * When a view is focusable, it may not want to take focus when in touch mode.
3855 * For example, a button would like focus when the user is navigating via a D-pad
3856 * so that the user can click on it, but once the user starts touching the screen,
3857 * the button shouldn't take focus
3858 * @return Whether the view is focusable in touch mode.
3859 * @attr ref android.R.styleable#View_focusableInTouchMode
3860 */
3861 @ViewDebug.ExportedProperty
3862 public final boolean isFocusableInTouchMode() {
3863 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3864 }
3865
3866 /**
3867 * Find the nearest view in the specified direction that can take focus.
3868 * This does not actually give focus to that view.
3869 *
3870 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3871 *
3872 * @return The nearest focusable in the specified direction, or null if none
3873 * can be found.
3874 */
3875 public View focusSearch(int direction) {
3876 if (mParent != null) {
3877 return mParent.focusSearch(this, direction);
3878 } else {
3879 return null;
3880 }
3881 }
3882
3883 /**
3884 * This method is the last chance for the focused view and its ancestors to
3885 * respond to an arrow key. This is called when the focused view did not
3886 * consume the key internally, nor could the view system find a new view in
3887 * the requested direction to give focus to.
3888 *
3889 * @param focused The currently focused view.
3890 * @param direction The direction focus wants to move. One of FOCUS_UP,
3891 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3892 * @return True if the this view consumed this unhandled move.
3893 */
3894 public boolean dispatchUnhandledMove(View focused, int direction) {
3895 return false;
3896 }
3897
3898 /**
3899 * If a user manually specified the next view id for a particular direction,
3900 * use the root to look up the view. Once a view is found, it is cached
3901 * for future lookups.
3902 * @param root The root view of the hierarchy containing this view.
3903 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3904 * @return The user specified next view, or null if there is none.
3905 */
3906 View findUserSetNextFocus(View root, int direction) {
3907 switch (direction) {
3908 case FOCUS_LEFT:
3909 if (mNextFocusLeftId == View.NO_ID) return null;
3910 return findViewShouldExist(root, mNextFocusLeftId);
3911 case FOCUS_RIGHT:
3912 if (mNextFocusRightId == View.NO_ID) return null;
3913 return findViewShouldExist(root, mNextFocusRightId);
3914 case FOCUS_UP:
3915 if (mNextFocusUpId == View.NO_ID) return null;
3916 return findViewShouldExist(root, mNextFocusUpId);
3917 case FOCUS_DOWN:
3918 if (mNextFocusDownId == View.NO_ID) return null;
3919 return findViewShouldExist(root, mNextFocusDownId);
3920 }
3921 return null;
3922 }
3923
3924 private static View findViewShouldExist(View root, int childViewId) {
3925 View result = root.findViewById(childViewId);
3926 if (result == null) {
3927 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3928 + "by user for id " + childViewId);
3929 }
3930 return result;
3931 }
3932
3933 /**
3934 * Find and return all focusable views that are descendants of this view,
3935 * possibly including this view if it is focusable itself.
3936 *
3937 * @param direction The direction of the focus
3938 * @return A list of focusable views
3939 */
3940 public ArrayList<View> getFocusables(int direction) {
3941 ArrayList<View> result = new ArrayList<View>(24);
3942 addFocusables(result, direction);
3943 return result;
3944 }
3945
3946 /**
3947 * Add any focusable views that are descendants of this view (possibly
3948 * including this view if it is focusable itself) to views. If we are in touch mode,
3949 * only add views that are also focusable in touch mode.
3950 *
3951 * @param views Focusable views found so far
3952 * @param direction The direction of the focus
3953 */
3954 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003955 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957
svetoslavganov75986cf2009-05-14 22:28:01 -07003958 /**
3959 * Adds any focusable views that are descendants of this view (possibly
3960 * including this view if it is focusable itself) to views. This method
3961 * adds all focusable views regardless if we are in touch mode or
3962 * only views focusable in touch mode if we are in touch mode depending on
3963 * the focusable mode paramater.
3964 *
3965 * @param views Focusable views found so far or null if all we are interested is
3966 * the number of focusables.
3967 * @param direction The direction of the focus.
3968 * @param focusableMode The type of focusables to be added.
3969 *
3970 * @see #FOCUSABLES_ALL
3971 * @see #FOCUSABLES_TOUCH_MODE
3972 */
3973 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3974 if (!isFocusable()) {
3975 return;
3976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977
svetoslavganov75986cf2009-05-14 22:28:01 -07003978 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3979 isInTouchMode() && !isFocusableInTouchMode()) {
3980 return;
3981 }
3982
3983 if (views != null) {
3984 views.add(this);
3985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 }
3987
3988 /**
3989 * Find and return all touchable views that are descendants of this view,
3990 * possibly including this view if it is touchable itself.
3991 *
3992 * @return A list of touchable views
3993 */
3994 public ArrayList<View> getTouchables() {
3995 ArrayList<View> result = new ArrayList<View>();
3996 addTouchables(result);
3997 return result;
3998 }
3999
4000 /**
4001 * Add any touchable views that are descendants of this view (possibly
4002 * including this view if it is touchable itself) to views.
4003 *
4004 * @param views Touchable views found so far
4005 */
4006 public void addTouchables(ArrayList<View> views) {
4007 final int viewFlags = mViewFlags;
4008
4009 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4010 && (viewFlags & ENABLED_MASK) == ENABLED) {
4011 views.add(this);
4012 }
4013 }
4014
4015 /**
4016 * Call this to try to give focus to a specific view or to one of its
4017 * descendants.
4018 *
4019 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4020 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4021 * while the device is in touch mode.
4022 *
4023 * See also {@link #focusSearch}, which is what you call to say that you
4024 * have focus, and you want your parent to look for the next one.
4025 *
4026 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4027 * {@link #FOCUS_DOWN} and <code>null</code>.
4028 *
4029 * @return Whether this view or one of its descendants actually took focus.
4030 */
4031 public final boolean requestFocus() {
4032 return requestFocus(View.FOCUS_DOWN);
4033 }
4034
4035
4036 /**
4037 * Call this to try to give focus to a specific view or to one of its
4038 * descendants and give it a hint about what direction focus is heading.
4039 *
4040 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4041 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4042 * while the device is in touch mode.
4043 *
4044 * See also {@link #focusSearch}, which is what you call to say that you
4045 * have focus, and you want your parent to look for the next one.
4046 *
4047 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4048 * <code>null</code> set for the previously focused rectangle.
4049 *
4050 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4051 * @return Whether this view or one of its descendants actually took focus.
4052 */
4053 public final boolean requestFocus(int direction) {
4054 return requestFocus(direction, null);
4055 }
4056
4057 /**
4058 * Call this to try to give focus to a specific view or to one of its descendants
4059 * and give it hints about the direction and a specific rectangle that the focus
4060 * is coming from. The rectangle can help give larger views a finer grained hint
4061 * about where focus is coming from, and therefore, where to show selection, or
4062 * forward focus change internally.
4063 *
4064 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4065 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4066 * while the device is in touch mode.
4067 *
4068 * A View will not take focus if it is not visible.
4069 *
4070 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4071 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4072 *
4073 * See also {@link #focusSearch}, which is what you call to say that you
4074 * have focus, and you want your parent to look for the next one.
4075 *
4076 * You may wish to override this method if your custom {@link View} has an internal
4077 * {@link View} that it wishes to forward the request to.
4078 *
4079 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4080 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4081 * to give a finer grained hint about where focus is coming from. May be null
4082 * if there is no hint.
4083 * @return Whether this view or one of its descendants actually took focus.
4084 */
4085 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4086 // need to be focusable
4087 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4088 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4089 return false;
4090 }
4091
4092 // need to be focusable in touch mode if in touch mode
4093 if (isInTouchMode() &&
4094 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4095 return false;
4096 }
4097
4098 // need to not have any parents blocking us
4099 if (hasAncestorThatBlocksDescendantFocus()) {
4100 return false;
4101 }
4102
4103 handleFocusGainInternal(direction, previouslyFocusedRect);
4104 return true;
4105 }
4106
Christopher Tate2c095f32010-10-04 14:13:40 -07004107 /** Gets the ViewRoot, or null if not attached. */
4108 /*package*/ ViewRoot getViewRoot() {
4109 View root = getRootView();
4110 return root != null ? (ViewRoot)root.getParent() : null;
4111 }
4112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 /**
4114 * Call this to try to give focus to a specific view or to one of its descendants. This is a
4115 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4116 * touch mode to request focus when they are touched.
4117 *
4118 * @return Whether this view or one of its descendants actually took focus.
4119 *
4120 * @see #isInTouchMode()
4121 *
4122 */
4123 public final boolean requestFocusFromTouch() {
4124 // Leave touch mode if we need to
4125 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07004126 ViewRoot viewRoot = getViewRoot();
4127 if (viewRoot != null) {
4128 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 }
4130 }
4131 return requestFocus(View.FOCUS_DOWN);
4132 }
4133
4134 /**
4135 * @return Whether any ancestor of this view blocks descendant focus.
4136 */
4137 private boolean hasAncestorThatBlocksDescendantFocus() {
4138 ViewParent ancestor = mParent;
4139 while (ancestor instanceof ViewGroup) {
4140 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4141 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4142 return true;
4143 } else {
4144 ancestor = vgAncestor.getParent();
4145 }
4146 }
4147 return false;
4148 }
4149
4150 /**
Romain Guya440b002010-02-24 15:57:54 -08004151 * @hide
4152 */
4153 public void dispatchStartTemporaryDetach() {
4154 onStartTemporaryDetach();
4155 }
4156
4157 /**
4158 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4160 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004161 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 */
4163 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004164 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004165 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004166 }
4167
4168 /**
4169 * @hide
4170 */
4171 public void dispatchFinishTemporaryDetach() {
4172 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004173 }
Romain Guy8506ab42009-06-11 17:35:47 -07004174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 /**
4176 * Called after {@link #onStartTemporaryDetach} when the container is done
4177 * changing the view.
4178 */
4179 public void onFinishTemporaryDetach() {
4180 }
Romain Guy8506ab42009-06-11 17:35:47 -07004181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 /**
4183 * capture information of this view for later analysis: developement only
4184 * check dynamic switch to make sure we only dump view
4185 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4186 */
4187 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004188 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004189 return;
4190 }
4191 ViewDebug.dumpCapturedView(subTag, v);
4192 }
4193
4194 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004195 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4196 * for this view's window. Returns null if the view is not currently attached
4197 * to the window. Normally you will not need to use this directly, but
4198 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4199 */
4200 public KeyEvent.DispatcherState getKeyDispatcherState() {
4201 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4202 }
4203
4204 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 * Dispatch a key event before it is processed by any input method
4206 * associated with the view hierarchy. This can be used to intercept
4207 * key events in special situations before the IME consumes them; a
4208 * typical example would be handling the BACK key to update the application's
4209 * UI instead of allowing the IME to see it and close itself.
4210 *
4211 * @param event The key event to be dispatched.
4212 * @return True if the event was handled, false otherwise.
4213 */
4214 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4215 return onKeyPreIme(event.getKeyCode(), event);
4216 }
4217
4218 /**
4219 * Dispatch a key event to the next view on the focus path. This path runs
4220 * from the top of the view tree down to the currently focused view. If this
4221 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4222 * the next node down the focus path. This method also fires any key
4223 * listeners.
4224 *
4225 * @param event The key event to be dispatched.
4226 * @return True if the event was handled, false otherwise.
4227 */
4228 public boolean dispatchKeyEvent(KeyEvent event) {
4229 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230
Romain Guyf607bdc2010-09-10 19:20:06 -07004231 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004232 if (android.util.Config.LOGV) {
4233 captureViewInfo("captureViewKeyEvent", this);
4234 }
4235
Romain Guyf607bdc2010-09-10 19:20:06 -07004236 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4238 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4239 return true;
4240 }
4241
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004242 return event.dispatch(this, mAttachInfo != null
4243 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 }
4245
4246 /**
4247 * Dispatches a key shortcut event.
4248 *
4249 * @param event The key event to be dispatched.
4250 * @return True if the event was handled by the view, false otherwise.
4251 */
4252 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4253 return onKeyShortcut(event.getKeyCode(), event);
4254 }
4255
4256 /**
4257 * Pass the touch screen motion event down to the target view, or this
4258 * view if it is the target.
4259 *
4260 * @param event The motion event to be dispatched.
4261 * @return True if the event was handled by the view, false otherwise.
4262 */
4263 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004264 if (!onFilterTouchEventForSecurity(event)) {
4265 return false;
4266 }
4267
Romain Guyf607bdc2010-09-10 19:20:06 -07004268 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4270 mOnTouchListener.onTouch(this, event)) {
4271 return true;
4272 }
4273 return onTouchEvent(event);
4274 }
4275
4276 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004277 * Filter the touch event to apply security policies.
4278 *
4279 * @param event The motion event to be filtered.
4280 * @return True if the event should be dispatched, false if the event should be dropped.
4281 *
4282 * @see #getFilterTouchesWhenObscured
4283 */
4284 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004285 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004286 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4287 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4288 // Window is obscured, drop this touch.
4289 return false;
4290 }
4291 return true;
4292 }
4293
4294 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 * Pass a trackball motion event down to the focused view.
4296 *
4297 * @param event The motion event to be dispatched.
4298 * @return True if the event was handled by the view, false otherwise.
4299 */
4300 public boolean dispatchTrackballEvent(MotionEvent event) {
4301 //Log.i("view", "view=" + this + ", " + event.toString());
4302 return onTrackballEvent(event);
4303 }
4304
4305 /**
4306 * Called when the window containing this view gains or loses window focus.
4307 * ViewGroups should override to route to their children.
4308 *
4309 * @param hasFocus True if the window containing this view now has focus,
4310 * false otherwise.
4311 */
4312 public void dispatchWindowFocusChanged(boolean hasFocus) {
4313 onWindowFocusChanged(hasFocus);
4314 }
4315
4316 /**
4317 * Called when the window containing this view gains or loses focus. Note
4318 * that this is separate from view focus: to receive key events, both
4319 * your view and its window must have focus. If a window is displayed
4320 * on top of yours that takes input focus, then your own window will lose
4321 * focus but the view focus will remain unchanged.
4322 *
4323 * @param hasWindowFocus True if the window containing this view now has
4324 * focus, false otherwise.
4325 */
4326 public void onWindowFocusChanged(boolean hasWindowFocus) {
4327 InputMethodManager imm = InputMethodManager.peekInstance();
4328 if (!hasWindowFocus) {
4329 if (isPressed()) {
4330 setPressed(false);
4331 }
4332 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4333 imm.focusOut(this);
4334 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004335 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004336 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004337 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4339 imm.focusIn(this);
4340 }
4341 refreshDrawableState();
4342 }
4343
4344 /**
4345 * Returns true if this view is in a window that currently has window focus.
4346 * Note that this is not the same as the view itself having focus.
4347 *
4348 * @return True if this view is in a window that currently has window focus.
4349 */
4350 public boolean hasWindowFocus() {
4351 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4352 }
4353
4354 /**
Adam Powell326d8082009-12-09 15:10:07 -08004355 * Dispatch a view visibility change down the view hierarchy.
4356 * ViewGroups should override to route to their children.
4357 * @param changedView The view whose visibility changed. Could be 'this' or
4358 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004359 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4360 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004361 */
4362 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4363 onVisibilityChanged(changedView, visibility);
4364 }
4365
4366 /**
4367 * Called when the visibility of the view or an ancestor of the view is changed.
4368 * @param changedView The view whose visibility changed. Could be 'this' or
4369 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004370 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4371 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004372 */
4373 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004374 if (visibility == VISIBLE) {
4375 if (mAttachInfo != null) {
4376 initialAwakenScrollBars();
4377 } else {
4378 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4379 }
4380 }
Adam Powell326d8082009-12-09 15:10:07 -08004381 }
4382
4383 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004384 * Dispatch a hint about whether this view is displayed. For instance, when
4385 * a View moves out of the screen, it might receives a display hint indicating
4386 * the view is not displayed. Applications should not <em>rely</em> on this hint
4387 * as there is no guarantee that they will receive one.
4388 *
4389 * @param hint A hint about whether or not this view is displayed:
4390 * {@link #VISIBLE} or {@link #INVISIBLE}.
4391 */
4392 public void dispatchDisplayHint(int hint) {
4393 onDisplayHint(hint);
4394 }
4395
4396 /**
4397 * Gives this view a hint about whether is displayed or not. For instance, when
4398 * a View moves out of the screen, it might receives a display hint indicating
4399 * the view is not displayed. Applications should not <em>rely</em> on this hint
4400 * as there is no guarantee that they will receive one.
4401 *
4402 * @param hint A hint about whether or not this view is displayed:
4403 * {@link #VISIBLE} or {@link #INVISIBLE}.
4404 */
4405 protected void onDisplayHint(int hint) {
4406 }
4407
4408 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409 * Dispatch a window visibility change down the view hierarchy.
4410 * ViewGroups should override to route to their children.
4411 *
4412 * @param visibility The new visibility of the window.
4413 *
4414 * @see #onWindowVisibilityChanged
4415 */
4416 public void dispatchWindowVisibilityChanged(int visibility) {
4417 onWindowVisibilityChanged(visibility);
4418 }
4419
4420 /**
4421 * Called when the window containing has change its visibility
4422 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4423 * that this tells you whether or not your window is being made visible
4424 * to the window manager; this does <em>not</em> tell you whether or not
4425 * your window is obscured by other windows on the screen, even if it
4426 * is itself visible.
4427 *
4428 * @param visibility The new visibility of the window.
4429 */
4430 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004431 if (visibility == VISIBLE) {
4432 initialAwakenScrollBars();
4433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004434 }
4435
4436 /**
4437 * Returns the current visibility of the window this view is attached to
4438 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4439 *
4440 * @return Returns the current visibility of the view's window.
4441 */
4442 public int getWindowVisibility() {
4443 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4444 }
4445
4446 /**
4447 * Retrieve the overall visible display size in which the window this view is
4448 * attached to has been positioned in. This takes into account screen
4449 * decorations above the window, for both cases where the window itself
4450 * is being position inside of them or the window is being placed under
4451 * then and covered insets are used for the window to position its content
4452 * inside. In effect, this tells you the available area where content can
4453 * be placed and remain visible to users.
4454 *
4455 * <p>This function requires an IPC back to the window manager to retrieve
4456 * the requested information, so should not be used in performance critical
4457 * code like drawing.
4458 *
4459 * @param outRect Filled in with the visible display frame. If the view
4460 * is not attached to a window, this is simply the raw display size.
4461 */
4462 public void getWindowVisibleDisplayFrame(Rect outRect) {
4463 if (mAttachInfo != null) {
4464 try {
4465 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4466 } catch (RemoteException e) {
4467 return;
4468 }
4469 // XXX This is really broken, and probably all needs to be done
4470 // in the window manager, and we need to know more about whether
4471 // we want the area behind or in front of the IME.
4472 final Rect insets = mAttachInfo.mVisibleInsets;
4473 outRect.left += insets.left;
4474 outRect.top += insets.top;
4475 outRect.right -= insets.right;
4476 outRect.bottom -= insets.bottom;
4477 return;
4478 }
4479 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4480 outRect.set(0, 0, d.getWidth(), d.getHeight());
4481 }
4482
4483 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004484 * Dispatch a notification about a resource configuration change down
4485 * the view hierarchy.
4486 * ViewGroups should override to route to their children.
4487 *
4488 * @param newConfig The new resource configuration.
4489 *
4490 * @see #onConfigurationChanged
4491 */
4492 public void dispatchConfigurationChanged(Configuration newConfig) {
4493 onConfigurationChanged(newConfig);
4494 }
4495
4496 /**
4497 * Called when the current configuration of the resources being used
4498 * by the application have changed. You can use this to decide when
4499 * to reload resources that can changed based on orientation and other
4500 * configuration characterstics. You only need to use this if you are
4501 * not relying on the normal {@link android.app.Activity} mechanism of
4502 * recreating the activity instance upon a configuration change.
4503 *
4504 * @param newConfig The new resource configuration.
4505 */
4506 protected void onConfigurationChanged(Configuration newConfig) {
4507 }
4508
4509 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 * Private function to aggregate all per-view attributes in to the view
4511 * root.
4512 */
4513 void dispatchCollectViewAttributes(int visibility) {
4514 performCollectViewAttributes(visibility);
4515 }
4516
4517 void performCollectViewAttributes(int visibility) {
4518 //noinspection PointlessBitwiseExpression
4519 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4520 == (VISIBLE | KEEP_SCREEN_ON)) {
4521 mAttachInfo.mKeepScreenOn = true;
4522 }
4523 }
4524
4525 void needGlobalAttributesUpdate(boolean force) {
4526 AttachInfo ai = mAttachInfo;
4527 if (ai != null) {
4528 if (ai.mKeepScreenOn || force) {
4529 ai.mRecomputeGlobalAttributes = true;
4530 }
4531 }
4532 }
4533
4534 /**
4535 * Returns whether the device is currently in touch mode. Touch mode is entered
4536 * once the user begins interacting with the device by touch, and affects various
4537 * things like whether focus is always visible to the user.
4538 *
4539 * @return Whether the device is in touch mode.
4540 */
4541 @ViewDebug.ExportedProperty
4542 public boolean isInTouchMode() {
4543 if (mAttachInfo != null) {
4544 return mAttachInfo.mInTouchMode;
4545 } else {
4546 return ViewRoot.isInTouchMode();
4547 }
4548 }
4549
4550 /**
4551 * Returns the context the view is running in, through which it can
4552 * access the current theme, resources, etc.
4553 *
4554 * @return The view's Context.
4555 */
4556 @ViewDebug.CapturedViewProperty
4557 public final Context getContext() {
4558 return mContext;
4559 }
4560
4561 /**
4562 * Handle a key event before it is processed by any input method
4563 * associated with the view hierarchy. This can be used to intercept
4564 * key events in special situations before the IME consumes them; a
4565 * typical example would be handling the BACK key to update the application's
4566 * UI instead of allowing the IME to see it and close itself.
4567 *
4568 * @param keyCode The value in event.getKeyCode().
4569 * @param event Description of the key event.
4570 * @return If you handled the event, return true. If you want to allow the
4571 * event to be handled by the next receiver, return false.
4572 */
4573 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4574 return false;
4575 }
4576
4577 /**
4578 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4579 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4580 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4581 * is released, if the view is enabled and clickable.
4582 *
4583 * @param keyCode A key code that represents the button pressed, from
4584 * {@link android.view.KeyEvent}.
4585 * @param event The KeyEvent object that defines the button action.
4586 */
4587 public boolean onKeyDown(int keyCode, KeyEvent event) {
4588 boolean result = false;
4589
4590 switch (keyCode) {
4591 case KeyEvent.KEYCODE_DPAD_CENTER:
4592 case KeyEvent.KEYCODE_ENTER: {
4593 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4594 return true;
4595 }
4596 // Long clickable items don't necessarily have to be clickable
4597 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4598 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4599 (event.getRepeatCount() == 0)) {
4600 setPressed(true);
4601 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004602 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004603 }
4604 return true;
4605 }
4606 break;
4607 }
4608 }
4609 return result;
4610 }
4611
4612 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004613 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4614 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4615 * the event).
4616 */
4617 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4618 return false;
4619 }
4620
4621 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4623 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4624 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4625 * {@link KeyEvent#KEYCODE_ENTER} is released.
4626 *
4627 * @param keyCode A key code that represents the button pressed, from
4628 * {@link android.view.KeyEvent}.
4629 * @param event The KeyEvent object that defines the button action.
4630 */
4631 public boolean onKeyUp(int keyCode, KeyEvent event) {
4632 boolean result = false;
4633
4634 switch (keyCode) {
4635 case KeyEvent.KEYCODE_DPAD_CENTER:
4636 case KeyEvent.KEYCODE_ENTER: {
4637 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4638 return true;
4639 }
4640 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4641 setPressed(false);
4642
4643 if (!mHasPerformedLongPress) {
4644 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004645 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004646
4647 result = performClick();
4648 }
4649 }
4650 break;
4651 }
4652 }
4653 return result;
4654 }
4655
4656 /**
4657 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4658 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4659 * the event).
4660 *
4661 * @param keyCode A key code that represents the button pressed, from
4662 * {@link android.view.KeyEvent}.
4663 * @param repeatCount The number of times the action was made.
4664 * @param event The KeyEvent object that defines the button action.
4665 */
4666 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4667 return false;
4668 }
4669
4670 /**
4671 * Called when an unhandled key shortcut event occurs.
4672 *
4673 * @param keyCode The value in event.getKeyCode().
4674 * @param event Description of the key event.
4675 * @return If you handled the event, return true. If you want to allow the
4676 * event to be handled by the next receiver, return false.
4677 */
4678 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4679 return false;
4680 }
4681
4682 /**
4683 * Check whether the called view is a text editor, in which case it
4684 * would make sense to automatically display a soft input window for
4685 * it. Subclasses should override this if they implement
4686 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004687 * a call on that method would return a non-null InputConnection, and
4688 * they are really a first-class editor that the user would normally
4689 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004690 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004691 * <p>The default implementation always returns false. This does
4692 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4693 * will not be called or the user can not otherwise perform edits on your
4694 * view; it is just a hint to the system that this is not the primary
4695 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004696 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004697 * @return Returns true if this view is a text editor, else false.
4698 */
4699 public boolean onCheckIsTextEditor() {
4700 return false;
4701 }
Romain Guy8506ab42009-06-11 17:35:47 -07004702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004703 /**
4704 * Create a new InputConnection for an InputMethod to interact
4705 * with the view. The default implementation returns null, since it doesn't
4706 * support input methods. You can override this to implement such support.
4707 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004708 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004709 * <p>When implementing this, you probably also want to implement
4710 * {@link #onCheckIsTextEditor()} to indicate you will return a
4711 * non-null InputConnection.
4712 *
4713 * @param outAttrs Fill in with attribute information about the connection.
4714 */
4715 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4716 return null;
4717 }
4718
4719 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004720 * Called by the {@link android.view.inputmethod.InputMethodManager}
4721 * when a view who is not the current
4722 * input connection target is trying to make a call on the manager. The
4723 * default implementation returns false; you can override this to return
4724 * true for certain views if you are performing InputConnection proxying
4725 * to them.
4726 * @param view The View that is making the InputMethodManager call.
4727 * @return Return true to allow the call, false to reject.
4728 */
4729 public boolean checkInputConnectionProxy(View view) {
4730 return false;
4731 }
Romain Guy8506ab42009-06-11 17:35:47 -07004732
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004733 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004734 * Show the context menu for this view. It is not safe to hold on to the
4735 * menu after returning from this method.
4736 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004737 * You should normally not overload this method. Overload
4738 * {@link #onCreateContextMenu(ContextMenu)} or define an
4739 * {@link OnCreateContextMenuListener} to add items to the context menu.
4740 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004741 * @param menu The context menu to populate
4742 */
4743 public void createContextMenu(ContextMenu menu) {
4744 ContextMenuInfo menuInfo = getContextMenuInfo();
4745
4746 // Sets the current menu info so all items added to menu will have
4747 // my extra info set.
4748 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4749
4750 onCreateContextMenu(menu);
4751 if (mOnCreateContextMenuListener != null) {
4752 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4753 }
4754
4755 // Clear the extra information so subsequent items that aren't mine don't
4756 // have my extra info.
4757 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4758
4759 if (mParent != null) {
4760 mParent.createContextMenu(menu);
4761 }
4762 }
4763
4764 /**
4765 * Views should implement this if they have extra information to associate
4766 * with the context menu. The return result is supplied as a parameter to
4767 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4768 * callback.
4769 *
4770 * @return Extra information about the item for which the context menu
4771 * should be shown. This information will vary across different
4772 * subclasses of View.
4773 */
4774 protected ContextMenuInfo getContextMenuInfo() {
4775 return null;
4776 }
4777
4778 /**
4779 * Views should implement this if the view itself is going to add items to
4780 * the context menu.
4781 *
4782 * @param menu the context menu to populate
4783 */
4784 protected void onCreateContextMenu(ContextMenu menu) {
4785 }
4786
4787 /**
4788 * Implement this method to handle trackball motion events. The
4789 * <em>relative</em> movement of the trackball since the last event
4790 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4791 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4792 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4793 * they will often be fractional values, representing the more fine-grained
4794 * movement information available from a trackball).
4795 *
4796 * @param event The motion event.
4797 * @return True if the event was handled, false otherwise.
4798 */
4799 public boolean onTrackballEvent(MotionEvent event) {
4800 return false;
4801 }
4802
4803 /**
4804 * Implement this method to handle touch screen motion events.
4805 *
4806 * @param event The motion event.
4807 * @return True if the event was handled, false otherwise.
4808 */
4809 public boolean onTouchEvent(MotionEvent event) {
4810 final int viewFlags = mViewFlags;
4811
4812 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4813 // A disabled view that is clickable still consumes the touch
4814 // events, it just doesn't respond to them.
4815 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4816 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4817 }
4818
4819 if (mTouchDelegate != null) {
4820 if (mTouchDelegate.onTouchEvent(event)) {
4821 return true;
4822 }
4823 }
4824
4825 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4826 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4827 switch (event.getAction()) {
4828 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004829 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4830 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004831 // take focus if we don't have it already and we should in
4832 // touch mode.
4833 boolean focusTaken = false;
4834 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4835 focusTaken = requestFocus();
4836 }
4837
4838 if (!mHasPerformedLongPress) {
4839 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004840 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004841
4842 // Only perform take click actions if we were in the pressed state
4843 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004844 // Use a Runnable and post this rather than calling
4845 // performClick directly. This lets other visual state
4846 // of the view update before click actions start.
4847 if (mPerformClick == null) {
4848 mPerformClick = new PerformClick();
4849 }
4850 if (!post(mPerformClick)) {
4851 performClick();
4852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004853 }
4854 }
4855
4856 if (mUnsetPressedState == null) {
4857 mUnsetPressedState = new UnsetPressedState();
4858 }
4859
Adam Powelle14579b2009-12-16 18:39:52 -08004860 if (prepressed) {
4861 mPrivateFlags |= PRESSED;
4862 refreshDrawableState();
4863 postDelayed(mUnsetPressedState,
4864 ViewConfiguration.getPressedStateDuration());
4865 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004866 // If the post failed, unpress right now
4867 mUnsetPressedState.run();
4868 }
Adam Powelle14579b2009-12-16 18:39:52 -08004869 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870 }
4871 break;
4872
4873 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004874 if (mPendingCheckForTap == null) {
4875 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004876 }
Adam Powelle14579b2009-12-16 18:39:52 -08004877 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004878 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004879 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004880 break;
4881
4882 case MotionEvent.ACTION_CANCEL:
4883 mPrivateFlags &= ~PRESSED;
4884 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004885 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004886 break;
4887
4888 case MotionEvent.ACTION_MOVE:
4889 final int x = (int) event.getX();
4890 final int y = (int) event.getY();
4891
4892 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004893 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004894 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004895 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004897 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004898 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004899
4900 // Need to switch from pressed to not pressed
4901 mPrivateFlags &= ~PRESSED;
4902 refreshDrawableState();
4903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004904 }
4905 break;
4906 }
4907 return true;
4908 }
4909
4910 return false;
4911 }
4912
4913 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004914 * Remove the longpress detection timer.
4915 */
4916 private void removeLongPressCallback() {
4917 if (mPendingCheckForLongPress != null) {
4918 removeCallbacks(mPendingCheckForLongPress);
4919 }
4920 }
Adam Powelle14579b2009-12-16 18:39:52 -08004921
4922 /**
Romain Guya440b002010-02-24 15:57:54 -08004923 * Remove the prepress detection timer.
4924 */
4925 private void removeUnsetPressCallback() {
4926 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4927 setPressed(false);
4928 removeCallbacks(mUnsetPressedState);
4929 }
4930 }
4931
4932 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004933 * Remove the tap detection timer.
4934 */
4935 private void removeTapCallback() {
4936 if (mPendingCheckForTap != null) {
4937 mPrivateFlags &= ~PREPRESSED;
4938 removeCallbacks(mPendingCheckForTap);
4939 }
4940 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004941
4942 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943 * Cancels a pending long press. Your subclass can use this if you
4944 * want the context menu to come up if the user presses and holds
4945 * at the same place, but you don't want it to come up if they press
4946 * and then move around enough to cause scrolling.
4947 */
4948 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004949 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004950
4951 /*
4952 * The prepressed state handled by the tap callback is a display
4953 * construct, but the tap callback will post a long press callback
4954 * less its own timeout. Remove it here.
4955 */
4956 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 }
4958
4959 /**
4960 * Sets the TouchDelegate for this View.
4961 */
4962 public void setTouchDelegate(TouchDelegate delegate) {
4963 mTouchDelegate = delegate;
4964 }
4965
4966 /**
4967 * Gets the TouchDelegate for this View.
4968 */
4969 public TouchDelegate getTouchDelegate() {
4970 return mTouchDelegate;
4971 }
4972
4973 /**
4974 * Set flags controlling behavior of this view.
4975 *
4976 * @param flags Constant indicating the value which should be set
4977 * @param mask Constant indicating the bit range that should be changed
4978 */
4979 void setFlags(int flags, int mask) {
4980 int old = mViewFlags;
4981 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4982
4983 int changed = mViewFlags ^ old;
4984 if (changed == 0) {
4985 return;
4986 }
4987 int privateFlags = mPrivateFlags;
4988
4989 /* Check if the FOCUSABLE bit has changed */
4990 if (((changed & FOCUSABLE_MASK) != 0) &&
4991 ((privateFlags & HAS_BOUNDS) !=0)) {
4992 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4993 && ((privateFlags & FOCUSED) != 0)) {
4994 /* Give up focus if we are no longer focusable */
4995 clearFocus();
4996 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4997 && ((privateFlags & FOCUSED) == 0)) {
4998 /*
4999 * Tell the view system that we are now available to take focus
5000 * if no one else already has it.
5001 */
5002 if (mParent != null) mParent.focusableViewAvailable(this);
5003 }
5004 }
5005
5006 if ((flags & VISIBILITY_MASK) == VISIBLE) {
5007 if ((changed & VISIBILITY_MASK) != 0) {
5008 /*
5009 * If this view is becoming visible, set the DRAWN flag so that
5010 * the next invalidate() will not be skipped.
5011 */
5012 mPrivateFlags |= DRAWN;
5013
5014 needGlobalAttributesUpdate(true);
5015
5016 // a view becoming visible is worth notifying the parent
5017 // about in case nothing has focus. even if this specific view
5018 // isn't focusable, it may contain something that is, so let
5019 // the root view try to give this focus if nothing else does.
5020 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
5021 mParent.focusableViewAvailable(this);
5022 }
5023 }
5024 }
5025
5026 /* Check if the GONE bit has changed */
5027 if ((changed & GONE) != 0) {
5028 needGlobalAttributesUpdate(false);
5029 requestLayout();
5030 invalidate();
5031
Romain Guyecd80ee2009-12-03 17:13:02 -08005032 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5033 if (hasFocus()) clearFocus();
5034 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005035 }
5036 if (mAttachInfo != null) {
5037 mAttachInfo.mViewVisibilityChanged = true;
5038 }
5039 }
5040
5041 /* Check if the VISIBLE bit has changed */
5042 if ((changed & INVISIBLE) != 0) {
5043 needGlobalAttributesUpdate(false);
5044 invalidate();
5045
5046 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5047 // root view becoming invisible shouldn't clear focus
5048 if (getRootView() != this) {
5049 clearFocus();
5050 }
5051 }
5052 if (mAttachInfo != null) {
5053 mAttachInfo.mViewVisibilityChanged = true;
5054 }
5055 }
5056
Adam Powell326d8082009-12-09 15:10:07 -08005057 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07005058 if (mParent instanceof ViewGroup) {
5059 ((ViewGroup)mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
5060 }
Adam Powell326d8082009-12-09 15:10:07 -08005061 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5062 }
5063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5065 destroyDrawingCache();
5066 }
5067
5068 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5069 destroyDrawingCache();
5070 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5071 }
5072
5073 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5074 destroyDrawingCache();
5075 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5076 }
5077
5078 if ((changed & DRAW_MASK) != 0) {
5079 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5080 if (mBGDrawable != null) {
5081 mPrivateFlags &= ~SKIP_DRAW;
5082 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5083 } else {
5084 mPrivateFlags |= SKIP_DRAW;
5085 }
5086 } else {
5087 mPrivateFlags &= ~SKIP_DRAW;
5088 }
5089 requestLayout();
5090 invalidate();
5091 }
5092
5093 if ((changed & KEEP_SCREEN_ON) != 0) {
5094 if (mParent != null) {
5095 mParent.recomputeViewAttributes(this);
5096 }
5097 }
5098 }
5099
5100 /**
5101 * Change the view's z order in the tree, so it's on top of other sibling
5102 * views
5103 */
5104 public void bringToFront() {
5105 if (mParent != null) {
5106 mParent.bringChildToFront(this);
5107 }
5108 }
5109
5110 /**
5111 * This is called in response to an internal scroll in this view (i.e., the
5112 * view scrolled its own contents). This is typically as a result of
5113 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5114 * called.
5115 *
5116 * @param l Current horizontal scroll origin.
5117 * @param t Current vertical scroll origin.
5118 * @param oldl Previous horizontal scroll origin.
5119 * @param oldt Previous vertical scroll origin.
5120 */
5121 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5122 mBackgroundSizeChanged = true;
5123
5124 final AttachInfo ai = mAttachInfo;
5125 if (ai != null) {
5126 ai.mViewScrollChanged = true;
5127 }
5128 }
5129
5130 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005131 * Interface definition for a callback to be invoked when the layout bounds of a view
5132 * changes due to layout processing.
5133 */
5134 public interface OnLayoutChangeListener {
5135 /**
5136 * Called when the focus state of a view has changed.
5137 *
5138 * @param v The view whose state has changed.
5139 * @param left The new value of the view's left property.
5140 * @param top The new value of the view's top property.
5141 * @param right The new value of the view's right property.
5142 * @param bottom The new value of the view's bottom property.
5143 * @param oldLeft The previous value of the view's left property.
5144 * @param oldTop The previous value of the view's top property.
5145 * @param oldRight The previous value of the view's right property.
5146 * @param oldBottom The previous value of the view's bottom property.
5147 */
5148 void onLayoutChange(View v, int left, int top, int right, int bottom,
5149 int oldLeft, int oldTop, int oldRight, int oldBottom);
5150 }
5151
5152 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005153 * This is called during layout when the size of this view has changed. If
5154 * you were just added to the view hierarchy, you're called with the old
5155 * values of 0.
5156 *
5157 * @param w Current width of this view.
5158 * @param h Current height of this view.
5159 * @param oldw Old width of this view.
5160 * @param oldh Old height of this view.
5161 */
5162 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5163 }
5164
5165 /**
5166 * Called by draw to draw the child views. This may be overridden
5167 * by derived classes to gain control just before its children are drawn
5168 * (but after its own view has been drawn).
5169 * @param canvas the canvas on which to draw the view
5170 */
5171 protected void dispatchDraw(Canvas canvas) {
5172 }
5173
5174 /**
5175 * Gets the parent of this view. Note that the parent is a
5176 * ViewParent and not necessarily a View.
5177 *
5178 * @return Parent of this view.
5179 */
5180 public final ViewParent getParent() {
5181 return mParent;
5182 }
5183
5184 /**
5185 * Return the scrolled left position of this view. This is the left edge of
5186 * the displayed part of your view. You do not need to draw any pixels
5187 * farther left, since those are outside of the frame of your view on
5188 * screen.
5189 *
5190 * @return The left edge of the displayed part of your view, in pixels.
5191 */
5192 public final int getScrollX() {
5193 return mScrollX;
5194 }
5195
5196 /**
5197 * Return the scrolled top position of this view. This is the top edge of
5198 * the displayed part of your view. You do not need to draw any pixels above
5199 * it, since those are outside of the frame of your view on screen.
5200 *
5201 * @return The top edge of the displayed part of your view, in pixels.
5202 */
5203 public final int getScrollY() {
5204 return mScrollY;
5205 }
5206
5207 /**
5208 * Return the width of the your view.
5209 *
5210 * @return The width of your view, in pixels.
5211 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005212 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005213 public final int getWidth() {
5214 return mRight - mLeft;
5215 }
5216
5217 /**
5218 * Return the height of your view.
5219 *
5220 * @return The height of your view, in pixels.
5221 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005222 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 public final int getHeight() {
5224 return mBottom - mTop;
5225 }
5226
5227 /**
5228 * Return the visible drawing bounds of your view. Fills in the output
5229 * rectangle with the values from getScrollX(), getScrollY(),
5230 * getWidth(), and getHeight().
5231 *
5232 * @param outRect The (scrolled) drawing bounds of the view.
5233 */
5234 public void getDrawingRect(Rect outRect) {
5235 outRect.left = mScrollX;
5236 outRect.top = mScrollY;
5237 outRect.right = mScrollX + (mRight - mLeft);
5238 outRect.bottom = mScrollY + (mBottom - mTop);
5239 }
5240
5241 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005242 * Like {@link #getMeasuredWidthAndState()}, but only returns the
5243 * raw width component (that is the result is masked by
5244 * {@link #MEASURED_SIZE_MASK}).
5245 *
5246 * @return The raw measured width of this view.
5247 */
5248 public final int getMeasuredWidth() {
5249 return mMeasuredWidth & MEASURED_SIZE_MASK;
5250 }
5251
5252 /**
5253 * Return the full width measurement information for this view as computed
5254 * by the most recent call to {@link #measure}. This result is a bit mask
5255 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 * This should be used during measurement and layout calculations only. Use
5257 * {@link #getWidth()} to see how wide a view is after layout.
5258 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005259 * @return The measured width of this view as a bit mask.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08005261 public final int getMeasuredWidthAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005262 return mMeasuredWidth;
5263 }
5264
5265 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005266 * Like {@link #getMeasuredHeightAndState()}, but only returns the
5267 * raw width component (that is the result is masked by
5268 * {@link #MEASURED_SIZE_MASK}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005270 * @return The raw measured height of this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005271 */
5272 public final int getMeasuredHeight() {
Dianne Hackborn189ee182010-12-02 21:48:53 -08005273 return mMeasuredHeight & MEASURED_SIZE_MASK;
5274 }
5275
5276 /**
5277 * Return the full height measurement information for this view as computed
5278 * by the most recent call to {@link #measure}. This result is a bit mask
5279 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5280 * This should be used during measurement and layout calculations only. Use
5281 * {@link #getHeight()} to see how wide a view is after layout.
5282 *
5283 * @return The measured width of this view as a bit mask.
5284 */
5285 public final int getMeasuredHeightAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005286 return mMeasuredHeight;
5287 }
5288
5289 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005290 * Return only the state bits of {@link #getMeasuredWidthAndState()}
5291 * and {@link #getMeasuredHeightAndState()}, combined into one integer.
5292 * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
5293 * and the height component is at the shifted bits
5294 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
5295 */
5296 public final int getMeasuredState() {
5297 return (mMeasuredWidth&MEASURED_STATE_MASK)
5298 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
5299 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
5300 }
5301
5302 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005303 * The transform matrix of this view, which is calculated based on the current
5304 * roation, scale, and pivot properties.
5305 *
5306 * @see #getRotation()
5307 * @see #getScaleX()
5308 * @see #getScaleY()
5309 * @see #getPivotX()
5310 * @see #getPivotY()
5311 * @return The current transform matrix for the view
5312 */
5313 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005314 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005315 return mMatrix;
5316 }
5317
5318 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005319 * Utility function to determine if the value is far enough away from zero to be
5320 * considered non-zero.
5321 * @param value A floating point value to check for zero-ness
5322 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5323 */
5324 private static boolean nonzero(float value) {
5325 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5326 }
5327
5328 /**
Jeff Brown86671742010-09-30 20:00:15 -07005329 * Returns true if the transform matrix is the identity matrix.
5330 * Recomputes the matrix if necessary.
Romain Guy33e72ae2010-07-17 12:40:29 -07005331 *
5332 * @return True if the transform matrix is the identity matrix, false otherwise.
5333 */
Jeff Brown86671742010-09-30 20:00:15 -07005334 final boolean hasIdentityMatrix() {
5335 updateMatrix();
5336 return mMatrixIsIdentity;
5337 }
5338
5339 /**
5340 * Recomputes the transform matrix if necessary.
5341 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005342 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005343 if (mMatrixDirty) {
5344 // transform-related properties have changed since the last time someone
5345 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005346
5347 // Figure out if we need to update the pivot point
5348 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5349 if ((mRight - mLeft) != mPrevWidth && (mBottom - mTop) != mPrevHeight) {
5350 mPrevWidth = mRight - mLeft;
5351 mPrevHeight = mBottom - mTop;
5352 mPivotX = (float) mPrevWidth / 2f;
5353 mPivotY = (float) mPrevHeight / 2f;
5354 }
5355 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005356 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005357 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5358 mMatrix.setTranslate(mTranslationX, mTranslationY);
5359 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5360 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5361 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005362 if (mCamera == null) {
5363 mCamera = new Camera();
5364 matrix3D = new Matrix();
5365 }
5366 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005367 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005368 mCamera.rotateX(mRotationX);
5369 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005370 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005371 mCamera.getMatrix(matrix3D);
5372 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005373 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005374 mMatrix.postConcat(matrix3D);
5375 mCamera.restore();
5376 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005377 mMatrixDirty = false;
5378 mMatrixIsIdentity = mMatrix.isIdentity();
5379 mInverseMatrixDirty = true;
5380 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005381 }
5382
5383 /**
5384 * Utility method to retrieve the inverse of the current mMatrix property.
5385 * We cache the matrix to avoid recalculating it when transform properties
5386 * have not changed.
5387 *
5388 * @return The inverse of the current matrix of this view.
5389 */
Jeff Brown86671742010-09-30 20:00:15 -07005390 final Matrix getInverseMatrix() {
5391 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005392 if (mInverseMatrixDirty) {
5393 if (mInverseMatrix == null) {
5394 mInverseMatrix = new Matrix();
5395 }
5396 mMatrix.invert(mInverseMatrix);
5397 mInverseMatrixDirty = false;
5398 }
5399 return mInverseMatrix;
5400 }
5401
5402 /**
5403 * The degrees that the view is rotated around the pivot point.
5404 *
5405 * @see #getPivotX()
5406 * @see #getPivotY()
5407 * @return The degrees of rotation.
5408 */
5409 public float getRotation() {
5410 return mRotation;
5411 }
5412
5413 /**
Chet Haase897247b2010-09-09 14:54:47 -07005414 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5415 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005416 *
5417 * @param rotation The degrees of rotation.
5418 * @see #getPivotX()
5419 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005420 *
5421 * @attr ref android.R.styleable#View_rotation
Chet Haasec3aa3612010-06-17 08:50:37 -07005422 */
5423 public void setRotation(float rotation) {
5424 if (mRotation != rotation) {
5425 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005426 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005427 mRotation = rotation;
5428 mMatrixDirty = true;
5429 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005430 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005431 }
5432 }
5433
5434 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005435 * The degrees that the view is rotated around the vertical axis through the pivot point.
5436 *
5437 * @see #getPivotX()
5438 * @see #getPivotY()
5439 * @return The degrees of Y rotation.
5440 */
5441 public float getRotationY() {
5442 return mRotationY;
5443 }
5444
5445 /**
Chet Haase897247b2010-09-09 14:54:47 -07005446 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5447 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5448 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005449 *
5450 * @param rotationY The degrees of Y rotation.
5451 * @see #getPivotX()
5452 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005453 *
5454 * @attr ref android.R.styleable#View_rotationY
Chet Haasefd2b0022010-08-06 13:08:56 -07005455 */
5456 public void setRotationY(float rotationY) {
5457 if (mRotationY != rotationY) {
5458 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005459 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005460 mRotationY = rotationY;
5461 mMatrixDirty = true;
5462 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005463 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005464 }
5465 }
5466
5467 /**
5468 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5469 *
5470 * @see #getPivotX()
5471 * @see #getPivotY()
5472 * @return The degrees of X rotation.
5473 */
5474 public float getRotationX() {
5475 return mRotationX;
5476 }
5477
5478 /**
Chet Haase897247b2010-09-09 14:54:47 -07005479 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5480 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5481 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005482 *
5483 * @param rotationX The degrees of X rotation.
5484 * @see #getPivotX()
5485 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005486 *
5487 * @attr ref android.R.styleable#View_rotationX
Chet Haasefd2b0022010-08-06 13:08:56 -07005488 */
5489 public void setRotationX(float rotationX) {
5490 if (mRotationX != rotationX) {
5491 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005492 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005493 mRotationX = rotationX;
5494 mMatrixDirty = true;
5495 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005496 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005497 }
5498 }
5499
5500 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005501 * The amount that the view is scaled in x around the pivot point, as a proportion of
5502 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5503 *
Joe Onorato93162322010-09-16 15:42:01 -04005504 * <p>By default, this is 1.0f.
5505 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005506 * @see #getPivotX()
5507 * @see #getPivotY()
5508 * @return The scaling factor.
5509 */
5510 public float getScaleX() {
5511 return mScaleX;
5512 }
5513
5514 /**
5515 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5516 * the view's unscaled width. A value of 1 means that no scaling is applied.
5517 *
5518 * @param scaleX The scaling factor.
5519 * @see #getPivotX()
5520 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005521 *
5522 * @attr ref android.R.styleable#View_scaleX
Chet Haasec3aa3612010-06-17 08:50:37 -07005523 */
5524 public void setScaleX(float scaleX) {
5525 if (mScaleX != scaleX) {
5526 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005527 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005528 mScaleX = scaleX;
5529 mMatrixDirty = true;
5530 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005531 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005532 }
5533 }
5534
5535 /**
5536 * The amount that the view is scaled in y around the pivot point, as a proportion of
5537 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5538 *
Joe Onorato93162322010-09-16 15:42:01 -04005539 * <p>By default, this is 1.0f.
5540 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005541 * @see #getPivotX()
5542 * @see #getPivotY()
5543 * @return The scaling factor.
5544 */
5545 public float getScaleY() {
5546 return mScaleY;
5547 }
5548
5549 /**
5550 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5551 * the view's unscaled width. A value of 1 means that no scaling is applied.
5552 *
5553 * @param scaleY The scaling factor.
5554 * @see #getPivotX()
5555 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005556 *
5557 * @attr ref android.R.styleable#View_scaleY
Chet Haasec3aa3612010-06-17 08:50:37 -07005558 */
5559 public void setScaleY(float scaleY) {
5560 if (mScaleY != scaleY) {
5561 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005562 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005563 mScaleY = scaleY;
5564 mMatrixDirty = true;
5565 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005566 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005567 }
5568 }
5569
5570 /**
5571 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5572 * and {@link #setScaleX(float) scaled}.
5573 *
5574 * @see #getRotation()
5575 * @see #getScaleX()
5576 * @see #getScaleY()
5577 * @see #getPivotY()
5578 * @return The x location of the pivot point.
5579 */
5580 public float getPivotX() {
5581 return mPivotX;
5582 }
5583
5584 /**
5585 * Sets the x location of the point around which the view is
5586 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005587 * By default, the pivot point is centered on the object.
5588 * Setting this property disables this behavior and causes the view to use only the
5589 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005590 *
5591 * @param pivotX The x location of the pivot point.
5592 * @see #getRotation()
5593 * @see #getScaleX()
5594 * @see #getScaleY()
5595 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005596 *
5597 * @attr ref android.R.styleable#View_transformPivotX
Chet Haasec3aa3612010-06-17 08:50:37 -07005598 */
5599 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005600 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005601 if (mPivotX != pivotX) {
5602 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005603 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005604 mPivotX = pivotX;
5605 mMatrixDirty = true;
5606 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005607 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005608 }
5609 }
5610
5611 /**
5612 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5613 * and {@link #setScaleY(float) scaled}.
5614 *
5615 * @see #getRotation()
5616 * @see #getScaleX()
5617 * @see #getScaleY()
5618 * @see #getPivotY()
5619 * @return The y location of the pivot point.
5620 */
5621 public float getPivotY() {
5622 return mPivotY;
5623 }
5624
5625 /**
5626 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005627 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5628 * Setting this property disables this behavior and causes the view to use only the
5629 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005630 *
5631 * @param pivotY The y location of the pivot point.
5632 * @see #getRotation()
5633 * @see #getScaleX()
5634 * @see #getScaleY()
5635 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005636 *
5637 * @attr ref android.R.styleable#View_transformPivotY
Chet Haasec3aa3612010-06-17 08:50:37 -07005638 */
5639 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005640 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005641 if (mPivotY != pivotY) {
5642 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005643 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005644 mPivotY = pivotY;
5645 mMatrixDirty = true;
5646 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005647 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005648 }
5649 }
5650
5651 /**
5652 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5653 * completely transparent and 1 means the view is completely opaque.
5654 *
Joe Onorato93162322010-09-16 15:42:01 -04005655 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005656 * @return The opacity of the view.
5657 */
5658 public float getAlpha() {
5659 return mAlpha;
5660 }
5661
5662 /**
5663 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5664 * completely transparent and 1 means the view is completely opaque.
5665 *
5666 * @param alpha The opacity of the view.
Chet Haase73066682010-11-29 15:55:32 -08005667 *
5668 * @attr ref android.R.styleable#View_alpha
Chet Haasec3aa3612010-06-17 08:50:37 -07005669 */
5670 public void setAlpha(float alpha) {
5671 mAlpha = alpha;
Chet Haaseed032702010-10-01 14:05:54 -07005672 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07005673 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005674 // subclass is handling alpha - don't optimize rendering cache invalidation
5675 invalidate();
5676 } else {
Romain Guya3496a92010-10-12 11:53:24 -07005677 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005678 invalidate(false);
5679 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005680 }
5681
5682 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005683 * Top position of this view relative to its parent.
5684 *
5685 * @return The top of this view, in pixels.
5686 */
5687 @ViewDebug.CapturedViewProperty
5688 public final int getTop() {
5689 return mTop;
5690 }
5691
5692 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005693 * Sets the top position of this view relative to its parent. This method is meant to be called
5694 * by the layout system and should not generally be called otherwise, because the property
5695 * may be changed at any time by the layout.
5696 *
5697 * @param top The top of this view, in pixels.
5698 */
5699 public final void setTop(int top) {
5700 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07005701 updateMatrix();
5702 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005703 final ViewParent p = mParent;
5704 if (p != null && mAttachInfo != null) {
5705 final Rect r = mAttachInfo.mTmpInvalRect;
5706 int minTop;
5707 int yLoc;
5708 if (top < mTop) {
5709 minTop = top;
5710 yLoc = top - mTop;
5711 } else {
5712 minTop = mTop;
5713 yLoc = 0;
5714 }
5715 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5716 p.invalidateChild(this, r);
5717 }
5718 } else {
5719 // Double-invalidation is necessary to capture view's old and new areas
5720 invalidate();
5721 }
5722
Chet Haaseed032702010-10-01 14:05:54 -07005723 int width = mRight - mLeft;
5724 int oldHeight = mBottom - mTop;
5725
Chet Haase21cd1382010-09-01 17:42:29 -07005726 mTop = top;
5727
Chet Haaseed032702010-10-01 14:05:54 -07005728 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5729
Chet Haase21cd1382010-09-01 17:42:29 -07005730 if (!mMatrixIsIdentity) {
5731 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5732 invalidate();
5733 }
5734 }
5735 }
5736
5737 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 * Bottom position of this view relative to its parent.
5739 *
5740 * @return The bottom of this view, in pixels.
5741 */
5742 @ViewDebug.CapturedViewProperty
5743 public final int getBottom() {
5744 return mBottom;
5745 }
5746
5747 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005748 * Sets the bottom position of this view relative to its parent. This method is meant to be
5749 * called by the layout system and should not generally be called otherwise, because the
5750 * property may be changed at any time by the layout.
5751 *
5752 * @param bottom The bottom of this view, in pixels.
5753 */
5754 public final void setBottom(int bottom) {
5755 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07005756 updateMatrix();
5757 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005758 final ViewParent p = mParent;
5759 if (p != null && mAttachInfo != null) {
5760 final Rect r = mAttachInfo.mTmpInvalRect;
5761 int maxBottom;
5762 if (bottom < mBottom) {
5763 maxBottom = mBottom;
5764 } else {
5765 maxBottom = bottom;
5766 }
5767 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5768 p.invalidateChild(this, r);
5769 }
5770 } else {
5771 // Double-invalidation is necessary to capture view's old and new areas
5772 invalidate();
5773 }
5774
Chet Haaseed032702010-10-01 14:05:54 -07005775 int width = mRight - mLeft;
5776 int oldHeight = mBottom - mTop;
5777
Chet Haase21cd1382010-09-01 17:42:29 -07005778 mBottom = bottom;
5779
Chet Haaseed032702010-10-01 14:05:54 -07005780 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5781
Chet Haase21cd1382010-09-01 17:42:29 -07005782 if (!mMatrixIsIdentity) {
5783 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5784 invalidate();
5785 }
5786 }
5787 }
5788
5789 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 * Left position of this view relative to its parent.
5791 *
5792 * @return The left edge of this view, in pixels.
5793 */
5794 @ViewDebug.CapturedViewProperty
5795 public final int getLeft() {
5796 return mLeft;
5797 }
5798
5799 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005800 * Sets the left position of this view relative to its parent. This method is meant to be called
5801 * by the layout system and should not generally be called otherwise, because the property
5802 * may be changed at any time by the layout.
5803 *
5804 * @param left The bottom of this view, in pixels.
5805 */
5806 public final void setLeft(int left) {
5807 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07005808 updateMatrix();
5809 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005810 final ViewParent p = mParent;
5811 if (p != null && mAttachInfo != null) {
5812 final Rect r = mAttachInfo.mTmpInvalRect;
5813 int minLeft;
5814 int xLoc;
5815 if (left < mLeft) {
5816 minLeft = left;
5817 xLoc = left - mLeft;
5818 } else {
5819 minLeft = mLeft;
5820 xLoc = 0;
5821 }
5822 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
5823 p.invalidateChild(this, r);
5824 }
5825 } else {
5826 // Double-invalidation is necessary to capture view's old and new areas
5827 invalidate();
5828 }
5829
Chet Haaseed032702010-10-01 14:05:54 -07005830 int oldWidth = mRight - mLeft;
5831 int height = mBottom - mTop;
5832
Chet Haase21cd1382010-09-01 17:42:29 -07005833 mLeft = left;
5834
Chet Haaseed032702010-10-01 14:05:54 -07005835 onSizeChanged(mRight - mLeft, height, oldWidth, height);
5836
Chet Haase21cd1382010-09-01 17:42:29 -07005837 if (!mMatrixIsIdentity) {
5838 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5839 invalidate();
5840 }
Chet Haaseed032702010-10-01 14:05:54 -07005841
Chet Haase21cd1382010-09-01 17:42:29 -07005842 }
5843 }
5844
5845 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005846 * Right position of this view relative to its parent.
5847 *
5848 * @return The right edge of this view, in pixels.
5849 */
5850 @ViewDebug.CapturedViewProperty
5851 public final int getRight() {
5852 return mRight;
5853 }
5854
5855 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005856 * Sets the right position of this view relative to its parent. This method is meant to be called
5857 * by the layout system and should not generally be called otherwise, because the property
5858 * may be changed at any time by the layout.
5859 *
5860 * @param right The bottom of this view, in pixels.
5861 */
5862 public final void setRight(int right) {
5863 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07005864 updateMatrix();
5865 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005866 final ViewParent p = mParent;
5867 if (p != null && mAttachInfo != null) {
5868 final Rect r = mAttachInfo.mTmpInvalRect;
5869 int maxRight;
5870 if (right < mRight) {
5871 maxRight = mRight;
5872 } else {
5873 maxRight = right;
5874 }
5875 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
5876 p.invalidateChild(this, r);
5877 }
5878 } else {
5879 // Double-invalidation is necessary to capture view's old and new areas
5880 invalidate();
5881 }
5882
Chet Haaseed032702010-10-01 14:05:54 -07005883 int oldWidth = mRight - mLeft;
5884 int height = mBottom - mTop;
5885
Chet Haase21cd1382010-09-01 17:42:29 -07005886 mRight = right;
5887
Chet Haaseed032702010-10-01 14:05:54 -07005888 onSizeChanged(mRight - mLeft, height, oldWidth, height);
5889
Chet Haase21cd1382010-09-01 17:42:29 -07005890 if (!mMatrixIsIdentity) {
5891 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5892 invalidate();
5893 }
5894 }
5895 }
5896
5897 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005898 * The visual x position of this view, in pixels. This is equivalent to the
5899 * {@link #setTranslationX(float) translationX} property plus the current
5900 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07005901 *
Chet Haasedf030d22010-07-30 17:22:38 -07005902 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005903 */
Chet Haasedf030d22010-07-30 17:22:38 -07005904 public float getX() {
5905 return mLeft + mTranslationX;
5906 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005907
Chet Haasedf030d22010-07-30 17:22:38 -07005908 /**
5909 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
5910 * {@link #setTranslationX(float) translationX} property to be the difference between
5911 * the x value passed in and the current {@link #getLeft() left} property.
5912 *
5913 * @param x The visual x position of this view, in pixels.
5914 */
5915 public void setX(float x) {
5916 setTranslationX(x - mLeft);
5917 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005918
Chet Haasedf030d22010-07-30 17:22:38 -07005919 /**
5920 * The visual y position of this view, in pixels. This is equivalent to the
5921 * {@link #setTranslationY(float) translationY} property plus the current
5922 * {@link #getTop() top} property.
5923 *
5924 * @return The visual y position of this view, in pixels.
5925 */
5926 public float getY() {
5927 return mTop + mTranslationY;
5928 }
5929
5930 /**
5931 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
5932 * {@link #setTranslationY(float) translationY} property to be the difference between
5933 * the y value passed in and the current {@link #getTop() top} property.
5934 *
5935 * @param y The visual y position of this view, in pixels.
5936 */
5937 public void setY(float y) {
5938 setTranslationY(y - mTop);
5939 }
5940
5941
5942 /**
5943 * The horizontal location of this view relative to its {@link #getLeft() left} position.
5944 * This position is post-layout, in addition to wherever the object's
5945 * layout placed it.
5946 *
5947 * @return The horizontal position of this view relative to its left position, in pixels.
5948 */
5949 public float getTranslationX() {
5950 return mTranslationX;
5951 }
5952
5953 /**
5954 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
5955 * This effectively positions the object post-layout, in addition to wherever the object's
5956 * layout placed it.
5957 *
5958 * @param translationX The horizontal position of this view relative to its left position,
5959 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08005960 *
5961 * @attr ref android.R.styleable#View_translationX
Chet Haasedf030d22010-07-30 17:22:38 -07005962 */
5963 public void setTranslationX(float translationX) {
5964 if (mTranslationX != translationX) {
5965 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005966 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07005967 mTranslationX = translationX;
5968 mMatrixDirty = true;
5969 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005970 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005971 }
5972 }
5973
5974 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005975 * The horizontal location of this view relative to its {@link #getTop() top} position.
5976 * This position is post-layout, in addition to wherever the object's
5977 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005978 *
Chet Haasedf030d22010-07-30 17:22:38 -07005979 * @return The vertical position of this view relative to its top position,
5980 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005981 */
Chet Haasedf030d22010-07-30 17:22:38 -07005982 public float getTranslationY() {
5983 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07005984 }
5985
5986 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005987 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
5988 * This effectively positions the object post-layout, in addition to wherever the object's
5989 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005990 *
Chet Haasedf030d22010-07-30 17:22:38 -07005991 * @param translationY The vertical position of this view relative to its top position,
5992 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08005993 *
5994 * @attr ref android.R.styleable#View_translationY
Chet Haasec3aa3612010-06-17 08:50:37 -07005995 */
Chet Haasedf030d22010-07-30 17:22:38 -07005996 public void setTranslationY(float translationY) {
5997 if (mTranslationY != translationY) {
5998 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005999 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006000 mTranslationY = translationY;
6001 mMatrixDirty = true;
6002 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006003 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006004 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006005 }
6006
6007 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 * Hit rectangle in parent's coordinates
6009 *
6010 * @param outRect The hit rectangle of the view.
6011 */
6012 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07006013 updateMatrix();
6014 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006015 outRect.set(mLeft, mTop, mRight, mBottom);
6016 } else {
6017 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07006018 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07006019 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07006020 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
6021 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07006022 }
6023 }
6024
6025 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07006026 * Determines whether the given point, in local coordinates is inside the view.
6027 */
6028 /*package*/ final boolean pointInView(float localX, float localY) {
6029 return localX >= 0 && localX < (mRight - mLeft)
6030 && localY >= 0 && localY < (mBottom - mTop);
6031 }
6032
6033 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07006034 * Utility method to determine whether the given point, in local coordinates,
6035 * is inside the view, where the area of the view is expanded by the slop factor.
6036 * This method is called while processing touch-move events to determine if the event
6037 * is still within the view.
6038 */
6039 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07006040 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07006041 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 }
6043
6044 /**
6045 * When a view has focus and the user navigates away from it, the next view is searched for
6046 * starting from the rectangle filled in by this method.
6047 *
6048 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
6049 * view maintains some idea of internal selection, such as a cursor, or a selected row
6050 * or column, you should override this method and fill in a more specific rectangle.
6051 *
6052 * @param r The rectangle to fill in, in this view's coordinates.
6053 */
6054 public void getFocusedRect(Rect r) {
6055 getDrawingRect(r);
6056 }
6057
6058 /**
6059 * If some part of this view is not clipped by any of its parents, then
6060 * return that area in r in global (root) coordinates. To convert r to local
6061 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
6062 * -globalOffset.y)) If the view is completely clipped or translated out,
6063 * return false.
6064 *
6065 * @param r If true is returned, r holds the global coordinates of the
6066 * visible portion of this view.
6067 * @param globalOffset If true is returned, globalOffset holds the dx,dy
6068 * between this view and its root. globalOffet may be null.
6069 * @return true if r is non-empty (i.e. part of the view is visible at the
6070 * root level.
6071 */
6072 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6073 int width = mRight - mLeft;
6074 int height = mBottom - mTop;
6075 if (width > 0 && height > 0) {
6076 r.set(0, 0, width, height);
6077 if (globalOffset != null) {
6078 globalOffset.set(-mScrollX, -mScrollY);
6079 }
6080 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6081 }
6082 return false;
6083 }
6084
6085 public final boolean getGlobalVisibleRect(Rect r) {
6086 return getGlobalVisibleRect(r, null);
6087 }
6088
6089 public final boolean getLocalVisibleRect(Rect r) {
6090 Point offset = new Point();
6091 if (getGlobalVisibleRect(r, offset)) {
6092 r.offset(-offset.x, -offset.y); // make r local
6093 return true;
6094 }
6095 return false;
6096 }
6097
6098 /**
6099 * Offset this view's vertical location by the specified number of pixels.
6100 *
6101 * @param offset the number of pixels to offset the view by
6102 */
6103 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006104 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006105 updateMatrix();
6106 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006107 final ViewParent p = mParent;
6108 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006109 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006110 int minTop;
6111 int maxBottom;
6112 int yLoc;
6113 if (offset < 0) {
6114 minTop = mTop + offset;
6115 maxBottom = mBottom;
6116 yLoc = offset;
6117 } else {
6118 minTop = mTop;
6119 maxBottom = mBottom + offset;
6120 yLoc = 0;
6121 }
6122 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6123 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006124 }
6125 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006126 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006127 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006128
Chet Haasec3aa3612010-06-17 08:50:37 -07006129 mTop += offset;
6130 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006131
Chet Haasec3aa3612010-06-17 08:50:37 -07006132 if (!mMatrixIsIdentity) {
6133 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006134 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006135 }
6136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 }
6138
6139 /**
6140 * Offset this view's horizontal location by the specified amount of pixels.
6141 *
6142 * @param offset the numer of pixels to offset the view by
6143 */
6144 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006145 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006146 updateMatrix();
6147 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006148 final ViewParent p = mParent;
6149 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006150 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006151 int minLeft;
6152 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006153 if (offset < 0) {
6154 minLeft = mLeft + offset;
6155 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006156 } else {
6157 minLeft = mLeft;
6158 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006159 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006160 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07006161 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006162 }
6163 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006164 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006165 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006166
Chet Haasec3aa3612010-06-17 08:50:37 -07006167 mLeft += offset;
6168 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006169
Chet Haasec3aa3612010-06-17 08:50:37 -07006170 if (!mMatrixIsIdentity) {
6171 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006172 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006173 }
6174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175 }
6176
6177 /**
6178 * Get the LayoutParams associated with this view. All views should have
6179 * layout parameters. These supply parameters to the <i>parent</i> of this
6180 * view specifying how it should be arranged. There are many subclasses of
6181 * ViewGroup.LayoutParams, and these correspond to the different subclasses
6182 * of ViewGroup that are responsible for arranging their children.
6183 * @return The LayoutParams associated with this view
6184 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07006185 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 public ViewGroup.LayoutParams getLayoutParams() {
6187 return mLayoutParams;
6188 }
6189
6190 /**
6191 * Set the layout parameters associated with this view. These supply
6192 * parameters to the <i>parent</i> of this view specifying how it should be
6193 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6194 * correspond to the different subclasses of ViewGroup that are responsible
6195 * for arranging their children.
6196 *
6197 * @param params the layout parameters for this view
6198 */
6199 public void setLayoutParams(ViewGroup.LayoutParams params) {
6200 if (params == null) {
6201 throw new NullPointerException("params == null");
6202 }
6203 mLayoutParams = params;
6204 requestLayout();
6205 }
6206
6207 /**
6208 * Set the scrolled position of your view. This will cause a call to
6209 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6210 * invalidated.
6211 * @param x the x position to scroll to
6212 * @param y the y position to scroll to
6213 */
6214 public void scrollTo(int x, int y) {
6215 if (mScrollX != x || mScrollY != y) {
6216 int oldX = mScrollX;
6217 int oldY = mScrollY;
6218 mScrollX = x;
6219 mScrollY = y;
6220 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006221 if (!awakenScrollBars()) {
6222 invalidate();
6223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 }
6225 }
6226
6227 /**
6228 * Move the scrolled position of your view. This will cause a call to
6229 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6230 * invalidated.
6231 * @param x the amount of pixels to scroll by horizontally
6232 * @param y the amount of pixels to scroll by vertically
6233 */
6234 public void scrollBy(int x, int y) {
6235 scrollTo(mScrollX + x, mScrollY + y);
6236 }
6237
6238 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006239 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6240 * animation to fade the scrollbars out after a default delay. If a subclass
6241 * provides animated scrolling, the start delay should equal the duration
6242 * of the scrolling animation.</p>
6243 *
6244 * <p>The animation starts only if at least one of the scrollbars is
6245 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6246 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6247 * this method returns true, and false otherwise. If the animation is
6248 * started, this method calls {@link #invalidate()}; in that case the
6249 * caller should not call {@link #invalidate()}.</p>
6250 *
6251 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006252 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006253 *
6254 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6255 * and {@link #scrollTo(int, int)}.</p>
6256 *
6257 * @return true if the animation is played, false otherwise
6258 *
6259 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006260 * @see #scrollBy(int, int)
6261 * @see #scrollTo(int, int)
6262 * @see #isHorizontalScrollBarEnabled()
6263 * @see #isVerticalScrollBarEnabled()
6264 * @see #setHorizontalScrollBarEnabled(boolean)
6265 * @see #setVerticalScrollBarEnabled(boolean)
6266 */
6267 protected boolean awakenScrollBars() {
6268 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006269 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006270 }
6271
6272 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006273 * Trigger the scrollbars to draw.
6274 * This method differs from awakenScrollBars() only in its default duration.
6275 * initialAwakenScrollBars() will show the scroll bars for longer than
6276 * usual to give the user more of a chance to notice them.
6277 *
6278 * @return true if the animation is played, false otherwise.
6279 */
6280 private boolean initialAwakenScrollBars() {
6281 return mScrollCache != null &&
6282 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6283 }
6284
6285 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006286 * <p>
6287 * Trigger the scrollbars to draw. When invoked this method starts an
6288 * animation to fade the scrollbars out after a fixed delay. If a subclass
6289 * provides animated scrolling, the start delay should equal the duration of
6290 * the scrolling animation.
6291 * </p>
6292 *
6293 * <p>
6294 * The animation starts only if at least one of the scrollbars is enabled,
6295 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6296 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6297 * this method returns true, and false otherwise. If the animation is
6298 * started, this method calls {@link #invalidate()}; in that case the caller
6299 * should not call {@link #invalidate()}.
6300 * </p>
6301 *
6302 * <p>
6303 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006304 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006305 * </p>
6306 *
6307 * @param startDelay the delay, in milliseconds, after which the animation
6308 * should start; when the delay is 0, the animation starts
6309 * immediately
6310 * @return true if the animation is played, false otherwise
6311 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006312 * @see #scrollBy(int, int)
6313 * @see #scrollTo(int, int)
6314 * @see #isHorizontalScrollBarEnabled()
6315 * @see #isVerticalScrollBarEnabled()
6316 * @see #setHorizontalScrollBarEnabled(boolean)
6317 * @see #setVerticalScrollBarEnabled(boolean)
6318 */
6319 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006320 return awakenScrollBars(startDelay, true);
6321 }
6322
6323 /**
6324 * <p>
6325 * Trigger the scrollbars to draw. When invoked this method starts an
6326 * animation to fade the scrollbars out after a fixed delay. If a subclass
6327 * provides animated scrolling, the start delay should equal the duration of
6328 * the scrolling animation.
6329 * </p>
6330 *
6331 * <p>
6332 * The animation starts only if at least one of the scrollbars is enabled,
6333 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6334 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6335 * this method returns true, and false otherwise. If the animation is
6336 * started, this method calls {@link #invalidate()} if the invalidate parameter
6337 * is set to true; in that case the caller
6338 * should not call {@link #invalidate()}.
6339 * </p>
6340 *
6341 * <p>
6342 * This method should be invoked everytime a subclass directly updates the
6343 * scroll parameters.
6344 * </p>
6345 *
6346 * @param startDelay the delay, in milliseconds, after which the animation
6347 * should start; when the delay is 0, the animation starts
6348 * immediately
6349 *
6350 * @param invalidate Wheter this method should call invalidate
6351 *
6352 * @return true if the animation is played, false otherwise
6353 *
6354 * @see #scrollBy(int, int)
6355 * @see #scrollTo(int, int)
6356 * @see #isHorizontalScrollBarEnabled()
6357 * @see #isVerticalScrollBarEnabled()
6358 * @see #setHorizontalScrollBarEnabled(boolean)
6359 * @see #setVerticalScrollBarEnabled(boolean)
6360 */
6361 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006362 final ScrollabilityCache scrollCache = mScrollCache;
6363
6364 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6365 return false;
6366 }
6367
6368 if (scrollCache.scrollBar == null) {
6369 scrollCache.scrollBar = new ScrollBarDrawable();
6370 }
6371
6372 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6373
Mike Cleron290947b2009-09-29 18:34:32 -07006374 if (invalidate) {
6375 // Invalidate to show the scrollbars
6376 invalidate();
6377 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006378
6379 if (scrollCache.state == ScrollabilityCache.OFF) {
6380 // FIXME: this is copied from WindowManagerService.
6381 // We should get this value from the system when it
6382 // is possible to do so.
6383 final int KEY_REPEAT_FIRST_DELAY = 750;
6384 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6385 }
6386
6387 // Tell mScrollCache when we should start fading. This may
6388 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006389 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006390 scrollCache.fadeStartTime = fadeStartTime;
6391 scrollCache.state = ScrollabilityCache.ON;
6392
6393 // Schedule our fader to run, unscheduling any old ones first
6394 if (mAttachInfo != null) {
6395 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6396 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6397 }
6398
6399 return true;
6400 }
6401
6402 return false;
6403 }
6404
6405 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 * Mark the the area defined by dirty as needing to be drawn. If the view is
6407 * visible, {@link #onDraw} will be called at some point in the future.
6408 * This must be called from a UI thread. To call from a non-UI thread, call
6409 * {@link #postInvalidate()}.
6410 *
6411 * WARNING: This method is destructive to dirty.
6412 * @param dirty the rectangle representing the bounds of the dirty region
6413 */
6414 public void invalidate(Rect dirty) {
6415 if (ViewDebug.TRACE_HIERARCHY) {
6416 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6417 }
6418
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006419 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6420 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6422 final ViewParent p = mParent;
6423 final AttachInfo ai = mAttachInfo;
6424 if (p != null && ai != null) {
6425 final int scrollX = mScrollX;
6426 final int scrollY = mScrollY;
6427 final Rect r = ai.mTmpInvalRect;
6428 r.set(dirty.left - scrollX, dirty.top - scrollY,
6429 dirty.right - scrollX, dirty.bottom - scrollY);
6430 mParent.invalidateChild(this, r);
6431 }
6432 }
6433 }
6434
6435 /**
6436 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6437 * The coordinates of the dirty rect are relative to the view.
6438 * If the view is visible, {@link #onDraw} will be called at some point
6439 * in the future. This must be called from a UI thread. To call
6440 * from a non-UI thread, call {@link #postInvalidate()}.
6441 * @param l the left position of the dirty region
6442 * @param t the top position of the dirty region
6443 * @param r the right position of the dirty region
6444 * @param b the bottom position of the dirty region
6445 */
6446 public void invalidate(int l, int t, int r, int b) {
6447 if (ViewDebug.TRACE_HIERARCHY) {
6448 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6449 }
6450
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006451 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6452 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6454 final ViewParent p = mParent;
6455 final AttachInfo ai = mAttachInfo;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006456 if (p != null && ai != null && ai.mHardwareAccelerated) {
6457 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6458 // with a null dirty rect, which tells the ViewRoot to redraw everything
6459 p.invalidateChild(this, null);
6460 return;
6461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 if (p != null && ai != null && l < r && t < b) {
6463 final int scrollX = mScrollX;
6464 final int scrollY = mScrollY;
6465 final Rect tmpr = ai.mTmpInvalRect;
6466 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6467 p.invalidateChild(this, tmpr);
6468 }
6469 }
6470 }
6471
6472 /**
6473 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6474 * be called at some point in the future. This must be called from a
6475 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6476 */
6477 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006478 invalidate(true);
6479 }
6480
6481 /**
6482 * This is where the invalidate() work actually happens. A full invalidate()
6483 * causes the drawing cache to be invalidated, but this function can be called with
6484 * invalidateCache set to false to skip that invalidation step for cases that do not
6485 * need it (for example, a component that remains at the same dimensions with the same
6486 * content).
6487 *
6488 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6489 * well. This is usually true for a full invalidate, but may be set to false if the
6490 * View's contents or dimensions have not changed.
6491 */
6492 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 if (ViewDebug.TRACE_HIERARCHY) {
6494 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6495 }
6496
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006497 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6498 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID)) {
Chet Haaseed032702010-10-01 14:05:54 -07006499 mPrivateFlags &= ~DRAWN;
6500 if (invalidateCache) {
6501 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006503 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006504 final ViewParent p = mParent;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006505 if (p != null && ai != null && ai.mHardwareAccelerated) {
6506 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6507 // with a null dirty rect, which tells the ViewRoot to redraw everything
6508 p.invalidateChild(this, null);
6509 return;
6510 }
Michael Jurkaebefea42010-11-15 16:04:01 -08006511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 if (p != null && ai != null) {
6513 final Rect r = ai.mTmpInvalRect;
6514 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6515 // Don't call invalidate -- we don't want to internally scroll
6516 // our own bounds
6517 p.invalidateChild(this, r);
6518 }
6519 }
6520 }
6521
6522 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006523 * Indicates whether this View is opaque. An opaque View guarantees that it will
6524 * draw all the pixels overlapping its bounds using a fully opaque color.
6525 *
6526 * Subclasses of View should override this method whenever possible to indicate
6527 * whether an instance is opaque. Opaque Views are treated in a special way by
6528 * the View hierarchy, possibly allowing it to perform optimizations during
6529 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006530 *
Romain Guy24443ea2009-05-11 11:56:30 -07006531 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006532 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006533 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006534 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006535 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6536 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006537 }
6538
6539 private void computeOpaqueFlags() {
6540 // Opaque if:
6541 // - Has a background
6542 // - Background is opaque
6543 // - Doesn't have scrollbars or scrollbars are inside overlay
6544
6545 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6546 mPrivateFlags |= OPAQUE_BACKGROUND;
6547 } else {
6548 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6549 }
6550
6551 final int flags = mViewFlags;
6552 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6553 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6554 mPrivateFlags |= OPAQUE_SCROLLBARS;
6555 } else {
6556 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6557 }
6558 }
6559
6560 /**
6561 * @hide
6562 */
6563 protected boolean hasOpaqueScrollbars() {
6564 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006565 }
6566
6567 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 * @return A handler associated with the thread running the View. This
6569 * handler can be used to pump events in the UI events queue.
6570 */
6571 public Handler getHandler() {
6572 if (mAttachInfo != null) {
6573 return mAttachInfo.mHandler;
6574 }
6575 return null;
6576 }
6577
6578 /**
6579 * Causes the Runnable to be added to the message queue.
6580 * The runnable will be run on the user interface thread.
6581 *
6582 * @param action The Runnable that will be executed.
6583 *
6584 * @return Returns true if the Runnable was successfully placed in to the
6585 * message queue. Returns false on failure, usually because the
6586 * looper processing the message queue is exiting.
6587 */
6588 public boolean post(Runnable action) {
6589 Handler handler;
6590 if (mAttachInfo != null) {
6591 handler = mAttachInfo.mHandler;
6592 } else {
6593 // Assume that post will succeed later
6594 ViewRoot.getRunQueue().post(action);
6595 return true;
6596 }
6597
6598 return handler.post(action);
6599 }
6600
6601 /**
6602 * Causes the Runnable to be added to the message queue, to be run
6603 * after the specified amount of time elapses.
6604 * The runnable will be run on the user interface thread.
6605 *
6606 * @param action The Runnable that will be executed.
6607 * @param delayMillis The delay (in milliseconds) until the Runnable
6608 * will be executed.
6609 *
6610 * @return true if the Runnable was successfully placed in to the
6611 * message queue. Returns false on failure, usually because the
6612 * looper processing the message queue is exiting. Note that a
6613 * result of true does not mean the Runnable will be processed --
6614 * if the looper is quit before the delivery time of the message
6615 * occurs then the message will be dropped.
6616 */
6617 public boolean postDelayed(Runnable action, long delayMillis) {
6618 Handler handler;
6619 if (mAttachInfo != null) {
6620 handler = mAttachInfo.mHandler;
6621 } else {
6622 // Assume that post will succeed later
6623 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6624 return true;
6625 }
6626
6627 return handler.postDelayed(action, delayMillis);
6628 }
6629
6630 /**
6631 * Removes the specified Runnable from the message queue.
6632 *
6633 * @param action The Runnable to remove from the message handling queue
6634 *
6635 * @return true if this view could ask the Handler to remove the Runnable,
6636 * false otherwise. When the returned value is true, the Runnable
6637 * may or may not have been actually removed from the message queue
6638 * (for instance, if the Runnable was not in the queue already.)
6639 */
6640 public boolean removeCallbacks(Runnable action) {
6641 Handler handler;
6642 if (mAttachInfo != null) {
6643 handler = mAttachInfo.mHandler;
6644 } else {
6645 // Assume that post will succeed later
6646 ViewRoot.getRunQueue().removeCallbacks(action);
6647 return true;
6648 }
6649
6650 handler.removeCallbacks(action);
6651 return true;
6652 }
6653
6654 /**
6655 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6656 * Use this to invalidate the View from a non-UI thread.
6657 *
6658 * @see #invalidate()
6659 */
6660 public void postInvalidate() {
6661 postInvalidateDelayed(0);
6662 }
6663
6664 /**
6665 * Cause an invalidate of the specified area to happen on a subsequent cycle
6666 * through the event loop. Use this to invalidate the View from a non-UI thread.
6667 *
6668 * @param left The left coordinate of the rectangle to invalidate.
6669 * @param top The top coordinate of the rectangle to invalidate.
6670 * @param right The right coordinate of the rectangle to invalidate.
6671 * @param bottom The bottom coordinate of the rectangle to invalidate.
6672 *
6673 * @see #invalidate(int, int, int, int)
6674 * @see #invalidate(Rect)
6675 */
6676 public void postInvalidate(int left, int top, int right, int bottom) {
6677 postInvalidateDelayed(0, left, top, right, bottom);
6678 }
6679
6680 /**
6681 * Cause an invalidate to happen on a subsequent cycle through the event
6682 * loop. Waits for the specified amount of time.
6683 *
6684 * @param delayMilliseconds the duration in milliseconds to delay the
6685 * invalidation by
6686 */
6687 public void postInvalidateDelayed(long delayMilliseconds) {
6688 // We try only with the AttachInfo because there's no point in invalidating
6689 // if we are not attached to our window
6690 if (mAttachInfo != null) {
6691 Message msg = Message.obtain();
6692 msg.what = AttachInfo.INVALIDATE_MSG;
6693 msg.obj = this;
6694 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6695 }
6696 }
6697
6698 /**
6699 * Cause an invalidate of the specified area to happen on a subsequent cycle
6700 * through the event loop. Waits for the specified amount of time.
6701 *
6702 * @param delayMilliseconds the duration in milliseconds to delay the
6703 * invalidation by
6704 * @param left The left coordinate of the rectangle to invalidate.
6705 * @param top The top coordinate of the rectangle to invalidate.
6706 * @param right The right coordinate of the rectangle to invalidate.
6707 * @param bottom The bottom coordinate of the rectangle to invalidate.
6708 */
6709 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6710 int right, int bottom) {
6711
6712 // We try only with the AttachInfo because there's no point in invalidating
6713 // if we are not attached to our window
6714 if (mAttachInfo != null) {
6715 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6716 info.target = this;
6717 info.left = left;
6718 info.top = top;
6719 info.right = right;
6720 info.bottom = bottom;
6721
6722 final Message msg = Message.obtain();
6723 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6724 msg.obj = info;
6725 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6726 }
6727 }
6728
6729 /**
6730 * Called by a parent to request that a child update its values for mScrollX
6731 * and mScrollY if necessary. This will typically be done if the child is
6732 * animating a scroll using a {@link android.widget.Scroller Scroller}
6733 * object.
6734 */
6735 public void computeScroll() {
6736 }
6737
6738 /**
6739 * <p>Indicate whether the horizontal edges are faded when the view is
6740 * scrolled horizontally.</p>
6741 *
6742 * @return true if the horizontal edges should are faded on scroll, false
6743 * otherwise
6744 *
6745 * @see #setHorizontalFadingEdgeEnabled(boolean)
6746 * @attr ref android.R.styleable#View_fadingEdge
6747 */
6748 public boolean isHorizontalFadingEdgeEnabled() {
6749 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6750 }
6751
6752 /**
6753 * <p>Define whether the horizontal edges should be faded when this view
6754 * is scrolled horizontally.</p>
6755 *
6756 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6757 * be faded when the view is scrolled
6758 * horizontally
6759 *
6760 * @see #isHorizontalFadingEdgeEnabled()
6761 * @attr ref android.R.styleable#View_fadingEdge
6762 */
6763 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6764 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6765 if (horizontalFadingEdgeEnabled) {
6766 initScrollCache();
6767 }
6768
6769 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6770 }
6771 }
6772
6773 /**
6774 * <p>Indicate whether the vertical edges are faded when the view is
6775 * scrolled horizontally.</p>
6776 *
6777 * @return true if the vertical edges should are faded on scroll, false
6778 * otherwise
6779 *
6780 * @see #setVerticalFadingEdgeEnabled(boolean)
6781 * @attr ref android.R.styleable#View_fadingEdge
6782 */
6783 public boolean isVerticalFadingEdgeEnabled() {
6784 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6785 }
6786
6787 /**
6788 * <p>Define whether the vertical edges should be faded when this view
6789 * is scrolled vertically.</p>
6790 *
6791 * @param verticalFadingEdgeEnabled true if the vertical edges should
6792 * be faded when the view is scrolled
6793 * vertically
6794 *
6795 * @see #isVerticalFadingEdgeEnabled()
6796 * @attr ref android.R.styleable#View_fadingEdge
6797 */
6798 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6799 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6800 if (verticalFadingEdgeEnabled) {
6801 initScrollCache();
6802 }
6803
6804 mViewFlags ^= FADING_EDGE_VERTICAL;
6805 }
6806 }
6807
6808 /**
6809 * Returns the strength, or intensity, of the top faded edge. The strength is
6810 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6811 * returns 0.0 or 1.0 but no value in between.
6812 *
6813 * Subclasses should override this method to provide a smoother fade transition
6814 * when scrolling occurs.
6815 *
6816 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6817 */
6818 protected float getTopFadingEdgeStrength() {
6819 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6820 }
6821
6822 /**
6823 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6824 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6825 * returns 0.0 or 1.0 but no value in between.
6826 *
6827 * Subclasses should override this method to provide a smoother fade transition
6828 * when scrolling occurs.
6829 *
6830 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6831 */
6832 protected float getBottomFadingEdgeStrength() {
6833 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6834 computeVerticalScrollRange() ? 1.0f : 0.0f;
6835 }
6836
6837 /**
6838 * Returns the strength, or intensity, of the left faded edge. The strength is
6839 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6840 * returns 0.0 or 1.0 but no value in between.
6841 *
6842 * Subclasses should override this method to provide a smoother fade transition
6843 * when scrolling occurs.
6844 *
6845 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6846 */
6847 protected float getLeftFadingEdgeStrength() {
6848 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6849 }
6850
6851 /**
6852 * Returns the strength, or intensity, of the right faded edge. The strength is
6853 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6854 * returns 0.0 or 1.0 but no value in between.
6855 *
6856 * Subclasses should override this method to provide a smoother fade transition
6857 * when scrolling occurs.
6858 *
6859 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6860 */
6861 protected float getRightFadingEdgeStrength() {
6862 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6863 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6864 }
6865
6866 /**
6867 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6868 * scrollbar is not drawn by default.</p>
6869 *
6870 * @return true if the horizontal scrollbar should be painted, false
6871 * otherwise
6872 *
6873 * @see #setHorizontalScrollBarEnabled(boolean)
6874 */
6875 public boolean isHorizontalScrollBarEnabled() {
6876 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6877 }
6878
6879 /**
6880 * <p>Define whether the horizontal scrollbar should be drawn or not. The
6881 * scrollbar is not drawn by default.</p>
6882 *
6883 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
6884 * be painted
6885 *
6886 * @see #isHorizontalScrollBarEnabled()
6887 */
6888 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
6889 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
6890 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006891 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006892 recomputePadding();
6893 }
6894 }
6895
6896 /**
6897 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
6898 * scrollbar is not drawn by default.</p>
6899 *
6900 * @return true if the vertical scrollbar should be painted, false
6901 * otherwise
6902 *
6903 * @see #setVerticalScrollBarEnabled(boolean)
6904 */
6905 public boolean isVerticalScrollBarEnabled() {
6906 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
6907 }
6908
6909 /**
6910 * <p>Define whether the vertical scrollbar should be drawn or not. The
6911 * scrollbar is not drawn by default.</p>
6912 *
6913 * @param verticalScrollBarEnabled true if the vertical scrollbar should
6914 * be painted
6915 *
6916 * @see #isVerticalScrollBarEnabled()
6917 */
6918 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
6919 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
6920 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006921 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006922 recomputePadding();
6923 }
6924 }
6925
6926 private void recomputePadding() {
6927 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
6928 }
Mike Cleronfe81d382009-09-28 14:22:16 -07006929
6930 /**
6931 * Define whether scrollbars will fade when the view is not scrolling.
6932 *
6933 * @param fadeScrollbars wheter to enable fading
6934 *
6935 */
6936 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
6937 initScrollCache();
6938 final ScrollabilityCache scrollabilityCache = mScrollCache;
6939 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07006940 if (fadeScrollbars) {
6941 scrollabilityCache.state = ScrollabilityCache.OFF;
6942 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07006943 scrollabilityCache.state = ScrollabilityCache.ON;
6944 }
6945 }
6946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07006948 *
6949 * Returns true if scrollbars will fade when this view is not scrolling
6950 *
6951 * @return true if scrollbar fading is enabled
6952 */
6953 public boolean isScrollbarFadingEnabled() {
6954 return mScrollCache != null && mScrollCache.fadeScrollBars;
6955 }
6956
6957 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
6959 * inset. When inset, they add to the padding of the view. And the scrollbars
6960 * can be drawn inside the padding area or on the edge of the view. For example,
6961 * if a view has a background drawable and you want to draw the scrollbars
6962 * inside the padding specified by the drawable, you can use
6963 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
6964 * appear at the edge of the view, ignoring the padding, then you can use
6965 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
6966 * @param style the style of the scrollbars. Should be one of
6967 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
6968 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
6969 * @see #SCROLLBARS_INSIDE_OVERLAY
6970 * @see #SCROLLBARS_INSIDE_INSET
6971 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6972 * @see #SCROLLBARS_OUTSIDE_INSET
6973 */
6974 public void setScrollBarStyle(int style) {
6975 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
6976 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07006977 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 recomputePadding();
6979 }
6980 }
6981
6982 /**
6983 * <p>Returns the current scrollbar style.</p>
6984 * @return the current scrollbar style
6985 * @see #SCROLLBARS_INSIDE_OVERLAY
6986 * @see #SCROLLBARS_INSIDE_INSET
6987 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6988 * @see #SCROLLBARS_OUTSIDE_INSET
6989 */
6990 public int getScrollBarStyle() {
6991 return mViewFlags & SCROLLBARS_STYLE_MASK;
6992 }
6993
6994 /**
6995 * <p>Compute the horizontal range that the horizontal scrollbar
6996 * represents.</p>
6997 *
6998 * <p>The range is expressed in arbitrary units that must be the same as the
6999 * units used by {@link #computeHorizontalScrollExtent()} and
7000 * {@link #computeHorizontalScrollOffset()}.</p>
7001 *
7002 * <p>The default range is the drawing width of this view.</p>
7003 *
7004 * @return the total horizontal range represented by the horizontal
7005 * scrollbar
7006 *
7007 * @see #computeHorizontalScrollExtent()
7008 * @see #computeHorizontalScrollOffset()
7009 * @see android.widget.ScrollBarDrawable
7010 */
7011 protected int computeHorizontalScrollRange() {
7012 return getWidth();
7013 }
7014
7015 /**
7016 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7017 * within the horizontal range. This value is used to compute the position
7018 * of the thumb within the scrollbar's track.</p>
7019 *
7020 * <p>The range is expressed in arbitrary units that must be the same as the
7021 * units used by {@link #computeHorizontalScrollRange()} and
7022 * {@link #computeHorizontalScrollExtent()}.</p>
7023 *
7024 * <p>The default offset is the scroll offset of this view.</p>
7025 *
7026 * @return the horizontal offset of the scrollbar's thumb
7027 *
7028 * @see #computeHorizontalScrollRange()
7029 * @see #computeHorizontalScrollExtent()
7030 * @see android.widget.ScrollBarDrawable
7031 */
7032 protected int computeHorizontalScrollOffset() {
7033 return mScrollX;
7034 }
7035
7036 /**
7037 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7038 * within the horizontal range. This value is used to compute the length
7039 * of the thumb within the scrollbar's track.</p>
7040 *
7041 * <p>The range is expressed in arbitrary units that must be the same as the
7042 * units used by {@link #computeHorizontalScrollRange()} and
7043 * {@link #computeHorizontalScrollOffset()}.</p>
7044 *
7045 * <p>The default extent is the drawing width of this view.</p>
7046 *
7047 * @return the horizontal extent of the scrollbar's thumb
7048 *
7049 * @see #computeHorizontalScrollRange()
7050 * @see #computeHorizontalScrollOffset()
7051 * @see android.widget.ScrollBarDrawable
7052 */
7053 protected int computeHorizontalScrollExtent() {
7054 return getWidth();
7055 }
7056
7057 /**
7058 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7059 *
7060 * <p>The range is expressed in arbitrary units that must be the same as the
7061 * units used by {@link #computeVerticalScrollExtent()} and
7062 * {@link #computeVerticalScrollOffset()}.</p>
7063 *
7064 * @return the total vertical range represented by the vertical scrollbar
7065 *
7066 * <p>The default range is the drawing height of this view.</p>
7067 *
7068 * @see #computeVerticalScrollExtent()
7069 * @see #computeVerticalScrollOffset()
7070 * @see android.widget.ScrollBarDrawable
7071 */
7072 protected int computeVerticalScrollRange() {
7073 return getHeight();
7074 }
7075
7076 /**
7077 * <p>Compute the vertical offset of the vertical scrollbar's thumb
7078 * within the horizontal range. This value is used to compute the position
7079 * of the thumb within the scrollbar's track.</p>
7080 *
7081 * <p>The range is expressed in arbitrary units that must be the same as the
7082 * units used by {@link #computeVerticalScrollRange()} and
7083 * {@link #computeVerticalScrollExtent()}.</p>
7084 *
7085 * <p>The default offset is the scroll offset of this view.</p>
7086 *
7087 * @return the vertical offset of the scrollbar's thumb
7088 *
7089 * @see #computeVerticalScrollRange()
7090 * @see #computeVerticalScrollExtent()
7091 * @see android.widget.ScrollBarDrawable
7092 */
7093 protected int computeVerticalScrollOffset() {
7094 return mScrollY;
7095 }
7096
7097 /**
7098 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7099 * within the vertical range. This value is used to compute the length
7100 * of the thumb within the scrollbar's track.</p>
7101 *
7102 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08007103 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007104 * {@link #computeVerticalScrollOffset()}.</p>
7105 *
7106 * <p>The default extent is the drawing height of this view.</p>
7107 *
7108 * @return the vertical extent of the scrollbar's thumb
7109 *
7110 * @see #computeVerticalScrollRange()
7111 * @see #computeVerticalScrollOffset()
7112 * @see android.widget.ScrollBarDrawable
7113 */
7114 protected int computeVerticalScrollExtent() {
7115 return getHeight();
7116 }
7117
7118 /**
7119 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7120 * scrollbars are painted only if they have been awakened first.</p>
7121 *
7122 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07007123 *
7124 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007125 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08007126 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007127 // scrollbars are drawn only when the animation is running
7128 final ScrollabilityCache cache = mScrollCache;
7129 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007130
7131 int state = cache.state;
7132
7133 if (state == ScrollabilityCache.OFF) {
7134 return;
7135 }
7136
7137 boolean invalidate = false;
7138
7139 if (state == ScrollabilityCache.FADING) {
7140 // We're fading -- get our fade interpolation
7141 if (cache.interpolatorValues == null) {
7142 cache.interpolatorValues = new float[1];
7143 }
7144
7145 float[] values = cache.interpolatorValues;
7146
7147 // Stops the animation if we're done
7148 if (cache.scrollBarInterpolator.timeToValues(values) ==
7149 Interpolator.Result.FREEZE_END) {
7150 cache.state = ScrollabilityCache.OFF;
7151 } else {
7152 cache.scrollBar.setAlpha(Math.round(values[0]));
7153 }
7154
7155 // This will make the scroll bars inval themselves after
7156 // drawing. We only want this when we're fading so that
7157 // we prevent excessive redraws
7158 invalidate = true;
7159 } else {
7160 // We're just on -- but we may have been fading before so
7161 // reset alpha
7162 cache.scrollBar.setAlpha(255);
7163 }
7164
7165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007166 final int viewFlags = mViewFlags;
7167
7168 final boolean drawHorizontalScrollBar =
7169 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7170 final boolean drawVerticalScrollBar =
7171 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7172 && !isVerticalScrollBarHidden();
7173
7174 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7175 final int width = mRight - mLeft;
7176 final int height = mBottom - mTop;
7177
7178 final ScrollBarDrawable scrollBar = cache.scrollBar;
7179 int size = scrollBar.getSize(false);
7180 if (size <= 0) {
7181 size = cache.scrollBarSize;
7182 }
7183
Mike Reede8853fc2009-09-04 14:01:48 -04007184 final int scrollX = mScrollX;
7185 final int scrollY = mScrollY;
7186 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7187
Mike Cleronf116bf82009-09-27 19:14:12 -07007188 int left, top, right, bottom;
7189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007191 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04007192 computeHorizontalScrollOffset(),
7193 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04007194 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07007195 getVerticalScrollbarWidth() : 0;
7196 top = scrollY + height - size - (mUserPaddingBottom & inside);
7197 left = scrollX + (mPaddingLeft & inside);
7198 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7199 bottom = top + size;
7200 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7201 if (invalidate) {
7202 invalidate(left, top, right, bottom);
7203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 }
7205
7206 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04007207 scrollBar.setParameters(computeVerticalScrollRange(),
7208 computeVerticalScrollOffset(),
7209 computeVerticalScrollExtent(), true);
7210 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07007211 left = scrollX + width - size - (mUserPaddingRight & inside);
7212 top = scrollY + (mPaddingTop & inside);
7213 right = left + size;
7214 bottom = scrollY + height - (mUserPaddingBottom & inside);
7215 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7216 if (invalidate) {
7217 invalidate(left, top, right, bottom);
7218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 }
7220 }
7221 }
7222 }
Romain Guy8506ab42009-06-11 17:35:47 -07007223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007225 * 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 -08007226 * FastScroller is visible.
7227 * @return whether to temporarily hide the vertical scrollbar
7228 * @hide
7229 */
7230 protected boolean isVerticalScrollBarHidden() {
7231 return false;
7232 }
7233
7234 /**
7235 * <p>Draw the horizontal scrollbar if
7236 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7237 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007238 * @param canvas the canvas on which to draw the scrollbar
7239 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007240 *
7241 * @see #isHorizontalScrollBarEnabled()
7242 * @see #computeHorizontalScrollRange()
7243 * @see #computeHorizontalScrollExtent()
7244 * @see #computeHorizontalScrollOffset()
7245 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007246 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007247 */
Romain Guy8fb95422010-08-17 18:38:51 -07007248 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7249 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007250 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007251 scrollBar.draw(canvas);
7252 }
Mike Reede8853fc2009-09-04 14:01:48 -04007253
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007254 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7256 * returns true.</p>
7257 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007258 * @param canvas the canvas on which to draw the scrollbar
7259 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007260 *
7261 * @see #isVerticalScrollBarEnabled()
7262 * @see #computeVerticalScrollRange()
7263 * @see #computeVerticalScrollExtent()
7264 * @see #computeVerticalScrollOffset()
7265 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007266 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007267 */
Romain Guy8fb95422010-08-17 18:38:51 -07007268 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7269 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007270 scrollBar.setBounds(l, t, r, b);
7271 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007272 }
7273
7274 /**
7275 * Implement this to do your drawing.
7276 *
7277 * @param canvas the canvas on which the background will be drawn
7278 */
7279 protected void onDraw(Canvas canvas) {
7280 }
7281
7282 /*
7283 * Caller is responsible for calling requestLayout if necessary.
7284 * (This allows addViewInLayout to not request a new layout.)
7285 */
7286 void assignParent(ViewParent parent) {
7287 if (mParent == null) {
7288 mParent = parent;
7289 } else if (parent == null) {
7290 mParent = null;
7291 } else {
7292 throw new RuntimeException("view " + this + " being added, but"
7293 + " it already has a parent");
7294 }
7295 }
7296
7297 /**
7298 * This is called when the view is attached to a window. At this point it
7299 * has a Surface and will start drawing. Note that this function is
7300 * guaranteed to be called before {@link #onDraw}, however it may be called
7301 * any time before the first onDraw -- including before or after
7302 * {@link #onMeasure}.
7303 *
7304 * @see #onDetachedFromWindow()
7305 */
7306 protected void onAttachedToWindow() {
7307 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7308 mParent.requestTransparentRegion(this);
7309 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007310 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7311 initialAwakenScrollBars();
7312 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 }
7315
7316 /**
7317 * This is called when the view is detached from a window. At this point it
7318 * no longer has a surface for drawing.
7319 *
7320 * @see #onAttachedToWindow()
7321 */
7322 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007323 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08007324 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007325 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 destroyDrawingCache();
7327 }
7328
7329 /**
7330 * @return The number of times this view has been attached to a window
7331 */
7332 protected int getWindowAttachCount() {
7333 return mWindowAttachCount;
7334 }
7335
7336 /**
7337 * Retrieve a unique token identifying the window this view is attached to.
7338 * @return Return the window's token for use in
7339 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7340 */
7341 public IBinder getWindowToken() {
7342 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7343 }
7344
7345 /**
7346 * Retrieve a unique token identifying the top-level "real" window of
7347 * the window that this view is attached to. That is, this is like
7348 * {@link #getWindowToken}, except if the window this view in is a panel
7349 * window (attached to another containing window), then the token of
7350 * the containing window is returned instead.
7351 *
7352 * @return Returns the associated window token, either
7353 * {@link #getWindowToken()} or the containing window's token.
7354 */
7355 public IBinder getApplicationWindowToken() {
7356 AttachInfo ai = mAttachInfo;
7357 if (ai != null) {
7358 IBinder appWindowToken = ai.mPanelParentWindowToken;
7359 if (appWindowToken == null) {
7360 appWindowToken = ai.mWindowToken;
7361 }
7362 return appWindowToken;
7363 }
7364 return null;
7365 }
7366
7367 /**
7368 * Retrieve private session object this view hierarchy is using to
7369 * communicate with the window manager.
7370 * @return the session object to communicate with the window manager
7371 */
7372 /*package*/ IWindowSession getWindowSession() {
7373 return mAttachInfo != null ? mAttachInfo.mSession : null;
7374 }
7375
7376 /**
7377 * @param info the {@link android.view.View.AttachInfo} to associated with
7378 * this view
7379 */
7380 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7381 //System.out.println("Attached! " + this);
7382 mAttachInfo = info;
7383 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007384 // We will need to evaluate the drawable state at least once.
7385 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386 if (mFloatingTreeObserver != null) {
7387 info.mTreeObserver.merge(mFloatingTreeObserver);
7388 mFloatingTreeObserver = null;
7389 }
7390 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7391 mAttachInfo.mScrollContainers.add(this);
7392 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7393 }
7394 performCollectViewAttributes(visibility);
7395 onAttachedToWindow();
7396 int vis = info.mWindowVisibility;
7397 if (vis != GONE) {
7398 onWindowVisibilityChanged(vis);
7399 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007400 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7401 // If nobody has evaluated the drawable state yet, then do it now.
7402 refreshDrawableState();
7403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007404 }
7405
7406 void dispatchDetachedFromWindow() {
7407 //System.out.println("Detached! " + this);
7408 AttachInfo info = mAttachInfo;
7409 if (info != null) {
7410 int vis = info.mWindowVisibility;
7411 if (vis != GONE) {
7412 onWindowVisibilityChanged(GONE);
7413 }
7414 }
7415
7416 onDetachedFromWindow();
7417 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7418 mAttachInfo.mScrollContainers.remove(this);
7419 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7420 }
7421 mAttachInfo = null;
7422 }
7423
7424 /**
7425 * Store this view hierarchy's frozen state into the given container.
7426 *
7427 * @param container The SparseArray in which to save the view's state.
7428 *
7429 * @see #restoreHierarchyState
7430 * @see #dispatchSaveInstanceState
7431 * @see #onSaveInstanceState
7432 */
7433 public void saveHierarchyState(SparseArray<Parcelable> container) {
7434 dispatchSaveInstanceState(container);
7435 }
7436
7437 /**
7438 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7439 * May be overridden to modify how freezing happens to a view's children; for example, some
7440 * views may want to not store state for their children.
7441 *
7442 * @param container The SparseArray in which to save the view's state.
7443 *
7444 * @see #dispatchRestoreInstanceState
7445 * @see #saveHierarchyState
7446 * @see #onSaveInstanceState
7447 */
7448 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7449 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7450 mPrivateFlags &= ~SAVE_STATE_CALLED;
7451 Parcelable state = onSaveInstanceState();
7452 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7453 throw new IllegalStateException(
7454 "Derived class did not call super.onSaveInstanceState()");
7455 }
7456 if (state != null) {
7457 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7458 // + ": " + state);
7459 container.put(mID, state);
7460 }
7461 }
7462 }
7463
7464 /**
7465 * Hook allowing a view to generate a representation of its internal state
7466 * that can later be used to create a new instance with that same state.
7467 * This state should only contain information that is not persistent or can
7468 * not be reconstructed later. For example, you will never store your
7469 * current position on screen because that will be computed again when a
7470 * new instance of the view is placed in its view hierarchy.
7471 * <p>
7472 * Some examples of things you may store here: the current cursor position
7473 * in a text view (but usually not the text itself since that is stored in a
7474 * content provider or other persistent storage), the currently selected
7475 * item in a list view.
7476 *
7477 * @return Returns a Parcelable object containing the view's current dynamic
7478 * state, or null if there is nothing interesting to save. The
7479 * default implementation returns null.
7480 * @see #onRestoreInstanceState
7481 * @see #saveHierarchyState
7482 * @see #dispatchSaveInstanceState
7483 * @see #setSaveEnabled(boolean)
7484 */
7485 protected Parcelable onSaveInstanceState() {
7486 mPrivateFlags |= SAVE_STATE_CALLED;
7487 return BaseSavedState.EMPTY_STATE;
7488 }
7489
7490 /**
7491 * Restore this view hierarchy's frozen state from the given container.
7492 *
7493 * @param container The SparseArray which holds previously frozen states.
7494 *
7495 * @see #saveHierarchyState
7496 * @see #dispatchRestoreInstanceState
7497 * @see #onRestoreInstanceState
7498 */
7499 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7500 dispatchRestoreInstanceState(container);
7501 }
7502
7503 /**
7504 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7505 * children. May be overridden to modify how restoreing happens to a view's children; for
7506 * example, some views may want to not store state for their children.
7507 *
7508 * @param container The SparseArray which holds previously saved state.
7509 *
7510 * @see #dispatchSaveInstanceState
7511 * @see #restoreHierarchyState
7512 * @see #onRestoreInstanceState
7513 */
7514 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7515 if (mID != NO_ID) {
7516 Parcelable state = container.get(mID);
7517 if (state != null) {
7518 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7519 // + ": " + state);
7520 mPrivateFlags &= ~SAVE_STATE_CALLED;
7521 onRestoreInstanceState(state);
7522 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7523 throw new IllegalStateException(
7524 "Derived class did not call super.onRestoreInstanceState()");
7525 }
7526 }
7527 }
7528 }
7529
7530 /**
7531 * Hook allowing a view to re-apply a representation of its internal state that had previously
7532 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7533 * null state.
7534 *
7535 * @param state The frozen state that had previously been returned by
7536 * {@link #onSaveInstanceState}.
7537 *
7538 * @see #onSaveInstanceState
7539 * @see #restoreHierarchyState
7540 * @see #dispatchRestoreInstanceState
7541 */
7542 protected void onRestoreInstanceState(Parcelable state) {
7543 mPrivateFlags |= SAVE_STATE_CALLED;
7544 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007545 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7546 + "received " + state.getClass().toString() + " instead. This usually happens "
7547 + "when two views of different type have the same id in the same hierarchy. "
7548 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7549 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007550 }
7551 }
7552
7553 /**
7554 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7555 *
7556 * @return the drawing start time in milliseconds
7557 */
7558 public long getDrawingTime() {
7559 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7560 }
7561
7562 /**
7563 * <p>Enables or disables the duplication of the parent's state into this view. When
7564 * duplication is enabled, this view gets its drawable state from its parent rather
7565 * than from its own internal properties.</p>
7566 *
7567 * <p>Note: in the current implementation, setting this property to true after the
7568 * view was added to a ViewGroup might have no effect at all. This property should
7569 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7570 *
7571 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7572 * property is enabled, an exception will be thrown.</p>
7573 *
7574 * @param enabled True to enable duplication of the parent's drawable state, false
7575 * to disable it.
7576 *
7577 * @see #getDrawableState()
7578 * @see #isDuplicateParentStateEnabled()
7579 */
7580 public void setDuplicateParentStateEnabled(boolean enabled) {
7581 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7582 }
7583
7584 /**
7585 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7586 *
7587 * @return True if this view's drawable state is duplicated from the parent,
7588 * false otherwise
7589 *
7590 * @see #getDrawableState()
7591 * @see #setDuplicateParentStateEnabled(boolean)
7592 */
7593 public boolean isDuplicateParentStateEnabled() {
7594 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7595 }
7596
7597 /**
7598 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
7599 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
7600 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
7601 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
7602 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
7603 * null.</p>
7604 *
7605 * @param enabled true to enable the drawing cache, false otherwise
7606 *
7607 * @see #isDrawingCacheEnabled()
7608 * @see #getDrawingCache()
7609 * @see #buildDrawingCache()
7610 */
7611 public void setDrawingCacheEnabled(boolean enabled) {
7612 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
7613 }
7614
7615 /**
7616 * <p>Indicates whether the drawing cache is enabled for this view.</p>
7617 *
7618 * @return true if the drawing cache is enabled
7619 *
7620 * @see #setDrawingCacheEnabled(boolean)
7621 * @see #getDrawingCache()
7622 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07007623 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624 public boolean isDrawingCacheEnabled() {
7625 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
7626 }
7627
7628 /**
Romain Guyb051e892010-09-28 19:09:36 -07007629 * <p>Returns a display list that can be used to draw this view again
7630 * without executing its draw method.</p>
7631 *
7632 * @return A DisplayList ready to replay, or null if caching is not enabled.
7633 */
7634 DisplayList getDisplayList() {
7635 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7636 return null;
7637 }
Romain Guyb051e892010-09-28 19:09:36 -07007638 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
7639 return null;
7640 }
7641
7642 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
7643 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mDisplayList == null)) {
7644
Romain Guyb051e892010-09-28 19:09:36 -07007645 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
7646
7647 final HardwareCanvas canvas = mDisplayList.start();
7648 try {
7649 int width = mRight - mLeft;
7650 int height = mBottom - mTop;
7651
7652 canvas.setViewport(width, height);
7653 canvas.onPreDraw();
7654
7655 final int restoreCount = canvas.save();
7656
Romain Guy2fe9a8f2010-10-04 20:17:01 -07007657 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07007658
7659 // Fast path for layouts with no backgrounds
7660 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7661 mPrivateFlags &= ~DIRTY_MASK;
7662 dispatchDraw(canvas);
7663 } else {
7664 draw(canvas);
7665 }
7666
7667 canvas.restoreToCount(restoreCount);
7668 } finally {
7669 canvas.onPostDraw();
7670
7671 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07007672 }
7673 }
7674
7675 return mDisplayList;
7676 }
7677
7678 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007679 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
7680 *
7681 * @return A non-scaled bitmap representing this view or null if cache is disabled.
7682 *
7683 * @see #getDrawingCache(boolean)
7684 */
7685 public Bitmap getDrawingCache() {
7686 return getDrawingCache(false);
7687 }
7688
7689 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
7691 * is null when caching is disabled. If caching is enabled and the cache is not ready,
7692 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
7693 * draw from the cache when the cache is enabled. To benefit from the cache, you must
7694 * request the drawing cache by calling this method and draw it on screen if the
7695 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007696 *
7697 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7698 * this method will create a bitmap of the same size as this view. Because this bitmap
7699 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7700 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7701 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7702 * size than the view. This implies that your application must be able to handle this
7703 * size.</p>
7704 *
7705 * @param autoScale Indicates whether the generated bitmap should be scaled based on
7706 * the current density of the screen when the application is in compatibility
7707 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 *
Romain Guyfbd8f692009-06-26 14:51:58 -07007709 * @return A bitmap representing this view or null if cache is disabled.
7710 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007711 * @see #setDrawingCacheEnabled(boolean)
7712 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07007713 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 * @see #destroyDrawingCache()
7715 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007716 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007717 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7718 return null;
7719 }
7720 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007721 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 }
Romain Guy02890fd2010-08-06 17:58:44 -07007723 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007724 }
7725
7726 /**
7727 * <p>Frees the resources used by the drawing cache. If you call
7728 * {@link #buildDrawingCache()} manually without calling
7729 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7730 * should cleanup the cache with this method afterwards.</p>
7731 *
7732 * @see #setDrawingCacheEnabled(boolean)
7733 * @see #buildDrawingCache()
7734 * @see #getDrawingCache()
7735 */
7736 public void destroyDrawingCache() {
7737 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007738 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007739 mDrawingCache = null;
7740 }
Romain Guyfbd8f692009-06-26 14:51:58 -07007741 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007742 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07007743 mUnscaledDrawingCache = null;
7744 }
Romain Guyb051e892010-09-28 19:09:36 -07007745 if (mDisplayList != null) {
Romain Guyb051e892010-09-28 19:09:36 -07007746 mDisplayList = null;
7747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 }
7749
7750 /**
7751 * Setting a solid background color for the drawing cache's bitmaps will improve
7752 * perfromance and memory usage. Note, though that this should only be used if this
7753 * view will always be drawn on top of a solid color.
7754 *
7755 * @param color The background color to use for the drawing cache's bitmap
7756 *
7757 * @see #setDrawingCacheEnabled(boolean)
7758 * @see #buildDrawingCache()
7759 * @see #getDrawingCache()
7760 */
7761 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08007762 if (color != mDrawingCacheBackgroundColor) {
7763 mDrawingCacheBackgroundColor = color;
7764 mPrivateFlags &= ~DRAWING_CACHE_VALID;
7765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007766 }
7767
7768 /**
7769 * @see #setDrawingCacheBackgroundColor(int)
7770 *
7771 * @return The background color to used for the drawing cache's bitmap
7772 */
7773 public int getDrawingCacheBackgroundColor() {
7774 return mDrawingCacheBackgroundColor;
7775 }
7776
7777 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007778 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
7779 *
7780 * @see #buildDrawingCache(boolean)
7781 */
7782 public void buildDrawingCache() {
7783 buildDrawingCache(false);
7784 }
7785
7786 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
7788 *
7789 * <p>If you call {@link #buildDrawingCache()} manually without calling
7790 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7791 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007792 *
7793 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7794 * this method will create a bitmap of the same size as this view. Because this bitmap
7795 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7796 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7797 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7798 * size than the view. This implies that your application must be able to handle this
7799 * size.</p>
Romain Guy0d9275e2010-10-26 14:22:30 -07007800 *
7801 * <p>You should avoid calling this method when hardware acceleration is enabled. If
7802 * you do not need the drawing cache bitmap, calling this method will increase memory
7803 * usage and cause the view to be rendered in software once, thus negatively impacting
7804 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 *
7806 * @see #getDrawingCache()
7807 * @see #destroyDrawingCache()
7808 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007809 public void buildDrawingCache(boolean autoScale) {
7810 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07007811 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007812
7813 if (ViewDebug.TRACE_HIERARCHY) {
7814 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816
Romain Guy8506ab42009-06-11 17:35:47 -07007817 int width = mRight - mLeft;
7818 int height = mBottom - mTop;
7819
7820 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007821 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007822
Romain Guye1123222009-06-29 14:24:56 -07007823 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007824 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7825 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827
7828 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007829 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08007830 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007831
7832 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007833 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08007834 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007835 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7836 destroyDrawingCache();
7837 return;
7838 }
7839
7840 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07007841 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842
7843 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 Bitmap.Config quality;
7845 if (!opaque) {
7846 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7847 case DRAWING_CACHE_QUALITY_AUTO:
7848 quality = Bitmap.Config.ARGB_8888;
7849 break;
7850 case DRAWING_CACHE_QUALITY_LOW:
7851 quality = Bitmap.Config.ARGB_4444;
7852 break;
7853 case DRAWING_CACHE_QUALITY_HIGH:
7854 quality = Bitmap.Config.ARGB_8888;
7855 break;
7856 default:
7857 quality = Bitmap.Config.ARGB_8888;
7858 break;
7859 }
7860 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07007861 // Optimization for translucent windows
7862 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08007863 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 }
7865
7866 // Try to cleanup memory
7867 if (bitmap != null) bitmap.recycle();
7868
7869 try {
7870 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07007871 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07007872 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07007873 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007874 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07007875 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007876 }
Adam Powell26153a32010-11-08 15:22:27 -08007877 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007878 } catch (OutOfMemoryError e) {
7879 // If there is not enough memory to create the bitmap cache, just
7880 // ignore the issue as bitmap caches are not required to draw the
7881 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07007882 if (autoScale) {
7883 mDrawingCache = null;
7884 } else {
7885 mUnscaledDrawingCache = null;
7886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 return;
7888 }
7889
7890 clear = drawingCacheBackgroundColor != 0;
7891 }
7892
7893 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007894 if (attachInfo != null) {
7895 canvas = attachInfo.mCanvas;
7896 if (canvas == null) {
7897 canvas = new Canvas();
7898 }
7899 canvas.setBitmap(bitmap);
7900 // Temporarily clobber the cached Canvas in case one of our children
7901 // is also using a drawing cache. Without this, the children would
7902 // steal the canvas by attaching their own bitmap to it and bad, bad
7903 // thing would happen (invisible views, corrupted drawings, etc.)
7904 attachInfo.mCanvas = null;
7905 } else {
7906 // This case should hopefully never or seldom happen
7907 canvas = new Canvas(bitmap);
7908 }
7909
7910 if (clear) {
7911 bitmap.eraseColor(drawingCacheBackgroundColor);
7912 }
7913
7914 computeScroll();
7915 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07007916
Romain Guye1123222009-06-29 14:24:56 -07007917 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007918 final float scale = attachInfo.mApplicationScale;
7919 canvas.scale(scale, scale);
7920 }
7921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007922 canvas.translate(-mScrollX, -mScrollY);
7923
Romain Guy5bcdff42009-05-14 21:27:18 -07007924 mPrivateFlags |= DRAWN;
Romain Guy0d9275e2010-10-26 14:22:30 -07007925 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated) {
7926 mPrivateFlags |= DRAWING_CACHE_VALID;
7927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007928
7929 // Fast path for layouts with no backgrounds
7930 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7931 if (ViewDebug.TRACE_HIERARCHY) {
7932 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7933 }
Romain Guy5bcdff42009-05-14 21:27:18 -07007934 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007935 dispatchDraw(canvas);
7936 } else {
7937 draw(canvas);
7938 }
7939
7940 canvas.restoreToCount(restoreCount);
7941
7942 if (attachInfo != null) {
7943 // Restore the cached Canvas for our siblings
7944 attachInfo.mCanvas = canvas;
7945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007946 }
7947 }
7948
7949 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007950 * Create a snapshot of the view into a bitmap. We should probably make
7951 * some form of this public, but should think about the API.
7952 */
Romain Guy223ff5c2010-03-02 17:07:47 -08007953 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007954 int width = mRight - mLeft;
7955 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007956
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007957 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07007958 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007959 width = (int) ((width * scale) + 0.5f);
7960 height = (int) ((height * scale) + 0.5f);
7961
Romain Guy8c11e312009-09-14 15:15:30 -07007962 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007963 if (bitmap == null) {
7964 throw new OutOfMemoryError();
7965 }
7966
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007967 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
7968
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007969 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007970 if (attachInfo != null) {
7971 canvas = attachInfo.mCanvas;
7972 if (canvas == null) {
7973 canvas = new Canvas();
7974 }
7975 canvas.setBitmap(bitmap);
7976 // Temporarily clobber the cached Canvas in case one of our children
7977 // is also using a drawing cache. Without this, the children would
7978 // steal the canvas by attaching their own bitmap to it and bad, bad
7979 // things would happen (invisible views, corrupted drawings, etc.)
7980 attachInfo.mCanvas = null;
7981 } else {
7982 // This case should hopefully never or seldom happen
7983 canvas = new Canvas(bitmap);
7984 }
7985
Romain Guy5bcdff42009-05-14 21:27:18 -07007986 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007987 bitmap.eraseColor(backgroundColor);
7988 }
7989
7990 computeScroll();
7991 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007992 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007993 canvas.translate(-mScrollX, -mScrollY);
7994
Romain Guy5bcdff42009-05-14 21:27:18 -07007995 // Temporarily remove the dirty mask
7996 int flags = mPrivateFlags;
7997 mPrivateFlags &= ~DIRTY_MASK;
7998
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007999 // Fast path for layouts with no backgrounds
8000 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8001 dispatchDraw(canvas);
8002 } else {
8003 draw(canvas);
8004 }
8005
Romain Guy5bcdff42009-05-14 21:27:18 -07008006 mPrivateFlags = flags;
8007
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008008 canvas.restoreToCount(restoreCount);
8009
8010 if (attachInfo != null) {
8011 // Restore the cached Canvas for our siblings
8012 attachInfo.mCanvas = canvas;
8013 }
Romain Guy8506ab42009-06-11 17:35:47 -07008014
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008015 return bitmap;
8016 }
8017
8018 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008019 * Indicates whether this View is currently in edit mode. A View is usually
8020 * in edit mode when displayed within a developer tool. For instance, if
8021 * this View is being drawn by a visual user interface builder, this method
8022 * should return true.
8023 *
8024 * Subclasses should check the return value of this method to provide
8025 * different behaviors if their normal behavior might interfere with the
8026 * host environment. For instance: the class spawns a thread in its
8027 * constructor, the drawing code relies on device-specific features, etc.
8028 *
8029 * This method is usually checked in the drawing code of custom widgets.
8030 *
8031 * @return True if this View is in edit mode, false otherwise.
8032 */
8033 public boolean isInEditMode() {
8034 return false;
8035 }
8036
8037 /**
8038 * If the View draws content inside its padding and enables fading edges,
8039 * it needs to support padding offsets. Padding offsets are added to the
8040 * fading edges to extend the length of the fade so that it covers pixels
8041 * drawn inside the padding.
8042 *
8043 * Subclasses of this class should override this method if they need
8044 * to draw content inside the padding.
8045 *
8046 * @return True if padding offset must be applied, false otherwise.
8047 *
8048 * @see #getLeftPaddingOffset()
8049 * @see #getRightPaddingOffset()
8050 * @see #getTopPaddingOffset()
8051 * @see #getBottomPaddingOffset()
8052 *
8053 * @since CURRENT
8054 */
8055 protected boolean isPaddingOffsetRequired() {
8056 return false;
8057 }
8058
8059 /**
8060 * Amount by which to extend the left fading region. Called only when
8061 * {@link #isPaddingOffsetRequired()} returns true.
8062 *
8063 * @return The left padding offset in pixels.
8064 *
8065 * @see #isPaddingOffsetRequired()
8066 *
8067 * @since CURRENT
8068 */
8069 protected int getLeftPaddingOffset() {
8070 return 0;
8071 }
8072
8073 /**
8074 * Amount by which to extend the right fading region. Called only when
8075 * {@link #isPaddingOffsetRequired()} returns true.
8076 *
8077 * @return The right padding offset in pixels.
8078 *
8079 * @see #isPaddingOffsetRequired()
8080 *
8081 * @since CURRENT
8082 */
8083 protected int getRightPaddingOffset() {
8084 return 0;
8085 }
8086
8087 /**
8088 * Amount by which to extend the top fading region. Called only when
8089 * {@link #isPaddingOffsetRequired()} returns true.
8090 *
8091 * @return The top padding offset in pixels.
8092 *
8093 * @see #isPaddingOffsetRequired()
8094 *
8095 * @since CURRENT
8096 */
8097 protected int getTopPaddingOffset() {
8098 return 0;
8099 }
8100
8101 /**
8102 * Amount by which to extend the bottom fading region. Called only when
8103 * {@link #isPaddingOffsetRequired()} returns true.
8104 *
8105 * @return The bottom padding offset in pixels.
8106 *
8107 * @see #isPaddingOffsetRequired()
8108 *
8109 * @since CURRENT
8110 */
8111 protected int getBottomPaddingOffset() {
8112 return 0;
8113 }
8114
8115 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008116 * <p>Indicates whether this view is attached to an hardware accelerated
8117 * window or not.</p>
8118 *
8119 * <p>Even if this method returns true, it does not mean that every call
8120 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8121 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8122 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8123 * window is hardware accelerated,
8124 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8125 * return false, and this method will return true.</p>
8126 *
8127 * @return True if the view is attached to a window and the window is
8128 * hardware accelerated; false in any other case.
8129 */
8130 public boolean isHardwareAccelerated() {
8131 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8132 }
8133
8134 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 * Manually render this view (and all of its children) to the given Canvas.
8136 * The view must have already done a full layout before this function is
8137 * called. When implementing a view, do not override this method; instead,
8138 * you should implement {@link #onDraw}.
8139 *
8140 * @param canvas The Canvas to which the View is rendered.
8141 */
8142 public void draw(Canvas canvas) {
8143 if (ViewDebug.TRACE_HIERARCHY) {
8144 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8145 }
8146
Romain Guy5bcdff42009-05-14 21:27:18 -07008147 final int privateFlags = mPrivateFlags;
8148 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8149 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8150 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008152 /*
8153 * Draw traversal performs several drawing steps which must be executed
8154 * in the appropriate order:
8155 *
8156 * 1. Draw the background
8157 * 2. If necessary, save the canvas' layers to prepare for fading
8158 * 3. Draw view's content
8159 * 4. Draw children
8160 * 5. If necessary, draw the fading edges and restore layers
8161 * 6. Draw decorations (scrollbars for instance)
8162 */
8163
8164 // Step 1, draw the background, if needed
8165 int saveCount;
8166
Romain Guy24443ea2009-05-11 11:56:30 -07008167 if (!dirtyOpaque) {
8168 final Drawable background = mBGDrawable;
8169 if (background != null) {
8170 final int scrollX = mScrollX;
8171 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008172
Romain Guy24443ea2009-05-11 11:56:30 -07008173 if (mBackgroundSizeChanged) {
8174 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8175 mBackgroundSizeChanged = false;
8176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177
Romain Guy24443ea2009-05-11 11:56:30 -07008178 if ((scrollX | scrollY) == 0) {
8179 background.draw(canvas);
8180 } else {
8181 canvas.translate(scrollX, scrollY);
8182 background.draw(canvas);
8183 canvas.translate(-scrollX, -scrollY);
8184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 }
8186 }
8187
8188 // skip step 2 & 5 if possible (common case)
8189 final int viewFlags = mViewFlags;
8190 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8191 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8192 if (!verticalEdges && !horizontalEdges) {
8193 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008194 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008195
8196 // Step 4, draw the children
8197 dispatchDraw(canvas);
8198
8199 // Step 6, draw decorations (scrollbars)
8200 onDrawScrollBars(canvas);
8201
8202 // we're done...
8203 return;
8204 }
8205
8206 /*
8207 * Here we do the full fledged routine...
8208 * (this is an uncommon case where speed matters less,
8209 * this is why we repeat some of the tests that have been
8210 * done above)
8211 */
8212
8213 boolean drawTop = false;
8214 boolean drawBottom = false;
8215 boolean drawLeft = false;
8216 boolean drawRight = false;
8217
8218 float topFadeStrength = 0.0f;
8219 float bottomFadeStrength = 0.0f;
8220 float leftFadeStrength = 0.0f;
8221 float rightFadeStrength = 0.0f;
8222
8223 // Step 2, save the canvas' layers
8224 int paddingLeft = mPaddingLeft;
8225 int paddingTop = mPaddingTop;
8226
8227 final boolean offsetRequired = isPaddingOffsetRequired();
8228 if (offsetRequired) {
8229 paddingLeft += getLeftPaddingOffset();
8230 paddingTop += getTopPaddingOffset();
8231 }
8232
8233 int left = mScrollX + paddingLeft;
8234 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8235 int top = mScrollY + paddingTop;
8236 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8237
8238 if (offsetRequired) {
8239 right += getRightPaddingOffset();
8240 bottom += getBottomPaddingOffset();
8241 }
8242
8243 final ScrollabilityCache scrollabilityCache = mScrollCache;
8244 int length = scrollabilityCache.fadingEdgeLength;
8245
8246 // clip the fade length if top and bottom fades overlap
8247 // overlapping fades produce odd-looking artifacts
8248 if (verticalEdges && (top + length > bottom - length)) {
8249 length = (bottom - top) / 2;
8250 }
8251
8252 // also clip horizontal fades if necessary
8253 if (horizontalEdges && (left + length > right - length)) {
8254 length = (right - left) / 2;
8255 }
8256
8257 if (verticalEdges) {
8258 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008259 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008260 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008261 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008262 }
8263
8264 if (horizontalEdges) {
8265 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008266 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008268 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008269 }
8270
8271 saveCount = canvas.getSaveCount();
8272
8273 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008274 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008275 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8276
8277 if (drawTop) {
8278 canvas.saveLayer(left, top, right, top + length, null, flags);
8279 }
8280
8281 if (drawBottom) {
8282 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8283 }
8284
8285 if (drawLeft) {
8286 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8287 }
8288
8289 if (drawRight) {
8290 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8291 }
8292 } else {
8293 scrollabilityCache.setFadeColor(solidColor);
8294 }
8295
8296 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008297 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008298
8299 // Step 4, draw the children
8300 dispatchDraw(canvas);
8301
8302 // Step 5, draw the fade effect and restore layers
8303 final Paint p = scrollabilityCache.paint;
8304 final Matrix matrix = scrollabilityCache.matrix;
8305 final Shader fade = scrollabilityCache.shader;
8306 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8307
8308 if (drawTop) {
8309 matrix.setScale(1, fadeHeight * topFadeStrength);
8310 matrix.postTranslate(left, top);
8311 fade.setLocalMatrix(matrix);
8312 canvas.drawRect(left, top, right, top + length, p);
8313 }
8314
8315 if (drawBottom) {
8316 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8317 matrix.postRotate(180);
8318 matrix.postTranslate(left, bottom);
8319 fade.setLocalMatrix(matrix);
8320 canvas.drawRect(left, bottom - length, right, bottom, p);
8321 }
8322
8323 if (drawLeft) {
8324 matrix.setScale(1, fadeHeight * leftFadeStrength);
8325 matrix.postRotate(-90);
8326 matrix.postTranslate(left, top);
8327 fade.setLocalMatrix(matrix);
8328 canvas.drawRect(left, top, left + length, bottom, p);
8329 }
8330
8331 if (drawRight) {
8332 matrix.setScale(1, fadeHeight * rightFadeStrength);
8333 matrix.postRotate(90);
8334 matrix.postTranslate(right, top);
8335 fade.setLocalMatrix(matrix);
8336 canvas.drawRect(right - length, top, right, bottom, p);
8337 }
8338
8339 canvas.restoreToCount(saveCount);
8340
8341 // Step 6, draw decorations (scrollbars)
8342 onDrawScrollBars(canvas);
8343 }
8344
8345 /**
8346 * Override this if your view is known to always be drawn on top of a solid color background,
8347 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8348 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8349 * should be set to 0xFF.
8350 *
8351 * @see #setVerticalFadingEdgeEnabled
8352 * @see #setHorizontalFadingEdgeEnabled
8353 *
8354 * @return The known solid color background for this view, or 0 if the color may vary
8355 */
8356 public int getSolidColor() {
8357 return 0;
8358 }
8359
8360 /**
8361 * Build a human readable string representation of the specified view flags.
8362 *
8363 * @param flags the view flags to convert to a string
8364 * @return a String representing the supplied flags
8365 */
8366 private static String printFlags(int flags) {
8367 String output = "";
8368 int numFlags = 0;
8369 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8370 output += "TAKES_FOCUS";
8371 numFlags++;
8372 }
8373
8374 switch (flags & VISIBILITY_MASK) {
8375 case INVISIBLE:
8376 if (numFlags > 0) {
8377 output += " ";
8378 }
8379 output += "INVISIBLE";
8380 // USELESS HERE numFlags++;
8381 break;
8382 case GONE:
8383 if (numFlags > 0) {
8384 output += " ";
8385 }
8386 output += "GONE";
8387 // USELESS HERE numFlags++;
8388 break;
8389 default:
8390 break;
8391 }
8392 return output;
8393 }
8394
8395 /**
8396 * Build a human readable string representation of the specified private
8397 * view flags.
8398 *
8399 * @param privateFlags the private view flags to convert to a string
8400 * @return a String representing the supplied flags
8401 */
8402 private static String printPrivateFlags(int privateFlags) {
8403 String output = "";
8404 int numFlags = 0;
8405
8406 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8407 output += "WANTS_FOCUS";
8408 numFlags++;
8409 }
8410
8411 if ((privateFlags & FOCUSED) == FOCUSED) {
8412 if (numFlags > 0) {
8413 output += " ";
8414 }
8415 output += "FOCUSED";
8416 numFlags++;
8417 }
8418
8419 if ((privateFlags & SELECTED) == SELECTED) {
8420 if (numFlags > 0) {
8421 output += " ";
8422 }
8423 output += "SELECTED";
8424 numFlags++;
8425 }
8426
8427 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8428 if (numFlags > 0) {
8429 output += " ";
8430 }
8431 output += "IS_ROOT_NAMESPACE";
8432 numFlags++;
8433 }
8434
8435 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8436 if (numFlags > 0) {
8437 output += " ";
8438 }
8439 output += "HAS_BOUNDS";
8440 numFlags++;
8441 }
8442
8443 if ((privateFlags & DRAWN) == DRAWN) {
8444 if (numFlags > 0) {
8445 output += " ";
8446 }
8447 output += "DRAWN";
8448 // USELESS HERE numFlags++;
8449 }
8450 return output;
8451 }
8452
8453 /**
8454 * <p>Indicates whether or not this view's layout will be requested during
8455 * the next hierarchy layout pass.</p>
8456 *
8457 * @return true if the layout will be forced during next layout pass
8458 */
8459 public boolean isLayoutRequested() {
8460 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8461 }
8462
8463 /**
8464 * Assign a size and position to a view and all of its
8465 * descendants
8466 *
8467 * <p>This is the second phase of the layout mechanism.
8468 * (The first is measuring). In this phase, each parent calls
8469 * layout on all of its children to position them.
8470 * This is typically done using the child measurements
8471 * that were stored in the measure pass().
8472 *
8473 * Derived classes with children should override
8474 * onLayout. In that method, they should
Chet Haase21cd1382010-09-01 17:42:29 -07008475 * call layout on each of their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 *
8477 * @param l Left position, relative to parent
8478 * @param t Top position, relative to parent
8479 * @param r Right position, relative to parent
8480 * @param b Bottom position, relative to parent
8481 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008482 @SuppressWarnings({"unchecked"})
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008483 public final void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008484 int oldL = mLeft;
8485 int oldT = mTop;
8486 int oldB = mBottom;
8487 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008488 boolean changed = setFrame(l, t, r, b);
8489 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8490 if (ViewDebug.TRACE_HIERARCHY) {
8491 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8492 }
8493
8494 onLayout(changed, l, t, r, b);
8495 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008496
8497 if (mOnLayoutChangeListeners != null) {
8498 ArrayList<OnLayoutChangeListener> listenersCopy =
8499 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8500 int numListeners = listenersCopy.size();
8501 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07008502 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07008503 }
8504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008505 }
8506 mPrivateFlags &= ~FORCE_LAYOUT;
8507 }
8508
8509 /**
8510 * Called from layout when this view should
8511 * assign a size and position to each of its children.
8512 *
8513 * Derived classes with children should override
8514 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008515 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516 * @param changed This is a new size or position for this view
8517 * @param left Left position, relative to parent
8518 * @param top Top position, relative to parent
8519 * @param right Right position, relative to parent
8520 * @param bottom Bottom position, relative to parent
8521 */
8522 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8523 }
8524
8525 /**
8526 * Assign a size and position to this view.
8527 *
8528 * This is called from layout.
8529 *
8530 * @param left Left position, relative to parent
8531 * @param top Top position, relative to parent
8532 * @param right Right position, relative to parent
8533 * @param bottom Bottom position, relative to parent
8534 * @return true if the new size and position are different than the
8535 * previous ones
8536 * {@hide}
8537 */
8538 protected boolean setFrame(int left, int top, int right, int bottom) {
8539 boolean changed = false;
8540
8541 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008542 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008543 + right + "," + bottom + ")");
8544 }
8545
8546 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8547 changed = true;
8548
8549 // Remember our drawn bit
8550 int drawn = mPrivateFlags & DRAWN;
8551
8552 // Invalidate our old position
8553 invalidate();
8554
8555
8556 int oldWidth = mRight - mLeft;
8557 int oldHeight = mBottom - mTop;
8558
8559 mLeft = left;
8560 mTop = top;
8561 mRight = right;
8562 mBottom = bottom;
8563
8564 mPrivateFlags |= HAS_BOUNDS;
8565
8566 int newWidth = right - left;
8567 int newHeight = bottom - top;
8568
8569 if (newWidth != oldWidth || newHeight != oldHeight) {
8570 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8571 }
8572
8573 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8574 // If we are visible, force the DRAWN bit to on so that
8575 // this invalidate will go through (at least to our parent).
8576 // This is because someone may have invalidated this view
8577 // before this call to setFrame came in, therby clearing
8578 // the DRAWN bit.
8579 mPrivateFlags |= DRAWN;
8580 invalidate();
8581 }
8582
8583 // Reset drawn bit to original value (invalidate turns it off)
8584 mPrivateFlags |= drawn;
8585
8586 mBackgroundSizeChanged = true;
8587 }
8588 return changed;
8589 }
8590
8591 /**
8592 * Finalize inflating a view from XML. This is called as the last phase
8593 * of inflation, after all child views have been added.
8594 *
8595 * <p>Even if the subclass overrides onFinishInflate, they should always be
8596 * sure to call the super method, so that we get called.
8597 */
8598 protected void onFinishInflate() {
8599 }
8600
8601 /**
8602 * Returns the resources associated with this view.
8603 *
8604 * @return Resources object.
8605 */
8606 public Resources getResources() {
8607 return mResources;
8608 }
8609
8610 /**
8611 * Invalidates the specified Drawable.
8612 *
8613 * @param drawable the drawable to invalidate
8614 */
8615 public void invalidateDrawable(Drawable drawable) {
8616 if (verifyDrawable(drawable)) {
8617 final Rect dirty = drawable.getBounds();
8618 final int scrollX = mScrollX;
8619 final int scrollY = mScrollY;
8620
8621 invalidate(dirty.left + scrollX, dirty.top + scrollY,
8622 dirty.right + scrollX, dirty.bottom + scrollY);
8623 }
8624 }
8625
8626 /**
8627 * Schedules an action on a drawable to occur at a specified time.
8628 *
8629 * @param who the recipient of the action
8630 * @param what the action to run on the drawable
8631 * @param when the time at which the action must occur. Uses the
8632 * {@link SystemClock#uptimeMillis} timebase.
8633 */
8634 public void scheduleDrawable(Drawable who, Runnable what, long when) {
8635 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8636 mAttachInfo.mHandler.postAtTime(what, who, when);
8637 }
8638 }
8639
8640 /**
8641 * Cancels a scheduled action on a drawable.
8642 *
8643 * @param who the recipient of the action
8644 * @param what the action to cancel
8645 */
8646 public void unscheduleDrawable(Drawable who, Runnable what) {
8647 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8648 mAttachInfo.mHandler.removeCallbacks(what, who);
8649 }
8650 }
8651
8652 /**
8653 * Unschedule any events associated with the given Drawable. This can be
8654 * used when selecting a new Drawable into a view, so that the previous
8655 * one is completely unscheduled.
8656 *
8657 * @param who The Drawable to unschedule.
8658 *
8659 * @see #drawableStateChanged
8660 */
8661 public void unscheduleDrawable(Drawable who) {
8662 if (mAttachInfo != null) {
8663 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
8664 }
8665 }
8666
8667 /**
8668 * If your view subclass is displaying its own Drawable objects, it should
8669 * override this function and return true for any Drawable it is
8670 * displaying. This allows animations for those drawables to be
8671 * scheduled.
8672 *
8673 * <p>Be sure to call through to the super class when overriding this
8674 * function.
8675 *
8676 * @param who The Drawable to verify. Return true if it is one you are
8677 * displaying, else return the result of calling through to the
8678 * super class.
8679 *
8680 * @return boolean If true than the Drawable is being displayed in the
8681 * view; else false and it is not allowed to animate.
8682 *
8683 * @see #unscheduleDrawable
8684 * @see #drawableStateChanged
8685 */
8686 protected boolean verifyDrawable(Drawable who) {
8687 return who == mBGDrawable;
8688 }
8689
8690 /**
8691 * This function is called whenever the state of the view changes in such
8692 * a way that it impacts the state of drawables being shown.
8693 *
8694 * <p>Be sure to call through to the superclass when overriding this
8695 * function.
8696 *
8697 * @see Drawable#setState
8698 */
8699 protected void drawableStateChanged() {
8700 Drawable d = mBGDrawable;
8701 if (d != null && d.isStateful()) {
8702 d.setState(getDrawableState());
8703 }
8704 }
8705
8706 /**
8707 * Call this to force a view to update its drawable state. This will cause
8708 * drawableStateChanged to be called on this view. Views that are interested
8709 * in the new state should call getDrawableState.
8710 *
8711 * @see #drawableStateChanged
8712 * @see #getDrawableState
8713 */
8714 public void refreshDrawableState() {
8715 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
8716 drawableStateChanged();
8717
8718 ViewParent parent = mParent;
8719 if (parent != null) {
8720 parent.childDrawableStateChanged(this);
8721 }
8722 }
8723
8724 /**
8725 * Return an array of resource IDs of the drawable states representing the
8726 * current state of the view.
8727 *
8728 * @return The current drawable state
8729 *
8730 * @see Drawable#setState
8731 * @see #drawableStateChanged
8732 * @see #onCreateDrawableState
8733 */
8734 public final int[] getDrawableState() {
8735 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
8736 return mDrawableState;
8737 } else {
8738 mDrawableState = onCreateDrawableState(0);
8739 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
8740 return mDrawableState;
8741 }
8742 }
8743
8744 /**
8745 * Generate the new {@link android.graphics.drawable.Drawable} state for
8746 * this view. This is called by the view
8747 * system when the cached Drawable state is determined to be invalid. To
8748 * retrieve the current state, you should use {@link #getDrawableState}.
8749 *
8750 * @param extraSpace if non-zero, this is the number of extra entries you
8751 * would like in the returned array in which you can place your own
8752 * states.
8753 *
8754 * @return Returns an array holding the current {@link Drawable} state of
8755 * the view.
8756 *
8757 * @see #mergeDrawableStates
8758 */
8759 protected int[] onCreateDrawableState(int extraSpace) {
8760 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
8761 mParent instanceof View) {
8762 return ((View) mParent).onCreateDrawableState(extraSpace);
8763 }
8764
8765 int[] drawableState;
8766
8767 int privateFlags = mPrivateFlags;
8768
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008769 int viewStateIndex = 0;
8770 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
8771 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
8772 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07008773 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008774 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
8775 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08008776 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
8777 // This is set if HW acceleration is requested, even if the current
8778 // process doesn't allow it. This is just to allow app preview
8779 // windows to better match their app.
8780 viewStateIndex |= VIEW_STATE_ACCELERATED;
8781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782
8783 drawableState = VIEW_STATE_SETS[viewStateIndex];
8784
8785 //noinspection ConstantIfStatement
8786 if (false) {
8787 Log.i("View", "drawableStateIndex=" + viewStateIndex);
8788 Log.i("View", toString()
8789 + " pressed=" + ((privateFlags & PRESSED) != 0)
8790 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
8791 + " fo=" + hasFocus()
8792 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008793 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008794 + ": " + Arrays.toString(drawableState));
8795 }
8796
8797 if (extraSpace == 0) {
8798 return drawableState;
8799 }
8800
8801 final int[] fullState;
8802 if (drawableState != null) {
8803 fullState = new int[drawableState.length + extraSpace];
8804 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
8805 } else {
8806 fullState = new int[extraSpace];
8807 }
8808
8809 return fullState;
8810 }
8811
8812 /**
8813 * Merge your own state values in <var>additionalState</var> into the base
8814 * state values <var>baseState</var> that were returned by
8815 * {@link #onCreateDrawableState}.
8816 *
8817 * @param baseState The base state values returned by
8818 * {@link #onCreateDrawableState}, which will be modified to also hold your
8819 * own additional state values.
8820 *
8821 * @param additionalState The additional state values you would like
8822 * added to <var>baseState</var>; this array is not modified.
8823 *
8824 * @return As a convenience, the <var>baseState</var> array you originally
8825 * passed into the function is returned.
8826 *
8827 * @see #onCreateDrawableState
8828 */
8829 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
8830 final int N = baseState.length;
8831 int i = N - 1;
8832 while (i >= 0 && baseState[i] == 0) {
8833 i--;
8834 }
8835 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
8836 return baseState;
8837 }
8838
8839 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07008840 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
8841 * on all Drawable objects associated with this view.
8842 */
8843 public void jumpDrawablesToCurrentState() {
8844 if (mBGDrawable != null) {
8845 mBGDrawable.jumpToCurrentState();
8846 }
8847 }
8848
8849 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 * Sets the background color for this view.
8851 * @param color the color of the background
8852 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008853 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008854 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07008855 if (mBGDrawable instanceof ColorDrawable) {
8856 ((ColorDrawable) mBGDrawable).setColor(color);
8857 } else {
8858 setBackgroundDrawable(new ColorDrawable(color));
8859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008860 }
8861
8862 /**
8863 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07008864 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008865 * @param resid The identifier of the resource.
8866 * @attr ref android.R.styleable#View_background
8867 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008868 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008869 public void setBackgroundResource(int resid) {
8870 if (resid != 0 && resid == mBackgroundResource) {
8871 return;
8872 }
8873
8874 Drawable d= null;
8875 if (resid != 0) {
8876 d = mResources.getDrawable(resid);
8877 }
8878 setBackgroundDrawable(d);
8879
8880 mBackgroundResource = resid;
8881 }
8882
8883 /**
8884 * Set the background to a given Drawable, or remove the background. If the
8885 * background has padding, this View's padding is set to the background's
8886 * padding. However, when a background is removed, this View's padding isn't
8887 * touched. If setting the padding is desired, please use
8888 * {@link #setPadding(int, int, int, int)}.
8889 *
8890 * @param d The Drawable to use as the background, or null to remove the
8891 * background
8892 */
8893 public void setBackgroundDrawable(Drawable d) {
8894 boolean requestLayout = false;
8895
8896 mBackgroundResource = 0;
8897
8898 /*
8899 * Regardless of whether we're setting a new background or not, we want
8900 * to clear the previous drawable.
8901 */
8902 if (mBGDrawable != null) {
8903 mBGDrawable.setCallback(null);
8904 unscheduleDrawable(mBGDrawable);
8905 }
8906
8907 if (d != null) {
8908 Rect padding = sThreadLocal.get();
8909 if (padding == null) {
8910 padding = new Rect();
8911 sThreadLocal.set(padding);
8912 }
8913 if (d.getPadding(padding)) {
8914 setPadding(padding.left, padding.top, padding.right, padding.bottom);
8915 }
8916
8917 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
8918 // if it has a different minimum size, we should layout again
8919 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
8920 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
8921 requestLayout = true;
8922 }
8923
8924 d.setCallback(this);
8925 if (d.isStateful()) {
8926 d.setState(getDrawableState());
8927 }
8928 d.setVisible(getVisibility() == VISIBLE, false);
8929 mBGDrawable = d;
8930
8931 if ((mPrivateFlags & SKIP_DRAW) != 0) {
8932 mPrivateFlags &= ~SKIP_DRAW;
8933 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8934 requestLayout = true;
8935 }
8936 } else {
8937 /* Remove the background */
8938 mBGDrawable = null;
8939
8940 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
8941 /*
8942 * This view ONLY drew the background before and we're removing
8943 * the background, so now it won't draw anything
8944 * (hence we SKIP_DRAW)
8945 */
8946 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
8947 mPrivateFlags |= SKIP_DRAW;
8948 }
8949
8950 /*
8951 * When the background is set, we try to apply its padding to this
8952 * View. When the background is removed, we don't touch this View's
8953 * padding. This is noted in the Javadocs. Hence, we don't need to
8954 * requestLayout(), the invalidate() below is sufficient.
8955 */
8956
8957 // The old background's minimum size could have affected this
8958 // View's layout, so let's requestLayout
8959 requestLayout = true;
8960 }
8961
Romain Guy8f1344f52009-05-15 16:03:59 -07008962 computeOpaqueFlags();
8963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 if (requestLayout) {
8965 requestLayout();
8966 }
8967
8968 mBackgroundSizeChanged = true;
8969 invalidate();
8970 }
8971
8972 /**
8973 * Gets the background drawable
8974 * @return The drawable used as the background for this view, if any.
8975 */
8976 public Drawable getBackground() {
8977 return mBGDrawable;
8978 }
8979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008980 /**
8981 * Sets the padding. The view may add on the space required to display
8982 * the scrollbars, depending on the style and visibility of the scrollbars.
8983 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
8984 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
8985 * from the values set in this call.
8986 *
8987 * @attr ref android.R.styleable#View_padding
8988 * @attr ref android.R.styleable#View_paddingBottom
8989 * @attr ref android.R.styleable#View_paddingLeft
8990 * @attr ref android.R.styleable#View_paddingRight
8991 * @attr ref android.R.styleable#View_paddingTop
8992 * @param left the left padding in pixels
8993 * @param top the top padding in pixels
8994 * @param right the right padding in pixels
8995 * @param bottom the bottom padding in pixels
8996 */
8997 public void setPadding(int left, int top, int right, int bottom) {
8998 boolean changed = false;
8999
9000 mUserPaddingRight = right;
9001 mUserPaddingBottom = bottom;
9002
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009003 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07009004
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009005 // Common case is there are no scroll bars.
9006 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
9007 // TODO: Deal with RTL languages to adjust left padding instead of right.
9008 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
9009 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9010 ? 0 : getVerticalScrollbarWidth();
9011 }
9012 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
9013 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9014 ? 0 : getHorizontalScrollbarHeight();
9015 }
9016 }
Romain Guy8506ab42009-06-11 17:35:47 -07009017
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009018 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009019 changed = true;
9020 mPaddingLeft = left;
9021 }
9022 if (mPaddingTop != top) {
9023 changed = true;
9024 mPaddingTop = top;
9025 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009026 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009028 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009029 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009030 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009032 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009033 }
9034
9035 if (changed) {
9036 requestLayout();
9037 }
9038 }
9039
9040 /**
9041 * Returns the top padding of this view.
9042 *
9043 * @return the top padding in pixels
9044 */
9045 public int getPaddingTop() {
9046 return mPaddingTop;
9047 }
9048
9049 /**
9050 * Returns the bottom padding of this view. If there are inset and enabled
9051 * scrollbars, this value may include the space required to display the
9052 * scrollbars as well.
9053 *
9054 * @return the bottom padding in pixels
9055 */
9056 public int getPaddingBottom() {
9057 return mPaddingBottom;
9058 }
9059
9060 /**
9061 * Returns the left padding of this view. If there are inset and enabled
9062 * scrollbars, this value may include the space required to display the
9063 * scrollbars as well.
9064 *
9065 * @return the left padding in pixels
9066 */
9067 public int getPaddingLeft() {
9068 return mPaddingLeft;
9069 }
9070
9071 /**
9072 * Returns the right padding of this view. If there are inset and enabled
9073 * scrollbars, this value may include the space required to display the
9074 * scrollbars as well.
9075 *
9076 * @return the right padding in pixels
9077 */
9078 public int getPaddingRight() {
9079 return mPaddingRight;
9080 }
9081
9082 /**
9083 * Changes the selection state of this view. A view can be selected or not.
9084 * Note that selection is not the same as focus. Views are typically
9085 * selected in the context of an AdapterView like ListView or GridView;
9086 * the selected view is the view that is highlighted.
9087 *
9088 * @param selected true if the view must be selected, false otherwise
9089 */
9090 public void setSelected(boolean selected) {
9091 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9092 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009093 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009094 invalidate();
9095 refreshDrawableState();
9096 dispatchSetSelected(selected);
9097 }
9098 }
9099
9100 /**
9101 * Dispatch setSelected to all of this View's children.
9102 *
9103 * @see #setSelected(boolean)
9104 *
9105 * @param selected The new selected state
9106 */
9107 protected void dispatchSetSelected(boolean selected) {
9108 }
9109
9110 /**
9111 * Indicates the selection state of this view.
9112 *
9113 * @return true if the view is selected, false otherwise
9114 */
9115 @ViewDebug.ExportedProperty
9116 public boolean isSelected() {
9117 return (mPrivateFlags & SELECTED) != 0;
9118 }
9119
9120 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009121 * Changes the activated state of this view. A view can be activated or not.
9122 * Note that activation is not the same as selection. Selection is
9123 * a transient property, representing the view (hierarchy) the user is
9124 * currently interacting with. Activation is a longer-term state that the
9125 * user can move views in and out of. For example, in a list view with
9126 * single or multiple selection enabled, the views in the current selection
9127 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9128 * here.) The activated state is propagated down to children of the view it
9129 * is set on.
9130 *
9131 * @param activated true if the view must be activated, false otherwise
9132 */
9133 public void setActivated(boolean activated) {
9134 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9135 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
9136 invalidate();
9137 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009138 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009139 }
9140 }
9141
9142 /**
9143 * Dispatch setActivated to all of this View's children.
9144 *
9145 * @see #setActivated(boolean)
9146 *
9147 * @param activated The new activated state
9148 */
9149 protected void dispatchSetActivated(boolean activated) {
9150 }
9151
9152 /**
9153 * Indicates the activation state of this view.
9154 *
9155 * @return true if the view is activated, false otherwise
9156 */
9157 @ViewDebug.ExportedProperty
9158 public boolean isActivated() {
9159 return (mPrivateFlags & ACTIVATED) != 0;
9160 }
9161
9162 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009163 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9164 * observer can be used to get notifications when global events, like
9165 * layout, happen.
9166 *
9167 * The returned ViewTreeObserver observer is not guaranteed to remain
9168 * valid for the lifetime of this View. If the caller of this method keeps
9169 * a long-lived reference to ViewTreeObserver, it should always check for
9170 * the return value of {@link ViewTreeObserver#isAlive()}.
9171 *
9172 * @return The ViewTreeObserver for this view's hierarchy.
9173 */
9174 public ViewTreeObserver getViewTreeObserver() {
9175 if (mAttachInfo != null) {
9176 return mAttachInfo.mTreeObserver;
9177 }
9178 if (mFloatingTreeObserver == null) {
9179 mFloatingTreeObserver = new ViewTreeObserver();
9180 }
9181 return mFloatingTreeObserver;
9182 }
9183
9184 /**
9185 * <p>Finds the topmost view in the current view hierarchy.</p>
9186 *
9187 * @return the topmost view containing this view
9188 */
9189 public View getRootView() {
9190 if (mAttachInfo != null) {
9191 final View v = mAttachInfo.mRootView;
9192 if (v != null) {
9193 return v;
9194 }
9195 }
Romain Guy8506ab42009-06-11 17:35:47 -07009196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009197 View parent = this;
9198
9199 while (parent.mParent != null && parent.mParent instanceof View) {
9200 parent = (View) parent.mParent;
9201 }
9202
9203 return parent;
9204 }
9205
9206 /**
9207 * <p>Computes the coordinates of this view on the screen. The argument
9208 * must be an array of two integers. After the method returns, the array
9209 * contains the x and y location in that order.</p>
9210 *
9211 * @param location an array of two integers in which to hold the coordinates
9212 */
9213 public void getLocationOnScreen(int[] location) {
9214 getLocationInWindow(location);
9215
9216 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009217 if (info != null) {
9218 location[0] += info.mWindowLeft;
9219 location[1] += info.mWindowTop;
9220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009221 }
9222
9223 /**
9224 * <p>Computes the coordinates of this view in its window. The argument
9225 * must be an array of two integers. After the method returns, the array
9226 * contains the x and y location in that order.</p>
9227 *
9228 * @param location an array of two integers in which to hold the coordinates
9229 */
9230 public void getLocationInWindow(int[] location) {
9231 if (location == null || location.length < 2) {
9232 throw new IllegalArgumentException("location must be an array of "
9233 + "two integers");
9234 }
9235
9236 location[0] = mLeft;
9237 location[1] = mTop;
9238
9239 ViewParent viewParent = mParent;
9240 while (viewParent instanceof View) {
9241 final View view = (View)viewParent;
9242 location[0] += view.mLeft - view.mScrollX;
9243 location[1] += view.mTop - view.mScrollY;
9244 viewParent = view.mParent;
9245 }
Romain Guy8506ab42009-06-11 17:35:47 -07009246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009247 if (viewParent instanceof ViewRoot) {
9248 // *cough*
9249 final ViewRoot vr = (ViewRoot)viewParent;
9250 location[1] -= vr.mCurScrollY;
9251 }
9252 }
9253
9254 /**
9255 * {@hide}
9256 * @param id the id of the view to be found
9257 * @return the view of the specified id, null if cannot be found
9258 */
9259 protected View findViewTraversal(int id) {
9260 if (id == mID) {
9261 return this;
9262 }
9263 return null;
9264 }
9265
9266 /**
9267 * {@hide}
9268 * @param tag the tag of the view to be found
9269 * @return the view of specified tag, null if cannot be found
9270 */
9271 protected View findViewWithTagTraversal(Object tag) {
9272 if (tag != null && tag.equals(mTag)) {
9273 return this;
9274 }
9275 return null;
9276 }
9277
9278 /**
9279 * Look for a child view with the given id. If this view has the given
9280 * id, return this view.
9281 *
9282 * @param id The id to search for.
9283 * @return The view that has the given id in the hierarchy or null
9284 */
9285 public final View findViewById(int id) {
9286 if (id < 0) {
9287 return null;
9288 }
9289 return findViewTraversal(id);
9290 }
9291
9292 /**
9293 * Look for a child view with the given tag. If this view has the given
9294 * tag, return this view.
9295 *
9296 * @param tag The tag to search for, using "tag.equals(getTag())".
9297 * @return The View that has the given tag in the hierarchy or null
9298 */
9299 public final View findViewWithTag(Object tag) {
9300 if (tag == null) {
9301 return null;
9302 }
9303 return findViewWithTagTraversal(tag);
9304 }
9305
9306 /**
9307 * Sets the identifier for this view. The identifier does not have to be
9308 * unique in this view's hierarchy. The identifier should be a positive
9309 * number.
9310 *
9311 * @see #NO_ID
9312 * @see #getId
9313 * @see #findViewById
9314 *
9315 * @param id a number used to identify the view
9316 *
9317 * @attr ref android.R.styleable#View_id
9318 */
9319 public void setId(int id) {
9320 mID = id;
9321 }
9322
9323 /**
9324 * {@hide}
9325 *
9326 * @param isRoot true if the view belongs to the root namespace, false
9327 * otherwise
9328 */
9329 public void setIsRootNamespace(boolean isRoot) {
9330 if (isRoot) {
9331 mPrivateFlags |= IS_ROOT_NAMESPACE;
9332 } else {
9333 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9334 }
9335 }
9336
9337 /**
9338 * {@hide}
9339 *
9340 * @return true if the view belongs to the root namespace, false otherwise
9341 */
9342 public boolean isRootNamespace() {
9343 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9344 }
9345
9346 /**
9347 * Returns this view's identifier.
9348 *
9349 * @return a positive integer used to identify the view or {@link #NO_ID}
9350 * if the view has no ID
9351 *
9352 * @see #setId
9353 * @see #findViewById
9354 * @attr ref android.R.styleable#View_id
9355 */
9356 @ViewDebug.CapturedViewProperty
9357 public int getId() {
9358 return mID;
9359 }
9360
9361 /**
9362 * Returns this view's tag.
9363 *
9364 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07009365 *
9366 * @see #setTag(Object)
9367 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009368 */
9369 @ViewDebug.ExportedProperty
9370 public Object getTag() {
9371 return mTag;
9372 }
9373
9374 /**
9375 * Sets the tag associated with this view. A tag can be used to mark
9376 * a view in its hierarchy and does not have to be unique within the
9377 * hierarchy. Tags can also be used to store data within a view without
9378 * resorting to another data structure.
9379 *
9380 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07009381 *
9382 * @see #getTag()
9383 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009384 */
9385 public void setTag(final Object tag) {
9386 mTag = tag;
9387 }
9388
9389 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009390 * Returns the tag associated with this view and the specified key.
9391 *
9392 * @param key The key identifying the tag
9393 *
9394 * @return the Object stored in this view as a tag
9395 *
9396 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009397 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009398 */
9399 public Object getTag(int key) {
9400 SparseArray<Object> tags = null;
9401 synchronized (sTagsLock) {
9402 if (sTags != null) {
9403 tags = sTags.get(this);
9404 }
9405 }
9406
9407 if (tags != null) return tags.get(key);
9408 return null;
9409 }
9410
9411 /**
9412 * Sets a tag associated with this view and a key. A tag can be used
9413 * to mark a view in its hierarchy and does not have to be unique within
9414 * the hierarchy. Tags can also be used to store data within a view
9415 * without resorting to another data structure.
9416 *
9417 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009418 * application to ensure it is unique (see the <a
9419 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9420 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009421 * the Android framework or not associated with any package will cause
9422 * an {@link IllegalArgumentException} to be thrown.
9423 *
9424 * @param key The key identifying the tag
9425 * @param tag An Object to tag the view with
9426 *
9427 * @throws IllegalArgumentException If they specified key is not valid
9428 *
9429 * @see #setTag(Object)
9430 * @see #getTag(int)
9431 */
9432 public void setTag(int key, final Object tag) {
9433 // If the package id is 0x00 or 0x01, it's either an undefined package
9434 // or a framework id
9435 if ((key >>> 24) < 2) {
9436 throw new IllegalArgumentException("The key must be an application-specific "
9437 + "resource id.");
9438 }
9439
9440 setTagInternal(this, key, tag);
9441 }
9442
9443 /**
9444 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9445 * framework id.
9446 *
9447 * @hide
9448 */
9449 public void setTagInternal(int key, Object tag) {
9450 if ((key >>> 24) != 0x1) {
9451 throw new IllegalArgumentException("The key must be a framework-specific "
9452 + "resource id.");
9453 }
9454
Romain Guy8506ab42009-06-11 17:35:47 -07009455 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009456 }
9457
9458 private static void setTagInternal(View view, int key, Object tag) {
9459 SparseArray<Object> tags = null;
9460 synchronized (sTagsLock) {
9461 if (sTags == null) {
9462 sTags = new WeakHashMap<View, SparseArray<Object>>();
9463 } else {
9464 tags = sTags.get(view);
9465 }
9466 }
9467
9468 if (tags == null) {
9469 tags = new SparseArray<Object>(2);
9470 synchronized (sTagsLock) {
9471 sTags.put(view, tags);
9472 }
9473 }
9474
9475 tags.put(key, tag);
9476 }
9477
9478 /**
Romain Guy13922e02009-05-12 17:56:14 -07009479 * @param consistency The type of consistency. See ViewDebug for more information.
9480 *
9481 * @hide
9482 */
9483 protected boolean dispatchConsistencyCheck(int consistency) {
9484 return onConsistencyCheck(consistency);
9485 }
9486
9487 /**
9488 * Method that subclasses should implement to check their consistency. The type of
9489 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009490 *
Romain Guy13922e02009-05-12 17:56:14 -07009491 * @param consistency The type of consistency. See ViewDebug for more information.
9492 *
9493 * @throws IllegalStateException if the view is in an inconsistent state.
9494 *
9495 * @hide
9496 */
9497 protected boolean onConsistencyCheck(int consistency) {
9498 boolean result = true;
9499
9500 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9501 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9502
9503 if (checkLayout) {
9504 if (getParent() == null) {
9505 result = false;
9506 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9507 "View " + this + " does not have a parent.");
9508 }
9509
9510 if (mAttachInfo == null) {
9511 result = false;
9512 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9513 "View " + this + " is not attached to a window.");
9514 }
9515 }
9516
9517 if (checkDrawing) {
9518 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9519 // from their draw() method
9520
9521 if ((mPrivateFlags & DRAWN) != DRAWN &&
9522 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9523 result = false;
9524 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9525 "View " + this + " was invalidated but its drawing cache is valid.");
9526 }
9527 }
9528
9529 return result;
9530 }
9531
9532 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009533 * Prints information about this view in the log output, with the tag
9534 * {@link #VIEW_LOG_TAG}.
9535 *
9536 * @hide
9537 */
9538 public void debug() {
9539 debug(0);
9540 }
9541
9542 /**
9543 * Prints information about this view in the log output, with the tag
9544 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
9545 * indentation defined by the <code>depth</code>.
9546 *
9547 * @param depth the indentation level
9548 *
9549 * @hide
9550 */
9551 protected void debug(int depth) {
9552 String output = debugIndent(depth - 1);
9553
9554 output += "+ " + this;
9555 int id = getId();
9556 if (id != -1) {
9557 output += " (id=" + id + ")";
9558 }
9559 Object tag = getTag();
9560 if (tag != null) {
9561 output += " (tag=" + tag + ")";
9562 }
9563 Log.d(VIEW_LOG_TAG, output);
9564
9565 if ((mPrivateFlags & FOCUSED) != 0) {
9566 output = debugIndent(depth) + " FOCUSED";
9567 Log.d(VIEW_LOG_TAG, output);
9568 }
9569
9570 output = debugIndent(depth);
9571 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
9572 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
9573 + "} ";
9574 Log.d(VIEW_LOG_TAG, output);
9575
9576 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
9577 || mPaddingBottom != 0) {
9578 output = debugIndent(depth);
9579 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
9580 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
9581 Log.d(VIEW_LOG_TAG, output);
9582 }
9583
9584 output = debugIndent(depth);
9585 output += "mMeasureWidth=" + mMeasuredWidth +
9586 " mMeasureHeight=" + mMeasuredHeight;
9587 Log.d(VIEW_LOG_TAG, output);
9588
9589 output = debugIndent(depth);
9590 if (mLayoutParams == null) {
9591 output += "BAD! no layout params";
9592 } else {
9593 output = mLayoutParams.debug(output);
9594 }
9595 Log.d(VIEW_LOG_TAG, output);
9596
9597 output = debugIndent(depth);
9598 output += "flags={";
9599 output += View.printFlags(mViewFlags);
9600 output += "}";
9601 Log.d(VIEW_LOG_TAG, output);
9602
9603 output = debugIndent(depth);
9604 output += "privateFlags={";
9605 output += View.printPrivateFlags(mPrivateFlags);
9606 output += "}";
9607 Log.d(VIEW_LOG_TAG, output);
9608 }
9609
9610 /**
9611 * Creates an string of whitespaces used for indentation.
9612 *
9613 * @param depth the indentation level
9614 * @return a String containing (depth * 2 + 3) * 2 white spaces
9615 *
9616 * @hide
9617 */
9618 protected static String debugIndent(int depth) {
9619 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
9620 for (int i = 0; i < (depth * 2) + 3; i++) {
9621 spaces.append(' ').append(' ');
9622 }
9623 return spaces.toString();
9624 }
9625
9626 /**
9627 * <p>Return the offset of the widget's text baseline from the widget's top
9628 * boundary. If this widget does not support baseline alignment, this
9629 * method returns -1. </p>
9630 *
9631 * @return the offset of the baseline within the widget's bounds or -1
9632 * if baseline alignment is not supported
9633 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07009634 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009635 public int getBaseline() {
9636 return -1;
9637 }
9638
9639 /**
9640 * Call this when something has changed which has invalidated the
9641 * layout of this view. This will schedule a layout pass of the view
9642 * tree.
9643 */
9644 public void requestLayout() {
9645 if (ViewDebug.TRACE_HIERARCHY) {
9646 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
9647 }
9648
9649 mPrivateFlags |= FORCE_LAYOUT;
9650
9651 if (mParent != null && !mParent.isLayoutRequested()) {
9652 mParent.requestLayout();
9653 }
9654 }
9655
9656 /**
9657 * Forces this view to be laid out during the next layout pass.
9658 * This method does not call requestLayout() or forceLayout()
9659 * on the parent.
9660 */
9661 public void forceLayout() {
9662 mPrivateFlags |= FORCE_LAYOUT;
9663 }
9664
9665 /**
9666 * <p>
9667 * This is called to find out how big a view should be. The parent
9668 * supplies constraint information in the width and height parameters.
9669 * </p>
9670 *
9671 * <p>
9672 * The actual mesurement work of a view is performed in
9673 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
9674 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
9675 * </p>
9676 *
9677 *
9678 * @param widthMeasureSpec Horizontal space requirements as imposed by the
9679 * parent
9680 * @param heightMeasureSpec Vertical space requirements as imposed by the
9681 * parent
9682 *
9683 * @see #onMeasure(int, int)
9684 */
9685 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
9686 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
9687 widthMeasureSpec != mOldWidthMeasureSpec ||
9688 heightMeasureSpec != mOldHeightMeasureSpec) {
9689
9690 // first clears the measured dimension flag
9691 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9692
9693 if (ViewDebug.TRACE_HIERARCHY) {
9694 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
9695 }
9696
9697 // measure ourselves, this should set the measured dimension flag back
9698 onMeasure(widthMeasureSpec, heightMeasureSpec);
9699
9700 // flag not set, setMeasuredDimension() was not invoked, we raise
9701 // an exception to warn the developer
9702 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9703 throw new IllegalStateException("onMeasure() did not set the"
9704 + " measured dimension by calling"
9705 + " setMeasuredDimension()");
9706 }
9707
9708 mPrivateFlags |= LAYOUT_REQUIRED;
9709 }
9710
9711 mOldWidthMeasureSpec = widthMeasureSpec;
9712 mOldHeightMeasureSpec = heightMeasureSpec;
9713 }
9714
9715 /**
9716 * <p>
9717 * Measure the view and its content to determine the measured width and the
9718 * measured height. This method is invoked by {@link #measure(int, int)} and
9719 * should be overriden by subclasses to provide accurate and efficient
9720 * measurement of their contents.
9721 * </p>
9722 *
9723 * <p>
9724 * <strong>CONTRACT:</strong> When overriding this method, you
9725 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
9726 * measured width and height of this view. Failure to do so will trigger an
9727 * <code>IllegalStateException</code>, thrown by
9728 * {@link #measure(int, int)}. Calling the superclass'
9729 * {@link #onMeasure(int, int)} is a valid use.
9730 * </p>
9731 *
9732 * <p>
9733 * The base class implementation of measure defaults to the background size,
9734 * unless a larger size is allowed by the MeasureSpec. Subclasses should
9735 * override {@link #onMeasure(int, int)} to provide better measurements of
9736 * their content.
9737 * </p>
9738 *
9739 * <p>
9740 * If this method is overridden, it is the subclass's responsibility to make
9741 * sure the measured height and width are at least the view's minimum height
9742 * and width ({@link #getSuggestedMinimumHeight()} and
9743 * {@link #getSuggestedMinimumWidth()}).
9744 * </p>
9745 *
9746 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
9747 * The requirements are encoded with
9748 * {@link android.view.View.MeasureSpec}.
9749 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
9750 * The requirements are encoded with
9751 * {@link android.view.View.MeasureSpec}.
9752 *
9753 * @see #getMeasuredWidth()
9754 * @see #getMeasuredHeight()
9755 * @see #setMeasuredDimension(int, int)
9756 * @see #getSuggestedMinimumHeight()
9757 * @see #getSuggestedMinimumWidth()
9758 * @see android.view.View.MeasureSpec#getMode(int)
9759 * @see android.view.View.MeasureSpec#getSize(int)
9760 */
9761 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9762 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
9763 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
9764 }
9765
9766 /**
9767 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
9768 * measured width and measured height. Failing to do so will trigger an
9769 * exception at measurement time.</p>
9770 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08009771 * @param measuredWidth The measured width of this view. May be a complex
9772 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
9773 * {@link #MEASURED_STATE_TOO_SMALL}.
9774 * @param measuredHeight The measured height of this view. May be a complex
9775 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
9776 * {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009777 */
9778 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
9779 mMeasuredWidth = measuredWidth;
9780 mMeasuredHeight = measuredHeight;
9781
9782 mPrivateFlags |= MEASURED_DIMENSION_SET;
9783 }
9784
9785 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08009786 * Merge two states as returned by {@link #getMeasuredState()}.
9787 * @param curState The current state as returned from a view or the result
9788 * of combining multiple views.
9789 * @param newState The new view state to combine.
9790 * @return Returns a new integer reflecting the combination of the two
9791 * states.
9792 */
9793 public static int combineMeasuredStates(int curState, int newState) {
9794 return curState | newState;
9795 }
9796
9797 /**
9798 * Version of {@link #resolveSizeAndState(int, int, int)}
9799 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
9800 */
9801 public static int resolveSize(int size, int measureSpec) {
9802 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
9803 }
9804
9805 /**
9806 * Utility to reconcile a desired size and state, with constraints imposed
9807 * by a MeasureSpec. Will take the desired size, unless a different size
9808 * is imposed by the constraints. The returned value is a compound integer,
9809 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
9810 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
9811 * size is smaller than the size the view wants to be.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009812 *
9813 * @param size How big the view wants to be
9814 * @param measureSpec Constraints imposed by the parent
Dianne Hackborn189ee182010-12-02 21:48:53 -08009815 * @return Size information bit mask as defined by
9816 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009817 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08009818 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009819 int result = size;
9820 int specMode = MeasureSpec.getMode(measureSpec);
9821 int specSize = MeasureSpec.getSize(measureSpec);
9822 switch (specMode) {
9823 case MeasureSpec.UNSPECIFIED:
9824 result = size;
9825 break;
9826 case MeasureSpec.AT_MOST:
Dianne Hackborn189ee182010-12-02 21:48:53 -08009827 if (specSize < size) {
9828 result = specSize | MEASURED_STATE_TOO_SMALL;
9829 } else {
9830 result = size;
9831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 break;
9833 case MeasureSpec.EXACTLY:
9834 result = specSize;
9835 break;
9836 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08009837 return result | (childMeasuredState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009838 }
9839
9840 /**
9841 * Utility to return a default size. Uses the supplied size if the
9842 * MeasureSpec imposed no contraints. Will get larger if allowed
9843 * by the MeasureSpec.
9844 *
9845 * @param size Default size for this view
9846 * @param measureSpec Constraints imposed by the parent
9847 * @return The size this view should be.
9848 */
9849 public static int getDefaultSize(int size, int measureSpec) {
9850 int result = size;
9851 int specMode = MeasureSpec.getMode(measureSpec);
9852 int specSize = MeasureSpec.getSize(measureSpec);
9853
9854 switch (specMode) {
9855 case MeasureSpec.UNSPECIFIED:
9856 result = size;
9857 break;
9858 case MeasureSpec.AT_MOST:
9859 case MeasureSpec.EXACTLY:
9860 result = specSize;
9861 break;
9862 }
9863 return result;
9864 }
9865
9866 /**
9867 * Returns the suggested minimum height that the view should use. This
9868 * returns the maximum of the view's minimum height
9869 * and the background's minimum height
9870 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
9871 * <p>
9872 * When being used in {@link #onMeasure(int, int)}, the caller should still
9873 * ensure the returned height is within the requirements of the parent.
9874 *
9875 * @return The suggested minimum height of the view.
9876 */
9877 protected int getSuggestedMinimumHeight() {
9878 int suggestedMinHeight = mMinHeight;
9879
9880 if (mBGDrawable != null) {
9881 final int bgMinHeight = mBGDrawable.getMinimumHeight();
9882 if (suggestedMinHeight < bgMinHeight) {
9883 suggestedMinHeight = bgMinHeight;
9884 }
9885 }
9886
9887 return suggestedMinHeight;
9888 }
9889
9890 /**
9891 * Returns the suggested minimum width that the view should use. This
9892 * returns the maximum of the view's minimum width)
9893 * and the background's minimum width
9894 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
9895 * <p>
9896 * When being used in {@link #onMeasure(int, int)}, the caller should still
9897 * ensure the returned width is within the requirements of the parent.
9898 *
9899 * @return The suggested minimum width of the view.
9900 */
9901 protected int getSuggestedMinimumWidth() {
9902 int suggestedMinWidth = mMinWidth;
9903
9904 if (mBGDrawable != null) {
9905 final int bgMinWidth = mBGDrawable.getMinimumWidth();
9906 if (suggestedMinWidth < bgMinWidth) {
9907 suggestedMinWidth = bgMinWidth;
9908 }
9909 }
9910
9911 return suggestedMinWidth;
9912 }
9913
9914 /**
9915 * Sets the minimum height of the view. It is not guaranteed the view will
9916 * be able to achieve this minimum height (for example, if its parent layout
9917 * constrains it with less available height).
9918 *
9919 * @param minHeight The minimum height the view will try to be.
9920 */
9921 public void setMinimumHeight(int minHeight) {
9922 mMinHeight = minHeight;
9923 }
9924
9925 /**
9926 * Sets the minimum width of the view. It is not guaranteed the view will
9927 * be able to achieve this minimum width (for example, if its parent layout
9928 * constrains it with less available width).
9929 *
9930 * @param minWidth The minimum width the view will try to be.
9931 */
9932 public void setMinimumWidth(int minWidth) {
9933 mMinWidth = minWidth;
9934 }
9935
9936 /**
9937 * Get the animation currently associated with this view.
9938 *
9939 * @return The animation that is currently playing or
9940 * scheduled to play for this view.
9941 */
9942 public Animation getAnimation() {
9943 return mCurrentAnimation;
9944 }
9945
9946 /**
9947 * Start the specified animation now.
9948 *
9949 * @param animation the animation to start now
9950 */
9951 public void startAnimation(Animation animation) {
9952 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
9953 setAnimation(animation);
9954 invalidate();
9955 }
9956
9957 /**
9958 * Cancels any animations for this view.
9959 */
9960 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08009961 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08009962 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08009963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009964 mCurrentAnimation = null;
9965 }
9966
9967 /**
9968 * Sets the next animation to play for this view.
9969 * If you want the animation to play immediately, use
9970 * startAnimation. This method provides allows fine-grained
9971 * control over the start time and invalidation, but you
9972 * must make sure that 1) the animation has a start time set, and
9973 * 2) the view will be invalidated when the animation is supposed to
9974 * start.
9975 *
9976 * @param animation The next animation, or null.
9977 */
9978 public void setAnimation(Animation animation) {
9979 mCurrentAnimation = animation;
9980 if (animation != null) {
9981 animation.reset();
9982 }
9983 }
9984
9985 /**
9986 * Invoked by a parent ViewGroup to notify the start of the animation
9987 * currently associated with this view. If you override this method,
9988 * always call super.onAnimationStart();
9989 *
9990 * @see #setAnimation(android.view.animation.Animation)
9991 * @see #getAnimation()
9992 */
9993 protected void onAnimationStart() {
9994 mPrivateFlags |= ANIMATION_STARTED;
9995 }
9996
9997 /**
9998 * Invoked by a parent ViewGroup to notify the end of the animation
9999 * currently associated with this view. If you override this method,
10000 * always call super.onAnimationEnd();
10001 *
10002 * @see #setAnimation(android.view.animation.Animation)
10003 * @see #getAnimation()
10004 */
10005 protected void onAnimationEnd() {
10006 mPrivateFlags &= ~ANIMATION_STARTED;
10007 }
10008
10009 /**
10010 * Invoked if there is a Transform that involves alpha. Subclass that can
10011 * draw themselves with the specified alpha should return true, and then
10012 * respect that alpha when their onDraw() is called. If this returns false
10013 * then the view may be redirected to draw into an offscreen buffer to
10014 * fulfill the request, which will look fine, but may be slower than if the
10015 * subclass handles it internally. The default implementation returns false.
10016 *
10017 * @param alpha The alpha (0..255) to apply to the view's drawing
10018 * @return true if the view can draw with the specified alpha.
10019 */
10020 protected boolean onSetAlpha(int alpha) {
10021 return false;
10022 }
10023
10024 /**
10025 * This is used by the RootView to perform an optimization when
10026 * the view hierarchy contains one or several SurfaceView.
10027 * SurfaceView is always considered transparent, but its children are not,
10028 * therefore all View objects remove themselves from the global transparent
10029 * region (passed as a parameter to this function).
10030 *
10031 * @param region The transparent region for this ViewRoot (window).
10032 *
10033 * @return Returns true if the effective visibility of the view at this
10034 * point is opaque, regardless of the transparent region; returns false
10035 * if it is possible for underlying windows to be seen behind the view.
10036 *
10037 * {@hide}
10038 */
10039 public boolean gatherTransparentRegion(Region region) {
10040 final AttachInfo attachInfo = mAttachInfo;
10041 if (region != null && attachInfo != null) {
10042 final int pflags = mPrivateFlags;
10043 if ((pflags & SKIP_DRAW) == 0) {
10044 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10045 // remove it from the transparent region.
10046 final int[] location = attachInfo.mTransparentLocation;
10047 getLocationInWindow(location);
10048 region.op(location[0], location[1], location[0] + mRight - mLeft,
10049 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10050 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10051 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10052 // exists, so we remove the background drawable's non-transparent
10053 // parts from this transparent region.
10054 applyDrawableToTransparentRegion(mBGDrawable, region);
10055 }
10056 }
10057 return true;
10058 }
10059
10060 /**
10061 * Play a sound effect for this view.
10062 *
10063 * <p>The framework will play sound effects for some built in actions, such as
10064 * clicking, but you may wish to play these effects in your widget,
10065 * for instance, for internal navigation.
10066 *
10067 * <p>The sound effect will only be played if sound effects are enabled by the user, and
10068 * {@link #isSoundEffectsEnabled()} is true.
10069 *
10070 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10071 */
10072 public void playSoundEffect(int soundConstant) {
10073 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10074 return;
10075 }
10076 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10077 }
10078
10079 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010080 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010081 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010082 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010083 *
10084 * <p>The framework will provide haptic feedback for some built in actions,
10085 * such as long presses, but you may wish to provide feedback for your
10086 * own widget.
10087 *
10088 * <p>The feedback will only be performed if
10089 * {@link #isHapticFeedbackEnabled()} is true.
10090 *
10091 * @param feedbackConstant One of the constants defined in
10092 * {@link HapticFeedbackConstants}
10093 */
10094 public boolean performHapticFeedback(int feedbackConstant) {
10095 return performHapticFeedback(feedbackConstant, 0);
10096 }
10097
10098 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010099 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010100 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010101 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010102 *
10103 * @param feedbackConstant One of the constants defined in
10104 * {@link HapticFeedbackConstants}
10105 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10106 */
10107 public boolean performHapticFeedback(int feedbackConstant, int flags) {
10108 if (mAttachInfo == null) {
10109 return false;
10110 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010111 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010112 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010113 && !isHapticFeedbackEnabled()) {
10114 return false;
10115 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010116 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10117 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010118 }
10119
10120 /**
Christopher Tate2c095f32010-10-04 14:13:40 -070010121 * !!! TODO: real docs
10122 *
10123 * The base class implementation makes the thumbnail the same size and appearance
10124 * as the view itself, and positions it with its center at the touch point.
10125 */
Christopher Tatea0374192010-10-05 13:06:41 -070010126 public static class DragThumbnailBuilder {
10127 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010128
10129 /**
10130 * Construct a thumbnail builder object for use with the given view.
10131 * @param view
10132 */
10133 public DragThumbnailBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010134 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010135 }
10136
Chris Tate6b391282010-10-14 15:48:59 -070010137 final public View getView() {
10138 return mView.get();
10139 }
10140
Christopher Tate2c095f32010-10-04 14:13:40 -070010141 /**
10142 * Provide the draggable-thumbnail metrics for the operation: the dimensions of
10143 * the thumbnail image itself, and the point within that thumbnail that should
10144 * be centered under the touch location while dragging.
10145 * <p>
10146 * The default implementation sets the dimensions of the thumbnail to be the
10147 * same as the dimensions of the View itself and centers the thumbnail under
10148 * the touch point.
10149 *
10150 * @param thumbnailSize The application should set the {@code x} member of this
10151 * parameter to the desired thumbnail width, and the {@code y} member to
10152 * the desired height.
10153 * @param thumbnailTouchPoint The application should set this point to be the
10154 * location within the thumbnail that should track directly underneath
10155 * the touch point on the screen during a drag.
10156 */
10157 public void onProvideThumbnailMetrics(Point thumbnailSize, Point thumbnailTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070010158 final View view = mView.get();
10159 if (view != null) {
10160 thumbnailSize.set(view.getWidth(), view.getHeight());
10161 thumbnailTouchPoint.set(thumbnailSize.x / 2, thumbnailSize.y / 2);
10162 } else {
10163 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10164 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010165 }
10166
10167 /**
10168 * Draw the thumbnail image for the upcoming drag. The thumbnail canvas was
10169 * created with the dimensions supplied by the onProvideThumbnailMetrics()
10170 * callback.
10171 *
10172 * @param canvas
10173 */
10174 public void onDrawThumbnail(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070010175 final View view = mView.get();
10176 if (view != null) {
10177 view.draw(canvas);
10178 } else {
10179 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag thumb but no view");
10180 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010181 }
10182 }
10183
10184 /**
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010185 * Drag and drop. App calls startDrag(), then callbacks to the thumbnail builder's
10186 * onProvideThumbnailMetrics() and onDrawThumbnail() methods happen, then the drag
10187 * operation is handed over to the OS.
Christopher Tatea53146c2010-09-07 11:57:52 -070010188 * !!! TODO: real docs
Christopher Tate407b4e92010-11-30 17:14:08 -080010189 *
10190 * @param data !!! TODO
10191 * @param thumbBuilder !!! TODO
10192 * @param myWindowOnly When {@code true}, indicates that the drag operation should be
10193 * restricted to the calling application. In this case only the calling application
10194 * will see any DragEvents related to this drag operation.
10195 * @param myLocalState An arbitrary object that will be passed as part of every DragEvent
10196 * delivered to the calling application during the course of the current drag operation.
10197 * This object is private to the application that called startDrag(), and is not
10198 * visible to other applications. It provides a lightweight way for the application to
10199 * propagate information from the initiator to the recipient of a drag within its own
10200 * application; for example, to help disambiguate between 'copy' and 'move' semantics.
10201 * @return {@code true} if the drag operation was initiated successfully; {@code false} if
10202 * an error prevented the drag from taking place.
Christopher Tatea53146c2010-09-07 11:57:52 -070010203 */
Christopher Tate2c095f32010-10-04 14:13:40 -070010204 public final boolean startDrag(ClipData data, DragThumbnailBuilder thumbBuilder,
Christopher Tate407b4e92010-11-30 17:14:08 -080010205 boolean myWindowOnly, Object myLocalState) {
Christopher Tate2c095f32010-10-04 14:13:40 -070010206 if (ViewDebug.DEBUG_DRAG) {
10207 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " local=" + myWindowOnly);
Christopher Tatea53146c2010-09-07 11:57:52 -070010208 }
10209 boolean okay = false;
10210
Christopher Tate2c095f32010-10-04 14:13:40 -070010211 Point thumbSize = new Point();
10212 Point thumbTouchPoint = new Point();
10213 thumbBuilder.onProvideThumbnailMetrics(thumbSize, thumbTouchPoint);
10214
10215 if ((thumbSize.x < 0) || (thumbSize.y < 0) ||
10216 (thumbTouchPoint.x < 0) || (thumbTouchPoint.y < 0)) {
10217 throw new IllegalStateException("Drag thumb dimensions must not be negative");
10218 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010219
Chris Tatea32dcf72010-10-14 12:13:50 -070010220 if (ViewDebug.DEBUG_DRAG) {
10221 Log.d(VIEW_LOG_TAG, "drag thumb: width=" + thumbSize.x + " height=" + thumbSize.y
10222 + " thumbX=" + thumbTouchPoint.x + " thumbY=" + thumbTouchPoint.y);
10223 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010224 Surface surface = new Surface();
10225 try {
10226 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Chris Tatea32dcf72010-10-14 12:13:50 -070010227 myWindowOnly, thumbSize.x, thumbSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070010228 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070010229 + " surface=" + surface);
10230 if (token != null) {
10231 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070010232 try {
Chris Tate6b391282010-10-14 15:48:59 -070010233 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate2c095f32010-10-04 14:13:40 -070010234 thumbBuilder.onDrawThumbnail(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070010235 } finally {
10236 surface.unlockCanvasAndPost(canvas);
10237 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010238
Christopher Tate407b4e92010-11-30 17:14:08 -080010239 final ViewRoot root = getViewRoot();
10240
10241 // Cache the local state object for delivery with DragEvents
10242 root.setLocalDragState(myLocalState);
10243
Christopher Tate2c095f32010-10-04 14:13:40 -070010244 // repurpose 'thumbSize' for the last touch point
Christopher Tate407b4e92010-11-30 17:14:08 -080010245 root.getLastTouchPoint(thumbSize);
Christopher Tate2c095f32010-10-04 14:13:40 -070010246
Christopher Tatea53146c2010-09-07 11:57:52 -070010247 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate2c095f32010-10-04 14:13:40 -070010248 (float) thumbSize.x, (float) thumbSize.y,
10249 (float) thumbTouchPoint.x, (float) thumbTouchPoint.y, data);
10250 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070010251 }
10252 } catch (Exception e) {
10253 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
10254 surface.destroy();
10255 }
10256
10257 return okay;
10258 }
10259
Christopher Tatea53146c2010-09-07 11:57:52 -070010260 /**
10261 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
10262 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
10263 *
10264 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
10265 * being dragged. onDragEvent() should return 'true' if the view can handle
10266 * a drop of that content. A view that returns 'false' here will receive no
10267 * further calls to onDragEvent() about the drag/drop operation.
10268 *
10269 * For DRAG_ENTERED, event.getClipDescription() describes the content being
10270 * dragged. This will be the same content description passed in the
10271 * DRAG_STARTED_EVENT invocation.
10272 *
10273 * For DRAG_EXITED, event.getClipDescription() describes the content being
10274 * dragged. This will be the same content description passed in the
10275 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
10276 * drag-acceptance visual state.
10277 *
10278 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10279 * coordinates of the current drag point. The view must return 'true' if it
10280 * can accept a drop of the current drag content, false otherwise.
10281 *
10282 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10283 * within the view; also, event.getClipData() returns the full data payload
10284 * being dropped. The view should return 'true' if it consumed the dropped
10285 * content, 'false' if it did not.
10286 *
10287 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
10288 * to its normal visual state.
10289 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010290 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070010291 return false;
10292 }
10293
10294 /**
10295 * Views typically don't need to override dispatchDragEvent(); it just calls
Chris Tate32affef2010-10-18 15:29:21 -070010296 * onDragEvent(event) and passes the result up appropriately.
Christopher Tatea53146c2010-09-07 11:57:52 -070010297 */
10298 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070010299 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10300 && mOnDragListener.onDrag(this, event)) {
10301 return true;
10302 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010303 return onDragEvent(event);
10304 }
10305
10306 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070010307 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
10308 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070010309 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070010310 */
10311 public void onCloseSystemDialogs(String reason) {
10312 }
10313
10314 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010315 * Given a Drawable whose bounds have been set to draw into this view,
10316 * update a Region being computed for {@link #gatherTransparentRegion} so
10317 * that any non-transparent parts of the Drawable are removed from the
10318 * given transparent region.
10319 *
10320 * @param dr The Drawable whose transparency is to be applied to the region.
10321 * @param region A Region holding the current transparency information,
10322 * where any parts of the region that are set are considered to be
10323 * transparent. On return, this region will be modified to have the
10324 * transparency information reduced by the corresponding parts of the
10325 * Drawable that are not transparent.
10326 * {@hide}
10327 */
10328 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
10329 if (DBG) {
10330 Log.i("View", "Getting transparent region for: " + this);
10331 }
10332 final Region r = dr.getTransparentRegion();
10333 final Rect db = dr.getBounds();
10334 final AttachInfo attachInfo = mAttachInfo;
10335 if (r != null && attachInfo != null) {
10336 final int w = getRight()-getLeft();
10337 final int h = getBottom()-getTop();
10338 if (db.left > 0) {
10339 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
10340 r.op(0, 0, db.left, h, Region.Op.UNION);
10341 }
10342 if (db.right < w) {
10343 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
10344 r.op(db.right, 0, w, h, Region.Op.UNION);
10345 }
10346 if (db.top > 0) {
10347 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
10348 r.op(0, 0, w, db.top, Region.Op.UNION);
10349 }
10350 if (db.bottom < h) {
10351 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
10352 r.op(0, db.bottom, w, h, Region.Op.UNION);
10353 }
10354 final int[] location = attachInfo.mTransparentLocation;
10355 getLocationInWindow(location);
10356 r.translate(location[0], location[1]);
10357 region.op(r, Region.Op.INTERSECT);
10358 } else {
10359 region.op(db, Region.Op.DIFFERENCE);
10360 }
10361 }
10362
Adam Powelle14579b2009-12-16 18:39:52 -080010363 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010364 mHasPerformedLongPress = false;
10365
10366 if (mPendingCheckForLongPress == null) {
10367 mPendingCheckForLongPress = new CheckForLongPress();
10368 }
10369 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080010370 postDelayed(mPendingCheckForLongPress,
10371 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010372 }
10373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010374 /**
10375 * Inflate a view from an XML resource. This convenience method wraps the {@link
10376 * LayoutInflater} class, which provides a full range of options for view inflation.
10377 *
10378 * @param context The Context object for your activity or application.
10379 * @param resource The resource ID to inflate
10380 * @param root A view group that will be the parent. Used to properly inflate the
10381 * layout_* parameters.
10382 * @see LayoutInflater
10383 */
10384 public static View inflate(Context context, int resource, ViewGroup root) {
10385 LayoutInflater factory = LayoutInflater.from(context);
10386 return factory.inflate(resource, root);
10387 }
Romain Guy33e72ae2010-07-17 12:40:29 -070010388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010389 /**
Adam Powell637d3372010-08-25 14:37:03 -070010390 * Scroll the view with standard behavior for scrolling beyond the normal
10391 * content boundaries. Views that call this method should override
10392 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
10393 * results of an over-scroll operation.
10394 *
10395 * Views can use this method to handle any touch or fling-based scrolling.
10396 *
10397 * @param deltaX Change in X in pixels
10398 * @param deltaY Change in Y in pixels
10399 * @param scrollX Current X scroll value in pixels before applying deltaX
10400 * @param scrollY Current Y scroll value in pixels before applying deltaY
10401 * @param scrollRangeX Maximum content scroll range along the X axis
10402 * @param scrollRangeY Maximum content scroll range along the Y axis
10403 * @param maxOverScrollX Number of pixels to overscroll by in either direction
10404 * along the X axis.
10405 * @param maxOverScrollY Number of pixels to overscroll by in either direction
10406 * along the Y axis.
10407 * @param isTouchEvent true if this scroll operation is the result of a touch event.
10408 * @return true if scrolling was clamped to an over-scroll boundary along either
10409 * axis, false otherwise.
10410 */
10411 protected boolean overScrollBy(int deltaX, int deltaY,
10412 int scrollX, int scrollY,
10413 int scrollRangeX, int scrollRangeY,
10414 int maxOverScrollX, int maxOverScrollY,
10415 boolean isTouchEvent) {
10416 final int overScrollMode = mOverScrollMode;
10417 final boolean canScrollHorizontal =
10418 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
10419 final boolean canScrollVertical =
10420 computeVerticalScrollRange() > computeVerticalScrollExtent();
10421 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
10422 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
10423 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
10424 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
10425
10426 int newScrollX = scrollX + deltaX;
10427 if (!overScrollHorizontal) {
10428 maxOverScrollX = 0;
10429 }
10430
10431 int newScrollY = scrollY + deltaY;
10432 if (!overScrollVertical) {
10433 maxOverScrollY = 0;
10434 }
10435
10436 // Clamp values if at the limits and record
10437 final int left = -maxOverScrollX;
10438 final int right = maxOverScrollX + scrollRangeX;
10439 final int top = -maxOverScrollY;
10440 final int bottom = maxOverScrollY + scrollRangeY;
10441
10442 boolean clampedX = false;
10443 if (newScrollX > right) {
10444 newScrollX = right;
10445 clampedX = true;
10446 } else if (newScrollX < left) {
10447 newScrollX = left;
10448 clampedX = true;
10449 }
10450
10451 boolean clampedY = false;
10452 if (newScrollY > bottom) {
10453 newScrollY = bottom;
10454 clampedY = true;
10455 } else if (newScrollY < top) {
10456 newScrollY = top;
10457 clampedY = true;
10458 }
10459
10460 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
10461
10462 return clampedX || clampedY;
10463 }
10464
10465 /**
10466 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
10467 * respond to the results of an over-scroll operation.
10468 *
10469 * @param scrollX New X scroll value in pixels
10470 * @param scrollY New Y scroll value in pixels
10471 * @param clampedX True if scrollX was clamped to an over-scroll boundary
10472 * @param clampedY True if scrollY was clamped to an over-scroll boundary
10473 */
10474 protected void onOverScrolled(int scrollX, int scrollY,
10475 boolean clampedX, boolean clampedY) {
10476 // Intentionally empty.
10477 }
10478
10479 /**
10480 * Returns the over-scroll mode for this view. The result will be
10481 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10482 * (allow over-scrolling only if the view content is larger than the container),
10483 * or {@link #OVER_SCROLL_NEVER}.
10484 *
10485 * @return This view's over-scroll mode.
10486 */
10487 public int getOverScrollMode() {
10488 return mOverScrollMode;
10489 }
10490
10491 /**
10492 * Set the over-scroll mode for this view. Valid over-scroll modes are
10493 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10494 * (allow over-scrolling only if the view content is larger than the container),
10495 * or {@link #OVER_SCROLL_NEVER}.
10496 *
10497 * Setting the over-scroll mode of a view will have an effect only if the
10498 * view is capable of scrolling.
10499 *
10500 * @param overScrollMode The new over-scroll mode for this view.
10501 */
10502 public void setOverScrollMode(int overScrollMode) {
10503 if (overScrollMode != OVER_SCROLL_ALWAYS &&
10504 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
10505 overScrollMode != OVER_SCROLL_NEVER) {
10506 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
10507 }
10508 mOverScrollMode = overScrollMode;
10509 }
10510
10511 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010512 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
10513 * Each MeasureSpec represents a requirement for either the width or the height.
10514 * A MeasureSpec is comprised of a size and a mode. There are three possible
10515 * modes:
10516 * <dl>
10517 * <dt>UNSPECIFIED</dt>
10518 * <dd>
10519 * The parent has not imposed any constraint on the child. It can be whatever size
10520 * it wants.
10521 * </dd>
10522 *
10523 * <dt>EXACTLY</dt>
10524 * <dd>
10525 * The parent has determined an exact size for the child. The child is going to be
10526 * given those bounds regardless of how big it wants to be.
10527 * </dd>
10528 *
10529 * <dt>AT_MOST</dt>
10530 * <dd>
10531 * The child can be as large as it wants up to the specified size.
10532 * </dd>
10533 * </dl>
10534 *
10535 * MeasureSpecs are implemented as ints to reduce object allocation. This class
10536 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
10537 */
10538 public static class MeasureSpec {
10539 private static final int MODE_SHIFT = 30;
10540 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
10541
10542 /**
10543 * Measure specification mode: The parent has not imposed any constraint
10544 * on the child. It can be whatever size it wants.
10545 */
10546 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
10547
10548 /**
10549 * Measure specification mode: The parent has determined an exact size
10550 * for the child. The child is going to be given those bounds regardless
10551 * of how big it wants to be.
10552 */
10553 public static final int EXACTLY = 1 << MODE_SHIFT;
10554
10555 /**
10556 * Measure specification mode: The child can be as large as it wants up
10557 * to the specified size.
10558 */
10559 public static final int AT_MOST = 2 << MODE_SHIFT;
10560
10561 /**
10562 * Creates a measure specification based on the supplied size and mode.
10563 *
10564 * The mode must always be one of the following:
10565 * <ul>
10566 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
10567 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
10568 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
10569 * </ul>
10570 *
10571 * @param size the size of the measure specification
10572 * @param mode the mode of the measure specification
10573 * @return the measure specification based on size and mode
10574 */
10575 public static int makeMeasureSpec(int size, int mode) {
10576 return size + mode;
10577 }
10578
10579 /**
10580 * Extracts the mode from the supplied measure specification.
10581 *
10582 * @param measureSpec the measure specification to extract the mode from
10583 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
10584 * {@link android.view.View.MeasureSpec#AT_MOST} or
10585 * {@link android.view.View.MeasureSpec#EXACTLY}
10586 */
10587 public static int getMode(int measureSpec) {
10588 return (measureSpec & MODE_MASK);
10589 }
10590
10591 /**
10592 * Extracts the size from the supplied measure specification.
10593 *
10594 * @param measureSpec the measure specification to extract the size from
10595 * @return the size in pixels defined in the supplied measure specification
10596 */
10597 public static int getSize(int measureSpec) {
10598 return (measureSpec & ~MODE_MASK);
10599 }
10600
10601 /**
10602 * Returns a String representation of the specified measure
10603 * specification.
10604 *
10605 * @param measureSpec the measure specification to convert to a String
10606 * @return a String with the following format: "MeasureSpec: MODE SIZE"
10607 */
10608 public static String toString(int measureSpec) {
10609 int mode = getMode(measureSpec);
10610 int size = getSize(measureSpec);
10611
10612 StringBuilder sb = new StringBuilder("MeasureSpec: ");
10613
10614 if (mode == UNSPECIFIED)
10615 sb.append("UNSPECIFIED ");
10616 else if (mode == EXACTLY)
10617 sb.append("EXACTLY ");
10618 else if (mode == AT_MOST)
10619 sb.append("AT_MOST ");
10620 else
10621 sb.append(mode).append(" ");
10622
10623 sb.append(size);
10624 return sb.toString();
10625 }
10626 }
10627
10628 class CheckForLongPress implements Runnable {
10629
10630 private int mOriginalWindowAttachCount;
10631
10632 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070010633 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010634 && mOriginalWindowAttachCount == mWindowAttachCount) {
10635 if (performLongClick()) {
10636 mHasPerformedLongPress = true;
10637 }
10638 }
10639 }
10640
10641 public void rememberWindowAttachCount() {
10642 mOriginalWindowAttachCount = mWindowAttachCount;
10643 }
10644 }
Adam Powelle14579b2009-12-16 18:39:52 -080010645
10646 private final class CheckForTap implements Runnable {
10647 public void run() {
10648 mPrivateFlags &= ~PREPRESSED;
10649 mPrivateFlags |= PRESSED;
10650 refreshDrawableState();
10651 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
10652 postCheckForLongClick(ViewConfiguration.getTapTimeout());
10653 }
10654 }
10655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010656
Adam Powella35d7682010-03-12 14:48:13 -080010657 private final class PerformClick implements Runnable {
10658 public void run() {
10659 performClick();
10660 }
10661 }
10662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010663 /**
10664 * Interface definition for a callback to be invoked when a key event is
10665 * dispatched to this view. The callback will be invoked before the key
10666 * event is given to the view.
10667 */
10668 public interface OnKeyListener {
10669 /**
10670 * Called when a key is dispatched to a view. This allows listeners to
10671 * get a chance to respond before the target view.
10672 *
10673 * @param v The view the key has been dispatched to.
10674 * @param keyCode The code for the physical key that was pressed
10675 * @param event The KeyEvent object containing full information about
10676 * the event.
10677 * @return True if the listener has consumed the event, false otherwise.
10678 */
10679 boolean onKey(View v, int keyCode, KeyEvent event);
10680 }
10681
10682 /**
10683 * Interface definition for a callback to be invoked when a touch event is
10684 * dispatched to this view. The callback will be invoked before the touch
10685 * event is given to the view.
10686 */
10687 public interface OnTouchListener {
10688 /**
10689 * Called when a touch event is dispatched to a view. This allows listeners to
10690 * get a chance to respond before the target view.
10691 *
10692 * @param v The view the touch event has been dispatched to.
10693 * @param event The MotionEvent object containing full information about
10694 * the event.
10695 * @return True if the listener has consumed the event, false otherwise.
10696 */
10697 boolean onTouch(View v, MotionEvent event);
10698 }
10699
10700 /**
10701 * Interface definition for a callback to be invoked when a view has been clicked and held.
10702 */
10703 public interface OnLongClickListener {
10704 /**
10705 * Called when a view has been clicked and held.
10706 *
10707 * @param v The view that was clicked and held.
10708 *
10709 * return True if the callback consumed the long click, false otherwise
10710 */
10711 boolean onLongClick(View v);
10712 }
10713
10714 /**
Chris Tate32affef2010-10-18 15:29:21 -070010715 * Interface definition for a callback to be invoked when a drag is being dispatched
10716 * to this view. The callback will be invoked before the hosting view's own
10717 * onDrag(event) method. If the listener wants to fall back to the hosting view's
10718 * onDrag(event) behavior, it should return 'false' from this callback.
10719 */
10720 public interface OnDragListener {
10721 /**
10722 * Called when a drag event is dispatched to a view. This allows listeners
10723 * to get a chance to override base View behavior.
10724 *
10725 * @param v The view the drag has been dispatched to.
10726 * @param event The DragEvent object containing full information
10727 * about the event.
10728 * @return true if the listener consumed the DragEvent, false in order to fall
10729 * back to the view's default handling.
10730 */
10731 boolean onDrag(View v, DragEvent event);
10732 }
10733
10734 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010735 * Interface definition for a callback to be invoked when the focus state of
10736 * a view changed.
10737 */
10738 public interface OnFocusChangeListener {
10739 /**
10740 * Called when the focus state of a view has changed.
10741 *
10742 * @param v The view whose state has changed.
10743 * @param hasFocus The new focus state of v.
10744 */
10745 void onFocusChange(View v, boolean hasFocus);
10746 }
10747
10748 /**
10749 * Interface definition for a callback to be invoked when a view is clicked.
10750 */
10751 public interface OnClickListener {
10752 /**
10753 * Called when a view has been clicked.
10754 *
10755 * @param v The view that was clicked.
10756 */
10757 void onClick(View v);
10758 }
10759
10760 /**
10761 * Interface definition for a callback to be invoked when the context menu
10762 * for this view is being built.
10763 */
10764 public interface OnCreateContextMenuListener {
10765 /**
10766 * Called when the context menu for this view is being built. It is not
10767 * safe to hold onto the menu after this method returns.
10768 *
10769 * @param menu The context menu that is being built
10770 * @param v The view for which the context menu is being built
10771 * @param menuInfo Extra information about the item for which the
10772 * context menu should be shown. This information will vary
10773 * depending on the class of v.
10774 */
10775 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
10776 }
10777
10778 private final class UnsetPressedState implements Runnable {
10779 public void run() {
10780 setPressed(false);
10781 }
10782 }
10783
10784 /**
10785 * Base class for derived classes that want to save and restore their own
10786 * state in {@link android.view.View#onSaveInstanceState()}.
10787 */
10788 public static class BaseSavedState extends AbsSavedState {
10789 /**
10790 * Constructor used when reading from a parcel. Reads the state of the superclass.
10791 *
10792 * @param source
10793 */
10794 public BaseSavedState(Parcel source) {
10795 super(source);
10796 }
10797
10798 /**
10799 * Constructor called by derived classes when creating their SavedState objects
10800 *
10801 * @param superState The state of the superclass of this view
10802 */
10803 public BaseSavedState(Parcelable superState) {
10804 super(superState);
10805 }
10806
10807 public static final Parcelable.Creator<BaseSavedState> CREATOR =
10808 new Parcelable.Creator<BaseSavedState>() {
10809 public BaseSavedState createFromParcel(Parcel in) {
10810 return new BaseSavedState(in);
10811 }
10812
10813 public BaseSavedState[] newArray(int size) {
10814 return new BaseSavedState[size];
10815 }
10816 };
10817 }
10818
10819 /**
10820 * A set of information given to a view when it is attached to its parent
10821 * window.
10822 */
10823 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010824 interface Callbacks {
10825 void playSoundEffect(int effectId);
10826 boolean performHapticFeedback(int effectId, boolean always);
10827 }
10828
10829 /**
10830 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
10831 * to a Handler. This class contains the target (View) to invalidate and
10832 * the coordinates of the dirty rectangle.
10833 *
10834 * For performance purposes, this class also implements a pool of up to
10835 * POOL_LIMIT objects that get reused. This reduces memory allocations
10836 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010837 */
Romain Guyd928d682009-03-31 17:52:16 -070010838 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010839 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070010840 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
10841 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070010842 public InvalidateInfo newInstance() {
10843 return new InvalidateInfo();
10844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845
Romain Guyd928d682009-03-31 17:52:16 -070010846 public void onAcquired(InvalidateInfo element) {
10847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010848
Romain Guyd928d682009-03-31 17:52:16 -070010849 public void onReleased(InvalidateInfo element) {
10850 }
10851 }, POOL_LIMIT)
10852 );
10853
10854 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010855
10856 View target;
10857
10858 int left;
10859 int top;
10860 int right;
10861 int bottom;
10862
Romain Guyd928d682009-03-31 17:52:16 -070010863 public void setNextPoolable(InvalidateInfo element) {
10864 mNext = element;
10865 }
10866
10867 public InvalidateInfo getNextPoolable() {
10868 return mNext;
10869 }
10870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010871 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070010872 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010873 }
10874
10875 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070010876 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010877 }
10878 }
10879
10880 final IWindowSession mSession;
10881
10882 final IWindow mWindow;
10883
10884 final IBinder mWindowToken;
10885
10886 final Callbacks mRootCallbacks;
10887
10888 /**
10889 * The top view of the hierarchy.
10890 */
10891 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070010892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010893 IBinder mPanelParentWindowToken;
10894 Surface mSurface;
10895
Romain Guyb051e892010-09-28 19:09:36 -070010896 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080010897 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070010898 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070010899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010900 /**
Romain Guy8506ab42009-06-11 17:35:47 -070010901 * Scale factor used by the compatibility mode
10902 */
10903 float mApplicationScale;
10904
10905 /**
10906 * Indicates whether the application is in compatibility mode
10907 */
10908 boolean mScalingRequired;
10909
10910 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010911 * Left position of this view's window
10912 */
10913 int mWindowLeft;
10914
10915 /**
10916 * Top position of this view's window
10917 */
10918 int mWindowTop;
10919
10920 /**
Adam Powell26153a32010-11-08 15:22:27 -080010921 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070010922 */
Adam Powell26153a32010-11-08 15:22:27 -080010923 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070010924
10925 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010926 * For windows that are full-screen but using insets to layout inside
10927 * of the screen decorations, these are the current insets for the
10928 * content of the window.
10929 */
10930 final Rect mContentInsets = new Rect();
10931
10932 /**
10933 * For windows that are full-screen but using insets to layout inside
10934 * of the screen decorations, these are the current insets for the
10935 * actual visible parts of the window.
10936 */
10937 final Rect mVisibleInsets = new Rect();
10938
10939 /**
10940 * The internal insets given by this window. This value is
10941 * supplied by the client (through
10942 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
10943 * be given to the window manager when changed to be used in laying
10944 * out windows behind it.
10945 */
10946 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
10947 = new ViewTreeObserver.InternalInsetsInfo();
10948
10949 /**
10950 * All views in the window's hierarchy that serve as scroll containers,
10951 * used to determine if the window can be resized or must be panned
10952 * to adjust for a soft input area.
10953 */
10954 final ArrayList<View> mScrollContainers = new ArrayList<View>();
10955
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070010956 final KeyEvent.DispatcherState mKeyDispatchState
10957 = new KeyEvent.DispatcherState();
10958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010959 /**
10960 * Indicates whether the view's window currently has the focus.
10961 */
10962 boolean mHasWindowFocus;
10963
10964 /**
10965 * The current visibility of the window.
10966 */
10967 int mWindowVisibility;
10968
10969 /**
10970 * Indicates the time at which drawing started to occur.
10971 */
10972 long mDrawingTime;
10973
10974 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070010975 * Indicates whether or not ignoring the DIRTY_MASK flags.
10976 */
10977 boolean mIgnoreDirtyState;
10978
10979 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010980 * Indicates whether the view's window is currently in touch mode.
10981 */
10982 boolean mInTouchMode;
10983
10984 /**
10985 * Indicates that ViewRoot should trigger a global layout change
10986 * the next time it performs a traversal
10987 */
10988 boolean mRecomputeGlobalAttributes;
10989
10990 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010991 * Set during a traveral if any views want to keep the screen on.
10992 */
10993 boolean mKeepScreenOn;
10994
10995 /**
10996 * Set if the visibility of any views has changed.
10997 */
10998 boolean mViewVisibilityChanged;
10999
11000 /**
11001 * Set to true if a view has been scrolled.
11002 */
11003 boolean mViewScrollChanged;
11004
11005 /**
11006 * Global to the view hierarchy used as a temporary for dealing with
11007 * x/y points in the transparent region computations.
11008 */
11009 final int[] mTransparentLocation = new int[2];
11010
11011 /**
11012 * Global to the view hierarchy used as a temporary for dealing with
11013 * x/y points in the ViewGroup.invalidateChild implementation.
11014 */
11015 final int[] mInvalidateChildLocation = new int[2];
11016
Chet Haasec3aa3612010-06-17 08:50:37 -070011017
11018 /**
11019 * Global to the view hierarchy used as a temporary for dealing with
11020 * x/y location when view is transformed.
11021 */
11022 final float[] mTmpTransformLocation = new float[2];
11023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011024 /**
11025 * The view tree observer used to dispatch global events like
11026 * layout, pre-draw, touch mode change, etc.
11027 */
11028 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11029
11030 /**
11031 * A Canvas used by the view hierarchy to perform bitmap caching.
11032 */
11033 Canvas mCanvas;
11034
11035 /**
11036 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11037 * handler can be used to pump events in the UI events queue.
11038 */
11039 final Handler mHandler;
11040
11041 /**
11042 * Identifier for messages requesting the view to be invalidated.
11043 * Such messages should be sent to {@link #mHandler}.
11044 */
11045 static final int INVALIDATE_MSG = 0x1;
11046
11047 /**
11048 * Identifier for messages requesting the view to invalidate a region.
11049 * Such messages should be sent to {@link #mHandler}.
11050 */
11051 static final int INVALIDATE_RECT_MSG = 0x2;
11052
11053 /**
11054 * Temporary for use in computing invalidate rectangles while
11055 * calling up the hierarchy.
11056 */
11057 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070011058
11059 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070011060 * Temporary for use in computing hit areas with transformed views
11061 */
11062 final RectF mTmpTransformRect = new RectF();
11063
11064 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070011065 * Temporary list for use in collecting focusable descendents of a view.
11066 */
11067 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011069 /**
11070 * Creates a new set of attachment information with the specified
11071 * events handler and thread.
11072 *
11073 * @param handler the events handler the view must use
11074 */
11075 AttachInfo(IWindowSession session, IWindow window,
11076 Handler handler, Callbacks effectPlayer) {
11077 mSession = session;
11078 mWindow = window;
11079 mWindowToken = window.asBinder();
11080 mHandler = handler;
11081 mRootCallbacks = effectPlayer;
11082 }
11083 }
11084
11085 /**
11086 * <p>ScrollabilityCache holds various fields used by a View when scrolling
11087 * is supported. This avoids keeping too many unused fields in most
11088 * instances of View.</p>
11089 */
Mike Cleronf116bf82009-09-27 19:14:12 -070011090 private static class ScrollabilityCache implements Runnable {
11091
11092 /**
11093 * Scrollbars are not visible
11094 */
11095 public static final int OFF = 0;
11096
11097 /**
11098 * Scrollbars are visible
11099 */
11100 public static final int ON = 1;
11101
11102 /**
11103 * Scrollbars are fading away
11104 */
11105 public static final int FADING = 2;
11106
11107 public boolean fadeScrollBars;
11108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011109 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070011110 public int scrollBarDefaultDelayBeforeFade;
11111 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011112
11113 public int scrollBarSize;
11114 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070011115 public float[] interpolatorValues;
11116 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011117
11118 public final Paint paint;
11119 public final Matrix matrix;
11120 public Shader shader;
11121
Mike Cleronf116bf82009-09-27 19:14:12 -070011122 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11123
Romain Guy8fb95422010-08-17 18:38:51 -070011124 private final float[] mOpaque = { 255.0f };
11125 private final float[] mTransparent = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070011126
11127 /**
11128 * When fading should start. This time moves into the future every time
11129 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11130 */
11131 public long fadeStartTime;
11132
11133
11134 /**
11135 * The current state of the scrollbars: ON, OFF, or FADING
11136 */
11137 public int state = OFF;
11138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011139 private int mLastColor;
11140
Mike Cleronf116bf82009-09-27 19:14:12 -070011141 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011142 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11143 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070011144 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11145 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011146
11147 paint = new Paint();
11148 matrix = new Matrix();
11149 // use use a height of 1, and then wack the matrix each time we
11150 // actually use it.
11151 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011153 paint.setShader(shader);
11154 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070011155 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011156 }
Romain Guy8506ab42009-06-11 17:35:47 -070011157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011158 public void setFadeColor(int color) {
11159 if (color != 0 && color != mLastColor) {
11160 mLastColor = color;
11161 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070011162
Romain Guye55e1a72009-08-27 10:42:26 -070011163 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11164 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011166 paint.setShader(shader);
11167 // Restore the default transfer mode (src_over)
11168 paint.setXfermode(null);
11169 }
11170 }
Mike Cleronf116bf82009-09-27 19:14:12 -070011171
11172 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070011173 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070011174 if (now >= fadeStartTime) {
11175
11176 // the animation fades the scrollbars out by changing
11177 // the opacity (alpha) from fully opaque to fully
11178 // transparent
11179 int nextFrame = (int) now;
11180 int framesCount = 0;
11181
11182 Interpolator interpolator = scrollBarInterpolator;
11183
11184 // Start opaque
11185 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
11186
11187 // End transparent
11188 nextFrame += scrollBarFadeDuration;
11189 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
11190
11191 state = FADING;
11192
11193 // Kick off the fade animation
11194 host.invalidate();
11195 }
11196 }
11197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011198 }
11199}