blob: f05ef8c588cdda89aa09d2ff33e05ca6933b3d9e [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
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080019import com.android.internal.R;
20import com.android.internal.util.Predicate;
21import com.android.internal.view.menu.MenuBuilder;
22
Christopher Tatea53146c2010-09-07 11:57:52 -070023import android.content.ClipData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080025import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.res.Resources;
27import android.content.res.TypedArray;
28import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070029import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070031import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.graphics.LinearGradient;
33import android.graphics.Matrix;
34import android.graphics.Paint;
35import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070036import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.graphics.PorterDuff;
38import android.graphics.PorterDuffXfermode;
39import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070040import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.graphics.Region;
42import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.graphics.drawable.ColorDrawable;
44import android.graphics.drawable.Drawable;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Message;
48import android.os.Parcel;
49import android.os.Parcelable;
50import android.os.RemoteException;
51import android.os.SystemClock;
52import android.os.SystemProperties;
53import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070055import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070056import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070057import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070058import android.util.Pools;
59import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.ContextMenu.ContextMenuInfo;
Gilles Debunnefb817032011-01-13 13:52:49 -080061import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070062import android.view.accessibility.AccessibilityEvent;
63import android.view.accessibility.AccessibilityEventSource;
64import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070066import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070067import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.view.inputmethod.InputConnection;
69import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.widget.ScrollBarDrawable;
71
Christopher Tatea0374192010-10-05 13:06:41 -070072import java.lang.ref.WeakReference;
svetoslavganov75986cf2009-05-14 22:28:01 -070073import java.lang.reflect.InvocationTargetException;
74import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import java.util.ArrayList;
76import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070077import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070078import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
80/**
81 * <p>
82 * This class represents the basic building block for user interface components. A View
83 * occupies a rectangular area on the screen and is responsible for drawing and
84 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070085 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
87 * are invisible containers that hold other Views (or other ViewGroups) and define
88 * their layout properties.
89 * </p>
90 *
91 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070092 * <p>For an introduction to using this class to develop your
93 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070095 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
102 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
103 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
104 * </p>
105 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700106 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 * <a name="Using"></a>
108 * <h3>Using Views</h3>
109 * <p>
110 * All of the views in a window are arranged in a single tree. You can add views
111 * either from code or by specifying a tree of views in one or more XML layout
112 * files. There are many specialized subclasses of views that act as controls or
113 * are capable of displaying text, images, or other content.
114 * </p>
115 * <p>
116 * Once you have created a tree of views, there are typically a few types of
117 * common operations you may wish to perform:
118 * <ul>
119 * <li><strong>Set properties:</strong> for example setting the text of a
120 * {@link android.widget.TextView}. The available properties and the methods
121 * that set them will vary among the different subclasses of views. Note that
122 * properties that are known at build time can be set in the XML layout
123 * files.</li>
124 * <li><strong>Set focus:</strong> The framework will handled moving focus in
125 * response to user input. To force focus to a specific view, call
126 * {@link #requestFocus}.</li>
127 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
128 * that will be notified when something interesting happens to the view. For
129 * example, all views will let you set a listener to be notified when the view
130 * gains or loses focus. You can register such a listener using
131 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
132 * specialized listeners. For example, a Button exposes a listener to notify
133 * clients when the button is clicked.</li>
134 * <li><strong>Set visibility:</strong> You can hide or show views using
135 * {@link #setVisibility}.</li>
136 * </ul>
137 * </p>
138 * <p><em>
139 * Note: The Android framework is responsible for measuring, laying out and
140 * drawing views. You should not call methods that perform these actions on
141 * views yourself unless you are actually implementing a
142 * {@link android.view.ViewGroup}.
143 * </em></p>
144 *
145 * <a name="Lifecycle"></a>
146 * <h3>Implementing a Custom View</h3>
147 *
148 * <p>
149 * To implement a custom view, you will usually begin by providing overrides for
150 * some of the standard methods that the framework calls on all views. You do
151 * not need to override all of these methods. In fact, you can start by just
152 * overriding {@link #onDraw(android.graphics.Canvas)}.
153 * <table border="2" width="85%" align="center" cellpadding="5">
154 * <thead>
155 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
156 * </thead>
157 *
158 * <tbody>
159 * <tr>
160 * <td rowspan="2">Creation</td>
161 * <td>Constructors</td>
162 * <td>There is a form of the constructor that are called when the view
163 * is created from code and a form that is called when the view is
164 * inflated from a layout file. The second form should parse and apply
165 * any attributes defined in the layout file.
166 * </td>
167 * </tr>
168 * <tr>
169 * <td><code>{@link #onFinishInflate()}</code></td>
170 * <td>Called after a view and all of its children has been inflated
171 * from XML.</td>
172 * </tr>
173 *
174 * <tr>
175 * <td rowspan="3">Layout</td>
176 * <td><code>{@link #onMeasure}</code></td>
177 * <td>Called to determine the size requirements for this view and all
178 * of its children.
179 * </td>
180 * </tr>
181 * <tr>
182 * <td><code>{@link #onLayout}</code></td>
183 * <td>Called when this view should assign a size and position to all
184 * of its children.
185 * </td>
186 * </tr>
187 * <tr>
188 * <td><code>{@link #onSizeChanged}</code></td>
189 * <td>Called when the size of this view has changed.
190 * </td>
191 * </tr>
192 *
193 * <tr>
194 * <td>Drawing</td>
195 * <td><code>{@link #onDraw}</code></td>
196 * <td>Called when the view should render its content.
197 * </td>
198 * </tr>
199 *
200 * <tr>
201 * <td rowspan="4">Event processing</td>
202 * <td><code>{@link #onKeyDown}</code></td>
203 * <td>Called when a new key event occurs.
204 * </td>
205 * </tr>
206 * <tr>
207 * <td><code>{@link #onKeyUp}</code></td>
208 * <td>Called when a key up event occurs.
209 * </td>
210 * </tr>
211 * <tr>
212 * <td><code>{@link #onTrackballEvent}</code></td>
213 * <td>Called when a trackball motion event occurs.
214 * </td>
215 * </tr>
216 * <tr>
217 * <td><code>{@link #onTouchEvent}</code></td>
218 * <td>Called when a touch screen motion event occurs.
219 * </td>
220 * </tr>
221 *
222 * <tr>
223 * <td rowspan="2">Focus</td>
224 * <td><code>{@link #onFocusChanged}</code></td>
225 * <td>Called when the view gains or loses focus.
226 * </td>
227 * </tr>
228 *
229 * <tr>
230 * <td><code>{@link #onWindowFocusChanged}</code></td>
231 * <td>Called when the window containing the view gains or loses focus.
232 * </td>
233 * </tr>
234 *
235 * <tr>
236 * <td rowspan="3">Attaching</td>
237 * <td><code>{@link #onAttachedToWindow()}</code></td>
238 * <td>Called when the view is attached to a window.
239 * </td>
240 * </tr>
241 *
242 * <tr>
243 * <td><code>{@link #onDetachedFromWindow}</code></td>
244 * <td>Called when the view is detached from its window.
245 * </td>
246 * </tr>
247 *
248 * <tr>
249 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
250 * <td>Called when the visibility of the window containing the view
251 * has changed.
252 * </td>
253 * </tr>
254 * </tbody>
255 *
256 * </table>
257 * </p>
258 *
259 * <a name="IDs"></a>
260 * <h3>IDs</h3>
261 * Views may have an integer id associated with them. These ids are typically
262 * assigned in the layout XML files, and are used to find specific views within
263 * the view tree. A common pattern is to:
264 * <ul>
265 * <li>Define a Button in the layout file and assign it a unique ID.
266 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700267 * &lt;Button
268 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 * android:layout_width="wrap_content"
270 * android:layout_height="wrap_content"
271 * android:text="@string/my_button_text"/&gt;
272 * </pre></li>
273 * <li>From the onCreate method of an Activity, find the Button
274 * <pre class="prettyprint">
275 * Button myButton = (Button) findViewById(R.id.my_button);
276 * </pre></li>
277 * </ul>
278 * <p>
279 * View IDs need not be unique throughout the tree, but it is good practice to
280 * ensure that they are at least unique within the part of the tree you are
281 * searching.
282 * </p>
283 *
284 * <a name="Position"></a>
285 * <h3>Position</h3>
286 * <p>
287 * The geometry of a view is that of a rectangle. A view has a location,
288 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
289 * two dimensions, expressed as a width and a height. The unit for location
290 * and dimensions is the pixel.
291 * </p>
292 *
293 * <p>
294 * It is possible to retrieve the location of a view by invoking the methods
295 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
296 * coordinate of the rectangle representing the view. The latter returns the
297 * top, or Y, coordinate of the rectangle representing the view. These methods
298 * both return the location of the view relative to its parent. For instance,
299 * when getLeft() returns 20, that means the view is located 20 pixels to the
300 * right of the left edge of its direct parent.
301 * </p>
302 *
303 * <p>
304 * In addition, several convenience methods are offered to avoid unnecessary
305 * computations, namely {@link #getRight()} and {@link #getBottom()}.
306 * These methods return the coordinates of the right and bottom edges of the
307 * rectangle representing the view. For instance, calling {@link #getRight()}
308 * is similar to the following computation: <code>getLeft() + getWidth()</code>
309 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
310 * </p>
311 *
312 * <a name="SizePaddingMargins"></a>
313 * <h3>Size, padding and margins</h3>
314 * <p>
315 * The size of a view is expressed with a width and a height. A view actually
316 * possess two pairs of width and height values.
317 * </p>
318 *
319 * <p>
320 * The first pair is known as <em>measured width</em> and
321 * <em>measured height</em>. These dimensions define how big a view wants to be
322 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
323 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
324 * and {@link #getMeasuredHeight()}.
325 * </p>
326 *
327 * <p>
328 * The second pair is simply known as <em>width</em> and <em>height</em>, or
329 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
330 * dimensions define the actual size of the view on screen, at drawing time and
331 * after layout. These values may, but do not have to, be different from the
332 * measured width and height. The width and height can be obtained by calling
333 * {@link #getWidth()} and {@link #getHeight()}.
334 * </p>
335 *
336 * <p>
337 * To measure its dimensions, a view takes into account its padding. The padding
338 * is expressed in pixels for the left, top, right and bottom parts of the view.
339 * Padding can be used to offset the content of the view by a specific amount of
340 * pixels. For instance, a left padding of 2 will push the view's content by
341 * 2 pixels to the right of the left edge. Padding can be set using the
342 * {@link #setPadding(int, int, int, int)} method and queried by calling
343 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
344 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
345 * </p>
346 *
347 * <p>
348 * Even though a view can define a padding, it does not provide any support for
349 * margins. However, view groups provide such a support. Refer to
350 * {@link android.view.ViewGroup} and
351 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
352 * </p>
353 *
354 * <a name="Layout"></a>
355 * <h3>Layout</h3>
356 * <p>
357 * Layout is a two pass process: a measure pass and a layout pass. The measuring
358 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
359 * of the view tree. Each view pushes dimension specifications down the tree
360 * during the recursion. At the end of the measure pass, every view has stored
361 * its measurements. The second pass happens in
362 * {@link #layout(int,int,int,int)} and is also top-down. During
363 * this pass each parent is responsible for positioning all of its children
364 * using the sizes computed in the measure pass.
365 * </p>
366 *
367 * <p>
368 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
369 * {@link #getMeasuredHeight()} values must be set, along with those for all of
370 * that view's descendants. A view's measured width and measured height values
371 * must respect the constraints imposed by the view's parents. This guarantees
372 * that at the end of the measure pass, all parents accept all of their
373 * children's measurements. A parent view may call measure() more than once on
374 * its children. For example, the parent may measure each child once with
375 * unspecified dimensions to find out how big they want to be, then call
376 * measure() on them again with actual numbers if the sum of all the children's
377 * unconstrained sizes is too big or too small.
378 * </p>
379 *
380 * <p>
381 * The measure pass uses two classes to communicate dimensions. The
382 * {@link MeasureSpec} class is used by views to tell their parents how they
383 * want to be measured and positioned. The base LayoutParams class just
384 * describes how big the view wants to be for both width and height. For each
385 * dimension, it can specify one of:
386 * <ul>
387 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800388 * <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 -0800389 * (minus padding)
390 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
391 * enclose its content (plus padding).
392 * </ul>
393 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
394 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
395 * an X and Y value.
396 * </p>
397 *
398 * <p>
399 * MeasureSpecs are used to push requirements down the tree from parent to
400 * child. A MeasureSpec can be in one of three modes:
401 * <ul>
402 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
403 * of a child view. For example, a LinearLayout may call measure() on its child
404 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
405 * tall the child view wants to be given a width of 240 pixels.
406 * <li>EXACTLY: This is used by the parent to impose an exact size on the
407 * child. The child must use this size, and guarantee that all of its
408 * descendants will fit within this size.
409 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
410 * child. The child must gurantee that it and all of its descendants will fit
411 * within this size.
412 * </ul>
413 * </p>
414 *
415 * <p>
416 * To intiate a layout, call {@link #requestLayout}. This method is typically
417 * called by a view on itself when it believes that is can no longer fit within
418 * its current bounds.
419 * </p>
420 *
421 * <a name="Drawing"></a>
422 * <h3>Drawing</h3>
423 * <p>
424 * Drawing is handled by walking the tree and rendering each view that
425 * intersects the the invalid region. Because the tree is traversed in-order,
426 * this means that parents will draw before (i.e., behind) their children, with
427 * siblings drawn in the order they appear in the tree.
428 * If you set a background drawable for a View, then the View will draw it for you
429 * before calling back to its <code>onDraw()</code> method.
430 * </p>
431 *
432 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700433 * 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 -0800434 * </p>
435 *
436 * <p>
437 * To force a view to draw, call {@link #invalidate()}.
438 * </p>
439 *
440 * <a name="EventHandlingThreading"></a>
441 * <h3>Event Handling and Threading</h3>
442 * <p>
443 * The basic cycle of a view is as follows:
444 * <ol>
445 * <li>An event comes in and is dispatched to the appropriate view. The view
446 * handles the event and notifies any listeners.</li>
447 * <li>If in the course of processing the event, the view's bounds may need
448 * to be changed, the view will call {@link #requestLayout()}.</li>
449 * <li>Similarly, if in the course of processing the event the view's appearance
450 * may need to be changed, the view will call {@link #invalidate()}.</li>
451 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
452 * the framework will take care of measuring, laying out, and drawing the tree
453 * as appropriate.</li>
454 * </ol>
455 * </p>
456 *
457 * <p><em>Note: The entire view tree is single threaded. You must always be on
458 * the UI thread when calling any method on any view.</em>
459 * If you are doing work on other threads and want to update the state of a view
460 * from that thread, you should use a {@link Handler}.
461 * </p>
462 *
463 * <a name="FocusHandling"></a>
464 * <h3>Focus Handling</h3>
465 * <p>
466 * The framework will handle routine focus movement in response to user input.
467 * This includes changing the focus as views are removed or hidden, or as new
468 * views become available. Views indicate their willingness to take focus
469 * through the {@link #isFocusable} method. To change whether a view can take
470 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
471 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
472 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
473 * </p>
474 * <p>
475 * Focus movement is based on an algorithm which finds the nearest neighbor in a
476 * given direction. In rare cases, the default algorithm may not match the
477 * intended behavior of the developer. In these situations, you can provide
478 * explicit overrides by using these XML attributes in the layout file:
479 * <pre>
480 * nextFocusDown
481 * nextFocusLeft
482 * nextFocusRight
483 * nextFocusUp
484 * </pre>
485 * </p>
486 *
487 *
488 * <p>
489 * To get a particular view to take focus, call {@link #requestFocus()}.
490 * </p>
491 *
492 * <a name="TouchMode"></a>
493 * <h3>Touch Mode</h3>
494 * <p>
495 * When a user is navigating a user interface via directional keys such as a D-pad, it is
496 * necessary to give focus to actionable items such as buttons so the user can see
497 * what will take input. If the device has touch capabilities, however, and the user
498 * begins interacting with the interface by touching it, it is no longer necessary to
499 * always highlight, or give focus to, a particular view. This motivates a mode
500 * for interaction named 'touch mode'.
501 * </p>
502 * <p>
503 * For a touch capable device, once the user touches the screen, the device
504 * will enter touch mode. From this point onward, only views for which
505 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
506 * Other views that are touchable, like buttons, will not take focus when touched; they will
507 * only fire the on click listeners.
508 * </p>
509 * <p>
510 * Any time a user hits a directional key, such as a D-pad direction, the view device will
511 * exit touch mode, and find a view to take focus, so that the user may resume interacting
512 * with the user interface without touching the screen again.
513 * </p>
514 * <p>
515 * The touch mode state is maintained across {@link android.app.Activity}s. Call
516 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
517 * </p>
518 *
519 * <a name="Scrolling"></a>
520 * <h3>Scrolling</h3>
521 * <p>
522 * The framework provides basic support for views that wish to internally
523 * scroll their content. This includes keeping track of the X and Y scroll
524 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700525 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
526 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 * </p>
528 *
529 * <a name="Tags"></a>
530 * <h3>Tags</h3>
531 * <p>
532 * Unlike IDs, tags are not used to identify views. Tags are essentially an
533 * extra piece of information that can be associated with a view. They are most
534 * often used as a convenience to store data related to views in the views
535 * themselves rather than by putting them in a separate structure.
536 * </p>
537 *
538 * <a name="Animation"></a>
539 * <h3>Animation</h3>
540 * <p>
541 * You can attach an {@link Animation} object to a view using
542 * {@link #setAnimation(Animation)} or
543 * {@link #startAnimation(Animation)}. The animation can alter the scale,
544 * rotation, translation and alpha of a view over time. If the animation is
545 * attached to a view that has children, the animation will affect the entire
546 * subtree rooted by that node. When an animation is started, the framework will
547 * take care of redrawing the appropriate views until the animation completes.
548 * </p>
Romain Guy171c5922011-01-06 10:04:23 -0800549 * <p>
550 * Starting with Android 3.0, the preferred way of animating views is to use the
551 * {@link android.animation} package APIs.
552 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 *
Jeff Brown85a31762010-09-01 17:01:00 -0700554 * <a name="Security"></a>
555 * <h3>Security</h3>
556 * <p>
557 * Sometimes it is essential that an application be able to verify that an action
558 * is being performed with the full knowledge and consent of the user, such as
559 * granting a permission request, making a purchase or clicking on an advertisement.
560 * Unfortunately, a malicious application could try to spoof the user into
561 * performing these actions, unaware, by concealing the intended purpose of the view.
562 * As a remedy, the framework offers a touch filtering mechanism that can be used to
563 * improve the security of views that provide access to sensitive functionality.
564 * </p><p>
565 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
Jeff Brown49ed71d2010-12-06 17:13:33 -0800566 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework
Jeff Brown85a31762010-09-01 17:01:00 -0700567 * will discard touches that are received whenever the view's window is obscured by
568 * another visible window. As a result, the view will not receive touches whenever a
569 * toast, dialog or other window appears above the view's window.
570 * </p><p>
571 * For more fine-grained control over security, consider overriding the
572 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
573 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
574 * </p>
575 *
Romain Guy171c5922011-01-06 10:04:23 -0800576 * @attr ref android.R.styleable#View_alpha
Romain Guyd6a463a2009-05-21 23:10:10 -0700577 * @attr ref android.R.styleable#View_background
578 * @attr ref android.R.styleable#View_clickable
579 * @attr ref android.R.styleable#View_contentDescription
580 * @attr ref android.R.styleable#View_drawingCacheQuality
581 * @attr ref android.R.styleable#View_duplicateParentState
582 * @attr ref android.R.styleable#View_id
583 * @attr ref android.R.styleable#View_fadingEdge
584 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700585 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700587 * @attr ref android.R.styleable#View_isScrollContainer
588 * @attr ref android.R.styleable#View_focusable
589 * @attr ref android.R.styleable#View_focusableInTouchMode
590 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
591 * @attr ref android.R.styleable#View_keepScreenOn
Romain Guy171c5922011-01-06 10:04:23 -0800592 * @attr ref android.R.styleable#View_layerType
Romain Guyd6a463a2009-05-21 23:10:10 -0700593 * @attr ref android.R.styleable#View_longClickable
594 * @attr ref android.R.styleable#View_minHeight
595 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 * @attr ref android.R.styleable#View_nextFocusDown
597 * @attr ref android.R.styleable#View_nextFocusLeft
598 * @attr ref android.R.styleable#View_nextFocusRight
599 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700600 * @attr ref android.R.styleable#View_onClick
601 * @attr ref android.R.styleable#View_padding
602 * @attr ref android.R.styleable#View_paddingBottom
603 * @attr ref android.R.styleable#View_paddingLeft
604 * @attr ref android.R.styleable#View_paddingRight
605 * @attr ref android.R.styleable#View_paddingTop
606 * @attr ref android.R.styleable#View_saveEnabled
Chet Haase73066682010-11-29 15:55:32 -0800607 * @attr ref android.R.styleable#View_rotation
608 * @attr ref android.R.styleable#View_rotationX
609 * @attr ref android.R.styleable#View_rotationY
610 * @attr ref android.R.styleable#View_scaleX
611 * @attr ref android.R.styleable#View_scaleY
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 * @attr ref android.R.styleable#View_scrollX
613 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700614 * @attr ref android.R.styleable#View_scrollbarSize
615 * @attr ref android.R.styleable#View_scrollbarStyle
616 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700617 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
618 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
620 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 * @attr ref android.R.styleable#View_scrollbarThumbVertical
622 * @attr ref android.R.styleable#View_scrollbarTrackVertical
623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
624 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700625 * @attr ref android.R.styleable#View_soundEffectsEnabled
626 * @attr ref android.R.styleable#View_tag
Chet Haase73066682010-11-29 15:55:32 -0800627 * @attr ref android.R.styleable#View_transformPivotX
628 * @attr ref android.R.styleable#View_transformPivotY
629 * @attr ref android.R.styleable#View_translationX
630 * @attr ref android.R.styleable#View_translationY
Romain Guyd6a463a2009-05-21 23:10:10 -0700631 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 *
633 * @see android.view.ViewGroup
634 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700635public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 private static final boolean DBG = false;
637
638 /**
639 * The logging tag used by this class with android.util.Log.
640 */
641 protected static final String VIEW_LOG_TAG = "View";
642
643 /**
644 * Used to mark a View that has no ID.
645 */
646 public static final int NO_ID = -1;
647
648 /**
649 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
650 * calling setFlags.
651 */
652 private static final int NOT_FOCUSABLE = 0x00000000;
653
654 /**
655 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
656 * setFlags.
657 */
658 private static final int FOCUSABLE = 0x00000001;
659
660 /**
661 * Mask for use with setFlags indicating bits used for focus.
662 */
663 private static final int FOCUSABLE_MASK = 0x00000001;
664
665 /**
666 * This view will adjust its padding to fit sytem windows (e.g. status bar)
667 */
668 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
669
670 /**
671 * This view is visible. Use with {@link #setVisibility}.
672 */
673 public static final int VISIBLE = 0x00000000;
674
675 /**
676 * This view is invisible, but it still takes up space for layout purposes.
677 * Use with {@link #setVisibility}.
678 */
679 public static final int INVISIBLE = 0x00000004;
680
681 /**
682 * This view is invisible, and it doesn't take any space for layout
683 * purposes. Use with {@link #setVisibility}.
684 */
685 public static final int GONE = 0x00000008;
686
687 /**
688 * Mask for use with setFlags indicating bits used for visibility.
689 * {@hide}
690 */
691 static final int VISIBILITY_MASK = 0x0000000C;
692
693 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
694
695 /**
696 * This view is enabled. Intrepretation varies by subclass.
697 * Use with ENABLED_MASK when calling setFlags.
698 * {@hide}
699 */
700 static final int ENABLED = 0x00000000;
701
702 /**
703 * This view is disabled. Intrepretation varies by subclass.
704 * Use with ENABLED_MASK when calling setFlags.
705 * {@hide}
706 */
707 static final int DISABLED = 0x00000020;
708
709 /**
710 * Mask for use with setFlags indicating bits used for indicating whether
711 * this view is enabled
712 * {@hide}
713 */
714 static final int ENABLED_MASK = 0x00000020;
715
716 /**
717 * This view won't draw. {@link #onDraw} won't be called and further
718 * optimizations
719 * will be performed. It is okay to have this flag set and a background.
720 * Use with DRAW_MASK when calling setFlags.
721 * {@hide}
722 */
723 static final int WILL_NOT_DRAW = 0x00000080;
724
725 /**
726 * Mask for use with setFlags indicating bits used for indicating whether
727 * this view is will draw
728 * {@hide}
729 */
730 static final int DRAW_MASK = 0x00000080;
731
732 /**
733 * <p>This view doesn't show scrollbars.</p>
734 * {@hide}
735 */
736 static final int SCROLLBARS_NONE = 0x00000000;
737
738 /**
739 * <p>This view shows horizontal scrollbars.</p>
740 * {@hide}
741 */
742 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
743
744 /**
745 * <p>This view shows vertical scrollbars.</p>
746 * {@hide}
747 */
748 static final int SCROLLBARS_VERTICAL = 0x00000200;
749
750 /**
751 * <p>Mask for use with setFlags indicating bits used for indicating which
752 * scrollbars are enabled.</p>
753 * {@hide}
754 */
755 static final int SCROLLBARS_MASK = 0x00000300;
756
Jeff Brown85a31762010-09-01 17:01:00 -0700757 /**
758 * Indicates that the view should filter touches when its window is obscured.
759 * Refer to the class comments for more information about this security feature.
760 * {@hide}
761 */
762 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
763
764 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765
766 /**
767 * <p>This view doesn't show fading edges.</p>
768 * {@hide}
769 */
770 static final int FADING_EDGE_NONE = 0x00000000;
771
772 /**
773 * <p>This view shows horizontal fading edges.</p>
774 * {@hide}
775 */
776 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
777
778 /**
779 * <p>This view shows vertical fading edges.</p>
780 * {@hide}
781 */
782 static final int FADING_EDGE_VERTICAL = 0x00002000;
783
784 /**
785 * <p>Mask for use with setFlags indicating bits used for indicating which
786 * fading edges are enabled.</p>
787 * {@hide}
788 */
789 static final int FADING_EDGE_MASK = 0x00003000;
790
791 /**
792 * <p>Indicates this view can be clicked. When clickable, a View reacts
793 * to clicks by notifying the OnClickListener.<p>
794 * {@hide}
795 */
796 static final int CLICKABLE = 0x00004000;
797
798 /**
799 * <p>Indicates this view is caching its drawing into a bitmap.</p>
800 * {@hide}
801 */
802 static final int DRAWING_CACHE_ENABLED = 0x00008000;
803
804 /**
805 * <p>Indicates that no icicle should be saved for this view.<p>
806 * {@hide}
807 */
808 static final int SAVE_DISABLED = 0x000010000;
809
810 /**
811 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
812 * property.</p>
813 * {@hide}
814 */
815 static final int SAVE_DISABLED_MASK = 0x000010000;
816
817 /**
818 * <p>Indicates that no drawing cache should ever be created for this view.<p>
819 * {@hide}
820 */
821 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
822
823 /**
824 * <p>Indicates this view can take / keep focus when int touch mode.</p>
825 * {@hide}
826 */
827 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
828
829 /**
830 * <p>Enables low quality mode for the drawing cache.</p>
831 */
832 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
833
834 /**
835 * <p>Enables high quality mode for the drawing cache.</p>
836 */
837 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
838
839 /**
840 * <p>Enables automatic quality mode for the drawing cache.</p>
841 */
842 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
843
844 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
845 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
846 };
847
848 /**
849 * <p>Mask for use with setFlags indicating bits used for the cache
850 * quality property.</p>
851 * {@hide}
852 */
853 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
854
855 /**
856 * <p>
857 * Indicates this view can be long clicked. When long clickable, a View
858 * reacts to long clicks by notifying the OnLongClickListener or showing a
859 * context menu.
860 * </p>
861 * {@hide}
862 */
863 static final int LONG_CLICKABLE = 0x00200000;
864
865 /**
866 * <p>Indicates that this view gets its drawable states from its direct parent
867 * and ignores its original internal states.</p>
868 *
869 * @hide
870 */
871 static final int DUPLICATE_PARENT_STATE = 0x00400000;
872
873 /**
874 * The scrollbar style to display the scrollbars inside the content area,
875 * without increasing the padding. The scrollbars will be overlaid with
876 * translucency on the view's content.
877 */
878 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
879
880 /**
881 * The scrollbar style to display the scrollbars inside the padded area,
882 * increasing the padding of the view. The scrollbars will not overlap the
883 * content area of the view.
884 */
885 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
886
887 /**
888 * The scrollbar style to display the scrollbars at the edge of the view,
889 * without increasing the padding. The scrollbars will be overlaid with
890 * translucency.
891 */
892 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
893
894 /**
895 * The scrollbar style to display the scrollbars at the edge of the view,
896 * increasing the padding of the view. The scrollbars will only overlap the
897 * background, if any.
898 */
899 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
900
901 /**
902 * Mask to check if the scrollbar style is overlay or inset.
903 * {@hide}
904 */
905 static final int SCROLLBARS_INSET_MASK = 0x01000000;
906
907 /**
908 * Mask to check if the scrollbar style is inside or outside.
909 * {@hide}
910 */
911 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
912
913 /**
914 * Mask for scrollbar style.
915 * {@hide}
916 */
917 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
918
919 /**
920 * View flag indicating that the screen should remain on while the
921 * window containing this view is visible to the user. This effectively
922 * takes care of automatically setting the WindowManager's
923 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
924 */
925 public static final int KEEP_SCREEN_ON = 0x04000000;
926
927 /**
928 * View flag indicating whether this view should have sound effects enabled
929 * for events such as clicking and touching.
930 */
931 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
932
933 /**
934 * View flag indicating whether this view should have haptic feedback
935 * enabled for events such as long presses.
936 */
937 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
938
939 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700940 * <p>Indicates that the view hierarchy should stop saving state when
941 * it reaches this view. If state saving is initiated immediately at
942 * the view, it will be allowed.
943 * {@hide}
944 */
945 static final int PARENT_SAVE_DISABLED = 0x20000000;
946
947 /**
948 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
949 * {@hide}
950 */
951 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
952
953 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700954 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
955 * should add all focusable Views regardless if they are focusable in touch mode.
956 */
957 public static final int FOCUSABLES_ALL = 0x00000000;
958
959 /**
960 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
961 * should add only Views focusable in touch mode.
962 */
963 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
964
965 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 * Use with {@link #focusSearch}. Move focus to the previous selectable
967 * item.
968 */
969 public static final int FOCUS_BACKWARD = 0x00000001;
970
971 /**
972 * Use with {@link #focusSearch}. Move focus to the next selectable
973 * item.
974 */
975 public static final int FOCUS_FORWARD = 0x00000002;
976
977 /**
978 * Use with {@link #focusSearch}. Move focus to the left.
979 */
980 public static final int FOCUS_LEFT = 0x00000011;
981
982 /**
983 * Use with {@link #focusSearch}. Move focus up.
984 */
985 public static final int FOCUS_UP = 0x00000021;
986
987 /**
988 * Use with {@link #focusSearch}. Move focus to the right.
989 */
990 public static final int FOCUS_RIGHT = 0x00000042;
991
992 /**
993 * Use with {@link #focusSearch}. Move focus down.
994 */
995 public static final int FOCUS_DOWN = 0x00000082;
996
997 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -0800998 * Bits of {@link #getMeasuredWidthAndState()} and
999 * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1000 */
1001 public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1002
1003 /**
1004 * Bits of {@link #getMeasuredWidthAndState()} and
1005 * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1006 */
1007 public static final int MEASURED_STATE_MASK = 0xff000000;
1008
1009 /**
1010 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1011 * for functions that combine both width and height into a single int,
1012 * such as {@link #getMeasuredState()} and the childState argument of
1013 * {@link #resolveSizeAndState(int, int, int)}.
1014 */
1015 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1016
1017 /**
1018 * Bit of {@link #getMeasuredWidthAndState()} and
1019 * {@link #getMeasuredWidthAndState()} that indicates the measured size
1020 * is smaller that the space the view would like to have.
1021 */
1022 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1023
1024 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 * Base View state sets
1026 */
1027 // Singles
1028 /**
1029 * Indicates the view has no states set. 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[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 /**
1038 * Indicates the view is enabled. 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[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 /**
1047 * Indicates the view is focused. 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[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 /**
1056 * Indicates the view is selected. 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 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001063 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 /**
1065 * Indicates the view is pressed. States are used with
1066 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1067 * view depending on its state.
1068 *
1069 * @see android.graphics.drawable.Drawable
1070 * @see #getDrawableState()
1071 * @hide
1072 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001073 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 /**
1075 * Indicates the view's window has focus. States are used with
1076 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1077 * view depending on its state.
1078 *
1079 * @see android.graphics.drawable.Drawable
1080 * @see #getDrawableState()
1081 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001082 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 // Doubles
1084 /**
1085 * Indicates the view is enabled and has the focus.
1086 *
1087 * @see #ENABLED_STATE_SET
1088 * @see #FOCUSED_STATE_SET
1089 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001090 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 /**
1092 * Indicates the view is enabled and selected.
1093 *
1094 * @see #ENABLED_STATE_SET
1095 * @see #SELECTED_STATE_SET
1096 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001097 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 /**
1099 * Indicates the view is enabled and that its window has focus.
1100 *
1101 * @see #ENABLED_STATE_SET
1102 * @see #WINDOW_FOCUSED_STATE_SET
1103 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001104 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 /**
1106 * Indicates the view is focused and selected.
1107 *
1108 * @see #FOCUSED_STATE_SET
1109 * @see #SELECTED_STATE_SET
1110 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001111 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 /**
1113 * Indicates the view has the focus and that its window has the focus.
1114 *
1115 * @see #FOCUSED_STATE_SET
1116 * @see #WINDOW_FOCUSED_STATE_SET
1117 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001118 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 /**
1120 * Indicates the view is selected and that its window has the focus.
1121 *
1122 * @see #SELECTED_STATE_SET
1123 * @see #WINDOW_FOCUSED_STATE_SET
1124 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001125 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 // Triples
1127 /**
1128 * Indicates the view is enabled, focused and selected.
1129 *
1130 * @see #ENABLED_STATE_SET
1131 * @see #FOCUSED_STATE_SET
1132 * @see #SELECTED_STATE_SET
1133 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001134 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 /**
1136 * Indicates the view is enabled, focused and its window has the focus.
1137 *
1138 * @see #ENABLED_STATE_SET
1139 * @see #FOCUSED_STATE_SET
1140 * @see #WINDOW_FOCUSED_STATE_SET
1141 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001142 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 /**
1144 * Indicates the view is enabled, selected and its window has the focus.
1145 *
1146 * @see #ENABLED_STATE_SET
1147 * @see #SELECTED_STATE_SET
1148 * @see #WINDOW_FOCUSED_STATE_SET
1149 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001150 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 /**
1152 * Indicates the view is focused, selected and its window has the focus.
1153 *
1154 * @see #FOCUSED_STATE_SET
1155 * @see #SELECTED_STATE_SET
1156 * @see #WINDOW_FOCUSED_STATE_SET
1157 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001158 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 /**
1160 * Indicates the view is enabled, focused, selected and its window
1161 * has the focus.
1162 *
1163 * @see #ENABLED_STATE_SET
1164 * @see #FOCUSED_STATE_SET
1165 * @see #SELECTED_STATE_SET
1166 * @see #WINDOW_FOCUSED_STATE_SET
1167 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001168 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 /**
1170 * Indicates the view is pressed and its window has the focus.
1171 *
1172 * @see #PRESSED_STATE_SET
1173 * @see #WINDOW_FOCUSED_STATE_SET
1174 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001175 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 /**
1177 * Indicates the view is pressed and selected.
1178 *
1179 * @see #PRESSED_STATE_SET
1180 * @see #SELECTED_STATE_SET
1181 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001182 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 /**
1184 * Indicates the view is pressed, selected and its window has the focus.
1185 *
1186 * @see #PRESSED_STATE_SET
1187 * @see #SELECTED_STATE_SET
1188 * @see #WINDOW_FOCUSED_STATE_SET
1189 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001190 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 /**
1192 * Indicates the view is pressed and focused.
1193 *
1194 * @see #PRESSED_STATE_SET
1195 * @see #FOCUSED_STATE_SET
1196 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001197 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 /**
1199 * Indicates the view is pressed, focused and its window has the focus.
1200 *
1201 * @see #PRESSED_STATE_SET
1202 * @see #FOCUSED_STATE_SET
1203 * @see #WINDOW_FOCUSED_STATE_SET
1204 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001205 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 /**
1207 * Indicates the view is pressed, focused and selected.
1208 *
1209 * @see #PRESSED_STATE_SET
1210 * @see #SELECTED_STATE_SET
1211 * @see #FOCUSED_STATE_SET
1212 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001213 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 /**
1215 * Indicates the view is pressed, focused, selected and its window has the focus.
1216 *
1217 * @see #PRESSED_STATE_SET
1218 * @see #FOCUSED_STATE_SET
1219 * @see #SELECTED_STATE_SET
1220 * @see #WINDOW_FOCUSED_STATE_SET
1221 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001222 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 /**
1224 * Indicates the view is pressed and enabled.
1225 *
1226 * @see #PRESSED_STATE_SET
1227 * @see #ENABLED_STATE_SET
1228 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001229 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 /**
1231 * Indicates the view is pressed, enabled and its window has the focus.
1232 *
1233 * @see #PRESSED_STATE_SET
1234 * @see #ENABLED_STATE_SET
1235 * @see #WINDOW_FOCUSED_STATE_SET
1236 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001237 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 /**
1239 * Indicates the view is pressed, enabled and selected.
1240 *
1241 * @see #PRESSED_STATE_SET
1242 * @see #ENABLED_STATE_SET
1243 * @see #SELECTED_STATE_SET
1244 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001245 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 /**
1247 * Indicates the view is pressed, enabled, selected and its window has the
1248 * focus.
1249 *
1250 * @see #PRESSED_STATE_SET
1251 * @see #ENABLED_STATE_SET
1252 * @see #SELECTED_STATE_SET
1253 * @see #WINDOW_FOCUSED_STATE_SET
1254 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001255 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 /**
1257 * Indicates the view is pressed, enabled and focused.
1258 *
1259 * @see #PRESSED_STATE_SET
1260 * @see #ENABLED_STATE_SET
1261 * @see #FOCUSED_STATE_SET
1262 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001263 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 /**
1265 * Indicates the view is pressed, enabled, focused and its window has the
1266 * focus.
1267 *
1268 * @see #PRESSED_STATE_SET
1269 * @see #ENABLED_STATE_SET
1270 * @see #FOCUSED_STATE_SET
1271 * @see #WINDOW_FOCUSED_STATE_SET
1272 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001273 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 /**
1275 * Indicates the view is pressed, enabled, focused and selected.
1276 *
1277 * @see #PRESSED_STATE_SET
1278 * @see #ENABLED_STATE_SET
1279 * @see #SELECTED_STATE_SET
1280 * @see #FOCUSED_STATE_SET
1281 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001282 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 /**
1284 * Indicates the view is pressed, enabled, focused, selected and its window
1285 * has the focus.
1286 *
1287 * @see #PRESSED_STATE_SET
1288 * @see #ENABLED_STATE_SET
1289 * @see #SELECTED_STATE_SET
1290 * @see #FOCUSED_STATE_SET
1291 * @see #WINDOW_FOCUSED_STATE_SET
1292 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001293 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294
1295 /**
1296 * The order here is very important to {@link #getDrawableState()}
1297 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001298 private static final int[][] VIEW_STATE_SETS;
1299
Romain Guyb051e892010-09-28 19:09:36 -07001300 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1301 static final int VIEW_STATE_SELECTED = 1 << 1;
1302 static final int VIEW_STATE_FOCUSED = 1 << 2;
1303 static final int VIEW_STATE_ENABLED = 1 << 3;
1304 static final int VIEW_STATE_PRESSED = 1 << 4;
1305 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001306 static final int VIEW_STATE_ACCELERATED = 1 << 6;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001307
1308 static final int[] VIEW_STATE_IDS = new int[] {
1309 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1310 R.attr.state_selected, VIEW_STATE_SELECTED,
1311 R.attr.state_focused, VIEW_STATE_FOCUSED,
1312 R.attr.state_enabled, VIEW_STATE_ENABLED,
1313 R.attr.state_pressed, VIEW_STATE_PRESSED,
1314 R.attr.state_activated, VIEW_STATE_ACTIVATED,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001315 R.attr.state_accelerated, VIEW_STATE_ACCELERATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 };
1317
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001318 static {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001319 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1320 throw new IllegalStateException(
1321 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1322 }
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001323 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001324 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001325 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001326 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001327 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001328 orderedIds[i * 2] = viewState;
1329 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001330 }
1331 }
1332 }
Romain Guyb051e892010-09-28 19:09:36 -07001333 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1334 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1335 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001336 int numBits = Integer.bitCount(i);
1337 int[] set = new int[numBits];
1338 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001339 for (int j = 0; j < orderedIds.length; j += 2) {
1340 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001341 set[pos++] = orderedIds[j];
1342 }
1343 }
1344 VIEW_STATE_SETS[i] = set;
1345 }
1346
1347 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1348 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1349 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1350 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1351 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1352 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1353 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1354 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1355 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1356 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1357 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1358 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1359 | VIEW_STATE_FOCUSED];
1360 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1361 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1362 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1363 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1364 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1365 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1366 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1367 | VIEW_STATE_ENABLED];
1368 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1369 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1370 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1371 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1372 | VIEW_STATE_ENABLED];
1373 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1374 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1375 | VIEW_STATE_ENABLED];
1376 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1377 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1378 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1379
1380 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1381 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1382 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1383 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1384 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1385 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1386 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1387 | VIEW_STATE_PRESSED];
1388 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1389 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1390 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1391 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1392 | VIEW_STATE_PRESSED];
1393 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1394 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1395 | VIEW_STATE_PRESSED];
1396 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1397 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1398 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1399 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1400 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1401 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1402 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1403 | VIEW_STATE_PRESSED];
1404 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1405 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1406 | VIEW_STATE_PRESSED];
1407 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1408 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1409 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1410 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1411 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1412 | VIEW_STATE_PRESSED];
1413 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1414 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1415 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1416 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1418 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1419 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1420 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1421 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1422 | VIEW_STATE_PRESSED];
1423 }
1424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 /**
1426 * Used by views that contain lists of items. This state indicates that
1427 * the view is showing the last item.
1428 * @hide
1429 */
1430 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1431 /**
1432 * Used by views that contain lists of items. This state indicates that
1433 * the view is showing the first item.
1434 * @hide
1435 */
1436 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1437 /**
1438 * Used by views that contain lists of items. This state indicates that
1439 * the view is showing the middle item.
1440 * @hide
1441 */
1442 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1443 /**
1444 * Used by views that contain lists of items. This state indicates that
1445 * the view is showing only one item.
1446 * @hide
1447 */
1448 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1449 /**
1450 * Used by views that contain lists of items. This state indicates that
1451 * the view is pressed and showing the last item.
1452 * @hide
1453 */
1454 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1455 /**
1456 * Used by views that contain lists of items. This state indicates that
1457 * the view is pressed and showing the first item.
1458 * @hide
1459 */
1460 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1461 /**
1462 * Used by views that contain lists of items. This state indicates that
1463 * the view is pressed and showing the middle item.
1464 * @hide
1465 */
1466 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1467 /**
1468 * Used by views that contain lists of items. This state indicates that
1469 * the view is pressed and showing only one item.
1470 * @hide
1471 */
1472 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1473
1474 /**
1475 * Temporary Rect currently for use in setBackground(). This will probably
1476 * be extended in the future to hold our own class with more than just
1477 * a Rect. :)
1478 */
1479 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001480
1481 /**
1482 * Map used to store views' tags.
1483 */
1484 private static WeakHashMap<View, SparseArray<Object>> sTags;
1485
1486 /**
1487 * Lock used to access sTags.
1488 */
1489 private static final Object sTagsLock = new Object();
1490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 /**
1492 * The animation currently associated with this view.
1493 * @hide
1494 */
1495 protected Animation mCurrentAnimation = null;
1496
1497 /**
1498 * Width as measured during measure pass.
1499 * {@hide}
1500 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001501 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001502 /*package*/ int mMeasuredWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503
1504 /**
1505 * Height as measured during measure pass.
1506 * {@hide}
1507 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001508 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001509 /*package*/ int mMeasuredHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510
1511 /**
1512 * The view's identifier.
1513 * {@hide}
1514 *
1515 * @see #setId(int)
1516 * @see #getId()
1517 */
1518 @ViewDebug.ExportedProperty(resolveId = true)
1519 int mID = NO_ID;
1520
1521 /**
1522 * The view's tag.
1523 * {@hide}
1524 *
1525 * @see #setTag(Object)
1526 * @see #getTag()
1527 */
1528 protected Object mTag;
1529
1530 // for mPrivateFlags:
1531 /** {@hide} */
1532 static final int WANTS_FOCUS = 0x00000001;
1533 /** {@hide} */
1534 static final int FOCUSED = 0x00000002;
1535 /** {@hide} */
1536 static final int SELECTED = 0x00000004;
1537 /** {@hide} */
1538 static final int IS_ROOT_NAMESPACE = 0x00000008;
1539 /** {@hide} */
1540 static final int HAS_BOUNDS = 0x00000010;
1541 /** {@hide} */
1542 static final int DRAWN = 0x00000020;
1543 /**
1544 * When this flag is set, this view is running an animation on behalf of its
1545 * children and should therefore not cancel invalidate requests, even if they
1546 * lie outside of this view's bounds.
1547 *
1548 * {@hide}
1549 */
1550 static final int DRAW_ANIMATION = 0x00000040;
1551 /** {@hide} */
1552 static final int SKIP_DRAW = 0x00000080;
1553 /** {@hide} */
1554 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1555 /** {@hide} */
1556 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1557 /** {@hide} */
1558 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1559 /** {@hide} */
1560 static final int MEASURED_DIMENSION_SET = 0x00000800;
1561 /** {@hide} */
1562 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001563 /** {@hide} */
1564 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565
1566 private static final int PRESSED = 0x00004000;
1567
1568 /** {@hide} */
1569 static final int DRAWING_CACHE_VALID = 0x00008000;
1570 /**
1571 * Flag used to indicate that this view should be drawn once more (and only once
1572 * more) after its animation has completed.
1573 * {@hide}
1574 */
1575 static final int ANIMATION_STARTED = 0x00010000;
1576
1577 private static final int SAVE_STATE_CALLED = 0x00020000;
1578
1579 /**
1580 * Indicates that the View returned true when onSetAlpha() was called and that
1581 * the alpha must be restored.
1582 * {@hide}
1583 */
1584 static final int ALPHA_SET = 0x00040000;
1585
1586 /**
1587 * Set by {@link #setScrollContainer(boolean)}.
1588 */
1589 static final int SCROLL_CONTAINER = 0x00080000;
1590
1591 /**
1592 * Set by {@link #setScrollContainer(boolean)}.
1593 */
1594 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1595
1596 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001597 * View flag indicating whether this view was invalidated (fully or partially.)
1598 *
1599 * @hide
1600 */
1601 static final int DIRTY = 0x00200000;
1602
1603 /**
1604 * View flag indicating whether this view was invalidated by an opaque
1605 * invalidate request.
1606 *
1607 * @hide
1608 */
1609 static final int DIRTY_OPAQUE = 0x00400000;
1610
1611 /**
1612 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1613 *
1614 * @hide
1615 */
1616 static final int DIRTY_MASK = 0x00600000;
1617
1618 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001619 * Indicates whether the background is opaque.
1620 *
1621 * @hide
1622 */
1623 static final int OPAQUE_BACKGROUND = 0x00800000;
1624
1625 /**
1626 * Indicates whether the scrollbars are opaque.
1627 *
1628 * @hide
1629 */
1630 static final int OPAQUE_SCROLLBARS = 0x01000000;
1631
1632 /**
1633 * Indicates whether the view is opaque.
1634 *
1635 * @hide
1636 */
1637 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001638
1639 /**
1640 * Indicates a prepressed state;
1641 * the short time between ACTION_DOWN and recognizing
1642 * a 'real' press. Prepressed is used to recognize quick taps
1643 * even when they are shorter than ViewConfiguration.getTapTimeout().
1644 *
1645 * @hide
1646 */
1647 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001648
1649 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001650 * Indicates whether the view is temporarily detached.
1651 *
1652 * @hide
1653 */
1654 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001655
1656 /**
1657 * Indicates that we should awaken scroll bars once attached
1658 *
1659 * @hide
1660 */
1661 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001662
1663 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001664 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1665 * for transform operations
1666 *
1667 * @hide
1668 */
Adam Powellf37df072010-09-17 16:22:49 -07001669 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001670
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001671 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001672 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001673
Chet Haasefd2b0022010-08-06 13:08:56 -07001674 /**
Adam Powell637d3372010-08-25 14:37:03 -07001675 * Always allow a user to over-scroll this view, provided it is a
1676 * view that can scroll.
1677 *
1678 * @see #getOverScrollMode()
1679 * @see #setOverScrollMode(int)
1680 */
1681 public static final int OVER_SCROLL_ALWAYS = 0;
1682
1683 /**
1684 * Allow a user to over-scroll this view only if the content is large
1685 * enough to meaningfully scroll, provided it is a view that can scroll.
1686 *
1687 * @see #getOverScrollMode()
1688 * @see #setOverScrollMode(int)
1689 */
1690 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1691
1692 /**
1693 * Never allow a user to over-scroll this view.
1694 *
1695 * @see #getOverScrollMode()
1696 * @see #setOverScrollMode(int)
1697 */
1698 public static final int OVER_SCROLL_NEVER = 2;
1699
1700 /**
1701 * Controls the over-scroll mode for this view.
1702 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1703 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1704 * and {@link #OVER_SCROLL_NEVER}.
1705 */
1706 private int mOverScrollMode;
1707
1708 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 * The parent this view is attached to.
1710 * {@hide}
1711 *
1712 * @see #getParent()
1713 */
1714 protected ViewParent mParent;
1715
1716 /**
1717 * {@hide}
1718 */
1719 AttachInfo mAttachInfo;
1720
1721 /**
1722 * {@hide}
1723 */
Romain Guy809a7f62009-05-14 15:44:42 -07001724 @ViewDebug.ExportedProperty(flagMapping = {
1725 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1726 name = "FORCE_LAYOUT"),
1727 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1728 name = "LAYOUT_REQUIRED"),
1729 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001730 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001731 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1732 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1733 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1734 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1735 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 int mPrivateFlags;
1737
1738 /**
1739 * Count of how many windows this view has been attached to.
1740 */
1741 int mWindowAttachCount;
1742
1743 /**
1744 * The layout parameters associated with this view and used by the parent
1745 * {@link android.view.ViewGroup} to determine how this view should be
1746 * laid out.
1747 * {@hide}
1748 */
1749 protected ViewGroup.LayoutParams mLayoutParams;
1750
1751 /**
1752 * The view flags hold various views states.
1753 * {@hide}
1754 */
1755 @ViewDebug.ExportedProperty
1756 int mViewFlags;
1757
1758 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001759 * 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
1762 * getMatrix(), which will automatically recalculate the matrix if necessary
1763 * to get the correct matrix based on the latest rotation and scale properties.
1764 */
1765 private final Matrix mMatrix = new Matrix();
1766
1767 /**
1768 * The transform matrix for the View. This transform is calculated internally
1769 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1770 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001771 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001772 * to get the correct matrix based on the latest rotation and scale properties.
1773 */
1774 private Matrix mInverseMatrix;
1775
1776 /**
1777 * An internal variable that tracks whether we need to recalculate the
1778 * transform matrix, based on whether the rotation or scaleX/Y properties
1779 * have changed since the matrix was last calculated.
1780 */
1781 private boolean mMatrixDirty = false;
1782
1783 /**
1784 * An internal variable that tracks whether we need to recalculate the
1785 * transform matrix, based on whether the rotation or scaleX/Y properties
1786 * have changed since the matrix was last calculated.
1787 */
1788 private boolean mInverseMatrixDirty = true;
1789
1790 /**
1791 * A variable that tracks whether we need to recalculate the
1792 * transform matrix, based on whether the rotation or scaleX/Y properties
1793 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001794 * is only valid after a call to updateMatrix() or to a function that
1795 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001796 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001797 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001798
1799 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001800 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1801 */
1802 private Camera mCamera = null;
1803
1804 /**
1805 * This matrix is used when computing the matrix for 3D rotations.
1806 */
1807 private Matrix matrix3D = null;
1808
1809 /**
1810 * These prev values are used to recalculate a centered pivot point when necessary. The
1811 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1812 * set), so thes values are only used then as well.
1813 */
1814 private int mPrevWidth = -1;
1815 private int mPrevHeight = -1;
1816
1817 /**
1818 * Convenience value to check for float values that are close enough to zero to be considered
1819 * zero.
1820 */
Romain Guy2542d192010-08-18 11:47:12 -07001821 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001822
1823 /**
1824 * The degrees rotation around the vertical axis through the pivot point.
1825 */
1826 @ViewDebug.ExportedProperty
1827 private float mRotationY = 0f;
1828
1829 /**
1830 * The degrees rotation around the horizontal axis through the pivot point.
1831 */
1832 @ViewDebug.ExportedProperty
1833 private float mRotationX = 0f;
1834
1835 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001836 * The degrees rotation around the pivot point.
1837 */
1838 @ViewDebug.ExportedProperty
1839 private float mRotation = 0f;
1840
1841 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001842 * The amount of translation of the object away from its left property (post-layout).
1843 */
1844 @ViewDebug.ExportedProperty
1845 private float mTranslationX = 0f;
1846
1847 /**
1848 * The amount of translation of the object away from its top property (post-layout).
1849 */
1850 @ViewDebug.ExportedProperty
1851 private float mTranslationY = 0f;
1852
1853 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001854 * The amount of scale in the x direction around the pivot point. A
1855 * value of 1 means no scaling is applied.
1856 */
1857 @ViewDebug.ExportedProperty
1858 private float mScaleX = 1f;
1859
1860 /**
1861 * The amount of scale in the y direction around the pivot point. A
1862 * value of 1 means no scaling is applied.
1863 */
1864 @ViewDebug.ExportedProperty
1865 private float mScaleY = 1f;
1866
1867 /**
1868 * The amount of scale in the x direction around the pivot point. A
1869 * value of 1 means no scaling is applied.
1870 */
1871 @ViewDebug.ExportedProperty
1872 private float mPivotX = 0f;
1873
1874 /**
1875 * The amount of scale in the y direction around the pivot point. A
1876 * value of 1 means no scaling is applied.
1877 */
1878 @ViewDebug.ExportedProperty
1879 private float mPivotY = 0f;
1880
1881 /**
1882 * The opacity of the View. This is a value from 0 to 1, where 0 means
1883 * completely transparent and 1 means completely opaque.
1884 */
1885 @ViewDebug.ExportedProperty
1886 private float mAlpha = 1f;
1887
1888 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 * The distance in pixels from the left edge of this view's parent
1890 * to the left edge of this view.
1891 * {@hide}
1892 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001893 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 protected int mLeft;
1895 /**
1896 * The distance in pixels from the left edge of this view's parent
1897 * to the right edge of this view.
1898 * {@hide}
1899 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001900 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 protected int mRight;
1902 /**
1903 * The distance in pixels from the top edge of this view's parent
1904 * to the top edge of this view.
1905 * {@hide}
1906 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001907 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 protected int mTop;
1909 /**
1910 * The distance in pixels from the top edge of this view's parent
1911 * to the bottom edge of this view.
1912 * {@hide}
1913 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001914 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 protected int mBottom;
1916
1917 /**
1918 * The offset, in pixels, by which the content of this view is scrolled
1919 * horizontally.
1920 * {@hide}
1921 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001922 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 protected int mScrollX;
1924 /**
1925 * The offset, in pixels, by which the content of this view is scrolled
1926 * vertically.
1927 * {@hide}
1928 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001929 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 protected int mScrollY;
1931
1932 /**
1933 * The left padding in pixels, that is the distance in pixels between the
1934 * left edge of this view and the left edge of its content.
1935 * {@hide}
1936 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001937 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 protected int mPaddingLeft;
1939 /**
1940 * The right padding in pixels, that is the distance in pixels between the
1941 * right edge of this view and the right edge of its content.
1942 * {@hide}
1943 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001944 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 protected int mPaddingRight;
1946 /**
1947 * The top padding in pixels, that is the distance in pixels between the
1948 * top edge of this view and the top edge of its content.
1949 * {@hide}
1950 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001951 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 protected int mPaddingTop;
1953 /**
1954 * The bottom padding in pixels, that is the distance in pixels between the
1955 * bottom edge of this view and the bottom edge of its content.
1956 * {@hide}
1957 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001958 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 protected int mPaddingBottom;
1960
1961 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001962 * Briefly describes the view and is primarily used for accessibility support.
1963 */
1964 private CharSequence mContentDescription;
1965
1966 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 * Cache the paddingRight set by the user to append to the scrollbar's size.
1968 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001969 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 int mUserPaddingRight;
1971
1972 /**
1973 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1974 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001975 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 int mUserPaddingBottom;
1977
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001978 /**
Adam Powell20232d02010-12-08 21:08:53 -08001979 * Cache the paddingLeft set by the user to append to the scrollbar's size.
1980 */
1981 @ViewDebug.ExportedProperty(category = "padding")
1982 int mUserPaddingLeft;
1983
1984 /**
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001985 * @hide
1986 */
1987 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1988 /**
1989 * @hide
1990 */
1991 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992
1993 private Resources mResources = null;
1994
1995 private Drawable mBGDrawable;
1996
1997 private int mBackgroundResource;
1998 private boolean mBackgroundSizeChanged;
1999
2000 /**
2001 * Listener used to dispatch focus change events.
2002 * This field should be made private, so it is hidden from the SDK.
2003 * {@hide}
2004 */
2005 protected OnFocusChangeListener mOnFocusChangeListener;
2006
2007 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002008 * Listeners for layout change events.
2009 */
2010 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2011
2012 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 * Listener used to dispatch click events.
2014 * This field should be made private, so it is hidden from the SDK.
2015 * {@hide}
2016 */
2017 protected OnClickListener mOnClickListener;
2018
2019 /**
2020 * Listener used to dispatch long click events.
2021 * This field should be made private, so it is hidden from the SDK.
2022 * {@hide}
2023 */
2024 protected OnLongClickListener mOnLongClickListener;
2025
2026 /**
2027 * Listener used to build the context menu.
2028 * This field should be made private, so it is hidden from the SDK.
2029 * {@hide}
2030 */
2031 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2032
2033 private OnKeyListener mOnKeyListener;
2034
2035 private OnTouchListener mOnTouchListener;
2036
Chris Tate32affef2010-10-18 15:29:21 -07002037 private OnDragListener mOnDragListener;
2038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 /**
2040 * The application environment this view lives in.
2041 * This field should be made private, so it is hidden from the SDK.
2042 * {@hide}
2043 */
2044 protected Context mContext;
2045
2046 private ScrollabilityCache mScrollCache;
2047
2048 private int[] mDrawableState = null;
2049
Romain Guy02890fd2010-08-06 17:58:44 -07002050 private Bitmap mDrawingCache;
2051 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07002052 private DisplayList mDisplayList;
Romain Guy6c319ca2011-01-11 14:29:25 -08002053 private HardwareLayer mHardwareLayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054
2055 /**
2056 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2057 * the user may specify which view to go to next.
2058 */
2059 private int mNextFocusLeftId = View.NO_ID;
2060
2061 /**
2062 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2063 * the user may specify which view to go to next.
2064 */
2065 private int mNextFocusRightId = View.NO_ID;
2066
2067 /**
2068 * When this view has focus and the next focus is {@link #FOCUS_UP},
2069 * the user may specify which view to go to next.
2070 */
2071 private int mNextFocusUpId = View.NO_ID;
2072
2073 /**
2074 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2075 * the user may specify which view to go to next.
2076 */
2077 private int mNextFocusDownId = View.NO_ID;
2078
Jeff Brown4e6319b2010-12-13 10:36:51 -08002079 /**
2080 * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2081 * the user may specify which view to go to next.
2082 */
2083 int mNextFocusForwardId = View.NO_ID;
2084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08002086 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08002087 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08002088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 private UnsetPressedState mUnsetPressedState;
2090
2091 /**
2092 * Whether the long press's action has been invoked. The tap's action is invoked on the
2093 * up event while a long press is invoked as soon as the long press duration is reached, so
2094 * a long press could be performed before the tap is checked, in which case the tap's action
2095 * should not be invoked.
2096 */
2097 private boolean mHasPerformedLongPress;
2098
2099 /**
2100 * The minimum height of the view. We'll try our best to have the height
2101 * of this view to at least this amount.
2102 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002103 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 private int mMinHeight;
2105
2106 /**
2107 * The minimum width of the view. We'll try our best to have the width
2108 * of this view to at least this amount.
2109 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002110 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 private int mMinWidth;
2112
2113 /**
2114 * The delegate to handle touch events that are physically in this view
2115 * but should be handled by another view.
2116 */
2117 private TouchDelegate mTouchDelegate = null;
2118
2119 /**
2120 * Solid color to use as a background when creating the drawing cache. Enables
2121 * the cache to use 16 bit bitmaps instead of 32 bit.
2122 */
2123 private int mDrawingCacheBackgroundColor = 0;
2124
2125 /**
2126 * Special tree observer used when mAttachInfo is null.
2127 */
2128 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002129
2130 /**
2131 * Cache the touch slop from the context that created the view.
2132 */
2133 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002136 * Cache drag/drop state
2137 *
2138 */
2139 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002140
2141 /**
Christopher Tate02d2b3b2011-01-10 20:43:53 -08002142 * Flag indicating that a drag can cross window boundaries
2143 * @hide
2144 */
2145 public static final int DRAG_FLAG_GLOBAL = 1;
2146
2147 /**
Adam Powell20232d02010-12-08 21:08:53 -08002148 * Position of the vertical scroll bar.
2149 */
2150 private int mVerticalScrollbarPosition;
2151
2152 /**
2153 * Position the scroll bar at the default position as determined by the system.
2154 */
2155 public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2156
2157 /**
2158 * Position the scroll bar along the left edge.
2159 */
2160 public static final int SCROLLBAR_POSITION_LEFT = 1;
2161
2162 /**
2163 * Position the scroll bar along the right edge.
2164 */
2165 public static final int SCROLLBAR_POSITION_RIGHT = 2;
2166
2167 /**
Romain Guy171c5922011-01-06 10:04:23 -08002168 * Indicates that the view does not have a layer.
2169 *
2170 * @see #getLayerType()
2171 * @see #setLayerType(int, android.graphics.Paint)
2172 * @see #LAYER_TYPE_SOFTWARE
2173 * @see #LAYER_TYPE_HARDWARE
2174 */
2175 public static final int LAYER_TYPE_NONE = 0;
2176
2177 /**
2178 * <p>Indicates that the view has a software layer. A software layer is backed
2179 * by a bitmap and causes the view to be rendered using Android's software
2180 * rendering pipeline, even if hardware acceleration is enabled.</p>
2181 *
2182 * <p>Software layers have various usages:</p>
2183 * <p>When the application is not using hardware acceleration, a software layer
2184 * is useful to apply a specific color filter and/or blending mode and/or
2185 * translucency to a view and all its children.</p>
2186 * <p>When the application is using hardware acceleration, a software layer
2187 * is useful to render drawing primitives not supported by the hardware
2188 * accelerated pipeline. It can also be used to cache a complex view tree
2189 * into a texture and reduce the complexity of drawing operations. For instance,
2190 * when animating a complex view tree with a translation, a software layer can
2191 * be used to render the view tree only once.</p>
2192 * <p>Software layers should be avoided when the affected view tree updates
2193 * often. Every update will require to re-render the software layer, which can
2194 * potentially be slow (particularly when hardware acceleration is turned on
2195 * since the layer will have to be uploaded into a hardware texture after every
2196 * update.)</p>
2197 *
2198 * @see #getLayerType()
2199 * @see #setLayerType(int, android.graphics.Paint)
2200 * @see #LAYER_TYPE_NONE
2201 * @see #LAYER_TYPE_HARDWARE
2202 */
2203 public static final int LAYER_TYPE_SOFTWARE = 1;
2204
2205 /**
2206 * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2207 * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2208 * OpenGL hardware) and causes the view to be rendered using Android's hardware
2209 * rendering pipeline, but only if hardware acceleration is turned on for the
2210 * view hierarchy. When hardware acceleration is turned off, hardware layers
2211 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2212 *
2213 * <p>A hardware layer is useful to apply a specific color filter and/or
2214 * blending mode and/or translucency to a view and all its children.</p>
Romain Guy6c319ca2011-01-11 14:29:25 -08002215 * <p>A hardware layer can be used to cache a complex view tree into a
2216 * texture and reduce the complexity of drawing operations. For instance,
2217 * when animating a complex view tree with a translation, a hardware layer can
2218 * be used to render the view tree only once.</p>
Romain Guy171c5922011-01-06 10:04:23 -08002219 * <p>A hardware layer can also be used to increase the rendering quality when
2220 * rotation transformations are applied on a view. It can also be used to
2221 * prevent potential clipping issues when applying 3D transforms on a view.</p>
2222 *
2223 * @see #getLayerType()
2224 * @see #setLayerType(int, android.graphics.Paint)
2225 * @see #LAYER_TYPE_NONE
2226 * @see #LAYER_TYPE_SOFTWARE
2227 */
2228 public static final int LAYER_TYPE_HARDWARE = 2;
2229
Romain Guy3aaff3a2011-01-12 14:18:47 -08002230 @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2231 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2232 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2233 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2234 })
Romain Guy171c5922011-01-06 10:04:23 -08002235 int mLayerType = LAYER_TYPE_NONE;
2236 Paint mLayerPaint;
2237
2238 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 * Simple constructor to use when creating a view from code.
2240 *
2241 * @param context The Context the view is running in, through which it can
2242 * access the current theme, resources, etc.
2243 */
2244 public View(Context context) {
2245 mContext = context;
2246 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002247 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002248 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Adam Powell637d3372010-08-25 14:37:03 -07002249 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
2251
2252 /**
2253 * Constructor that is called when inflating a view from XML. This is called
2254 * when a view is being constructed from an XML file, supplying attributes
2255 * that were specified in the XML file. This version uses a default style of
2256 * 0, so the only attribute values applied are those in the Context's Theme
2257 * and the given AttributeSet.
2258 *
2259 * <p>
2260 * The method onFinishInflate() will be called after all children have been
2261 * added.
2262 *
2263 * @param context The Context the view is running in, through which it can
2264 * access the current theme, resources, etc.
2265 * @param attrs The attributes of the XML tag that is inflating the view.
2266 * @see #View(Context, AttributeSet, int)
2267 */
2268 public View(Context context, AttributeSet attrs) {
2269 this(context, attrs, 0);
2270 }
2271
2272 /**
2273 * Perform inflation from XML and apply a class-specific base style. This
2274 * constructor of View allows subclasses to use their own base style when
2275 * they are inflating. For example, a Button class's constructor would call
2276 * this version of the super class constructor and supply
2277 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2278 * the theme's button style to modify all of the base view attributes (in
2279 * particular its background) as well as the Button class's attributes.
2280 *
2281 * @param context The Context the view is running in, through which it can
2282 * access the current theme, resources, etc.
2283 * @param attrs The attributes of the XML tag that is inflating the view.
2284 * @param defStyle The default style to apply to this view. If 0, no style
2285 * will be applied (beyond what is included in the theme). This may
2286 * either be an attribute resource, whose value will be retrieved
2287 * from the current theme, or an explicit style resource.
2288 * @see #View(Context, AttributeSet)
2289 */
2290 public View(Context context, AttributeSet attrs, int defStyle) {
2291 this(context);
2292
2293 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2294 defStyle, 0);
2295
2296 Drawable background = null;
2297
2298 int leftPadding = -1;
2299 int topPadding = -1;
2300 int rightPadding = -1;
2301 int bottomPadding = -1;
2302
2303 int padding = -1;
2304
2305 int viewFlagValues = 0;
2306 int viewFlagMasks = 0;
2307
2308 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 int x = 0;
2311 int y = 0;
2312
Chet Haase73066682010-11-29 15:55:32 -08002313 float tx = 0;
2314 float ty = 0;
2315 float rotation = 0;
2316 float rotationX = 0;
2317 float rotationY = 0;
2318 float sx = 1f;
2319 float sy = 1f;
2320 boolean transformSet = false;
2321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2323
Adam Powell637d3372010-08-25 14:37:03 -07002324 int overScrollMode = mOverScrollMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 final int N = a.getIndexCount();
2326 for (int i = 0; i < N; i++) {
2327 int attr = a.getIndex(i);
2328 switch (attr) {
2329 case com.android.internal.R.styleable.View_background:
2330 background = a.getDrawable(attr);
2331 break;
2332 case com.android.internal.R.styleable.View_padding:
2333 padding = a.getDimensionPixelSize(attr, -1);
2334 break;
2335 case com.android.internal.R.styleable.View_paddingLeft:
2336 leftPadding = a.getDimensionPixelSize(attr, -1);
2337 break;
2338 case com.android.internal.R.styleable.View_paddingTop:
2339 topPadding = a.getDimensionPixelSize(attr, -1);
2340 break;
2341 case com.android.internal.R.styleable.View_paddingRight:
2342 rightPadding = a.getDimensionPixelSize(attr, -1);
2343 break;
2344 case com.android.internal.R.styleable.View_paddingBottom:
2345 bottomPadding = a.getDimensionPixelSize(attr, -1);
2346 break;
2347 case com.android.internal.R.styleable.View_scrollX:
2348 x = a.getDimensionPixelOffset(attr, 0);
2349 break;
2350 case com.android.internal.R.styleable.View_scrollY:
2351 y = a.getDimensionPixelOffset(attr, 0);
2352 break;
Chet Haase73066682010-11-29 15:55:32 -08002353 case com.android.internal.R.styleable.View_alpha:
2354 setAlpha(a.getFloat(attr, 1f));
2355 break;
2356 case com.android.internal.R.styleable.View_transformPivotX:
2357 setPivotX(a.getDimensionPixelOffset(attr, 0));
2358 break;
2359 case com.android.internal.R.styleable.View_transformPivotY:
2360 setPivotY(a.getDimensionPixelOffset(attr, 0));
2361 break;
2362 case com.android.internal.R.styleable.View_translationX:
2363 tx = a.getDimensionPixelOffset(attr, 0);
2364 transformSet = true;
2365 break;
2366 case com.android.internal.R.styleable.View_translationY:
2367 ty = a.getDimensionPixelOffset(attr, 0);
2368 transformSet = true;
2369 break;
2370 case com.android.internal.R.styleable.View_rotation:
2371 rotation = a.getFloat(attr, 0);
2372 transformSet = true;
2373 break;
2374 case com.android.internal.R.styleable.View_rotationX:
2375 rotationX = a.getFloat(attr, 0);
2376 transformSet = true;
2377 break;
2378 case com.android.internal.R.styleable.View_rotationY:
2379 rotationY = a.getFloat(attr, 0);
2380 transformSet = true;
2381 break;
2382 case com.android.internal.R.styleable.View_scaleX:
2383 sx = a.getFloat(attr, 1f);
2384 transformSet = true;
2385 break;
2386 case com.android.internal.R.styleable.View_scaleY:
2387 sy = a.getFloat(attr, 1f);
2388 transformSet = true;
2389 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 case com.android.internal.R.styleable.View_id:
2391 mID = a.getResourceId(attr, NO_ID);
2392 break;
2393 case com.android.internal.R.styleable.View_tag:
2394 mTag = a.getText(attr);
2395 break;
2396 case com.android.internal.R.styleable.View_fitsSystemWindows:
2397 if (a.getBoolean(attr, false)) {
2398 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2399 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2400 }
2401 break;
2402 case com.android.internal.R.styleable.View_focusable:
2403 if (a.getBoolean(attr, false)) {
2404 viewFlagValues |= FOCUSABLE;
2405 viewFlagMasks |= FOCUSABLE_MASK;
2406 }
2407 break;
2408 case com.android.internal.R.styleable.View_focusableInTouchMode:
2409 if (a.getBoolean(attr, false)) {
2410 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2411 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2412 }
2413 break;
2414 case com.android.internal.R.styleable.View_clickable:
2415 if (a.getBoolean(attr, false)) {
2416 viewFlagValues |= CLICKABLE;
2417 viewFlagMasks |= CLICKABLE;
2418 }
2419 break;
2420 case com.android.internal.R.styleable.View_longClickable:
2421 if (a.getBoolean(attr, false)) {
2422 viewFlagValues |= LONG_CLICKABLE;
2423 viewFlagMasks |= LONG_CLICKABLE;
2424 }
2425 break;
2426 case com.android.internal.R.styleable.View_saveEnabled:
2427 if (!a.getBoolean(attr, true)) {
2428 viewFlagValues |= SAVE_DISABLED;
2429 viewFlagMasks |= SAVE_DISABLED_MASK;
2430 }
2431 break;
2432 case com.android.internal.R.styleable.View_duplicateParentState:
2433 if (a.getBoolean(attr, false)) {
2434 viewFlagValues |= DUPLICATE_PARENT_STATE;
2435 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2436 }
2437 break;
2438 case com.android.internal.R.styleable.View_visibility:
2439 final int visibility = a.getInt(attr, 0);
2440 if (visibility != 0) {
2441 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2442 viewFlagMasks |= VISIBILITY_MASK;
2443 }
2444 break;
2445 case com.android.internal.R.styleable.View_drawingCacheQuality:
2446 final int cacheQuality = a.getInt(attr, 0);
2447 if (cacheQuality != 0) {
2448 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2449 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2450 }
2451 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002452 case com.android.internal.R.styleable.View_contentDescription:
2453 mContentDescription = a.getString(attr);
2454 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2456 if (!a.getBoolean(attr, true)) {
2457 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2458 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2459 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002460 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2462 if (!a.getBoolean(attr, true)) {
2463 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2464 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2465 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002466 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 case R.styleable.View_scrollbars:
2468 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2469 if (scrollbars != SCROLLBARS_NONE) {
2470 viewFlagValues |= scrollbars;
2471 viewFlagMasks |= SCROLLBARS_MASK;
2472 initializeScrollbars(a);
2473 }
2474 break;
2475 case R.styleable.View_fadingEdge:
2476 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2477 if (fadingEdge != FADING_EDGE_NONE) {
2478 viewFlagValues |= fadingEdge;
2479 viewFlagMasks |= FADING_EDGE_MASK;
2480 initializeFadingEdge(a);
2481 }
2482 break;
2483 case R.styleable.View_scrollbarStyle:
2484 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2485 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2486 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2487 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2488 }
2489 break;
2490 case R.styleable.View_isScrollContainer:
2491 setScrollContainer = true;
2492 if (a.getBoolean(attr, false)) {
2493 setScrollContainer(true);
2494 }
2495 break;
2496 case com.android.internal.R.styleable.View_keepScreenOn:
2497 if (a.getBoolean(attr, false)) {
2498 viewFlagValues |= KEEP_SCREEN_ON;
2499 viewFlagMasks |= KEEP_SCREEN_ON;
2500 }
2501 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002502 case R.styleable.View_filterTouchesWhenObscured:
2503 if (a.getBoolean(attr, false)) {
2504 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2505 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2506 }
2507 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 case R.styleable.View_nextFocusLeft:
2509 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2510 break;
2511 case R.styleable.View_nextFocusRight:
2512 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2513 break;
2514 case R.styleable.View_nextFocusUp:
2515 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2516 break;
2517 case R.styleable.View_nextFocusDown:
2518 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2519 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002520 case R.styleable.View_nextFocusForward:
2521 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2522 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 case R.styleable.View_minWidth:
2524 mMinWidth = a.getDimensionPixelSize(attr, 0);
2525 break;
2526 case R.styleable.View_minHeight:
2527 mMinHeight = a.getDimensionPixelSize(attr, 0);
2528 break;
Romain Guy9a817362009-05-01 10:57:14 -07002529 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002530 if (context.isRestricted()) {
2531 throw new IllegalStateException("The android:onClick attribute cannot "
2532 + "be used within a restricted context");
2533 }
2534
Romain Guy9a817362009-05-01 10:57:14 -07002535 final String handlerName = a.getString(attr);
2536 if (handlerName != null) {
2537 setOnClickListener(new OnClickListener() {
2538 private Method mHandler;
2539
2540 public void onClick(View v) {
2541 if (mHandler == null) {
2542 try {
2543 mHandler = getContext().getClass().getMethod(handlerName,
2544 View.class);
2545 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002546 int id = getId();
2547 String idText = id == NO_ID ? "" : " with id '"
2548 + getContext().getResources().getResourceEntryName(
2549 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002550 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002551 handlerName + "(View) in the activity "
2552 + getContext().getClass() + " for onClick handler"
2553 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002554 }
2555 }
2556
2557 try {
2558 mHandler.invoke(getContext(), View.this);
2559 } catch (IllegalAccessException e) {
2560 throw new IllegalStateException("Could not execute non "
2561 + "public method of the activity", e);
2562 } catch (InvocationTargetException e) {
2563 throw new IllegalStateException("Could not execute "
2564 + "method of the activity", e);
2565 }
2566 }
2567 });
2568 }
2569 break;
Adam Powell637d3372010-08-25 14:37:03 -07002570 case R.styleable.View_overScrollMode:
2571 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2572 break;
Adam Powell20232d02010-12-08 21:08:53 -08002573 case R.styleable.View_verticalScrollbarPosition:
2574 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2575 break;
Romain Guy171c5922011-01-06 10:04:23 -08002576 case R.styleable.View_layerType:
2577 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
2578 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 }
2580 }
2581
Adam Powell637d3372010-08-25 14:37:03 -07002582 setOverScrollMode(overScrollMode);
2583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 if (background != null) {
2585 setBackgroundDrawable(background);
2586 }
2587
2588 if (padding >= 0) {
2589 leftPadding = padding;
2590 topPadding = padding;
2591 rightPadding = padding;
2592 bottomPadding = padding;
2593 }
2594
2595 // If the user specified the padding (either with android:padding or
2596 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2597 // use the default padding or the padding from the background drawable
2598 // (stored at this point in mPadding*)
2599 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2600 topPadding >= 0 ? topPadding : mPaddingTop,
2601 rightPadding >= 0 ? rightPadding : mPaddingRight,
2602 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2603
2604 if (viewFlagMasks != 0) {
2605 setFlags(viewFlagValues, viewFlagMasks);
2606 }
2607
2608 // Needs to be called after mViewFlags is set
2609 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2610 recomputePadding();
2611 }
2612
2613 if (x != 0 || y != 0) {
2614 scrollTo(x, y);
2615 }
2616
Chet Haase73066682010-11-29 15:55:32 -08002617 if (transformSet) {
2618 setTranslationX(tx);
2619 setTranslationY(ty);
2620 setRotation(rotation);
2621 setRotationX(rotationX);
2622 setRotationY(rotationY);
2623 setScaleX(sx);
2624 setScaleY(sy);
2625 }
2626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2628 setScrollContainer(true);
2629 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002630
2631 computeOpaqueFlags();
2632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 a.recycle();
2634 }
2635
2636 /**
2637 * Non-public constructor for use in testing
2638 */
2639 View() {
2640 }
2641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 /**
2643 * <p>
2644 * Initializes the fading edges from a given set of styled attributes. This
2645 * method should be called by subclasses that need fading edges and when an
2646 * instance of these subclasses is created programmatically rather than
2647 * being inflated from XML. This method is automatically called when the XML
2648 * is inflated.
2649 * </p>
2650 *
2651 * @param a the styled attributes set to initialize the fading edges from
2652 */
2653 protected void initializeFadingEdge(TypedArray a) {
2654 initScrollCache();
2655
2656 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2657 R.styleable.View_fadingEdgeLength,
2658 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2659 }
2660
2661 /**
2662 * Returns the size of the vertical faded edges used to indicate that more
2663 * content in this view is visible.
2664 *
2665 * @return The size in pixels of the vertical faded edge or 0 if vertical
2666 * faded edges are not enabled for this view.
2667 * @attr ref android.R.styleable#View_fadingEdgeLength
2668 */
2669 public int getVerticalFadingEdgeLength() {
2670 if (isVerticalFadingEdgeEnabled()) {
2671 ScrollabilityCache cache = mScrollCache;
2672 if (cache != null) {
2673 return cache.fadingEdgeLength;
2674 }
2675 }
2676 return 0;
2677 }
2678
2679 /**
2680 * Set the size of the faded edge used to indicate that more content in this
2681 * view is available. Will not change whether the fading edge is enabled; use
2682 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2683 * to enable the fading edge for the vertical or horizontal fading edges.
2684 *
2685 * @param length The size in pixels of the faded edge used to indicate that more
2686 * content in this view is visible.
2687 */
2688 public void setFadingEdgeLength(int length) {
2689 initScrollCache();
2690 mScrollCache.fadingEdgeLength = length;
2691 }
2692
2693 /**
2694 * Returns the size of the horizontal faded edges used to indicate that more
2695 * content in this view is visible.
2696 *
2697 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2698 * faded edges are not enabled for this view.
2699 * @attr ref android.R.styleable#View_fadingEdgeLength
2700 */
2701 public int getHorizontalFadingEdgeLength() {
2702 if (isHorizontalFadingEdgeEnabled()) {
2703 ScrollabilityCache cache = mScrollCache;
2704 if (cache != null) {
2705 return cache.fadingEdgeLength;
2706 }
2707 }
2708 return 0;
2709 }
2710
2711 /**
2712 * Returns the width of the vertical scrollbar.
2713 *
2714 * @return The width in pixels of the vertical scrollbar or 0 if there
2715 * is no vertical scrollbar.
2716 */
2717 public int getVerticalScrollbarWidth() {
2718 ScrollabilityCache cache = mScrollCache;
2719 if (cache != null) {
2720 ScrollBarDrawable scrollBar = cache.scrollBar;
2721 if (scrollBar != null) {
2722 int size = scrollBar.getSize(true);
2723 if (size <= 0) {
2724 size = cache.scrollBarSize;
2725 }
2726 return size;
2727 }
2728 return 0;
2729 }
2730 return 0;
2731 }
2732
2733 /**
2734 * Returns the height of the horizontal scrollbar.
2735 *
2736 * @return The height in pixels of the horizontal scrollbar or 0 if
2737 * there is no horizontal scrollbar.
2738 */
2739 protected int getHorizontalScrollbarHeight() {
2740 ScrollabilityCache cache = mScrollCache;
2741 if (cache != null) {
2742 ScrollBarDrawable scrollBar = cache.scrollBar;
2743 if (scrollBar != null) {
2744 int size = scrollBar.getSize(false);
2745 if (size <= 0) {
2746 size = cache.scrollBarSize;
2747 }
2748 return size;
2749 }
2750 return 0;
2751 }
2752 return 0;
2753 }
2754
2755 /**
2756 * <p>
2757 * Initializes the scrollbars from a given set of styled attributes. This
2758 * method should be called by subclasses that need scrollbars and when an
2759 * instance of these subclasses is created programmatically rather than
2760 * being inflated from XML. This method is automatically called when the XML
2761 * is inflated.
2762 * </p>
2763 *
2764 * @param a the styled attributes set to initialize the scrollbars from
2765 */
2766 protected void initializeScrollbars(TypedArray a) {
2767 initScrollCache();
2768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002770
2771 if (scrollabilityCache.scrollBar == null) {
2772 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2773 }
2774
Romain Guy8bda2482010-03-02 11:42:11 -08002775 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776
Mike Cleronf116bf82009-09-27 19:14:12 -07002777 if (!fadeScrollbars) {
2778 scrollabilityCache.state = ScrollabilityCache.ON;
2779 }
2780 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2781
2782
2783 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2784 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2785 .getScrollBarFadeDuration());
2786 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2787 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2788 ViewConfiguration.getScrollDefaultDelay());
2789
2790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2792 com.android.internal.R.styleable.View_scrollbarSize,
2793 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2794
2795 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2796 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2797
2798 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2799 if (thumb != null) {
2800 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2801 }
2802
2803 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2804 false);
2805 if (alwaysDraw) {
2806 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2807 }
2808
2809 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2810 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2811
2812 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2813 if (thumb != null) {
2814 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2815 }
2816
2817 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2818 false);
2819 if (alwaysDraw) {
2820 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2821 }
2822
2823 // Re-apply user/background padding so that scrollbar(s) get added
2824 recomputePadding();
2825 }
2826
2827 /**
2828 * <p>
2829 * Initalizes the scrollability cache if necessary.
2830 * </p>
2831 */
2832 private void initScrollCache() {
2833 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002834 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 }
2836 }
2837
2838 /**
Adam Powell20232d02010-12-08 21:08:53 -08002839 * Set the position of the vertical scroll bar. Should be one of
2840 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
2841 * {@link #SCROLLBAR_POSITION_RIGHT}.
2842 *
2843 * @param position Where the vertical scroll bar should be positioned.
2844 */
2845 public void setVerticalScrollbarPosition(int position) {
2846 if (mVerticalScrollbarPosition != position) {
2847 mVerticalScrollbarPosition = position;
2848 computeOpaqueFlags();
2849 recomputePadding();
2850 }
2851 }
2852
2853 /**
2854 * @return The position where the vertical scroll bar will show, if applicable.
2855 * @see #setVerticalScrollbarPosition(int)
2856 */
2857 public int getVerticalScrollbarPosition() {
2858 return mVerticalScrollbarPosition;
2859 }
2860
2861 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 * Register a callback to be invoked when focus of this view changed.
2863 *
2864 * @param l The callback that will run.
2865 */
2866 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2867 mOnFocusChangeListener = l;
2868 }
2869
2870 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002871 * Add a listener that will be called when the bounds of the view change due to
2872 * layout processing.
2873 *
2874 * @param listener The listener that will be called when layout bounds change.
2875 */
2876 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2877 if (mOnLayoutChangeListeners == null) {
2878 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2879 }
2880 mOnLayoutChangeListeners.add(listener);
2881 }
2882
2883 /**
2884 * Remove a listener for layout changes.
2885 *
2886 * @param listener The listener for layout bounds change.
2887 */
2888 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2889 if (mOnLayoutChangeListeners == null) {
2890 return;
2891 }
2892 mOnLayoutChangeListeners.remove(listener);
2893 }
2894
2895 /**
2896 * Gets the current list of listeners for layout changes.
Chet Haase21cd1382010-09-01 17:42:29 -07002897 */
2898 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2899 return mOnLayoutChangeListeners;
2900 }
2901
2902 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 * Returns the focus-change callback registered for this view.
2904 *
2905 * @return The callback, or null if one is not registered.
2906 */
2907 public OnFocusChangeListener getOnFocusChangeListener() {
2908 return mOnFocusChangeListener;
2909 }
2910
2911 /**
2912 * Register a callback to be invoked when this view is clicked. If this view is not
2913 * clickable, it becomes clickable.
2914 *
2915 * @param l The callback that will run
2916 *
2917 * @see #setClickable(boolean)
2918 */
2919 public void setOnClickListener(OnClickListener l) {
2920 if (!isClickable()) {
2921 setClickable(true);
2922 }
2923 mOnClickListener = l;
2924 }
2925
2926 /**
2927 * Register a callback to be invoked when this view is clicked and held. If this view is not
2928 * long clickable, it becomes long clickable.
2929 *
2930 * @param l The callback that will run
2931 *
2932 * @see #setLongClickable(boolean)
2933 */
2934 public void setOnLongClickListener(OnLongClickListener l) {
2935 if (!isLongClickable()) {
2936 setLongClickable(true);
2937 }
2938 mOnLongClickListener = l;
2939 }
2940
2941 /**
2942 * Register a callback to be invoked when the context menu for this view is
2943 * being built. If this view is not long clickable, it becomes long clickable.
2944 *
2945 * @param l The callback that will run
2946 *
2947 */
2948 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2949 if (!isLongClickable()) {
2950 setLongClickable(true);
2951 }
2952 mOnCreateContextMenuListener = l;
2953 }
2954
2955 /**
2956 * Call this view's OnClickListener, if it is defined.
2957 *
2958 * @return True there was an assigned OnClickListener that was called, false
2959 * otherwise is returned.
2960 */
2961 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002962 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 if (mOnClickListener != null) {
2965 playSoundEffect(SoundEffectConstants.CLICK);
2966 mOnClickListener.onClick(this);
2967 return true;
2968 }
2969
2970 return false;
2971 }
2972
2973 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002974 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2975 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002977 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 */
2979 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002980 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 boolean handled = false;
2983 if (mOnLongClickListener != null) {
2984 handled = mOnLongClickListener.onLongClick(View.this);
2985 }
2986 if (!handled) {
2987 handled = showContextMenu();
2988 }
2989 if (handled) {
2990 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2991 }
2992 return handled;
2993 }
2994
2995 /**
2996 * Bring up the context menu for this view.
2997 *
2998 * @return Whether a context menu was displayed.
2999 */
3000 public boolean showContextMenu() {
3001 return getParent().showContextMenuForChild(this);
3002 }
3003
3004 /**
Adam Powell6e346362010-07-23 10:18:23 -07003005 * Start an action mode.
3006 *
3007 * @param callback Callback that will control the lifecycle of the action mode
3008 * @return The new action mode if it is started, null otherwise
3009 *
3010 * @see ActionMode
3011 */
3012 public ActionMode startActionMode(ActionMode.Callback callback) {
3013 return getParent().startActionModeForChild(this, callback);
3014 }
3015
3016 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 * Register a callback to be invoked when a key is pressed in this view.
3018 * @param l the key listener to attach to this view
3019 */
3020 public void setOnKeyListener(OnKeyListener l) {
3021 mOnKeyListener = l;
3022 }
3023
3024 /**
3025 * Register a callback to be invoked when a touch event is sent to this view.
3026 * @param l the touch listener to attach to this view
3027 */
3028 public void setOnTouchListener(OnTouchListener l) {
3029 mOnTouchListener = l;
3030 }
3031
3032 /**
Chris Tate32affef2010-10-18 15:29:21 -07003033 * Register a callback to be invoked when a drag event is sent to this view.
3034 * @param l The drag listener to attach to this view
3035 */
3036 public void setOnDragListener(OnDragListener l) {
3037 mOnDragListener = l;
3038 }
3039
3040 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
3042 *
3043 * Note: this does not check whether this {@link View} should get focus, it just
3044 * gives it focus no matter what. It should only be called internally by framework
3045 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3046 *
3047 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
3048 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
3049 * focus moved when requestFocus() is called. It may not always
3050 * apply, in which case use the default View.FOCUS_DOWN.
3051 * @param previouslyFocusedRect The rectangle of the view that had focus
3052 * prior in this View's coordinate system.
3053 */
3054 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3055 if (DBG) {
3056 System.out.println(this + " requestFocus()");
3057 }
3058
3059 if ((mPrivateFlags & FOCUSED) == 0) {
3060 mPrivateFlags |= FOCUSED;
3061
3062 if (mParent != null) {
3063 mParent.requestChildFocus(this, this);
3064 }
3065
3066 onFocusChanged(true, direction, previouslyFocusedRect);
3067 refreshDrawableState();
3068 }
3069 }
3070
3071 /**
3072 * Request that a rectangle of this view be visible on the screen,
3073 * scrolling if necessary just enough.
3074 *
3075 * <p>A View should call this if it maintains some notion of which part
3076 * of its content is interesting. For example, a text editing view
3077 * should call this when its cursor moves.
3078 *
3079 * @param rectangle The rectangle.
3080 * @return Whether any parent scrolled.
3081 */
3082 public boolean requestRectangleOnScreen(Rect rectangle) {
3083 return requestRectangleOnScreen(rectangle, false);
3084 }
3085
3086 /**
3087 * Request that a rectangle of this view be visible on the screen,
3088 * scrolling if necessary just enough.
3089 *
3090 * <p>A View should call this if it maintains some notion of which part
3091 * of its content is interesting. For example, a text editing view
3092 * should call this when its cursor moves.
3093 *
3094 * <p>When <code>immediate</code> is set to true, scrolling will not be
3095 * animated.
3096 *
3097 * @param rectangle The rectangle.
3098 * @param immediate True to forbid animated scrolling, false otherwise
3099 * @return Whether any parent scrolled.
3100 */
3101 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3102 View child = this;
3103 ViewParent parent = mParent;
3104 boolean scrolled = false;
3105 while (parent != null) {
3106 scrolled |= parent.requestChildRectangleOnScreen(child,
3107 rectangle, immediate);
3108
3109 // offset rect so next call has the rectangle in the
3110 // coordinate system of its direct child.
3111 rectangle.offset(child.getLeft(), child.getTop());
3112 rectangle.offset(-child.getScrollX(), -child.getScrollY());
3113
3114 if (!(parent instanceof View)) {
3115 break;
3116 }
Romain Guy8506ab42009-06-11 17:35:47 -07003117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 child = (View) parent;
3119 parent = child.getParent();
3120 }
3121 return scrolled;
3122 }
3123
3124 /**
3125 * Called when this view wants to give up focus. This will cause
3126 * {@link #onFocusChanged} to be called.
3127 */
3128 public void clearFocus() {
3129 if (DBG) {
3130 System.out.println(this + " clearFocus()");
3131 }
3132
3133 if ((mPrivateFlags & FOCUSED) != 0) {
3134 mPrivateFlags &= ~FOCUSED;
3135
3136 if (mParent != null) {
3137 mParent.clearChildFocus(this);
3138 }
3139
3140 onFocusChanged(false, 0, null);
3141 refreshDrawableState();
3142 }
3143 }
3144
3145 /**
3146 * Called to clear the focus of a view that is about to be removed.
3147 * Doesn't call clearChildFocus, which prevents this view from taking
3148 * focus again before it has been removed from the parent
3149 */
3150 void clearFocusForRemoval() {
3151 if ((mPrivateFlags & FOCUSED) != 0) {
3152 mPrivateFlags &= ~FOCUSED;
3153
3154 onFocusChanged(false, 0, null);
3155 refreshDrawableState();
3156 }
3157 }
3158
3159 /**
3160 * Called internally by the view system when a new view is getting focus.
3161 * This is what clears the old focus.
3162 */
3163 void unFocus() {
3164 if (DBG) {
3165 System.out.println(this + " unFocus()");
3166 }
3167
3168 if ((mPrivateFlags & FOCUSED) != 0) {
3169 mPrivateFlags &= ~FOCUSED;
3170
3171 onFocusChanged(false, 0, null);
3172 refreshDrawableState();
3173 }
3174 }
3175
3176 /**
3177 * Returns true if this view has focus iteself, or is the ancestor of the
3178 * view that has focus.
3179 *
3180 * @return True if this view has or contains focus, false otherwise.
3181 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003182 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003183 public boolean hasFocus() {
3184 return (mPrivateFlags & FOCUSED) != 0;
3185 }
3186
3187 /**
3188 * Returns true if this view is focusable or if it contains a reachable View
3189 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3190 * is a View whose parents do not block descendants focus.
3191 *
3192 * Only {@link #VISIBLE} views are considered focusable.
3193 *
3194 * @return True if the view is focusable or if the view contains a focusable
3195 * View, false otherwise.
3196 *
3197 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3198 */
3199 public boolean hasFocusable() {
3200 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3201 }
3202
3203 /**
3204 * Called by the view system when the focus state of this view changes.
3205 * When the focus change event is caused by directional navigation, direction
3206 * and previouslyFocusedRect provide insight into where the focus is coming from.
3207 * When overriding, be sure to call up through to the super class so that
3208 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07003209 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 * @param gainFocus True if the View has focus; false otherwise.
3211 * @param direction The direction focus has moved when requestFocus()
3212 * is called to give this view focus. Values are
Jeff Brown4e6319b2010-12-13 10:36:51 -08003213 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3214 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3215 * It may not always apply, in which case use the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 * @param previouslyFocusedRect The rectangle, in this view's coordinate
3217 * system, of the previously focused view. If applicable, this will be
3218 * passed in as finer grained information about where the focus is coming
3219 * from (in addition to direction). Will be <code>null</code> otherwise.
3220 */
3221 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003222 if (gainFocus) {
3223 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3224 }
3225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 InputMethodManager imm = InputMethodManager.peekInstance();
3227 if (!gainFocus) {
3228 if (isPressed()) {
3229 setPressed(false);
3230 }
3231 if (imm != null && mAttachInfo != null
3232 && mAttachInfo.mHasWindowFocus) {
3233 imm.focusOut(this);
3234 }
Romain Guya2431d02009-04-30 16:30:00 -07003235 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 } else if (imm != null && mAttachInfo != null
3237 && mAttachInfo.mHasWindowFocus) {
3238 imm.focusIn(this);
3239 }
Romain Guy8506ab42009-06-11 17:35:47 -07003240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241 invalidate();
3242 if (mOnFocusChangeListener != null) {
3243 mOnFocusChangeListener.onFocusChange(this, gainFocus);
3244 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003245
3246 if (mAttachInfo != null) {
3247 mAttachInfo.mKeyDispatchState.reset(this);
3248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 }
3250
3251 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07003252 * {@inheritDoc}
3253 */
3254 public void sendAccessibilityEvent(int eventType) {
3255 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3256 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3257 }
3258 }
3259
3260 /**
3261 * {@inheritDoc}
3262 */
3263 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
Svetoslav Ganov9cd1eca2011-01-13 14:24:02 -08003264 if (!isShown()) {
3265 return;
3266 }
svetoslavganov75986cf2009-05-14 22:28:01 -07003267 event.setClassName(getClass().getName());
3268 event.setPackageName(getContext().getPackageName());
3269 event.setEnabled(isEnabled());
3270 event.setContentDescription(mContentDescription);
3271
3272 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3273 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3274 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3275 event.setItemCount(focusablesTempList.size());
3276 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3277 focusablesTempList.clear();
3278 }
3279
3280 dispatchPopulateAccessibilityEvent(event);
3281
3282 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3283 }
3284
3285 /**
3286 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3287 * to be populated.
3288 *
3289 * @param event The event.
3290 *
3291 * @return True if the event population was completed.
3292 */
3293 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3294 return false;
3295 }
3296
3297 /**
3298 * Gets the {@link View} description. It briefly describes the view and is
3299 * primarily used for accessibility support. Set this property to enable
3300 * better accessibility support for your application. This is especially
3301 * true for views that do not have textual representation (For example,
3302 * ImageButton).
3303 *
3304 * @return The content descriptiopn.
3305 *
3306 * @attr ref android.R.styleable#View_contentDescription
3307 */
3308 public CharSequence getContentDescription() {
3309 return mContentDescription;
3310 }
3311
3312 /**
3313 * Sets the {@link View} description. It briefly describes the view and is
3314 * primarily used for accessibility support. Set this property to enable
3315 * better accessibility support for your application. This is especially
3316 * true for views that do not have textual representation (For example,
3317 * ImageButton).
3318 *
3319 * @param contentDescription The content description.
3320 *
3321 * @attr ref android.R.styleable#View_contentDescription
3322 */
3323 public void setContentDescription(CharSequence contentDescription) {
3324 mContentDescription = contentDescription;
3325 }
3326
3327 /**
Romain Guya2431d02009-04-30 16:30:00 -07003328 * Invoked whenever this view loses focus, either by losing window focus or by losing
3329 * focus within its window. This method can be used to clear any state tied to the
3330 * focus. For instance, if a button is held pressed with the trackball and the window
3331 * loses focus, this method can be used to cancel the press.
3332 *
3333 * Subclasses of View overriding this method should always call super.onFocusLost().
3334 *
3335 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003336 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003337 *
3338 * @hide pending API council approval
3339 */
3340 protected void onFocusLost() {
3341 resetPressedState();
3342 }
3343
3344 private void resetPressedState() {
3345 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3346 return;
3347 }
3348
3349 if (isPressed()) {
3350 setPressed(false);
3351
3352 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003353 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003354 }
3355 }
3356 }
3357
3358 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 * Returns true if this view has focus
3360 *
3361 * @return True if this view has focus, false otherwise.
3362 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003363 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 public boolean isFocused() {
3365 return (mPrivateFlags & FOCUSED) != 0;
3366 }
3367
3368 /**
3369 * Find the view in the hierarchy rooted at this view that currently has
3370 * focus.
3371 *
3372 * @return The view that currently has focus, or null if no focused view can
3373 * be found.
3374 */
3375 public View findFocus() {
3376 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3377 }
3378
3379 /**
3380 * Change whether this view is one of the set of scrollable containers in
3381 * its window. This will be used to determine whether the window can
3382 * resize or must pan when a soft input area is open -- scrollable
3383 * containers allow the window to use resize mode since the container
3384 * will appropriately shrink.
3385 */
3386 public void setScrollContainer(boolean isScrollContainer) {
3387 if (isScrollContainer) {
3388 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3389 mAttachInfo.mScrollContainers.add(this);
3390 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3391 }
3392 mPrivateFlags |= SCROLL_CONTAINER;
3393 } else {
3394 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3395 mAttachInfo.mScrollContainers.remove(this);
3396 }
3397 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3398 }
3399 }
3400
3401 /**
3402 * Returns the quality of the drawing cache.
3403 *
3404 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3405 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3406 *
3407 * @see #setDrawingCacheQuality(int)
3408 * @see #setDrawingCacheEnabled(boolean)
3409 * @see #isDrawingCacheEnabled()
3410 *
3411 * @attr ref android.R.styleable#View_drawingCacheQuality
3412 */
3413 public int getDrawingCacheQuality() {
3414 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3415 }
3416
3417 /**
3418 * Set the drawing cache quality of this view. This value is used only when the
3419 * drawing cache is enabled
3420 *
3421 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3422 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3423 *
3424 * @see #getDrawingCacheQuality()
3425 * @see #setDrawingCacheEnabled(boolean)
3426 * @see #isDrawingCacheEnabled()
3427 *
3428 * @attr ref android.R.styleable#View_drawingCacheQuality
3429 */
3430 public void setDrawingCacheQuality(int quality) {
3431 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3432 }
3433
3434 /**
3435 * Returns whether the screen should remain on, corresponding to the current
3436 * value of {@link #KEEP_SCREEN_ON}.
3437 *
3438 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3439 *
3440 * @see #setKeepScreenOn(boolean)
3441 *
3442 * @attr ref android.R.styleable#View_keepScreenOn
3443 */
3444 public boolean getKeepScreenOn() {
3445 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3446 }
3447
3448 /**
3449 * Controls whether the screen should remain on, modifying the
3450 * value of {@link #KEEP_SCREEN_ON}.
3451 *
3452 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3453 *
3454 * @see #getKeepScreenOn()
3455 *
3456 * @attr ref android.R.styleable#View_keepScreenOn
3457 */
3458 public void setKeepScreenOn(boolean keepScreenOn) {
3459 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3460 }
3461
3462 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003463 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3464 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 *
3466 * @attr ref android.R.styleable#View_nextFocusLeft
3467 */
3468 public int getNextFocusLeftId() {
3469 return mNextFocusLeftId;
3470 }
3471
3472 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003473 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3474 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
3475 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 *
3477 * @attr ref android.R.styleable#View_nextFocusLeft
3478 */
3479 public void setNextFocusLeftId(int nextFocusLeftId) {
3480 mNextFocusLeftId = nextFocusLeftId;
3481 }
3482
3483 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003484 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3485 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 *
3487 * @attr ref android.R.styleable#View_nextFocusRight
3488 */
3489 public int getNextFocusRightId() {
3490 return mNextFocusRightId;
3491 }
3492
3493 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003494 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3495 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
3496 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 *
3498 * @attr ref android.R.styleable#View_nextFocusRight
3499 */
3500 public void setNextFocusRightId(int nextFocusRightId) {
3501 mNextFocusRightId = nextFocusRightId;
3502 }
3503
3504 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003505 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3506 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 *
3508 * @attr ref android.R.styleable#View_nextFocusUp
3509 */
3510 public int getNextFocusUpId() {
3511 return mNextFocusUpId;
3512 }
3513
3514 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003515 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3516 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
3517 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 *
3519 * @attr ref android.R.styleable#View_nextFocusUp
3520 */
3521 public void setNextFocusUpId(int nextFocusUpId) {
3522 mNextFocusUpId = nextFocusUpId;
3523 }
3524
3525 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003526 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3527 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 *
3529 * @attr ref android.R.styleable#View_nextFocusDown
3530 */
3531 public int getNextFocusDownId() {
3532 return mNextFocusDownId;
3533 }
3534
3535 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003536 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3537 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
3538 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 *
3540 * @attr ref android.R.styleable#View_nextFocusDown
3541 */
3542 public void setNextFocusDownId(int nextFocusDownId) {
3543 mNextFocusDownId = nextFocusDownId;
3544 }
3545
3546 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003547 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3548 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3549 *
3550 * @attr ref android.R.styleable#View_nextFocusForward
3551 */
3552 public int getNextFocusForwardId() {
3553 return mNextFocusForwardId;
3554 }
3555
3556 /**
3557 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3558 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
3559 * decide automatically.
3560 *
3561 * @attr ref android.R.styleable#View_nextFocusForward
3562 */
3563 public void setNextFocusForwardId(int nextFocusForwardId) {
3564 mNextFocusForwardId = nextFocusForwardId;
3565 }
3566
3567 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 * Returns the visibility of this view and all of its ancestors
3569 *
3570 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3571 */
3572 public boolean isShown() {
3573 View current = this;
3574 //noinspection ConstantConditions
3575 do {
3576 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3577 return false;
3578 }
3579 ViewParent parent = current.mParent;
3580 if (parent == null) {
3581 return false; // We are not attached to the view root
3582 }
3583 if (!(parent instanceof View)) {
3584 return true;
3585 }
3586 current = (View) parent;
3587 } while (current != null);
3588
3589 return false;
3590 }
3591
3592 /**
3593 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3594 * is set
3595 *
3596 * @param insets Insets for system windows
3597 *
3598 * @return True if this view applied the insets, false otherwise
3599 */
3600 protected boolean fitSystemWindows(Rect insets) {
3601 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3602 mPaddingLeft = insets.left;
3603 mPaddingTop = insets.top;
3604 mPaddingRight = insets.right;
3605 mPaddingBottom = insets.bottom;
3606 requestLayout();
3607 return true;
3608 }
3609 return false;
3610 }
3611
3612 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003613 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3614 * @return True if window has FITS_SYSTEM_WINDOWS set
3615 *
3616 * @hide
3617 */
3618 public boolean isFitsSystemWindowsFlagSet() {
3619 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3620 }
3621
3622 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 * Returns the visibility status for this view.
3624 *
3625 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3626 * @attr ref android.R.styleable#View_visibility
3627 */
3628 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003629 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3630 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3631 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 })
3633 public int getVisibility() {
3634 return mViewFlags & VISIBILITY_MASK;
3635 }
3636
3637 /**
3638 * Set the enabled state of this view.
3639 *
3640 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3641 * @attr ref android.R.styleable#View_visibility
3642 */
3643 @RemotableViewMethod
3644 public void setVisibility(int visibility) {
3645 setFlags(visibility, VISIBILITY_MASK);
3646 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3647 }
3648
3649 /**
3650 * Returns the enabled status for this view. The interpretation of the
3651 * enabled state varies by subclass.
3652 *
3653 * @return True if this view is enabled, false otherwise.
3654 */
3655 @ViewDebug.ExportedProperty
3656 public boolean isEnabled() {
3657 return (mViewFlags & ENABLED_MASK) == ENABLED;
3658 }
3659
3660 /**
3661 * Set the enabled state of this view. The interpretation of the enabled
3662 * state varies by subclass.
3663 *
3664 * @param enabled True if this view is enabled, false otherwise.
3665 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003666 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003668 if (enabled == isEnabled()) return;
3669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3671
3672 /*
3673 * The View most likely has to change its appearance, so refresh
3674 * the drawable state.
3675 */
3676 refreshDrawableState();
3677
3678 // Invalidate too, since the default behavior for views is to be
3679 // be drawn at 50% alpha rather than to change the drawable.
3680 invalidate();
3681 }
3682
3683 /**
3684 * Set whether this view can receive the focus.
3685 *
3686 * Setting this to false will also ensure that this view is not focusable
3687 * in touch mode.
3688 *
3689 * @param focusable If true, this view can receive the focus.
3690 *
3691 * @see #setFocusableInTouchMode(boolean)
3692 * @attr ref android.R.styleable#View_focusable
3693 */
3694 public void setFocusable(boolean focusable) {
3695 if (!focusable) {
3696 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3697 }
3698 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3699 }
3700
3701 /**
3702 * Set whether this view can receive focus while in touch mode.
3703 *
3704 * Setting this to true will also ensure that this view is focusable.
3705 *
3706 * @param focusableInTouchMode If true, this view can receive the focus while
3707 * in touch mode.
3708 *
3709 * @see #setFocusable(boolean)
3710 * @attr ref android.R.styleable#View_focusableInTouchMode
3711 */
3712 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3713 // Focusable in touch mode should always be set before the focusable flag
3714 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3715 // which, in touch mode, will not successfully request focus on this view
3716 // because the focusable in touch mode flag is not set
3717 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3718 if (focusableInTouchMode) {
3719 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3720 }
3721 }
3722
3723 /**
3724 * Set whether this view should have sound effects enabled for events such as
3725 * clicking and touching.
3726 *
3727 * <p>You may wish to disable sound effects for a view if you already play sounds,
3728 * for instance, a dial key that plays dtmf tones.
3729 *
3730 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3731 * @see #isSoundEffectsEnabled()
3732 * @see #playSoundEffect(int)
3733 * @attr ref android.R.styleable#View_soundEffectsEnabled
3734 */
3735 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3736 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3737 }
3738
3739 /**
3740 * @return whether this view should have sound effects enabled for events such as
3741 * clicking and touching.
3742 *
3743 * @see #setSoundEffectsEnabled(boolean)
3744 * @see #playSoundEffect(int)
3745 * @attr ref android.R.styleable#View_soundEffectsEnabled
3746 */
3747 @ViewDebug.ExportedProperty
3748 public boolean isSoundEffectsEnabled() {
3749 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3750 }
3751
3752 /**
3753 * Set whether this view should have haptic feedback for events such as
3754 * long presses.
3755 *
3756 * <p>You may wish to disable haptic feedback if your view already controls
3757 * its own haptic feedback.
3758 *
3759 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3760 * @see #isHapticFeedbackEnabled()
3761 * @see #performHapticFeedback(int)
3762 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3763 */
3764 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3765 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3766 }
3767
3768 /**
3769 * @return whether this view should have haptic feedback enabled for events
3770 * long presses.
3771 *
3772 * @see #setHapticFeedbackEnabled(boolean)
3773 * @see #performHapticFeedback(int)
3774 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3775 */
3776 @ViewDebug.ExportedProperty
3777 public boolean isHapticFeedbackEnabled() {
3778 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3779 }
3780
3781 /**
3782 * If this view doesn't do any drawing on its own, set this flag to
3783 * allow further optimizations. By default, this flag is not set on
3784 * View, but could be set on some View subclasses such as ViewGroup.
3785 *
3786 * Typically, if you override {@link #onDraw} you should clear this flag.
3787 *
3788 * @param willNotDraw whether or not this View draw on its own
3789 */
3790 public void setWillNotDraw(boolean willNotDraw) {
3791 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3792 }
3793
3794 /**
3795 * Returns whether or not this View draws on its own.
3796 *
3797 * @return true if this view has nothing to draw, false otherwise
3798 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003799 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800 public boolean willNotDraw() {
3801 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3802 }
3803
3804 /**
3805 * When a View's drawing cache is enabled, drawing is redirected to an
3806 * offscreen bitmap. Some views, like an ImageView, must be able to
3807 * bypass this mechanism if they already draw a single bitmap, to avoid
3808 * unnecessary usage of the memory.
3809 *
3810 * @param willNotCacheDrawing true if this view does not cache its
3811 * drawing, false otherwise
3812 */
3813 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3814 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3815 }
3816
3817 /**
3818 * Returns whether or not this View can cache its drawing or not.
3819 *
3820 * @return true if this view does not cache its drawing, false otherwise
3821 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003822 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 public boolean willNotCacheDrawing() {
3824 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3825 }
3826
3827 /**
3828 * Indicates whether this view reacts to click events or not.
3829 *
3830 * @return true if the view is clickable, false otherwise
3831 *
3832 * @see #setClickable(boolean)
3833 * @attr ref android.R.styleable#View_clickable
3834 */
3835 @ViewDebug.ExportedProperty
3836 public boolean isClickable() {
3837 return (mViewFlags & CLICKABLE) == CLICKABLE;
3838 }
3839
3840 /**
3841 * Enables or disables click events for this view. When a view
3842 * is clickable it will change its state to "pressed" on every click.
3843 * Subclasses should set the view clickable to visually react to
3844 * user's clicks.
3845 *
3846 * @param clickable true to make the view clickable, false otherwise
3847 *
3848 * @see #isClickable()
3849 * @attr ref android.R.styleable#View_clickable
3850 */
3851 public void setClickable(boolean clickable) {
3852 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3853 }
3854
3855 /**
3856 * Indicates whether this view reacts to long click events or not.
3857 *
3858 * @return true if the view is long clickable, false otherwise
3859 *
3860 * @see #setLongClickable(boolean)
3861 * @attr ref android.R.styleable#View_longClickable
3862 */
3863 public boolean isLongClickable() {
3864 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3865 }
3866
3867 /**
3868 * Enables or disables long click events for this view. When a view is long
3869 * clickable it reacts to the user holding down the button for a longer
3870 * duration than a tap. This event can either launch the listener or a
3871 * context menu.
3872 *
3873 * @param longClickable true to make the view long clickable, false otherwise
3874 * @see #isLongClickable()
3875 * @attr ref android.R.styleable#View_longClickable
3876 */
3877 public void setLongClickable(boolean longClickable) {
3878 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3879 }
3880
3881 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003882 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 *
3884 * @see #isClickable()
3885 * @see #setClickable(boolean)
3886 *
3887 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3888 * the View's internal state from a previously set "pressed" state.
3889 */
3890 public void setPressed(boolean pressed) {
3891 if (pressed) {
3892 mPrivateFlags |= PRESSED;
3893 } else {
3894 mPrivateFlags &= ~PRESSED;
3895 }
3896 refreshDrawableState();
3897 dispatchSetPressed(pressed);
3898 }
3899
3900 /**
3901 * Dispatch setPressed to all of this View's children.
3902 *
3903 * @see #setPressed(boolean)
3904 *
3905 * @param pressed The new pressed state
3906 */
3907 protected void dispatchSetPressed(boolean pressed) {
3908 }
3909
3910 /**
3911 * Indicates whether the view is currently in pressed state. Unless
3912 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3913 * the pressed state.
3914 *
3915 * @see #setPressed
3916 * @see #isClickable()
3917 * @see #setClickable(boolean)
3918 *
3919 * @return true if the view is currently pressed, false otherwise
3920 */
3921 public boolean isPressed() {
3922 return (mPrivateFlags & PRESSED) == PRESSED;
3923 }
3924
3925 /**
3926 * Indicates whether this view will save its state (that is,
3927 * whether its {@link #onSaveInstanceState} method will be called).
3928 *
3929 * @return Returns true if the view state saving is enabled, else false.
3930 *
3931 * @see #setSaveEnabled(boolean)
3932 * @attr ref android.R.styleable#View_saveEnabled
3933 */
3934 public boolean isSaveEnabled() {
3935 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3936 }
3937
3938 /**
3939 * Controls whether the saving of this view's state is
3940 * enabled (that is, whether its {@link #onSaveInstanceState} method
3941 * will be called). Note that even if freezing is enabled, the
3942 * view still must have an id assigned to it (via {@link #setId setId()})
3943 * for its state to be saved. This flag can only disable the
3944 * saving of this view; any child views may still have their state saved.
3945 *
3946 * @param enabled Set to false to <em>disable</em> state saving, or true
3947 * (the default) to allow it.
3948 *
3949 * @see #isSaveEnabled()
3950 * @see #setId(int)
3951 * @see #onSaveInstanceState()
3952 * @attr ref android.R.styleable#View_saveEnabled
3953 */
3954 public void setSaveEnabled(boolean enabled) {
3955 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3956 }
3957
Jeff Brown85a31762010-09-01 17:01:00 -07003958 /**
3959 * Gets whether the framework should discard touches when the view's
3960 * window is obscured by another visible window.
3961 * Refer to the {@link View} security documentation for more details.
3962 *
3963 * @return True if touch filtering is enabled.
3964 *
3965 * @see #setFilterTouchesWhenObscured(boolean)
3966 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3967 */
3968 @ViewDebug.ExportedProperty
3969 public boolean getFilterTouchesWhenObscured() {
3970 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3971 }
3972
3973 /**
3974 * Sets whether the framework should discard touches when the view's
3975 * window is obscured by another visible window.
3976 * Refer to the {@link View} security documentation for more details.
3977 *
3978 * @param enabled True if touch filtering should be enabled.
3979 *
3980 * @see #getFilterTouchesWhenObscured
3981 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3982 */
3983 public void setFilterTouchesWhenObscured(boolean enabled) {
3984 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3985 FILTER_TOUCHES_WHEN_OBSCURED);
3986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987
3988 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003989 * Indicates whether the entire hierarchy under this view will save its
3990 * state when a state saving traversal occurs from its parent. The default
3991 * is true; if false, these views will not be saved unless
3992 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3993 *
3994 * @return Returns true if the view state saving from parent is enabled, else false.
3995 *
3996 * @see #setSaveFromParentEnabled(boolean)
3997 */
3998 public boolean isSaveFromParentEnabled() {
3999 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4000 }
4001
4002 /**
4003 * Controls whether the entire hierarchy under this view will save its
4004 * state when a state saving traversal occurs from its parent. The default
4005 * is true; if false, these views will not be saved unless
4006 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4007 *
4008 * @param enabled Set to false to <em>disable</em> state saving, or true
4009 * (the default) to allow it.
4010 *
4011 * @see #isSaveFromParentEnabled()
4012 * @see #setId(int)
4013 * @see #onSaveInstanceState()
4014 */
4015 public void setSaveFromParentEnabled(boolean enabled) {
4016 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4017 }
4018
4019
4020 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 * Returns whether this View is able to take focus.
4022 *
4023 * @return True if this view can take focus, or false otherwise.
4024 * @attr ref android.R.styleable#View_focusable
4025 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004026 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 public final boolean isFocusable() {
4028 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4029 }
4030
4031 /**
4032 * When a view is focusable, it may not want to take focus when in touch mode.
4033 * For example, a button would like focus when the user is navigating via a D-pad
4034 * so that the user can click on it, but once the user starts touching the screen,
4035 * the button shouldn't take focus
4036 * @return Whether the view is focusable in touch mode.
4037 * @attr ref android.R.styleable#View_focusableInTouchMode
4038 */
4039 @ViewDebug.ExportedProperty
4040 public final boolean isFocusableInTouchMode() {
4041 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4042 }
4043
4044 /**
4045 * Find the nearest view in the specified direction that can take focus.
4046 * This does not actually give focus to that view.
4047 *
4048 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4049 *
4050 * @return The nearest focusable in the specified direction, or null if none
4051 * can be found.
4052 */
4053 public View focusSearch(int direction) {
4054 if (mParent != null) {
4055 return mParent.focusSearch(this, direction);
4056 } else {
4057 return null;
4058 }
4059 }
4060
4061 /**
4062 * This method is the last chance for the focused view and its ancestors to
4063 * respond to an arrow key. This is called when the focused view did not
4064 * consume the key internally, nor could the view system find a new view in
4065 * the requested direction to give focus to.
4066 *
4067 * @param focused The currently focused view.
4068 * @param direction The direction focus wants to move. One of FOCUS_UP,
4069 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4070 * @return True if the this view consumed this unhandled move.
4071 */
4072 public boolean dispatchUnhandledMove(View focused, int direction) {
4073 return false;
4074 }
4075
4076 /**
4077 * If a user manually specified the next view id for a particular direction,
Jeff Brown4e6319b2010-12-13 10:36:51 -08004078 * use the root to look up the view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079 * @param root The root view of the hierarchy containing this view.
Jeff Brown4e6319b2010-12-13 10:36:51 -08004080 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4081 * or FOCUS_BACKWARD.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 * @return The user specified next view, or null if there is none.
4083 */
4084 View findUserSetNextFocus(View root, int direction) {
4085 switch (direction) {
4086 case FOCUS_LEFT:
4087 if (mNextFocusLeftId == View.NO_ID) return null;
4088 return findViewShouldExist(root, mNextFocusLeftId);
4089 case FOCUS_RIGHT:
4090 if (mNextFocusRightId == View.NO_ID) return null;
4091 return findViewShouldExist(root, mNextFocusRightId);
4092 case FOCUS_UP:
4093 if (mNextFocusUpId == View.NO_ID) return null;
4094 return findViewShouldExist(root, mNextFocusUpId);
4095 case FOCUS_DOWN:
4096 if (mNextFocusDownId == View.NO_ID) return null;
4097 return findViewShouldExist(root, mNextFocusDownId);
Jeff Brown4e6319b2010-12-13 10:36:51 -08004098 case FOCUS_FORWARD:
4099 if (mNextFocusForwardId == View.NO_ID) return null;
4100 return findViewShouldExist(root, mNextFocusForwardId);
4101 case FOCUS_BACKWARD: {
4102 final int id = mID;
4103 return root.findViewByPredicate(new Predicate<View>() {
4104 @Override
4105 public boolean apply(View t) {
4106 return t.mNextFocusForwardId == id;
4107 }
4108 });
4109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 }
4111 return null;
4112 }
4113
4114 private static View findViewShouldExist(View root, int childViewId) {
4115 View result = root.findViewById(childViewId);
4116 if (result == null) {
4117 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4118 + "by user for id " + childViewId);
4119 }
4120 return result;
4121 }
4122
4123 /**
4124 * Find and return all focusable views that are descendants of this view,
4125 * possibly including this view if it is focusable itself.
4126 *
4127 * @param direction The direction of the focus
4128 * @return A list of focusable views
4129 */
4130 public ArrayList<View> getFocusables(int direction) {
4131 ArrayList<View> result = new ArrayList<View>(24);
4132 addFocusables(result, direction);
4133 return result;
4134 }
4135
4136 /**
4137 * Add any focusable views that are descendants of this view (possibly
4138 * including this view if it is focusable itself) to views. If we are in touch mode,
4139 * only add views that are also focusable in touch mode.
4140 *
4141 * @param views Focusable views found so far
4142 * @param direction The direction of the focus
4143 */
4144 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07004145 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147
svetoslavganov75986cf2009-05-14 22:28:01 -07004148 /**
4149 * Adds any focusable views that are descendants of this view (possibly
4150 * including this view if it is focusable itself) to views. This method
4151 * adds all focusable views regardless if we are in touch mode or
4152 * only views focusable in touch mode if we are in touch mode depending on
4153 * the focusable mode paramater.
4154 *
4155 * @param views Focusable views found so far or null if all we are interested is
4156 * the number of focusables.
4157 * @param direction The direction of the focus.
4158 * @param focusableMode The type of focusables to be added.
4159 *
4160 * @see #FOCUSABLES_ALL
4161 * @see #FOCUSABLES_TOUCH_MODE
4162 */
4163 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4164 if (!isFocusable()) {
4165 return;
4166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167
svetoslavganov75986cf2009-05-14 22:28:01 -07004168 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4169 isInTouchMode() && !isFocusableInTouchMode()) {
4170 return;
4171 }
4172
4173 if (views != null) {
4174 views.add(this);
4175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 }
4177
4178 /**
4179 * Find and return all touchable views that are descendants of this view,
4180 * possibly including this view if it is touchable itself.
4181 *
4182 * @return A list of touchable views
4183 */
4184 public ArrayList<View> getTouchables() {
4185 ArrayList<View> result = new ArrayList<View>();
4186 addTouchables(result);
4187 return result;
4188 }
4189
4190 /**
4191 * Add any touchable views that are descendants of this view (possibly
4192 * including this view if it is touchable itself) to views.
4193 *
4194 * @param views Touchable views found so far
4195 */
4196 public void addTouchables(ArrayList<View> views) {
4197 final int viewFlags = mViewFlags;
4198
4199 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4200 && (viewFlags & ENABLED_MASK) == ENABLED) {
4201 views.add(this);
4202 }
4203 }
4204
4205 /**
4206 * Call this to try to give focus to a specific view or to one of its
4207 * descendants.
4208 *
4209 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4210 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4211 * while the device is in touch mode.
4212 *
4213 * See also {@link #focusSearch}, which is what you call to say that you
4214 * have focus, and you want your parent to look for the next one.
4215 *
4216 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4217 * {@link #FOCUS_DOWN} and <code>null</code>.
4218 *
4219 * @return Whether this view or one of its descendants actually took focus.
4220 */
4221 public final boolean requestFocus() {
4222 return requestFocus(View.FOCUS_DOWN);
4223 }
4224
4225
4226 /**
4227 * Call this to try to give focus to a specific view or to one of its
4228 * descendants and give it a hint about what direction focus is heading.
4229 *
4230 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4231 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4232 * while the device is in touch mode.
4233 *
4234 * See also {@link #focusSearch}, which is what you call to say that you
4235 * have focus, and you want your parent to look for the next one.
4236 *
4237 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4238 * <code>null</code> set for the previously focused rectangle.
4239 *
4240 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4241 * @return Whether this view or one of its descendants actually took focus.
4242 */
4243 public final boolean requestFocus(int direction) {
4244 return requestFocus(direction, null);
4245 }
4246
4247 /**
4248 * Call this to try to give focus to a specific view or to one of its descendants
4249 * and give it hints about the direction and a specific rectangle that the focus
4250 * is coming from. The rectangle can help give larger views a finer grained hint
4251 * about where focus is coming from, and therefore, where to show selection, or
4252 * forward focus change internally.
4253 *
4254 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4255 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4256 * while the device is in touch mode.
4257 *
4258 * A View will not take focus if it is not visible.
4259 *
4260 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4261 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4262 *
4263 * See also {@link #focusSearch}, which is what you call to say that you
4264 * have focus, and you want your parent to look for the next one.
4265 *
4266 * You may wish to override this method if your custom {@link View} has an internal
4267 * {@link View} that it wishes to forward the request to.
4268 *
4269 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4270 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4271 * to give a finer grained hint about where focus is coming from. May be null
4272 * if there is no hint.
4273 * @return Whether this view or one of its descendants actually took focus.
4274 */
4275 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4276 // need to be focusable
4277 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4278 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4279 return false;
4280 }
4281
4282 // need to be focusable in touch mode if in touch mode
4283 if (isInTouchMode() &&
4284 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4285 return false;
4286 }
4287
4288 // need to not have any parents blocking us
4289 if (hasAncestorThatBlocksDescendantFocus()) {
4290 return false;
4291 }
4292
4293 handleFocusGainInternal(direction, previouslyFocusedRect);
4294 return true;
4295 }
4296
Christopher Tate2c095f32010-10-04 14:13:40 -07004297 /** Gets the ViewRoot, or null if not attached. */
4298 /*package*/ ViewRoot getViewRoot() {
4299 View root = getRootView();
4300 return root != null ? (ViewRoot)root.getParent() : null;
4301 }
4302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 /**
4304 * Call this to try to give focus to a specific view or to one of its descendants. This is a
4305 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4306 * touch mode to request focus when they are touched.
4307 *
4308 * @return Whether this view or one of its descendants actually took focus.
4309 *
4310 * @see #isInTouchMode()
4311 *
4312 */
4313 public final boolean requestFocusFromTouch() {
4314 // Leave touch mode if we need to
4315 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07004316 ViewRoot viewRoot = getViewRoot();
4317 if (viewRoot != null) {
4318 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 }
4320 }
4321 return requestFocus(View.FOCUS_DOWN);
4322 }
4323
4324 /**
4325 * @return Whether any ancestor of this view blocks descendant focus.
4326 */
4327 private boolean hasAncestorThatBlocksDescendantFocus() {
4328 ViewParent ancestor = mParent;
4329 while (ancestor instanceof ViewGroup) {
4330 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4331 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4332 return true;
4333 } else {
4334 ancestor = vgAncestor.getParent();
4335 }
4336 }
4337 return false;
4338 }
4339
4340 /**
Romain Guya440b002010-02-24 15:57:54 -08004341 * @hide
4342 */
4343 public void dispatchStartTemporaryDetach() {
4344 onStartTemporaryDetach();
4345 }
4346
4347 /**
4348 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4350 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004351 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004352 */
4353 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004354 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004355 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004356 }
4357
4358 /**
4359 * @hide
4360 */
4361 public void dispatchFinishTemporaryDetach() {
4362 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004363 }
Romain Guy8506ab42009-06-11 17:35:47 -07004364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 /**
4366 * Called after {@link #onStartTemporaryDetach} when the container is done
4367 * changing the view.
4368 */
4369 public void onFinishTemporaryDetach() {
4370 }
Romain Guy8506ab42009-06-11 17:35:47 -07004371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 /**
4373 * capture information of this view for later analysis: developement only
4374 * check dynamic switch to make sure we only dump view
4375 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4376 */
4377 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004378 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 return;
4380 }
4381 ViewDebug.dumpCapturedView(subTag, v);
4382 }
4383
4384 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004385 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4386 * for this view's window. Returns null if the view is not currently attached
4387 * to the window. Normally you will not need to use this directly, but
4388 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4389 */
4390 public KeyEvent.DispatcherState getKeyDispatcherState() {
4391 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4392 }
4393
4394 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004395 * Dispatch a key event before it is processed by any input method
4396 * associated with the view hierarchy. This can be used to intercept
4397 * key events in special situations before the IME consumes them; a
4398 * typical example would be handling the BACK key to update the application's
4399 * UI instead of allowing the IME to see it and close itself.
4400 *
4401 * @param event The key event to be dispatched.
4402 * @return True if the event was handled, false otherwise.
4403 */
4404 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4405 return onKeyPreIme(event.getKeyCode(), event);
4406 }
4407
4408 /**
4409 * Dispatch a key event to the next view on the focus path. This path runs
4410 * from the top of the view tree down to the currently focused view. If this
4411 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4412 * the next node down the focus path. This method also fires any key
4413 * listeners.
4414 *
4415 * @param event The key event to be dispatched.
4416 * @return True if the event was handled, false otherwise.
4417 */
4418 public boolean dispatchKeyEvent(KeyEvent event) {
4419 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420
Romain Guyf607bdc2010-09-10 19:20:06 -07004421 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 if (android.util.Config.LOGV) {
4423 captureViewInfo("captureViewKeyEvent", this);
4424 }
4425
Romain Guyf607bdc2010-09-10 19:20:06 -07004426 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4428 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4429 return true;
4430 }
4431
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004432 return event.dispatch(this, mAttachInfo != null
4433 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004434 }
4435
4436 /**
4437 * Dispatches a key shortcut event.
4438 *
4439 * @param event The key event to be dispatched.
4440 * @return True if the event was handled by the view, false otherwise.
4441 */
4442 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4443 return onKeyShortcut(event.getKeyCode(), event);
4444 }
4445
4446 /**
4447 * Pass the touch screen motion event down to the target view, or this
4448 * view if it is the target.
4449 *
4450 * @param event The motion event to be dispatched.
4451 * @return True if the event was handled by the view, false otherwise.
4452 */
4453 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004454 if (!onFilterTouchEventForSecurity(event)) {
4455 return false;
4456 }
4457
Romain Guyf607bdc2010-09-10 19:20:06 -07004458 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004459 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4460 mOnTouchListener.onTouch(this, event)) {
4461 return true;
4462 }
4463 return onTouchEvent(event);
4464 }
4465
4466 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004467 * Filter the touch event to apply security policies.
4468 *
4469 * @param event The motion event to be filtered.
4470 * @return True if the event should be dispatched, false if the event should be dropped.
4471 *
4472 * @see #getFilterTouchesWhenObscured
4473 */
4474 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004475 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004476 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4477 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4478 // Window is obscured, drop this touch.
4479 return false;
4480 }
4481 return true;
4482 }
4483
4484 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 * Pass a trackball motion event down to the focused view.
4486 *
4487 * @param event The motion event to be dispatched.
4488 * @return True if the event was handled by the view, false otherwise.
4489 */
4490 public boolean dispatchTrackballEvent(MotionEvent event) {
4491 //Log.i("view", "view=" + this + ", " + event.toString());
4492 return onTrackballEvent(event);
4493 }
4494
4495 /**
4496 * Called when the window containing this view gains or loses window focus.
4497 * ViewGroups should override to route to their children.
4498 *
4499 * @param hasFocus True if the window containing this view now has focus,
4500 * false otherwise.
4501 */
4502 public void dispatchWindowFocusChanged(boolean hasFocus) {
4503 onWindowFocusChanged(hasFocus);
4504 }
4505
4506 /**
4507 * Called when the window containing this view gains or loses focus. Note
4508 * that this is separate from view focus: to receive key events, both
4509 * your view and its window must have focus. If a window is displayed
4510 * on top of yours that takes input focus, then your own window will lose
4511 * focus but the view focus will remain unchanged.
4512 *
4513 * @param hasWindowFocus True if the window containing this view now has
4514 * focus, false otherwise.
4515 */
4516 public void onWindowFocusChanged(boolean hasWindowFocus) {
4517 InputMethodManager imm = InputMethodManager.peekInstance();
4518 if (!hasWindowFocus) {
4519 if (isPressed()) {
4520 setPressed(false);
4521 }
4522 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4523 imm.focusOut(this);
4524 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004525 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004526 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004527 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004528 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4529 imm.focusIn(this);
4530 }
4531 refreshDrawableState();
4532 }
4533
4534 /**
4535 * Returns true if this view is in a window that currently has window focus.
4536 * Note that this is not the same as the view itself having focus.
4537 *
4538 * @return True if this view is in a window that currently has window focus.
4539 */
4540 public boolean hasWindowFocus() {
4541 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4542 }
4543
4544 /**
Adam Powell326d8082009-12-09 15:10:07 -08004545 * Dispatch a view visibility change down the view hierarchy.
4546 * ViewGroups should override to route to their children.
4547 * @param changedView The view whose visibility changed. Could be 'this' or
4548 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004549 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4550 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004551 */
4552 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4553 onVisibilityChanged(changedView, visibility);
4554 }
4555
4556 /**
4557 * Called when the visibility of the view or an ancestor of the view is changed.
4558 * @param changedView The view whose visibility changed. Could be 'this' or
4559 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004560 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4561 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004562 */
4563 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004564 if (visibility == VISIBLE) {
4565 if (mAttachInfo != null) {
4566 initialAwakenScrollBars();
4567 } else {
4568 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4569 }
4570 }
Adam Powell326d8082009-12-09 15:10:07 -08004571 }
4572
4573 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004574 * Dispatch a hint about whether this view is displayed. For instance, when
4575 * a View moves out of the screen, it might receives a display hint indicating
4576 * the view is not displayed. Applications should not <em>rely</em> on this hint
4577 * as there is no guarantee that they will receive one.
4578 *
4579 * @param hint A hint about whether or not this view is displayed:
4580 * {@link #VISIBLE} or {@link #INVISIBLE}.
4581 */
4582 public void dispatchDisplayHint(int hint) {
4583 onDisplayHint(hint);
4584 }
4585
4586 /**
4587 * Gives this view a hint about whether is displayed or not. For instance, when
4588 * a View moves out of the screen, it might receives a display hint indicating
4589 * the view is not displayed. Applications should not <em>rely</em> on this hint
4590 * as there is no guarantee that they will receive one.
4591 *
4592 * @param hint A hint about whether or not this view is displayed:
4593 * {@link #VISIBLE} or {@link #INVISIBLE}.
4594 */
4595 protected void onDisplayHint(int hint) {
4596 }
4597
4598 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 * Dispatch a window visibility change down the view hierarchy.
4600 * ViewGroups should override to route to their children.
4601 *
4602 * @param visibility The new visibility of the window.
4603 *
4604 * @see #onWindowVisibilityChanged
4605 */
4606 public void dispatchWindowVisibilityChanged(int visibility) {
4607 onWindowVisibilityChanged(visibility);
4608 }
4609
4610 /**
4611 * Called when the window containing has change its visibility
4612 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4613 * that this tells you whether or not your window is being made visible
4614 * to the window manager; this does <em>not</em> tell you whether or not
4615 * your window is obscured by other windows on the screen, even if it
4616 * is itself visible.
4617 *
4618 * @param visibility The new visibility of the window.
4619 */
4620 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004621 if (visibility == VISIBLE) {
4622 initialAwakenScrollBars();
4623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004624 }
4625
4626 /**
4627 * Returns the current visibility of the window this view is attached to
4628 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4629 *
4630 * @return Returns the current visibility of the view's window.
4631 */
4632 public int getWindowVisibility() {
4633 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4634 }
4635
4636 /**
4637 * Retrieve the overall visible display size in which the window this view is
4638 * attached to has been positioned in. This takes into account screen
4639 * decorations above the window, for both cases where the window itself
4640 * is being position inside of them or the window is being placed under
4641 * then and covered insets are used for the window to position its content
4642 * inside. In effect, this tells you the available area where content can
4643 * be placed and remain visible to users.
4644 *
4645 * <p>This function requires an IPC back to the window manager to retrieve
4646 * the requested information, so should not be used in performance critical
4647 * code like drawing.
4648 *
4649 * @param outRect Filled in with the visible display frame. If the view
4650 * is not attached to a window, this is simply the raw display size.
4651 */
4652 public void getWindowVisibleDisplayFrame(Rect outRect) {
4653 if (mAttachInfo != null) {
4654 try {
4655 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4656 } catch (RemoteException e) {
4657 return;
4658 }
4659 // XXX This is really broken, and probably all needs to be done
4660 // in the window manager, and we need to know more about whether
4661 // we want the area behind or in front of the IME.
4662 final Rect insets = mAttachInfo.mVisibleInsets;
4663 outRect.left += insets.left;
4664 outRect.top += insets.top;
4665 outRect.right -= insets.right;
4666 outRect.bottom -= insets.bottom;
4667 return;
4668 }
4669 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4670 outRect.set(0, 0, d.getWidth(), d.getHeight());
4671 }
4672
4673 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004674 * Dispatch a notification about a resource configuration change down
4675 * the view hierarchy.
4676 * ViewGroups should override to route to their children.
4677 *
4678 * @param newConfig The new resource configuration.
4679 *
4680 * @see #onConfigurationChanged
4681 */
4682 public void dispatchConfigurationChanged(Configuration newConfig) {
4683 onConfigurationChanged(newConfig);
4684 }
4685
4686 /**
4687 * Called when the current configuration of the resources being used
4688 * by the application have changed. You can use this to decide when
4689 * to reload resources that can changed based on orientation and other
4690 * configuration characterstics. You only need to use this if you are
4691 * not relying on the normal {@link android.app.Activity} mechanism of
4692 * recreating the activity instance upon a configuration change.
4693 *
4694 * @param newConfig The new resource configuration.
4695 */
4696 protected void onConfigurationChanged(Configuration newConfig) {
4697 }
4698
4699 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700 * Private function to aggregate all per-view attributes in to the view
4701 * root.
4702 */
4703 void dispatchCollectViewAttributes(int visibility) {
4704 performCollectViewAttributes(visibility);
4705 }
4706
4707 void performCollectViewAttributes(int visibility) {
4708 //noinspection PointlessBitwiseExpression
4709 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4710 == (VISIBLE | KEEP_SCREEN_ON)) {
4711 mAttachInfo.mKeepScreenOn = true;
4712 }
4713 }
4714
4715 void needGlobalAttributesUpdate(boolean force) {
4716 AttachInfo ai = mAttachInfo;
4717 if (ai != null) {
4718 if (ai.mKeepScreenOn || force) {
4719 ai.mRecomputeGlobalAttributes = true;
4720 }
4721 }
4722 }
4723
4724 /**
4725 * Returns whether the device is currently in touch mode. Touch mode is entered
4726 * once the user begins interacting with the device by touch, and affects various
4727 * things like whether focus is always visible to the user.
4728 *
4729 * @return Whether the device is in touch mode.
4730 */
4731 @ViewDebug.ExportedProperty
4732 public boolean isInTouchMode() {
4733 if (mAttachInfo != null) {
4734 return mAttachInfo.mInTouchMode;
4735 } else {
4736 return ViewRoot.isInTouchMode();
4737 }
4738 }
4739
4740 /**
4741 * Returns the context the view is running in, through which it can
4742 * access the current theme, resources, etc.
4743 *
4744 * @return The view's Context.
4745 */
4746 @ViewDebug.CapturedViewProperty
4747 public final Context getContext() {
4748 return mContext;
4749 }
4750
4751 /**
4752 * Handle a key event before it is processed by any input method
4753 * associated with the view hierarchy. This can be used to intercept
4754 * key events in special situations before the IME consumes them; a
4755 * typical example would be handling the BACK key to update the application's
4756 * UI instead of allowing the IME to see it and close itself.
4757 *
4758 * @param keyCode The value in event.getKeyCode().
4759 * @param event Description of the key event.
4760 * @return If you handled the event, return true. If you want to allow the
4761 * event to be handled by the next receiver, return false.
4762 */
4763 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4764 return false;
4765 }
4766
4767 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004768 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
4769 * KeyEvent.Callback.onKeyDown()}: perform press of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004770 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4771 * is released, if the view is enabled and clickable.
4772 *
4773 * @param keyCode A key code that represents the button pressed, from
4774 * {@link android.view.KeyEvent}.
4775 * @param event The KeyEvent object that defines the button action.
4776 */
4777 public boolean onKeyDown(int keyCode, KeyEvent event) {
4778 boolean result = false;
4779
4780 switch (keyCode) {
4781 case KeyEvent.KEYCODE_DPAD_CENTER:
4782 case KeyEvent.KEYCODE_ENTER: {
4783 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4784 return true;
4785 }
4786 // Long clickable items don't necessarily have to be clickable
4787 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4788 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4789 (event.getRepeatCount() == 0)) {
4790 setPressed(true);
4791 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004792 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004793 }
4794 return true;
4795 }
4796 break;
4797 }
4798 }
4799 return result;
4800 }
4801
4802 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004803 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4804 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4805 * the event).
4806 */
4807 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4808 return false;
4809 }
4810
4811 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004812 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
4813 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004814 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4815 * {@link KeyEvent#KEYCODE_ENTER} is released.
4816 *
4817 * @param keyCode A key code that represents the button pressed, from
4818 * {@link android.view.KeyEvent}.
4819 * @param event The KeyEvent object that defines the button action.
4820 */
4821 public boolean onKeyUp(int keyCode, KeyEvent event) {
4822 boolean result = false;
4823
4824 switch (keyCode) {
4825 case KeyEvent.KEYCODE_DPAD_CENTER:
4826 case KeyEvent.KEYCODE_ENTER: {
4827 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4828 return true;
4829 }
4830 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4831 setPressed(false);
4832
4833 if (!mHasPerformedLongPress) {
4834 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004835 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004836
4837 result = performClick();
4838 }
4839 }
4840 break;
4841 }
4842 }
4843 return result;
4844 }
4845
4846 /**
4847 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4848 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4849 * the event).
4850 *
4851 * @param keyCode A key code that represents the button pressed, from
4852 * {@link android.view.KeyEvent}.
4853 * @param repeatCount The number of times the action was made.
4854 * @param event The KeyEvent object that defines the button action.
4855 */
4856 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4857 return false;
4858 }
4859
4860 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08004861 * Called on the focused view when a key shortcut event is not handled.
4862 * Override this method to implement local key shortcuts for the View.
4863 * Key shortcuts can also be implemented by setting the
4864 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004865 *
4866 * @param keyCode The value in event.getKeyCode().
4867 * @param event Description of the key event.
4868 * @return If you handled the event, return true. If you want to allow the
4869 * event to be handled by the next receiver, return false.
4870 */
4871 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4872 return false;
4873 }
4874
4875 /**
4876 * Check whether the called view is a text editor, in which case it
4877 * would make sense to automatically display a soft input window for
4878 * it. Subclasses should override this if they implement
4879 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004880 * a call on that method would return a non-null InputConnection, and
4881 * they are really a first-class editor that the user would normally
4882 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004883 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004884 * <p>The default implementation always returns false. This does
4885 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4886 * will not be called or the user can not otherwise perform edits on your
4887 * view; it is just a hint to the system that this is not the primary
4888 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004889 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890 * @return Returns true if this view is a text editor, else false.
4891 */
4892 public boolean onCheckIsTextEditor() {
4893 return false;
4894 }
Romain Guy8506ab42009-06-11 17:35:47 -07004895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 /**
4897 * Create a new InputConnection for an InputMethod to interact
4898 * with the view. The default implementation returns null, since it doesn't
4899 * support input methods. You can override this to implement such support.
4900 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004901 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 * <p>When implementing this, you probably also want to implement
4903 * {@link #onCheckIsTextEditor()} to indicate you will return a
4904 * non-null InputConnection.
4905 *
4906 * @param outAttrs Fill in with attribute information about the connection.
4907 */
4908 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4909 return null;
4910 }
4911
4912 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004913 * Called by the {@link android.view.inputmethod.InputMethodManager}
4914 * when a view who is not the current
4915 * input connection target is trying to make a call on the manager. The
4916 * default implementation returns false; you can override this to return
4917 * true for certain views if you are performing InputConnection proxying
4918 * to them.
4919 * @param view The View that is making the InputMethodManager call.
4920 * @return Return true to allow the call, false to reject.
4921 */
4922 public boolean checkInputConnectionProxy(View view) {
4923 return false;
4924 }
Romain Guy8506ab42009-06-11 17:35:47 -07004925
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004926 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004927 * Show the context menu for this view. It is not safe to hold on to the
4928 * menu after returning from this method.
4929 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004930 * You should normally not overload this method. Overload
4931 * {@link #onCreateContextMenu(ContextMenu)} or define an
4932 * {@link OnCreateContextMenuListener} to add items to the context menu.
4933 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004934 * @param menu The context menu to populate
4935 */
4936 public void createContextMenu(ContextMenu menu) {
4937 ContextMenuInfo menuInfo = getContextMenuInfo();
4938
4939 // Sets the current menu info so all items added to menu will have
4940 // my extra info set.
4941 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4942
4943 onCreateContextMenu(menu);
4944 if (mOnCreateContextMenuListener != null) {
4945 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4946 }
4947
4948 // Clear the extra information so subsequent items that aren't mine don't
4949 // have my extra info.
4950 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4951
4952 if (mParent != null) {
4953 mParent.createContextMenu(menu);
4954 }
4955 }
4956
4957 /**
4958 * Views should implement this if they have extra information to associate
4959 * with the context menu. The return result is supplied as a parameter to
4960 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4961 * callback.
4962 *
4963 * @return Extra information about the item for which the context menu
4964 * should be shown. This information will vary across different
4965 * subclasses of View.
4966 */
4967 protected ContextMenuInfo getContextMenuInfo() {
4968 return null;
4969 }
4970
4971 /**
4972 * Views should implement this if the view itself is going to add items to
4973 * the context menu.
4974 *
4975 * @param menu the context menu to populate
4976 */
4977 protected void onCreateContextMenu(ContextMenu menu) {
4978 }
4979
4980 /**
4981 * Implement this method to handle trackball motion events. The
4982 * <em>relative</em> movement of the trackball since the last event
4983 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4984 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4985 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4986 * they will often be fractional values, representing the more fine-grained
4987 * movement information available from a trackball).
4988 *
4989 * @param event The motion event.
4990 * @return True if the event was handled, false otherwise.
4991 */
4992 public boolean onTrackballEvent(MotionEvent event) {
4993 return false;
4994 }
4995
4996 /**
4997 * Implement this method to handle touch screen motion events.
4998 *
4999 * @param event The motion event.
5000 * @return True if the event was handled, false otherwise.
5001 */
5002 public boolean onTouchEvent(MotionEvent event) {
5003 final int viewFlags = mViewFlags;
5004
5005 if ((viewFlags & ENABLED_MASK) == DISABLED) {
5006 // A disabled view that is clickable still consumes the touch
5007 // events, it just doesn't respond to them.
5008 return (((viewFlags & CLICKABLE) == CLICKABLE ||
5009 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
5010 }
5011
5012 if (mTouchDelegate != null) {
5013 if (mTouchDelegate.onTouchEvent(event)) {
5014 return true;
5015 }
5016 }
5017
5018 if (((viewFlags & CLICKABLE) == CLICKABLE ||
5019 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
5020 switch (event.getAction()) {
5021 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08005022 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
5023 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005024 // take focus if we don't have it already and we should in
5025 // touch mode.
5026 boolean focusTaken = false;
5027 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
5028 focusTaken = requestFocus();
5029 }
5030
5031 if (!mHasPerformedLongPress) {
5032 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05005033 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005034
5035 // Only perform take click actions if we were in the pressed state
5036 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08005037 // Use a Runnable and post this rather than calling
5038 // performClick directly. This lets other visual state
5039 // of the view update before click actions start.
5040 if (mPerformClick == null) {
5041 mPerformClick = new PerformClick();
5042 }
5043 if (!post(mPerformClick)) {
5044 performClick();
5045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005046 }
5047 }
5048
5049 if (mUnsetPressedState == null) {
5050 mUnsetPressedState = new UnsetPressedState();
5051 }
5052
Adam Powelle14579b2009-12-16 18:39:52 -08005053 if (prepressed) {
5054 mPrivateFlags |= PRESSED;
5055 refreshDrawableState();
5056 postDelayed(mUnsetPressedState,
5057 ViewConfiguration.getPressedStateDuration());
5058 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 // If the post failed, unpress right now
5060 mUnsetPressedState.run();
5061 }
Adam Powelle14579b2009-12-16 18:39:52 -08005062 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005063 }
5064 break;
5065
5066 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08005067 if (mPendingCheckForTap == null) {
5068 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 }
Adam Powelle14579b2009-12-16 18:39:52 -08005070 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08005071 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08005072 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005073 break;
5074
5075 case MotionEvent.ACTION_CANCEL:
5076 mPrivateFlags &= ~PRESSED;
5077 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08005078 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005079 break;
5080
5081 case MotionEvent.ACTION_MOVE:
5082 final int x = (int) event.getX();
5083 final int y = (int) event.getY();
5084
5085 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07005086 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005087 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08005088 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08005090 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05005091 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092
5093 // Need to switch from pressed to not pressed
5094 mPrivateFlags &= ~PRESSED;
5095 refreshDrawableState();
5096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 }
5098 break;
5099 }
5100 return true;
5101 }
5102
5103 return false;
5104 }
5105
5106 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05005107 * Remove the longpress detection timer.
5108 */
5109 private void removeLongPressCallback() {
5110 if (mPendingCheckForLongPress != null) {
5111 removeCallbacks(mPendingCheckForLongPress);
5112 }
5113 }
Adam Powelle14579b2009-12-16 18:39:52 -08005114
5115 /**
Romain Guya440b002010-02-24 15:57:54 -08005116 * Remove the prepress detection timer.
5117 */
5118 private void removeUnsetPressCallback() {
5119 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
5120 setPressed(false);
5121 removeCallbacks(mUnsetPressedState);
5122 }
5123 }
5124
5125 /**
Adam Powelle14579b2009-12-16 18:39:52 -08005126 * Remove the tap detection timer.
5127 */
5128 private void removeTapCallback() {
5129 if (mPendingCheckForTap != null) {
5130 mPrivateFlags &= ~PREPRESSED;
5131 removeCallbacks(mPendingCheckForTap);
5132 }
5133 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05005134
5135 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 * Cancels a pending long press. Your subclass can use this if you
5137 * want the context menu to come up if the user presses and holds
5138 * at the same place, but you don't want it to come up if they press
5139 * and then move around enough to cause scrolling.
5140 */
5141 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05005142 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08005143
5144 /*
5145 * The prepressed state handled by the tap callback is a display
5146 * construct, but the tap callback will post a long press callback
5147 * less its own timeout. Remove it here.
5148 */
5149 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150 }
5151
5152 /**
5153 * Sets the TouchDelegate for this View.
5154 */
5155 public void setTouchDelegate(TouchDelegate delegate) {
5156 mTouchDelegate = delegate;
5157 }
5158
5159 /**
5160 * Gets the TouchDelegate for this View.
5161 */
5162 public TouchDelegate getTouchDelegate() {
5163 return mTouchDelegate;
5164 }
5165
5166 /**
5167 * Set flags controlling behavior of this view.
5168 *
5169 * @param flags Constant indicating the value which should be set
5170 * @param mask Constant indicating the bit range that should be changed
5171 */
5172 void setFlags(int flags, int mask) {
5173 int old = mViewFlags;
5174 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
5175
5176 int changed = mViewFlags ^ old;
5177 if (changed == 0) {
5178 return;
5179 }
5180 int privateFlags = mPrivateFlags;
5181
5182 /* Check if the FOCUSABLE bit has changed */
5183 if (((changed & FOCUSABLE_MASK) != 0) &&
5184 ((privateFlags & HAS_BOUNDS) !=0)) {
5185 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
5186 && ((privateFlags & FOCUSED) != 0)) {
5187 /* Give up focus if we are no longer focusable */
5188 clearFocus();
5189 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
5190 && ((privateFlags & FOCUSED) == 0)) {
5191 /*
5192 * Tell the view system that we are now available to take focus
5193 * if no one else already has it.
5194 */
5195 if (mParent != null) mParent.focusableViewAvailable(this);
5196 }
5197 }
5198
5199 if ((flags & VISIBILITY_MASK) == VISIBLE) {
5200 if ((changed & VISIBILITY_MASK) != 0) {
5201 /*
5202 * If this view is becoming visible, set the DRAWN flag so that
5203 * the next invalidate() will not be skipped.
5204 */
5205 mPrivateFlags |= DRAWN;
5206
5207 needGlobalAttributesUpdate(true);
5208
5209 // a view becoming visible is worth notifying the parent
5210 // about in case nothing has focus. even if this specific view
5211 // isn't focusable, it may contain something that is, so let
5212 // the root view try to give this focus if nothing else does.
5213 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
5214 mParent.focusableViewAvailable(this);
5215 }
5216 }
5217 }
5218
5219 /* Check if the GONE bit has changed */
5220 if ((changed & GONE) != 0) {
5221 needGlobalAttributesUpdate(false);
5222 requestLayout();
5223 invalidate();
5224
Romain Guyecd80ee2009-12-03 17:13:02 -08005225 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5226 if (hasFocus()) clearFocus();
5227 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005228 }
5229 if (mAttachInfo != null) {
5230 mAttachInfo.mViewVisibilityChanged = true;
5231 }
5232 }
5233
5234 /* Check if the VISIBLE bit has changed */
5235 if ((changed & INVISIBLE) != 0) {
5236 needGlobalAttributesUpdate(false);
5237 invalidate();
5238
5239 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5240 // root view becoming invisible shouldn't clear focus
5241 if (getRootView() != this) {
5242 clearFocus();
5243 }
5244 }
5245 if (mAttachInfo != null) {
5246 mAttachInfo.mViewVisibilityChanged = true;
5247 }
5248 }
5249
Adam Powell326d8082009-12-09 15:10:07 -08005250 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07005251 if (mParent instanceof ViewGroup) {
5252 ((ViewGroup)mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
5253 }
Adam Powell326d8082009-12-09 15:10:07 -08005254 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5255 }
5256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5258 destroyDrawingCache();
5259 }
5260
5261 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5262 destroyDrawingCache();
5263 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5264 }
5265
5266 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5267 destroyDrawingCache();
5268 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5269 }
5270
5271 if ((changed & DRAW_MASK) != 0) {
5272 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5273 if (mBGDrawable != null) {
5274 mPrivateFlags &= ~SKIP_DRAW;
5275 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5276 } else {
5277 mPrivateFlags |= SKIP_DRAW;
5278 }
5279 } else {
5280 mPrivateFlags &= ~SKIP_DRAW;
5281 }
5282 requestLayout();
5283 invalidate();
5284 }
5285
5286 if ((changed & KEEP_SCREEN_ON) != 0) {
5287 if (mParent != null) {
5288 mParent.recomputeViewAttributes(this);
5289 }
5290 }
5291 }
5292
5293 /**
5294 * Change the view's z order in the tree, so it's on top of other sibling
5295 * views
5296 */
5297 public void bringToFront() {
5298 if (mParent != null) {
5299 mParent.bringChildToFront(this);
5300 }
5301 }
5302
5303 /**
5304 * This is called in response to an internal scroll in this view (i.e., the
5305 * view scrolled its own contents). This is typically as a result of
5306 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5307 * called.
5308 *
5309 * @param l Current horizontal scroll origin.
5310 * @param t Current vertical scroll origin.
5311 * @param oldl Previous horizontal scroll origin.
5312 * @param oldt Previous vertical scroll origin.
5313 */
5314 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5315 mBackgroundSizeChanged = true;
5316
5317 final AttachInfo ai = mAttachInfo;
5318 if (ai != null) {
5319 ai.mViewScrollChanged = true;
5320 }
5321 }
5322
5323 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005324 * Interface definition for a callback to be invoked when the layout bounds of a view
5325 * changes due to layout processing.
5326 */
5327 public interface OnLayoutChangeListener {
5328 /**
5329 * Called when the focus state of a view has changed.
5330 *
5331 * @param v The view whose state has changed.
5332 * @param left The new value of the view's left property.
5333 * @param top The new value of the view's top property.
5334 * @param right The new value of the view's right property.
5335 * @param bottom The new value of the view's bottom property.
5336 * @param oldLeft The previous value of the view's left property.
5337 * @param oldTop The previous value of the view's top property.
5338 * @param oldRight The previous value of the view's right property.
5339 * @param oldBottom The previous value of the view's bottom property.
5340 */
5341 void onLayoutChange(View v, int left, int top, int right, int bottom,
5342 int oldLeft, int oldTop, int oldRight, int oldBottom);
5343 }
5344
5345 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005346 * This is called during layout when the size of this view has changed. If
5347 * you were just added to the view hierarchy, you're called with the old
5348 * values of 0.
5349 *
5350 * @param w Current width of this view.
5351 * @param h Current height of this view.
5352 * @param oldw Old width of this view.
5353 * @param oldh Old height of this view.
5354 */
5355 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5356 }
5357
5358 /**
5359 * Called by draw to draw the child views. This may be overridden
5360 * by derived classes to gain control just before its children are drawn
5361 * (but after its own view has been drawn).
5362 * @param canvas the canvas on which to draw the view
5363 */
5364 protected void dispatchDraw(Canvas canvas) {
5365 }
5366
5367 /**
5368 * Gets the parent of this view. Note that the parent is a
5369 * ViewParent and not necessarily a View.
5370 *
5371 * @return Parent of this view.
5372 */
5373 public final ViewParent getParent() {
5374 return mParent;
5375 }
5376
5377 /**
5378 * Return the scrolled left position of this view. This is the left edge of
5379 * the displayed part of your view. You do not need to draw any pixels
5380 * farther left, since those are outside of the frame of your view on
5381 * screen.
5382 *
5383 * @return The left edge of the displayed part of your view, in pixels.
5384 */
5385 public final int getScrollX() {
5386 return mScrollX;
5387 }
5388
5389 /**
5390 * Return the scrolled top position of this view. This is the top edge of
5391 * the displayed part of your view. You do not need to draw any pixels above
5392 * it, since those are outside of the frame of your view on screen.
5393 *
5394 * @return The top edge of the displayed part of your view, in pixels.
5395 */
5396 public final int getScrollY() {
5397 return mScrollY;
5398 }
5399
5400 /**
5401 * Return the width of the your view.
5402 *
5403 * @return The width of your view, in pixels.
5404 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005405 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005406 public final int getWidth() {
5407 return mRight - mLeft;
5408 }
5409
5410 /**
5411 * Return the height of your view.
5412 *
5413 * @return The height of your view, in pixels.
5414 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005415 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005416 public final int getHeight() {
5417 return mBottom - mTop;
5418 }
5419
5420 /**
5421 * Return the visible drawing bounds of your view. Fills in the output
5422 * rectangle with the values from getScrollX(), getScrollY(),
5423 * getWidth(), and getHeight().
5424 *
5425 * @param outRect The (scrolled) drawing bounds of the view.
5426 */
5427 public void getDrawingRect(Rect outRect) {
5428 outRect.left = mScrollX;
5429 outRect.top = mScrollY;
5430 outRect.right = mScrollX + (mRight - mLeft);
5431 outRect.bottom = mScrollY + (mBottom - mTop);
5432 }
5433
5434 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005435 * Like {@link #getMeasuredWidthAndState()}, but only returns the
5436 * raw width component (that is the result is masked by
5437 * {@link #MEASURED_SIZE_MASK}).
5438 *
5439 * @return The raw measured width of this view.
5440 */
5441 public final int getMeasuredWidth() {
5442 return mMeasuredWidth & MEASURED_SIZE_MASK;
5443 }
5444
5445 /**
5446 * Return the full width measurement information for this view as computed
5447 * by the most recent call to {@link #measure}. This result is a bit mask
5448 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005449 * This should be used during measurement and layout calculations only. Use
5450 * {@link #getWidth()} to see how wide a view is after layout.
5451 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005452 * @return The measured width of this view as a bit mask.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005453 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08005454 public final int getMeasuredWidthAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 return mMeasuredWidth;
5456 }
5457
5458 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005459 * Like {@link #getMeasuredHeightAndState()}, but only returns the
5460 * raw width component (that is the result is masked by
5461 * {@link #MEASURED_SIZE_MASK}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005462 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005463 * @return The raw measured height of this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 */
5465 public final int getMeasuredHeight() {
Dianne Hackborn189ee182010-12-02 21:48:53 -08005466 return mMeasuredHeight & MEASURED_SIZE_MASK;
5467 }
5468
5469 /**
5470 * Return the full height measurement information for this view as computed
5471 * by the most recent call to {@link #measure}. This result is a bit mask
5472 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5473 * This should be used during measurement and layout calculations only. Use
5474 * {@link #getHeight()} to see how wide a view is after layout.
5475 *
5476 * @return The measured width of this view as a bit mask.
5477 */
5478 public final int getMeasuredHeightAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 return mMeasuredHeight;
5480 }
5481
5482 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005483 * Return only the state bits of {@link #getMeasuredWidthAndState()}
5484 * and {@link #getMeasuredHeightAndState()}, combined into one integer.
5485 * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
5486 * and the height component is at the shifted bits
5487 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
5488 */
5489 public final int getMeasuredState() {
5490 return (mMeasuredWidth&MEASURED_STATE_MASK)
5491 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
5492 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
5493 }
5494
5495 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005496 * The transform matrix of this view, which is calculated based on the current
5497 * roation, scale, and pivot properties.
5498 *
5499 * @see #getRotation()
5500 * @see #getScaleX()
5501 * @see #getScaleY()
5502 * @see #getPivotX()
5503 * @see #getPivotY()
5504 * @return The current transform matrix for the view
5505 */
5506 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005507 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005508 return mMatrix;
5509 }
5510
5511 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005512 * Utility function to determine if the value is far enough away from zero to be
5513 * considered non-zero.
5514 * @param value A floating point value to check for zero-ness
5515 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5516 */
5517 private static boolean nonzero(float value) {
5518 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5519 }
5520
5521 /**
Jeff Brown86671742010-09-30 20:00:15 -07005522 * Returns true if the transform matrix is the identity matrix.
5523 * Recomputes the matrix if necessary.
Romain Guy33e72ae2010-07-17 12:40:29 -07005524 *
5525 * @return True if the transform matrix is the identity matrix, false otherwise.
5526 */
Jeff Brown86671742010-09-30 20:00:15 -07005527 final boolean hasIdentityMatrix() {
5528 updateMatrix();
5529 return mMatrixIsIdentity;
5530 }
5531
5532 /**
5533 * Recomputes the transform matrix if necessary.
5534 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005535 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005536 if (mMatrixDirty) {
5537 // transform-related properties have changed since the last time someone
5538 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005539
5540 // Figure out if we need to update the pivot point
5541 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005542 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005543 mPrevWidth = mRight - mLeft;
5544 mPrevHeight = mBottom - mTop;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -08005545 mPivotX = mPrevWidth / 2f;
5546 mPivotY = mPrevHeight / 2f;
Chet Haasefd2b0022010-08-06 13:08:56 -07005547 }
5548 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005549 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005550 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5551 mMatrix.setTranslate(mTranslationX, mTranslationY);
5552 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5553 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5554 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005555 if (mCamera == null) {
5556 mCamera = new Camera();
5557 matrix3D = new Matrix();
5558 }
5559 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005560 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005561 mCamera.rotateX(mRotationX);
5562 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005563 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005564 mCamera.getMatrix(matrix3D);
5565 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005566 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005567 mMatrix.postConcat(matrix3D);
5568 mCamera.restore();
5569 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005570 mMatrixDirty = false;
5571 mMatrixIsIdentity = mMatrix.isIdentity();
5572 mInverseMatrixDirty = true;
5573 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005574 }
5575
5576 /**
5577 * Utility method to retrieve the inverse of the current mMatrix property.
5578 * We cache the matrix to avoid recalculating it when transform properties
5579 * have not changed.
5580 *
5581 * @return The inverse of the current matrix of this view.
5582 */
Jeff Brown86671742010-09-30 20:00:15 -07005583 final Matrix getInverseMatrix() {
5584 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005585 if (mInverseMatrixDirty) {
5586 if (mInverseMatrix == null) {
5587 mInverseMatrix = new Matrix();
5588 }
5589 mMatrix.invert(mInverseMatrix);
5590 mInverseMatrixDirty = false;
5591 }
5592 return mInverseMatrix;
5593 }
5594
5595 /**
5596 * The degrees that the view is rotated around the pivot point.
5597 *
5598 * @see #getPivotX()
5599 * @see #getPivotY()
5600 * @return The degrees of rotation.
5601 */
5602 public float getRotation() {
5603 return mRotation;
5604 }
5605
5606 /**
Chet Haase897247b2010-09-09 14:54:47 -07005607 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5608 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005609 *
5610 * @param rotation The degrees of rotation.
5611 * @see #getPivotX()
5612 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005613 *
5614 * @attr ref android.R.styleable#View_rotation
Chet Haasec3aa3612010-06-17 08:50:37 -07005615 */
5616 public void setRotation(float rotation) {
5617 if (mRotation != rotation) {
5618 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005619 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005620 mRotation = rotation;
5621 mMatrixDirty = true;
5622 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005623 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005624 }
5625 }
5626
5627 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005628 * The degrees that the view is rotated around the vertical axis through the pivot point.
5629 *
5630 * @see #getPivotX()
5631 * @see #getPivotY()
5632 * @return The degrees of Y rotation.
5633 */
5634 public float getRotationY() {
5635 return mRotationY;
5636 }
5637
5638 /**
Chet Haase897247b2010-09-09 14:54:47 -07005639 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5640 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5641 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005642 *
5643 * @param rotationY The degrees of Y rotation.
5644 * @see #getPivotX()
5645 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005646 *
5647 * @attr ref android.R.styleable#View_rotationY
Chet Haasefd2b0022010-08-06 13:08:56 -07005648 */
5649 public void setRotationY(float rotationY) {
5650 if (mRotationY != rotationY) {
5651 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005652 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005653 mRotationY = rotationY;
5654 mMatrixDirty = true;
5655 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005656 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005657 }
5658 }
5659
5660 /**
5661 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5662 *
5663 * @see #getPivotX()
5664 * @see #getPivotY()
5665 * @return The degrees of X rotation.
5666 */
5667 public float getRotationX() {
5668 return mRotationX;
5669 }
5670
5671 /**
Chet Haase897247b2010-09-09 14:54:47 -07005672 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5673 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5674 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005675 *
5676 * @param rotationX The degrees of X rotation.
5677 * @see #getPivotX()
5678 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005679 *
5680 * @attr ref android.R.styleable#View_rotationX
Chet Haasefd2b0022010-08-06 13:08:56 -07005681 */
5682 public void setRotationX(float rotationX) {
5683 if (mRotationX != rotationX) {
5684 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005685 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005686 mRotationX = rotationX;
5687 mMatrixDirty = true;
5688 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005689 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005690 }
5691 }
5692
5693 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005694 * The amount that the view is scaled in x around the pivot point, as a proportion of
5695 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5696 *
Joe Onorato93162322010-09-16 15:42:01 -04005697 * <p>By default, this is 1.0f.
5698 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005699 * @see #getPivotX()
5700 * @see #getPivotY()
5701 * @return The scaling factor.
5702 */
5703 public float getScaleX() {
5704 return mScaleX;
5705 }
5706
5707 /**
5708 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5709 * the view's unscaled width. A value of 1 means that no scaling is applied.
5710 *
5711 * @param scaleX The scaling factor.
5712 * @see #getPivotX()
5713 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005714 *
5715 * @attr ref android.R.styleable#View_scaleX
Chet Haasec3aa3612010-06-17 08:50:37 -07005716 */
5717 public void setScaleX(float scaleX) {
5718 if (mScaleX != scaleX) {
5719 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005720 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005721 mScaleX = scaleX;
5722 mMatrixDirty = true;
5723 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005724 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005725 }
5726 }
5727
5728 /**
5729 * The amount that the view is scaled in y around the pivot point, as a proportion of
5730 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5731 *
Joe Onorato93162322010-09-16 15:42:01 -04005732 * <p>By default, this is 1.0f.
5733 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005734 * @see #getPivotX()
5735 * @see #getPivotY()
5736 * @return The scaling factor.
5737 */
5738 public float getScaleY() {
5739 return mScaleY;
5740 }
5741
5742 /**
5743 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5744 * the view's unscaled width. A value of 1 means that no scaling is applied.
5745 *
5746 * @param scaleY The scaling factor.
5747 * @see #getPivotX()
5748 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005749 *
5750 * @attr ref android.R.styleable#View_scaleY
Chet Haasec3aa3612010-06-17 08:50:37 -07005751 */
5752 public void setScaleY(float scaleY) {
5753 if (mScaleY != scaleY) {
5754 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005755 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005756 mScaleY = scaleY;
5757 mMatrixDirty = true;
5758 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005759 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005760 }
5761 }
5762
5763 /**
5764 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5765 * and {@link #setScaleX(float) scaled}.
5766 *
5767 * @see #getRotation()
5768 * @see #getScaleX()
5769 * @see #getScaleY()
5770 * @see #getPivotY()
5771 * @return The x location of the pivot point.
5772 */
5773 public float getPivotX() {
5774 return mPivotX;
5775 }
5776
5777 /**
5778 * Sets the x location of the point around which the view is
5779 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005780 * By default, the pivot point is centered on the object.
5781 * Setting this property disables this behavior and causes the view to use only the
5782 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005783 *
5784 * @param pivotX The x location of the pivot point.
5785 * @see #getRotation()
5786 * @see #getScaleX()
5787 * @see #getScaleY()
5788 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005789 *
5790 * @attr ref android.R.styleable#View_transformPivotX
Chet Haasec3aa3612010-06-17 08:50:37 -07005791 */
5792 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005793 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005794 if (mPivotX != pivotX) {
5795 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005796 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005797 mPivotX = pivotX;
5798 mMatrixDirty = true;
5799 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005800 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005801 }
5802 }
5803
5804 /**
5805 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5806 * and {@link #setScaleY(float) scaled}.
5807 *
5808 * @see #getRotation()
5809 * @see #getScaleX()
5810 * @see #getScaleY()
5811 * @see #getPivotY()
5812 * @return The y location of the pivot point.
5813 */
5814 public float getPivotY() {
5815 return mPivotY;
5816 }
5817
5818 /**
5819 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005820 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5821 * Setting this property disables this behavior and causes the view to use only the
5822 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005823 *
5824 * @param pivotY The y location of the pivot point.
5825 * @see #getRotation()
5826 * @see #getScaleX()
5827 * @see #getScaleY()
5828 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005829 *
5830 * @attr ref android.R.styleable#View_transformPivotY
Chet Haasec3aa3612010-06-17 08:50:37 -07005831 */
5832 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005833 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005834 if (mPivotY != pivotY) {
5835 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005836 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005837 mPivotY = pivotY;
5838 mMatrixDirty = true;
5839 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005840 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005841 }
5842 }
5843
5844 /**
5845 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5846 * completely transparent and 1 means the view is completely opaque.
5847 *
Joe Onorato93162322010-09-16 15:42:01 -04005848 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005849 * @return The opacity of the view.
5850 */
5851 public float getAlpha() {
5852 return mAlpha;
5853 }
5854
5855 /**
Romain Guy171c5922011-01-06 10:04:23 -08005856 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5857 * completely transparent and 1 means the view is completely opaque.</p>
5858 *
5859 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
5860 * responsible for applying the opacity itself. Otherwise, calling this method is
5861 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
5862 * setting a hardware layer.</p>
Chet Haasec3aa3612010-06-17 08:50:37 -07005863 *
5864 * @param alpha The opacity of the view.
Chet Haase73066682010-11-29 15:55:32 -08005865 *
Romain Guy171c5922011-01-06 10:04:23 -08005866 * @see #setLayerType(int, android.graphics.Paint)
5867 *
Chet Haase73066682010-11-29 15:55:32 -08005868 * @attr ref android.R.styleable#View_alpha
Chet Haasec3aa3612010-06-17 08:50:37 -07005869 */
5870 public void setAlpha(float alpha) {
5871 mAlpha = alpha;
Chet Haaseed032702010-10-01 14:05:54 -07005872 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07005873 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005874 // subclass is handling alpha - don't optimize rendering cache invalidation
5875 invalidate();
5876 } else {
Romain Guya3496a92010-10-12 11:53:24 -07005877 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005878 invalidate(false);
5879 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005880 }
5881
5882 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 * Top position of this view relative to its parent.
5884 *
5885 * @return The top of this view, in pixels.
5886 */
5887 @ViewDebug.CapturedViewProperty
5888 public final int getTop() {
5889 return mTop;
5890 }
5891
5892 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005893 * Sets the top position of this view relative to its parent. This method is meant to be called
5894 * by the layout system and should not generally be called otherwise, because the property
5895 * may be changed at any time by the layout.
5896 *
5897 * @param top The top of this view, in pixels.
5898 */
5899 public final void setTop(int top) {
5900 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07005901 updateMatrix();
5902 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005903 final ViewParent p = mParent;
5904 if (p != null && mAttachInfo != null) {
5905 final Rect r = mAttachInfo.mTmpInvalRect;
5906 int minTop;
5907 int yLoc;
5908 if (top < mTop) {
5909 minTop = top;
5910 yLoc = top - mTop;
5911 } else {
5912 minTop = mTop;
5913 yLoc = 0;
5914 }
5915 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5916 p.invalidateChild(this, r);
5917 }
5918 } else {
5919 // Double-invalidation is necessary to capture view's old and new areas
5920 invalidate();
5921 }
5922
Chet Haaseed032702010-10-01 14:05:54 -07005923 int width = mRight - mLeft;
5924 int oldHeight = mBottom - mTop;
5925
Chet Haase21cd1382010-09-01 17:42:29 -07005926 mTop = top;
5927
Chet Haaseed032702010-10-01 14:05:54 -07005928 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5929
Chet Haase21cd1382010-09-01 17:42:29 -07005930 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005931 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5932 // A change in dimension means an auto-centered pivot point changes, too
5933 mMatrixDirty = true;
5934 }
Chet Haase21cd1382010-09-01 17:42:29 -07005935 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5936 invalidate();
5937 }
Chet Haase55dbb652010-12-21 20:15:08 -08005938 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07005939 }
5940 }
5941
5942 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 * Bottom position of this view relative to its parent.
5944 *
5945 * @return The bottom of this view, in pixels.
5946 */
5947 @ViewDebug.CapturedViewProperty
5948 public final int getBottom() {
5949 return mBottom;
5950 }
5951
5952 /**
Michael Jurkadab559a2011-01-04 20:31:51 -08005953 * True if this view has changed since the last time being drawn.
5954 *
5955 * @return The dirty state of this view.
5956 */
5957 public boolean isDirty() {
5958 return (mPrivateFlags & DIRTY_MASK) != 0;
5959 }
5960
5961 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005962 * Sets the bottom position of this view relative to its parent. This method is meant to be
5963 * called by the layout system and should not generally be called otherwise, because the
5964 * property may be changed at any time by the layout.
5965 *
5966 * @param bottom The bottom of this view, in pixels.
5967 */
5968 public final void setBottom(int bottom) {
5969 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07005970 updateMatrix();
5971 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005972 final ViewParent p = mParent;
5973 if (p != null && mAttachInfo != null) {
5974 final Rect r = mAttachInfo.mTmpInvalRect;
5975 int maxBottom;
5976 if (bottom < mBottom) {
5977 maxBottom = mBottom;
5978 } else {
5979 maxBottom = bottom;
5980 }
5981 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5982 p.invalidateChild(this, r);
5983 }
5984 } else {
5985 // Double-invalidation is necessary to capture view's old and new areas
5986 invalidate();
5987 }
5988
Chet Haaseed032702010-10-01 14:05:54 -07005989 int width = mRight - mLeft;
5990 int oldHeight = mBottom - mTop;
5991
Chet Haase21cd1382010-09-01 17:42:29 -07005992 mBottom = bottom;
5993
Chet Haaseed032702010-10-01 14:05:54 -07005994 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5995
Chet Haase21cd1382010-09-01 17:42:29 -07005996 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005997 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5998 // A change in dimension means an auto-centered pivot point changes, too
5999 mMatrixDirty = true;
6000 }
Chet Haase21cd1382010-09-01 17:42:29 -07006001 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6002 invalidate();
6003 }
Chet Haase55dbb652010-12-21 20:15:08 -08006004 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006005 }
6006 }
6007
6008 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 * Left position of this view relative to its parent.
6010 *
6011 * @return The left edge of this view, in pixels.
6012 */
6013 @ViewDebug.CapturedViewProperty
6014 public final int getLeft() {
6015 return mLeft;
6016 }
6017
6018 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006019 * Sets the left position of this view relative to its parent. This method is meant to be called
6020 * by the layout system and should not generally be called otherwise, because the property
6021 * may be changed at any time by the layout.
6022 *
6023 * @param left The bottom of this view, in pixels.
6024 */
6025 public final void setLeft(int left) {
6026 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07006027 updateMatrix();
6028 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006029 final ViewParent p = mParent;
6030 if (p != null && mAttachInfo != null) {
6031 final Rect r = mAttachInfo.mTmpInvalRect;
6032 int minLeft;
6033 int xLoc;
6034 if (left < mLeft) {
6035 minLeft = left;
6036 xLoc = left - mLeft;
6037 } else {
6038 minLeft = mLeft;
6039 xLoc = 0;
6040 }
6041 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
6042 p.invalidateChild(this, r);
6043 }
6044 } else {
6045 // Double-invalidation is necessary to capture view's old and new areas
6046 invalidate();
6047 }
6048
Chet Haaseed032702010-10-01 14:05:54 -07006049 int oldWidth = mRight - mLeft;
6050 int height = mBottom - mTop;
6051
Chet Haase21cd1382010-09-01 17:42:29 -07006052 mLeft = left;
6053
Chet Haaseed032702010-10-01 14:05:54 -07006054 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6055
Chet Haase21cd1382010-09-01 17:42:29 -07006056 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006057 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6058 // A change in dimension means an auto-centered pivot point changes, too
6059 mMatrixDirty = true;
6060 }
Chet Haase21cd1382010-09-01 17:42:29 -07006061 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6062 invalidate();
6063 }
Chet Haase55dbb652010-12-21 20:15:08 -08006064 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006065 }
6066 }
6067
6068 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006069 * Right position of this view relative to its parent.
6070 *
6071 * @return The right edge of this view, in pixels.
6072 */
6073 @ViewDebug.CapturedViewProperty
6074 public final int getRight() {
6075 return mRight;
6076 }
6077
6078 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006079 * Sets the right position of this view relative to its parent. This method is meant to be called
6080 * by the layout system and should not generally be called otherwise, because the property
6081 * may be changed at any time by the layout.
6082 *
6083 * @param right The bottom of this view, in pixels.
6084 */
6085 public final void setRight(int right) {
6086 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07006087 updateMatrix();
6088 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006089 final ViewParent p = mParent;
6090 if (p != null && mAttachInfo != null) {
6091 final Rect r = mAttachInfo.mTmpInvalRect;
6092 int maxRight;
6093 if (right < mRight) {
6094 maxRight = mRight;
6095 } else {
6096 maxRight = right;
6097 }
6098 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
6099 p.invalidateChild(this, r);
6100 }
6101 } else {
6102 // Double-invalidation is necessary to capture view's old and new areas
6103 invalidate();
6104 }
6105
Chet Haaseed032702010-10-01 14:05:54 -07006106 int oldWidth = mRight - mLeft;
6107 int height = mBottom - mTop;
6108
Chet Haase21cd1382010-09-01 17:42:29 -07006109 mRight = right;
6110
Chet Haaseed032702010-10-01 14:05:54 -07006111 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6112
Chet Haase21cd1382010-09-01 17:42:29 -07006113 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006114 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6115 // A change in dimension means an auto-centered pivot point changes, too
6116 mMatrixDirty = true;
6117 }
Chet Haase21cd1382010-09-01 17:42:29 -07006118 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6119 invalidate();
6120 }
Chet Haase55dbb652010-12-21 20:15:08 -08006121 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006122 }
6123 }
6124
6125 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006126 * The visual x position of this view, in pixels. This is equivalent to the
6127 * {@link #setTranslationX(float) translationX} property plus the current
6128 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07006129 *
Chet Haasedf030d22010-07-30 17:22:38 -07006130 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006131 */
Chet Haasedf030d22010-07-30 17:22:38 -07006132 public float getX() {
6133 return mLeft + mTranslationX;
6134 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006135
Chet Haasedf030d22010-07-30 17:22:38 -07006136 /**
6137 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
6138 * {@link #setTranslationX(float) translationX} property to be the difference between
6139 * the x value passed in and the current {@link #getLeft() left} property.
6140 *
6141 * @param x The visual x position of this view, in pixels.
6142 */
6143 public void setX(float x) {
6144 setTranslationX(x - mLeft);
6145 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006146
Chet Haasedf030d22010-07-30 17:22:38 -07006147 /**
6148 * The visual y position of this view, in pixels. This is equivalent to the
6149 * {@link #setTranslationY(float) translationY} property plus the current
6150 * {@link #getTop() top} property.
6151 *
6152 * @return The visual y position of this view, in pixels.
6153 */
6154 public float getY() {
6155 return mTop + mTranslationY;
6156 }
6157
6158 /**
6159 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
6160 * {@link #setTranslationY(float) translationY} property to be the difference between
6161 * the y value passed in and the current {@link #getTop() top} property.
6162 *
6163 * @param y The visual y position of this view, in pixels.
6164 */
6165 public void setY(float y) {
6166 setTranslationY(y - mTop);
6167 }
6168
6169
6170 /**
6171 * The horizontal location of this view relative to its {@link #getLeft() left} position.
6172 * This position is post-layout, in addition to wherever the object's
6173 * layout placed it.
6174 *
6175 * @return The horizontal position of this view relative to its left position, in pixels.
6176 */
6177 public float getTranslationX() {
6178 return mTranslationX;
6179 }
6180
6181 /**
6182 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
6183 * This effectively positions the object post-layout, in addition to wherever the object's
6184 * layout placed it.
6185 *
6186 * @param translationX The horizontal position of this view relative to its left position,
6187 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006188 *
6189 * @attr ref android.R.styleable#View_translationX
Chet Haasedf030d22010-07-30 17:22:38 -07006190 */
6191 public void setTranslationX(float translationX) {
6192 if (mTranslationX != translationX) {
6193 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006194 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006195 mTranslationX = translationX;
6196 mMatrixDirty = true;
6197 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006198 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006199 }
6200 }
6201
6202 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006203 * The horizontal location of this view relative to its {@link #getTop() top} position.
6204 * This position is post-layout, in addition to wherever the object's
6205 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006206 *
Chet Haasedf030d22010-07-30 17:22:38 -07006207 * @return The vertical position of this view relative to its top position,
6208 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006209 */
Chet Haasedf030d22010-07-30 17:22:38 -07006210 public float getTranslationY() {
6211 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07006212 }
6213
6214 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006215 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
6216 * This effectively positions the object post-layout, in addition to wherever the object's
6217 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006218 *
Chet Haasedf030d22010-07-30 17:22:38 -07006219 * @param translationY The vertical position of this view relative to its top position,
6220 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006221 *
6222 * @attr ref android.R.styleable#View_translationY
Chet Haasec3aa3612010-06-17 08:50:37 -07006223 */
Chet Haasedf030d22010-07-30 17:22:38 -07006224 public void setTranslationY(float translationY) {
6225 if (mTranslationY != translationY) {
6226 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006227 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006228 mTranslationY = translationY;
6229 mMatrixDirty = true;
6230 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006231 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006232 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006233 }
6234
6235 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 * Hit rectangle in parent's coordinates
6237 *
6238 * @param outRect The hit rectangle of the view.
6239 */
6240 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07006241 updateMatrix();
6242 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006243 outRect.set(mLeft, mTop, mRight, mBottom);
6244 } else {
6245 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07006246 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07006247 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07006248 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
6249 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07006250 }
6251 }
6252
6253 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07006254 * Determines whether the given point, in local coordinates is inside the view.
6255 */
6256 /*package*/ final boolean pointInView(float localX, float localY) {
6257 return localX >= 0 && localX < (mRight - mLeft)
6258 && localY >= 0 && localY < (mBottom - mTop);
6259 }
6260
6261 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07006262 * Utility method to determine whether the given point, in local coordinates,
6263 * is inside the view, where the area of the view is expanded by the slop factor.
6264 * This method is called while processing touch-move events to determine if the event
6265 * is still within the view.
6266 */
6267 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07006268 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07006269 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006270 }
6271
6272 /**
6273 * When a view has focus and the user navigates away from it, the next view is searched for
6274 * starting from the rectangle filled in by this method.
6275 *
6276 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
6277 * view maintains some idea of internal selection, such as a cursor, or a selected row
6278 * or column, you should override this method and fill in a more specific rectangle.
6279 *
6280 * @param r The rectangle to fill in, in this view's coordinates.
6281 */
6282 public void getFocusedRect(Rect r) {
6283 getDrawingRect(r);
6284 }
6285
6286 /**
6287 * If some part of this view is not clipped by any of its parents, then
6288 * return that area in r in global (root) coordinates. To convert r to local
6289 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
6290 * -globalOffset.y)) If the view is completely clipped or translated out,
6291 * return false.
6292 *
6293 * @param r If true is returned, r holds the global coordinates of the
6294 * visible portion of this view.
6295 * @param globalOffset If true is returned, globalOffset holds the dx,dy
6296 * between this view and its root. globalOffet may be null.
6297 * @return true if r is non-empty (i.e. part of the view is visible at the
6298 * root level.
6299 */
6300 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6301 int width = mRight - mLeft;
6302 int height = mBottom - mTop;
6303 if (width > 0 && height > 0) {
6304 r.set(0, 0, width, height);
6305 if (globalOffset != null) {
6306 globalOffset.set(-mScrollX, -mScrollY);
6307 }
6308 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6309 }
6310 return false;
6311 }
6312
6313 public final boolean getGlobalVisibleRect(Rect r) {
6314 return getGlobalVisibleRect(r, null);
6315 }
6316
6317 public final boolean getLocalVisibleRect(Rect r) {
6318 Point offset = new Point();
6319 if (getGlobalVisibleRect(r, offset)) {
6320 r.offset(-offset.x, -offset.y); // make r local
6321 return true;
6322 }
6323 return false;
6324 }
6325
6326 /**
6327 * Offset this view's vertical location by the specified number of pixels.
6328 *
6329 * @param offset the number of pixels to offset the view by
6330 */
6331 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006332 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006333 updateMatrix();
6334 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006335 final ViewParent p = mParent;
6336 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006337 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006338 int minTop;
6339 int maxBottom;
6340 int yLoc;
6341 if (offset < 0) {
6342 minTop = mTop + offset;
6343 maxBottom = mBottom;
6344 yLoc = offset;
6345 } else {
6346 minTop = mTop;
6347 maxBottom = mBottom + offset;
6348 yLoc = 0;
6349 }
6350 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6351 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006352 }
6353 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006354 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006355 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006356
Chet Haasec3aa3612010-06-17 08:50:37 -07006357 mTop += offset;
6358 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006359
Chet Haasec3aa3612010-06-17 08:50:37 -07006360 if (!mMatrixIsIdentity) {
6361 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006362 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006363 }
6364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 }
6366
6367 /**
6368 * Offset this view's horizontal location by the specified amount of pixels.
6369 *
6370 * @param offset the numer of pixels to offset the view by
6371 */
6372 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006373 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006374 updateMatrix();
6375 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006376 final ViewParent p = mParent;
6377 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006378 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006379 int minLeft;
6380 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006381 if (offset < 0) {
6382 minLeft = mLeft + offset;
6383 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006384 } else {
6385 minLeft = mLeft;
6386 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006387 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006388 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07006389 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006390 }
6391 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006392 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006393 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006394
Chet Haasec3aa3612010-06-17 08:50:37 -07006395 mLeft += offset;
6396 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006397
Chet Haasec3aa3612010-06-17 08:50:37 -07006398 if (!mMatrixIsIdentity) {
6399 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006400 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006401 }
6402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 }
6404
6405 /**
6406 * Get the LayoutParams associated with this view. All views should have
6407 * layout parameters. These supply parameters to the <i>parent</i> of this
6408 * view specifying how it should be arranged. There are many subclasses of
6409 * ViewGroup.LayoutParams, and these correspond to the different subclasses
6410 * of ViewGroup that are responsible for arranging their children.
6411 * @return The LayoutParams associated with this view
6412 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07006413 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 public ViewGroup.LayoutParams getLayoutParams() {
6415 return mLayoutParams;
6416 }
6417
6418 /**
6419 * Set the layout parameters associated with this view. These supply
6420 * parameters to the <i>parent</i> of this view specifying how it should be
6421 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6422 * correspond to the different subclasses of ViewGroup that are responsible
6423 * for arranging their children.
6424 *
6425 * @param params the layout parameters for this view
6426 */
6427 public void setLayoutParams(ViewGroup.LayoutParams params) {
6428 if (params == null) {
6429 throw new NullPointerException("params == null");
6430 }
6431 mLayoutParams = params;
6432 requestLayout();
6433 }
6434
6435 /**
6436 * Set the scrolled position of your view. This will cause a call to
6437 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6438 * invalidated.
6439 * @param x the x position to scroll to
6440 * @param y the y position to scroll to
6441 */
6442 public void scrollTo(int x, int y) {
6443 if (mScrollX != x || mScrollY != y) {
6444 int oldX = mScrollX;
6445 int oldY = mScrollY;
6446 mScrollX = x;
6447 mScrollY = y;
6448 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006449 if (!awakenScrollBars()) {
6450 invalidate();
6451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 }
6453 }
6454
6455 /**
6456 * Move the scrolled position of your view. This will cause a call to
6457 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6458 * invalidated.
6459 * @param x the amount of pixels to scroll by horizontally
6460 * @param y the amount of pixels to scroll by vertically
6461 */
6462 public void scrollBy(int x, int y) {
6463 scrollTo(mScrollX + x, mScrollY + y);
6464 }
6465
6466 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006467 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6468 * animation to fade the scrollbars out after a default delay. If a subclass
6469 * provides animated scrolling, the start delay should equal the duration
6470 * of the scrolling animation.</p>
6471 *
6472 * <p>The animation starts only if at least one of the scrollbars is
6473 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6474 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6475 * this method returns true, and false otherwise. If the animation is
6476 * started, this method calls {@link #invalidate()}; in that case the
6477 * caller should not call {@link #invalidate()}.</p>
6478 *
6479 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006480 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006481 *
6482 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6483 * and {@link #scrollTo(int, int)}.</p>
6484 *
6485 * @return true if the animation is played, false otherwise
6486 *
6487 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006488 * @see #scrollBy(int, int)
6489 * @see #scrollTo(int, int)
6490 * @see #isHorizontalScrollBarEnabled()
6491 * @see #isVerticalScrollBarEnabled()
6492 * @see #setHorizontalScrollBarEnabled(boolean)
6493 * @see #setVerticalScrollBarEnabled(boolean)
6494 */
6495 protected boolean awakenScrollBars() {
6496 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006497 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006498 }
6499
6500 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006501 * Trigger the scrollbars to draw.
6502 * This method differs from awakenScrollBars() only in its default duration.
6503 * initialAwakenScrollBars() will show the scroll bars for longer than
6504 * usual to give the user more of a chance to notice them.
6505 *
6506 * @return true if the animation is played, false otherwise.
6507 */
6508 private boolean initialAwakenScrollBars() {
6509 return mScrollCache != null &&
6510 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6511 }
6512
6513 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006514 * <p>
6515 * Trigger the scrollbars to draw. When invoked this method starts an
6516 * animation to fade the scrollbars out after a fixed delay. If a subclass
6517 * provides animated scrolling, the start delay should equal the duration of
6518 * the scrolling animation.
6519 * </p>
6520 *
6521 * <p>
6522 * The animation starts only if at least one of the scrollbars is enabled,
6523 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6524 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6525 * this method returns true, and false otherwise. If the animation is
6526 * started, this method calls {@link #invalidate()}; in that case the caller
6527 * should not call {@link #invalidate()}.
6528 * </p>
6529 *
6530 * <p>
6531 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006532 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006533 * </p>
6534 *
6535 * @param startDelay the delay, in milliseconds, after which the animation
6536 * should start; when the delay is 0, the animation starts
6537 * immediately
6538 * @return true if the animation is played, false otherwise
6539 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006540 * @see #scrollBy(int, int)
6541 * @see #scrollTo(int, int)
6542 * @see #isHorizontalScrollBarEnabled()
6543 * @see #isVerticalScrollBarEnabled()
6544 * @see #setHorizontalScrollBarEnabled(boolean)
6545 * @see #setVerticalScrollBarEnabled(boolean)
6546 */
6547 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006548 return awakenScrollBars(startDelay, true);
6549 }
6550
6551 /**
6552 * <p>
6553 * Trigger the scrollbars to draw. When invoked this method starts an
6554 * animation to fade the scrollbars out after a fixed delay. If a subclass
6555 * provides animated scrolling, the start delay should equal the duration of
6556 * the scrolling animation.
6557 * </p>
6558 *
6559 * <p>
6560 * The animation starts only if at least one of the scrollbars is enabled,
6561 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6562 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6563 * this method returns true, and false otherwise. If the animation is
6564 * started, this method calls {@link #invalidate()} if the invalidate parameter
6565 * is set to true; in that case the caller
6566 * should not call {@link #invalidate()}.
6567 * </p>
6568 *
6569 * <p>
6570 * This method should be invoked everytime a subclass directly updates the
6571 * scroll parameters.
6572 * </p>
6573 *
6574 * @param startDelay the delay, in milliseconds, after which the animation
6575 * should start; when the delay is 0, the animation starts
6576 * immediately
6577 *
6578 * @param invalidate Wheter this method should call invalidate
6579 *
6580 * @return true if the animation is played, false otherwise
6581 *
6582 * @see #scrollBy(int, int)
6583 * @see #scrollTo(int, int)
6584 * @see #isHorizontalScrollBarEnabled()
6585 * @see #isVerticalScrollBarEnabled()
6586 * @see #setHorizontalScrollBarEnabled(boolean)
6587 * @see #setVerticalScrollBarEnabled(boolean)
6588 */
6589 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006590 final ScrollabilityCache scrollCache = mScrollCache;
6591
6592 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6593 return false;
6594 }
6595
6596 if (scrollCache.scrollBar == null) {
6597 scrollCache.scrollBar = new ScrollBarDrawable();
6598 }
6599
6600 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6601
Mike Cleron290947b2009-09-29 18:34:32 -07006602 if (invalidate) {
6603 // Invalidate to show the scrollbars
6604 invalidate();
6605 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006606
6607 if (scrollCache.state == ScrollabilityCache.OFF) {
6608 // FIXME: this is copied from WindowManagerService.
6609 // We should get this value from the system when it
6610 // is possible to do so.
6611 final int KEY_REPEAT_FIRST_DELAY = 750;
6612 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6613 }
6614
6615 // Tell mScrollCache when we should start fading. This may
6616 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006617 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006618 scrollCache.fadeStartTime = fadeStartTime;
6619 scrollCache.state = ScrollabilityCache.ON;
6620
6621 // Schedule our fader to run, unscheduling any old ones first
6622 if (mAttachInfo != null) {
6623 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6624 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6625 }
6626
6627 return true;
6628 }
6629
6630 return false;
6631 }
6632
6633 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006634 * Mark the the area defined by dirty as needing to be drawn. If the view is
6635 * visible, {@link #onDraw} will be called at some point in the future.
6636 * This must be called from a UI thread. To call from a non-UI thread, call
6637 * {@link #postInvalidate()}.
6638 *
6639 * WARNING: This method is destructive to dirty.
6640 * @param dirty the rectangle representing the bounds of the dirty region
6641 */
6642 public void invalidate(Rect dirty) {
6643 if (ViewDebug.TRACE_HIERARCHY) {
6644 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6645 }
6646
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006647 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6648 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006649 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6650 final ViewParent p = mParent;
6651 final AttachInfo ai = mAttachInfo;
Romain Guyaf636eb2010-12-09 17:47:21 -08006652 if (p != null && ai != null && ai.mHardwareAccelerated) {
6653 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6654 // with a null dirty rect, which tells the ViewRoot to redraw everything
6655 p.invalidateChild(this, null);
6656 return;
6657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 if (p != null && ai != null) {
6659 final int scrollX = mScrollX;
6660 final int scrollY = mScrollY;
6661 final Rect r = ai.mTmpInvalRect;
6662 r.set(dirty.left - scrollX, dirty.top - scrollY,
6663 dirty.right - scrollX, dirty.bottom - scrollY);
6664 mParent.invalidateChild(this, r);
6665 }
6666 }
6667 }
6668
6669 /**
6670 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6671 * The coordinates of the dirty rect are relative to the view.
6672 * If the view is visible, {@link #onDraw} will be called at some point
6673 * in the future. This must be called from a UI thread. To call
6674 * from a non-UI thread, call {@link #postInvalidate()}.
6675 * @param l the left position of the dirty region
6676 * @param t the top position of the dirty region
6677 * @param r the right position of the dirty region
6678 * @param b the bottom position of the dirty region
6679 */
6680 public void invalidate(int l, int t, int r, int b) {
6681 if (ViewDebug.TRACE_HIERARCHY) {
6682 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6683 }
6684
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006685 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6686 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6688 final ViewParent p = mParent;
6689 final AttachInfo ai = mAttachInfo;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006690 if (p != null && ai != null && ai.mHardwareAccelerated) {
6691 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6692 // with a null dirty rect, which tells the ViewRoot to redraw everything
6693 p.invalidateChild(this, null);
6694 return;
6695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 if (p != null && ai != null && l < r && t < b) {
6697 final int scrollX = mScrollX;
6698 final int scrollY = mScrollY;
6699 final Rect tmpr = ai.mTmpInvalRect;
6700 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6701 p.invalidateChild(this, tmpr);
6702 }
6703 }
6704 }
6705
6706 /**
6707 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6708 * be called at some point in the future. This must be called from a
6709 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6710 */
6711 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006712 invalidate(true);
6713 }
6714
6715 /**
6716 * This is where the invalidate() work actually happens. A full invalidate()
6717 * causes the drawing cache to be invalidated, but this function can be called with
6718 * invalidateCache set to false to skip that invalidation step for cases that do not
6719 * need it (for example, a component that remains at the same dimensions with the same
6720 * content).
6721 *
6722 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6723 * well. This is usually true for a full invalidate, but may be set to false if the
6724 * View's contents or dimensions have not changed.
6725 */
6726 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 if (ViewDebug.TRACE_HIERARCHY) {
6728 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6729 }
6730
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006731 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6732 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID)) {
Chet Haaseed032702010-10-01 14:05:54 -07006733 mPrivateFlags &= ~DRAWN;
6734 if (invalidateCache) {
6735 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006738 final ViewParent p = mParent;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006739 if (p != null && ai != null && ai.mHardwareAccelerated) {
6740 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6741 // with a null dirty rect, which tells the ViewRoot to redraw everything
6742 p.invalidateChild(this, null);
6743 return;
6744 }
Michael Jurkaebefea42010-11-15 16:04:01 -08006745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 if (p != null && ai != null) {
6747 final Rect r = ai.mTmpInvalRect;
6748 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6749 // Don't call invalidate -- we don't want to internally scroll
6750 // our own bounds
6751 p.invalidateChild(this, r);
6752 }
6753 }
6754 }
6755
6756 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006757 * Indicates whether this View is opaque. An opaque View guarantees that it will
6758 * draw all the pixels overlapping its bounds using a fully opaque color.
6759 *
6760 * Subclasses of View should override this method whenever possible to indicate
6761 * whether an instance is opaque. Opaque Views are treated in a special way by
6762 * the View hierarchy, possibly allowing it to perform optimizations during
6763 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006764 *
Romain Guy24443ea2009-05-11 11:56:30 -07006765 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006766 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006767 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006768 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006769 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6770 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006771 }
6772
Adam Powell20232d02010-12-08 21:08:53 -08006773 /**
6774 * @hide
6775 */
6776 protected void computeOpaqueFlags() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006777 // Opaque if:
6778 // - Has a background
6779 // - Background is opaque
6780 // - Doesn't have scrollbars or scrollbars are inside overlay
6781
6782 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6783 mPrivateFlags |= OPAQUE_BACKGROUND;
6784 } else {
6785 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6786 }
6787
6788 final int flags = mViewFlags;
6789 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6790 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6791 mPrivateFlags |= OPAQUE_SCROLLBARS;
6792 } else {
6793 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6794 }
6795 }
6796
6797 /**
6798 * @hide
6799 */
6800 protected boolean hasOpaqueScrollbars() {
6801 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006802 }
6803
6804 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 * @return A handler associated with the thread running the View. This
6806 * handler can be used to pump events in the UI events queue.
6807 */
6808 public Handler getHandler() {
6809 if (mAttachInfo != null) {
6810 return mAttachInfo.mHandler;
6811 }
6812 return null;
6813 }
6814
6815 /**
6816 * Causes the Runnable to be added to the message queue.
6817 * The runnable will be run on the user interface thread.
6818 *
6819 * @param action The Runnable that will be executed.
6820 *
6821 * @return Returns true if the Runnable was successfully placed in to the
6822 * message queue. Returns false on failure, usually because the
6823 * looper processing the message queue is exiting.
6824 */
6825 public boolean post(Runnable action) {
6826 Handler handler;
6827 if (mAttachInfo != null) {
6828 handler = mAttachInfo.mHandler;
6829 } else {
6830 // Assume that post will succeed later
6831 ViewRoot.getRunQueue().post(action);
6832 return true;
6833 }
6834
6835 return handler.post(action);
6836 }
6837
6838 /**
6839 * Causes the Runnable to be added to the message queue, to be run
6840 * after the specified amount of time elapses.
6841 * The runnable will be run on the user interface thread.
6842 *
6843 * @param action The Runnable that will be executed.
6844 * @param delayMillis The delay (in milliseconds) until the Runnable
6845 * will be executed.
6846 *
6847 * @return true if the Runnable was successfully placed in to the
6848 * message queue. Returns false on failure, usually because the
6849 * looper processing the message queue is exiting. Note that a
6850 * result of true does not mean the Runnable will be processed --
6851 * if the looper is quit before the delivery time of the message
6852 * occurs then the message will be dropped.
6853 */
6854 public boolean postDelayed(Runnable action, long delayMillis) {
6855 Handler handler;
6856 if (mAttachInfo != null) {
6857 handler = mAttachInfo.mHandler;
6858 } else {
6859 // Assume that post will succeed later
6860 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6861 return true;
6862 }
6863
6864 return handler.postDelayed(action, delayMillis);
6865 }
6866
6867 /**
6868 * Removes the specified Runnable from the message queue.
6869 *
6870 * @param action The Runnable to remove from the message handling queue
6871 *
6872 * @return true if this view could ask the Handler to remove the Runnable,
6873 * false otherwise. When the returned value is true, the Runnable
6874 * may or may not have been actually removed from the message queue
6875 * (for instance, if the Runnable was not in the queue already.)
6876 */
6877 public boolean removeCallbacks(Runnable action) {
6878 Handler handler;
6879 if (mAttachInfo != null) {
6880 handler = mAttachInfo.mHandler;
6881 } else {
6882 // Assume that post will succeed later
6883 ViewRoot.getRunQueue().removeCallbacks(action);
6884 return true;
6885 }
6886
6887 handler.removeCallbacks(action);
6888 return true;
6889 }
6890
6891 /**
6892 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6893 * Use this to invalidate the View from a non-UI thread.
6894 *
6895 * @see #invalidate()
6896 */
6897 public void postInvalidate() {
6898 postInvalidateDelayed(0);
6899 }
6900
6901 /**
6902 * Cause an invalidate of the specified area to happen on a subsequent cycle
6903 * through the event loop. Use this to invalidate the View from a non-UI thread.
6904 *
6905 * @param left The left coordinate of the rectangle to invalidate.
6906 * @param top The top coordinate of the rectangle to invalidate.
6907 * @param right The right coordinate of the rectangle to invalidate.
6908 * @param bottom The bottom coordinate of the rectangle to invalidate.
6909 *
6910 * @see #invalidate(int, int, int, int)
6911 * @see #invalidate(Rect)
6912 */
6913 public void postInvalidate(int left, int top, int right, int bottom) {
6914 postInvalidateDelayed(0, left, top, right, bottom);
6915 }
6916
6917 /**
6918 * Cause an invalidate to happen on a subsequent cycle through the event
6919 * loop. Waits for the specified amount of time.
6920 *
6921 * @param delayMilliseconds the duration in milliseconds to delay the
6922 * invalidation by
6923 */
6924 public void postInvalidateDelayed(long delayMilliseconds) {
6925 // We try only with the AttachInfo because there's no point in invalidating
6926 // if we are not attached to our window
6927 if (mAttachInfo != null) {
6928 Message msg = Message.obtain();
6929 msg.what = AttachInfo.INVALIDATE_MSG;
6930 msg.obj = this;
6931 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6932 }
6933 }
6934
6935 /**
6936 * Cause an invalidate of the specified area to happen on a subsequent cycle
6937 * through the event loop. Waits for the specified amount of time.
6938 *
6939 * @param delayMilliseconds the duration in milliseconds to delay the
6940 * invalidation by
6941 * @param left The left coordinate of the rectangle to invalidate.
6942 * @param top The top coordinate of the rectangle to invalidate.
6943 * @param right The right coordinate of the rectangle to invalidate.
6944 * @param bottom The bottom coordinate of the rectangle to invalidate.
6945 */
6946 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6947 int right, int bottom) {
6948
6949 // We try only with the AttachInfo because there's no point in invalidating
6950 // if we are not attached to our window
6951 if (mAttachInfo != null) {
6952 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6953 info.target = this;
6954 info.left = left;
6955 info.top = top;
6956 info.right = right;
6957 info.bottom = bottom;
6958
6959 final Message msg = Message.obtain();
6960 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6961 msg.obj = info;
6962 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6963 }
6964 }
6965
6966 /**
6967 * Called by a parent to request that a child update its values for mScrollX
6968 * and mScrollY if necessary. This will typically be done if the child is
6969 * animating a scroll using a {@link android.widget.Scroller Scroller}
6970 * object.
6971 */
6972 public void computeScroll() {
6973 }
6974
6975 /**
6976 * <p>Indicate whether the horizontal edges are faded when the view is
6977 * scrolled horizontally.</p>
6978 *
6979 * @return true if the horizontal edges should are faded on scroll, false
6980 * otherwise
6981 *
6982 * @see #setHorizontalFadingEdgeEnabled(boolean)
6983 * @attr ref android.R.styleable#View_fadingEdge
6984 */
6985 public boolean isHorizontalFadingEdgeEnabled() {
6986 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6987 }
6988
6989 /**
6990 * <p>Define whether the horizontal edges should be faded when this view
6991 * is scrolled horizontally.</p>
6992 *
6993 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6994 * be faded when the view is scrolled
6995 * horizontally
6996 *
6997 * @see #isHorizontalFadingEdgeEnabled()
6998 * @attr ref android.R.styleable#View_fadingEdge
6999 */
7000 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
7001 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
7002 if (horizontalFadingEdgeEnabled) {
7003 initScrollCache();
7004 }
7005
7006 mViewFlags ^= FADING_EDGE_HORIZONTAL;
7007 }
7008 }
7009
7010 /**
7011 * <p>Indicate whether the vertical edges are faded when the view is
7012 * scrolled horizontally.</p>
7013 *
7014 * @return true if the vertical edges should are faded on scroll, false
7015 * otherwise
7016 *
7017 * @see #setVerticalFadingEdgeEnabled(boolean)
7018 * @attr ref android.R.styleable#View_fadingEdge
7019 */
7020 public boolean isVerticalFadingEdgeEnabled() {
7021 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
7022 }
7023
7024 /**
7025 * <p>Define whether the vertical edges should be faded when this view
7026 * is scrolled vertically.</p>
7027 *
7028 * @param verticalFadingEdgeEnabled true if the vertical edges should
7029 * be faded when the view is scrolled
7030 * vertically
7031 *
7032 * @see #isVerticalFadingEdgeEnabled()
7033 * @attr ref android.R.styleable#View_fadingEdge
7034 */
7035 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
7036 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
7037 if (verticalFadingEdgeEnabled) {
7038 initScrollCache();
7039 }
7040
7041 mViewFlags ^= FADING_EDGE_VERTICAL;
7042 }
7043 }
7044
7045 /**
7046 * Returns the strength, or intensity, of the top faded edge. The strength is
7047 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7048 * returns 0.0 or 1.0 but no value in between.
7049 *
7050 * Subclasses should override this method to provide a smoother fade transition
7051 * when scrolling occurs.
7052 *
7053 * @return the intensity of the top fade as a float between 0.0f and 1.0f
7054 */
7055 protected float getTopFadingEdgeStrength() {
7056 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
7057 }
7058
7059 /**
7060 * Returns the strength, or intensity, of the bottom faded edge. The strength is
7061 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7062 * returns 0.0 or 1.0 but no value in between.
7063 *
7064 * Subclasses should override this method to provide a smoother fade transition
7065 * when scrolling occurs.
7066 *
7067 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
7068 */
7069 protected float getBottomFadingEdgeStrength() {
7070 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
7071 computeVerticalScrollRange() ? 1.0f : 0.0f;
7072 }
7073
7074 /**
7075 * Returns the strength, or intensity, of the left faded edge. The strength is
7076 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7077 * returns 0.0 or 1.0 but no value in between.
7078 *
7079 * Subclasses should override this method to provide a smoother fade transition
7080 * when scrolling occurs.
7081 *
7082 * @return the intensity of the left fade as a float between 0.0f and 1.0f
7083 */
7084 protected float getLeftFadingEdgeStrength() {
7085 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
7086 }
7087
7088 /**
7089 * Returns the strength, or intensity, of the right faded edge. The strength is
7090 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7091 * returns 0.0 or 1.0 but no value in between.
7092 *
7093 * Subclasses should override this method to provide a smoother fade transition
7094 * when scrolling occurs.
7095 *
7096 * @return the intensity of the right fade as a float between 0.0f and 1.0f
7097 */
7098 protected float getRightFadingEdgeStrength() {
7099 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
7100 computeHorizontalScrollRange() ? 1.0f : 0.0f;
7101 }
7102
7103 /**
7104 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
7105 * scrollbar is not drawn by default.</p>
7106 *
7107 * @return true if the horizontal scrollbar should be painted, false
7108 * otherwise
7109 *
7110 * @see #setHorizontalScrollBarEnabled(boolean)
7111 */
7112 public boolean isHorizontalScrollBarEnabled() {
7113 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7114 }
7115
7116 /**
7117 * <p>Define whether the horizontal scrollbar should be drawn or not. The
7118 * scrollbar is not drawn by default.</p>
7119 *
7120 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
7121 * be painted
7122 *
7123 * @see #isHorizontalScrollBarEnabled()
7124 */
7125 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
7126 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
7127 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007128 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007129 recomputePadding();
7130 }
7131 }
7132
7133 /**
7134 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
7135 * scrollbar is not drawn by default.</p>
7136 *
7137 * @return true if the vertical scrollbar should be painted, false
7138 * otherwise
7139 *
7140 * @see #setVerticalScrollBarEnabled(boolean)
7141 */
7142 public boolean isVerticalScrollBarEnabled() {
7143 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
7144 }
7145
7146 /**
7147 * <p>Define whether the vertical scrollbar should be drawn or not. The
7148 * scrollbar is not drawn by default.</p>
7149 *
7150 * @param verticalScrollBarEnabled true if the vertical scrollbar should
7151 * be painted
7152 *
7153 * @see #isVerticalScrollBarEnabled()
7154 */
7155 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
7156 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
7157 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007158 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007159 recomputePadding();
7160 }
7161 }
7162
Adam Powell20232d02010-12-08 21:08:53 -08007163 /**
7164 * @hide
7165 */
7166 protected void recomputePadding() {
7167 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007168 }
Mike Cleronfe81d382009-09-28 14:22:16 -07007169
7170 /**
7171 * Define whether scrollbars will fade when the view is not scrolling.
7172 *
7173 * @param fadeScrollbars wheter to enable fading
7174 *
7175 */
7176 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
7177 initScrollCache();
7178 final ScrollabilityCache scrollabilityCache = mScrollCache;
7179 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07007180 if (fadeScrollbars) {
7181 scrollabilityCache.state = ScrollabilityCache.OFF;
7182 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07007183 scrollabilityCache.state = ScrollabilityCache.ON;
7184 }
7185 }
7186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07007188 *
7189 * Returns true if scrollbars will fade when this view is not scrolling
7190 *
7191 * @return true if scrollbar fading is enabled
7192 */
7193 public boolean isScrollbarFadingEnabled() {
7194 return mScrollCache != null && mScrollCache.fadeScrollBars;
7195 }
7196
7197 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007198 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
7199 * inset. When inset, they add to the padding of the view. And the scrollbars
7200 * can be drawn inside the padding area or on the edge of the view. For example,
7201 * if a view has a background drawable and you want to draw the scrollbars
7202 * inside the padding specified by the drawable, you can use
7203 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
7204 * appear at the edge of the view, ignoring the padding, then you can use
7205 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
7206 * @param style the style of the scrollbars. Should be one of
7207 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
7208 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
7209 * @see #SCROLLBARS_INSIDE_OVERLAY
7210 * @see #SCROLLBARS_INSIDE_INSET
7211 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7212 * @see #SCROLLBARS_OUTSIDE_INSET
7213 */
7214 public void setScrollBarStyle(int style) {
7215 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
7216 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07007217 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007218 recomputePadding();
7219 }
7220 }
7221
7222 /**
7223 * <p>Returns the current scrollbar style.</p>
7224 * @return the current scrollbar style
7225 * @see #SCROLLBARS_INSIDE_OVERLAY
7226 * @see #SCROLLBARS_INSIDE_INSET
7227 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7228 * @see #SCROLLBARS_OUTSIDE_INSET
7229 */
7230 public int getScrollBarStyle() {
7231 return mViewFlags & SCROLLBARS_STYLE_MASK;
7232 }
7233
7234 /**
7235 * <p>Compute the horizontal range that the horizontal scrollbar
7236 * represents.</p>
7237 *
7238 * <p>The range is expressed in arbitrary units that must be the same as the
7239 * units used by {@link #computeHorizontalScrollExtent()} and
7240 * {@link #computeHorizontalScrollOffset()}.</p>
7241 *
7242 * <p>The default range is the drawing width of this view.</p>
7243 *
7244 * @return the total horizontal range represented by the horizontal
7245 * scrollbar
7246 *
7247 * @see #computeHorizontalScrollExtent()
7248 * @see #computeHorizontalScrollOffset()
7249 * @see android.widget.ScrollBarDrawable
7250 */
7251 protected int computeHorizontalScrollRange() {
7252 return getWidth();
7253 }
7254
7255 /**
7256 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7257 * within the horizontal range. This value is used to compute the position
7258 * of the thumb within the scrollbar's track.</p>
7259 *
7260 * <p>The range is expressed in arbitrary units that must be the same as the
7261 * units used by {@link #computeHorizontalScrollRange()} and
7262 * {@link #computeHorizontalScrollExtent()}.</p>
7263 *
7264 * <p>The default offset is the scroll offset of this view.</p>
7265 *
7266 * @return the horizontal offset of the scrollbar's thumb
7267 *
7268 * @see #computeHorizontalScrollRange()
7269 * @see #computeHorizontalScrollExtent()
7270 * @see android.widget.ScrollBarDrawable
7271 */
7272 protected int computeHorizontalScrollOffset() {
7273 return mScrollX;
7274 }
7275
7276 /**
7277 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7278 * within the horizontal range. This value is used to compute the length
7279 * of the thumb within the scrollbar's track.</p>
7280 *
7281 * <p>The range is expressed in arbitrary units that must be the same as the
7282 * units used by {@link #computeHorizontalScrollRange()} and
7283 * {@link #computeHorizontalScrollOffset()}.</p>
7284 *
7285 * <p>The default extent is the drawing width of this view.</p>
7286 *
7287 * @return the horizontal extent of the scrollbar's thumb
7288 *
7289 * @see #computeHorizontalScrollRange()
7290 * @see #computeHorizontalScrollOffset()
7291 * @see android.widget.ScrollBarDrawable
7292 */
7293 protected int computeHorizontalScrollExtent() {
7294 return getWidth();
7295 }
7296
7297 /**
7298 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7299 *
7300 * <p>The range is expressed in arbitrary units that must be the same as the
7301 * units used by {@link #computeVerticalScrollExtent()} and
7302 * {@link #computeVerticalScrollOffset()}.</p>
7303 *
7304 * @return the total vertical range represented by the vertical scrollbar
7305 *
7306 * <p>The default range is the drawing height of this view.</p>
7307 *
7308 * @see #computeVerticalScrollExtent()
7309 * @see #computeVerticalScrollOffset()
7310 * @see android.widget.ScrollBarDrawable
7311 */
7312 protected int computeVerticalScrollRange() {
7313 return getHeight();
7314 }
7315
7316 /**
7317 * <p>Compute the vertical offset of the vertical scrollbar's thumb
7318 * within the horizontal range. This value is used to compute the position
7319 * of the thumb within the scrollbar's track.</p>
7320 *
7321 * <p>The range is expressed in arbitrary units that must be the same as the
7322 * units used by {@link #computeVerticalScrollRange()} and
7323 * {@link #computeVerticalScrollExtent()}.</p>
7324 *
7325 * <p>The default offset is the scroll offset of this view.</p>
7326 *
7327 * @return the vertical offset of the scrollbar's thumb
7328 *
7329 * @see #computeVerticalScrollRange()
7330 * @see #computeVerticalScrollExtent()
7331 * @see android.widget.ScrollBarDrawable
7332 */
7333 protected int computeVerticalScrollOffset() {
7334 return mScrollY;
7335 }
7336
7337 /**
7338 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7339 * within the vertical range. This value is used to compute the length
7340 * of the thumb within the scrollbar's track.</p>
7341 *
7342 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08007343 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 * {@link #computeVerticalScrollOffset()}.</p>
7345 *
7346 * <p>The default extent is the drawing height of this view.</p>
7347 *
7348 * @return the vertical extent of the scrollbar's thumb
7349 *
7350 * @see #computeVerticalScrollRange()
7351 * @see #computeVerticalScrollOffset()
7352 * @see android.widget.ScrollBarDrawable
7353 */
7354 protected int computeVerticalScrollExtent() {
7355 return getHeight();
7356 }
7357
7358 /**
7359 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7360 * scrollbars are painted only if they have been awakened first.</p>
7361 *
7362 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07007363 *
7364 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007365 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08007366 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007367 // scrollbars are drawn only when the animation is running
7368 final ScrollabilityCache cache = mScrollCache;
7369 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007370
7371 int state = cache.state;
7372
7373 if (state == ScrollabilityCache.OFF) {
7374 return;
7375 }
7376
7377 boolean invalidate = false;
7378
7379 if (state == ScrollabilityCache.FADING) {
7380 // We're fading -- get our fade interpolation
7381 if (cache.interpolatorValues == null) {
7382 cache.interpolatorValues = new float[1];
7383 }
7384
7385 float[] values = cache.interpolatorValues;
7386
7387 // Stops the animation if we're done
7388 if (cache.scrollBarInterpolator.timeToValues(values) ==
7389 Interpolator.Result.FREEZE_END) {
7390 cache.state = ScrollabilityCache.OFF;
7391 } else {
7392 cache.scrollBar.setAlpha(Math.round(values[0]));
7393 }
7394
7395 // This will make the scroll bars inval themselves after
7396 // drawing. We only want this when we're fading so that
7397 // we prevent excessive redraws
7398 invalidate = true;
7399 } else {
7400 // We're just on -- but we may have been fading before so
7401 // reset alpha
7402 cache.scrollBar.setAlpha(255);
7403 }
7404
7405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406 final int viewFlags = mViewFlags;
7407
7408 final boolean drawHorizontalScrollBar =
7409 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7410 final boolean drawVerticalScrollBar =
7411 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7412 && !isVerticalScrollBarHidden();
7413
7414 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7415 final int width = mRight - mLeft;
7416 final int height = mBottom - mTop;
7417
7418 final ScrollBarDrawable scrollBar = cache.scrollBar;
7419 int size = scrollBar.getSize(false);
7420 if (size <= 0) {
7421 size = cache.scrollBarSize;
7422 }
7423
Mike Reede8853fc2009-09-04 14:01:48 -04007424 final int scrollX = mScrollX;
7425 final int scrollY = mScrollY;
7426 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7427
Mike Cleronf116bf82009-09-27 19:14:12 -07007428 int left, top, right, bottom;
7429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007430 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007431 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04007432 computeHorizontalScrollOffset(),
7433 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04007434 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07007435 getVerticalScrollbarWidth() : 0;
7436 top = scrollY + height - size - (mUserPaddingBottom & inside);
7437 left = scrollX + (mPaddingLeft & inside);
7438 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7439 bottom = top + size;
7440 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7441 if (invalidate) {
7442 invalidate(left, top, right, bottom);
7443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007444 }
7445
7446 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04007447 scrollBar.setParameters(computeVerticalScrollRange(),
7448 computeVerticalScrollOffset(),
7449 computeVerticalScrollExtent(), true);
Adam Powell20232d02010-12-08 21:08:53 -08007450 switch (mVerticalScrollbarPosition) {
7451 default:
7452 case SCROLLBAR_POSITION_DEFAULT:
7453 case SCROLLBAR_POSITION_RIGHT:
7454 left = scrollX + width - size - (mUserPaddingRight & inside);
7455 break;
7456 case SCROLLBAR_POSITION_LEFT:
7457 left = scrollX + (mUserPaddingLeft & inside);
7458 break;
7459 }
Mike Cleronf116bf82009-09-27 19:14:12 -07007460 top = scrollY + (mPaddingTop & inside);
7461 right = left + size;
7462 bottom = scrollY + height - (mUserPaddingBottom & inside);
7463 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7464 if (invalidate) {
7465 invalidate(left, top, right, bottom);
7466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007467 }
7468 }
7469 }
7470 }
Romain Guy8506ab42009-06-11 17:35:47 -07007471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007472 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007473 * 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 -08007474 * FastScroller is visible.
7475 * @return whether to temporarily hide the vertical scrollbar
7476 * @hide
7477 */
7478 protected boolean isVerticalScrollBarHidden() {
7479 return false;
7480 }
7481
7482 /**
7483 * <p>Draw the horizontal scrollbar if
7484 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7485 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007486 * @param canvas the canvas on which to draw the scrollbar
7487 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007488 *
7489 * @see #isHorizontalScrollBarEnabled()
7490 * @see #computeHorizontalScrollRange()
7491 * @see #computeHorizontalScrollExtent()
7492 * @see #computeHorizontalScrollOffset()
7493 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007494 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007495 */
Romain Guy8fb95422010-08-17 18:38:51 -07007496 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7497 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007498 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007499 scrollBar.draw(canvas);
7500 }
Mike Reede8853fc2009-09-04 14:01:48 -04007501
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007502 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007503 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7504 * returns true.</p>
7505 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 * @param canvas the canvas on which to draw the scrollbar
7507 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007508 *
7509 * @see #isVerticalScrollBarEnabled()
7510 * @see #computeVerticalScrollRange()
7511 * @see #computeVerticalScrollExtent()
7512 * @see #computeVerticalScrollOffset()
7513 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007514 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007515 */
Romain Guy8fb95422010-08-17 18:38:51 -07007516 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7517 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007518 scrollBar.setBounds(l, t, r, b);
7519 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 }
7521
7522 /**
7523 * Implement this to do your drawing.
7524 *
7525 * @param canvas the canvas on which the background will be drawn
7526 */
7527 protected void onDraw(Canvas canvas) {
7528 }
7529
7530 /*
7531 * Caller is responsible for calling requestLayout if necessary.
7532 * (This allows addViewInLayout to not request a new layout.)
7533 */
7534 void assignParent(ViewParent parent) {
7535 if (mParent == null) {
7536 mParent = parent;
7537 } else if (parent == null) {
7538 mParent = null;
7539 } else {
7540 throw new RuntimeException("view " + this + " being added, but"
7541 + " it already has a parent");
7542 }
7543 }
7544
7545 /**
7546 * This is called when the view is attached to a window. At this point it
7547 * has a Surface and will start drawing. Note that this function is
7548 * guaranteed to be called before {@link #onDraw}, however it may be called
7549 * any time before the first onDraw -- including before or after
7550 * {@link #onMeasure}.
7551 *
7552 * @see #onDetachedFromWindow()
7553 */
7554 protected void onAttachedToWindow() {
7555 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7556 mParent.requestTransparentRegion(this);
7557 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007558 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7559 initialAwakenScrollBars();
7560 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7561 }
Chet Haasea9b61ac2010-12-20 07:40:25 -08007562 jumpDrawablesToCurrentState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007563 }
7564
7565 /**
7566 * This is called when the view is detached from a window. At this point it
7567 * no longer has a surface for drawing.
7568 *
7569 * @see #onAttachedToWindow()
7570 */
7571 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007572 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guy6c319ca2011-01-11 14:29:25 -08007573
Romain Guya440b002010-02-24 15:57:54 -08007574 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007575 removeLongPressCallback();
Romain Guy6c319ca2011-01-11 14:29:25 -08007576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007577 destroyDrawingCache();
Romain Guy6c319ca2011-01-11 14:29:25 -08007578
7579 if (mHardwareLayer != null) {
7580 mHardwareLayer.destroy();
7581 mHardwareLayer = null;
7582 }
Romain Guy8dd5b1e2011-01-14 17:28:51 -08007583
7584 if (mAttachInfo != null) {
7585 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
7586 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this);
7587 }
7588
Patrick Dubroyec84c3a2011-01-13 17:55:37 -08007589 mCurrentAnimation = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590 }
7591
7592 /**
7593 * @return The number of times this view has been attached to a window
7594 */
7595 protected int getWindowAttachCount() {
7596 return mWindowAttachCount;
7597 }
7598
7599 /**
7600 * Retrieve a unique token identifying the window this view is attached to.
7601 * @return Return the window's token for use in
7602 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7603 */
7604 public IBinder getWindowToken() {
7605 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7606 }
7607
7608 /**
7609 * Retrieve a unique token identifying the top-level "real" window of
7610 * the window that this view is attached to. That is, this is like
7611 * {@link #getWindowToken}, except if the window this view in is a panel
7612 * window (attached to another containing window), then the token of
7613 * the containing window is returned instead.
7614 *
7615 * @return Returns the associated window token, either
7616 * {@link #getWindowToken()} or the containing window's token.
7617 */
7618 public IBinder getApplicationWindowToken() {
7619 AttachInfo ai = mAttachInfo;
7620 if (ai != null) {
7621 IBinder appWindowToken = ai.mPanelParentWindowToken;
7622 if (appWindowToken == null) {
7623 appWindowToken = ai.mWindowToken;
7624 }
7625 return appWindowToken;
7626 }
7627 return null;
7628 }
7629
7630 /**
7631 * Retrieve private session object this view hierarchy is using to
7632 * communicate with the window manager.
7633 * @return the session object to communicate with the window manager
7634 */
7635 /*package*/ IWindowSession getWindowSession() {
7636 return mAttachInfo != null ? mAttachInfo.mSession : null;
7637 }
7638
7639 /**
7640 * @param info the {@link android.view.View.AttachInfo} to associated with
7641 * this view
7642 */
7643 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7644 //System.out.println("Attached! " + this);
7645 mAttachInfo = info;
7646 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007647 // We will need to evaluate the drawable state at least once.
7648 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 if (mFloatingTreeObserver != null) {
7650 info.mTreeObserver.merge(mFloatingTreeObserver);
7651 mFloatingTreeObserver = null;
7652 }
7653 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7654 mAttachInfo.mScrollContainers.add(this);
7655 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7656 }
7657 performCollectViewAttributes(visibility);
7658 onAttachedToWindow();
7659 int vis = info.mWindowVisibility;
7660 if (vis != GONE) {
7661 onWindowVisibilityChanged(vis);
7662 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007663 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7664 // If nobody has evaluated the drawable state yet, then do it now.
7665 refreshDrawableState();
7666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 }
7668
7669 void dispatchDetachedFromWindow() {
7670 //System.out.println("Detached! " + this);
7671 AttachInfo info = mAttachInfo;
7672 if (info != null) {
7673 int vis = info.mWindowVisibility;
7674 if (vis != GONE) {
7675 onWindowVisibilityChanged(GONE);
7676 }
7677 }
7678
7679 onDetachedFromWindow();
7680 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7681 mAttachInfo.mScrollContainers.remove(this);
7682 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7683 }
7684 mAttachInfo = null;
7685 }
7686
7687 /**
7688 * Store this view hierarchy's frozen state into the given container.
7689 *
7690 * @param container The SparseArray in which to save the view's state.
7691 *
7692 * @see #restoreHierarchyState
7693 * @see #dispatchSaveInstanceState
7694 * @see #onSaveInstanceState
7695 */
7696 public void saveHierarchyState(SparseArray<Parcelable> container) {
7697 dispatchSaveInstanceState(container);
7698 }
7699
7700 /**
7701 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7702 * May be overridden to modify how freezing happens to a view's children; for example, some
7703 * views may want to not store state for their children.
7704 *
7705 * @param container The SparseArray in which to save the view's state.
7706 *
7707 * @see #dispatchRestoreInstanceState
7708 * @see #saveHierarchyState
7709 * @see #onSaveInstanceState
7710 */
7711 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7712 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7713 mPrivateFlags &= ~SAVE_STATE_CALLED;
7714 Parcelable state = onSaveInstanceState();
7715 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7716 throw new IllegalStateException(
7717 "Derived class did not call super.onSaveInstanceState()");
7718 }
7719 if (state != null) {
7720 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7721 // + ": " + state);
7722 container.put(mID, state);
7723 }
7724 }
7725 }
7726
7727 /**
7728 * Hook allowing a view to generate a representation of its internal state
7729 * that can later be used to create a new instance with that same state.
7730 * This state should only contain information that is not persistent or can
7731 * not be reconstructed later. For example, you will never store your
7732 * current position on screen because that will be computed again when a
7733 * new instance of the view is placed in its view hierarchy.
7734 * <p>
7735 * Some examples of things you may store here: the current cursor position
7736 * in a text view (but usually not the text itself since that is stored in a
7737 * content provider or other persistent storage), the currently selected
7738 * item in a list view.
7739 *
7740 * @return Returns a Parcelable object containing the view's current dynamic
7741 * state, or null if there is nothing interesting to save. The
7742 * default implementation returns null.
7743 * @see #onRestoreInstanceState
7744 * @see #saveHierarchyState
7745 * @see #dispatchSaveInstanceState
7746 * @see #setSaveEnabled(boolean)
7747 */
7748 protected Parcelable onSaveInstanceState() {
7749 mPrivateFlags |= SAVE_STATE_CALLED;
7750 return BaseSavedState.EMPTY_STATE;
7751 }
7752
7753 /**
7754 * Restore this view hierarchy's frozen state from the given container.
7755 *
7756 * @param container The SparseArray which holds previously frozen states.
7757 *
7758 * @see #saveHierarchyState
7759 * @see #dispatchRestoreInstanceState
7760 * @see #onRestoreInstanceState
7761 */
7762 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7763 dispatchRestoreInstanceState(container);
7764 }
7765
7766 /**
7767 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7768 * children. May be overridden to modify how restoreing happens to a view's children; for
7769 * example, some views may want to not store state for their children.
7770 *
7771 * @param container The SparseArray which holds previously saved state.
7772 *
7773 * @see #dispatchSaveInstanceState
7774 * @see #restoreHierarchyState
7775 * @see #onRestoreInstanceState
7776 */
7777 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7778 if (mID != NO_ID) {
7779 Parcelable state = container.get(mID);
7780 if (state != null) {
7781 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7782 // + ": " + state);
7783 mPrivateFlags &= ~SAVE_STATE_CALLED;
7784 onRestoreInstanceState(state);
7785 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7786 throw new IllegalStateException(
7787 "Derived class did not call super.onRestoreInstanceState()");
7788 }
7789 }
7790 }
7791 }
7792
7793 /**
7794 * Hook allowing a view to re-apply a representation of its internal state that had previously
7795 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7796 * null state.
7797 *
7798 * @param state The frozen state that had previously been returned by
7799 * {@link #onSaveInstanceState}.
7800 *
7801 * @see #onSaveInstanceState
7802 * @see #restoreHierarchyState
7803 * @see #dispatchRestoreInstanceState
7804 */
7805 protected void onRestoreInstanceState(Parcelable state) {
7806 mPrivateFlags |= SAVE_STATE_CALLED;
7807 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007808 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7809 + "received " + state.getClass().toString() + " instead. This usually happens "
7810 + "when two views of different type have the same id in the same hierarchy. "
7811 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7812 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007813 }
7814 }
7815
7816 /**
7817 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7818 *
7819 * @return the drawing start time in milliseconds
7820 */
7821 public long getDrawingTime() {
7822 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7823 }
7824
7825 /**
7826 * <p>Enables or disables the duplication of the parent's state into this view. When
7827 * duplication is enabled, this view gets its drawable state from its parent rather
7828 * than from its own internal properties.</p>
7829 *
7830 * <p>Note: in the current implementation, setting this property to true after the
7831 * view was added to a ViewGroup might have no effect at all. This property should
7832 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7833 *
7834 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7835 * property is enabled, an exception will be thrown.</p>
Gilles Debunnefb817032011-01-13 13:52:49 -08007836 *
7837 * <p>Note: if the child view uses and updates additionnal states which are unknown to the
7838 * parent, these states should not be affected by this method.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007839 *
7840 * @param enabled True to enable duplication of the parent's drawable state, false
7841 * to disable it.
7842 *
7843 * @see #getDrawableState()
7844 * @see #isDuplicateParentStateEnabled()
7845 */
7846 public void setDuplicateParentStateEnabled(boolean enabled) {
7847 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7848 }
7849
7850 /**
7851 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7852 *
7853 * @return True if this view's drawable state is duplicated from the parent,
7854 * false otherwise
7855 *
7856 * @see #getDrawableState()
7857 * @see #setDuplicateParentStateEnabled(boolean)
7858 */
7859 public boolean isDuplicateParentStateEnabled() {
7860 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7861 }
7862
7863 /**
Romain Guy171c5922011-01-06 10:04:23 -08007864 * <p>Specifies the type of layer backing this view. The layer can be
7865 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
7866 * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
7867 *
7868 * <p>A layer is associated with an optional {@link android.graphics.Paint}
7869 * instance that controls how the layer is composed on screen. The following
7870 * properties of the paint are taken into account when composing the layer:</p>
7871 * <ul>
7872 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
7873 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
7874 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
7875 * </ul>
7876 *
7877 * <p>If this view has an alpha value set to < 1.0 by calling
7878 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
7879 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
7880 * equivalent to setting a hardware layer on this view and providing a paint with
7881 * the desired alpha value.<p>
7882 *
7883 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
7884 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
7885 * for more information on when and how to use layers.</p>
7886 *
7887 * @param layerType The ype of layer to use with this view, must be one of
7888 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
7889 * {@link #LAYER_TYPE_HARDWARE}
7890 * @param paint The paint used to compose the layer. This argument is optional
7891 * and can be null. It is ignored when the layer type is
7892 * {@link #LAYER_TYPE_NONE}
7893 *
7894 * @see #getLayerType()
7895 * @see #LAYER_TYPE_NONE
7896 * @see #LAYER_TYPE_SOFTWARE
7897 * @see #LAYER_TYPE_HARDWARE
7898 * @see #setAlpha(float)
7899 *
7900 * @attr ref android.R.styleable#View_layerType
7901 */
7902 public void setLayerType(int layerType, Paint paint) {
7903 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
7904 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
7905 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
7906 }
Romain Guy6c319ca2011-01-11 14:29:25 -08007907
7908 if (layerType == mLayerType) return;
Romain Guy171c5922011-01-06 10:04:23 -08007909
7910 // Destroy any previous software drawing cache if needed
Romain Guy6c319ca2011-01-11 14:29:25 -08007911 switch (mLayerType) {
7912 case LAYER_TYPE_SOFTWARE:
7913 if (mDrawingCache != null) {
7914 mDrawingCache.recycle();
7915 mDrawingCache = null;
7916 }
7917
7918 if (mUnscaledDrawingCache != null) {
7919 mUnscaledDrawingCache.recycle();
7920 mUnscaledDrawingCache = null;
7921 }
7922 break;
7923 case LAYER_TYPE_HARDWARE:
7924 if (mHardwareLayer != null) {
7925 mHardwareLayer.destroy();
7926 mHardwareLayer = null;
7927 }
7928 break;
7929 default:
7930 break;
Romain Guy171c5922011-01-06 10:04:23 -08007931 }
7932
7933 mLayerType = layerType;
7934 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
7935
Romain Guy6c319ca2011-01-11 14:29:25 -08007936 // TODO: Make sure we invalidate the parent's display list
Romain Guy171c5922011-01-06 10:04:23 -08007937 invalidate();
7938 }
7939
7940 /**
7941 * Indicates what type of layer is currently associated with this view. By default
7942 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
7943 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
7944 * for more information on the different types of layers.
7945 *
7946 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
7947 * {@link #LAYER_TYPE_HARDWARE}
7948 *
7949 * @see #setLayerType(int, android.graphics.Paint)
7950 * @see #LAYER_TYPE_NONE
7951 * @see #LAYER_TYPE_SOFTWARE
7952 * @see #LAYER_TYPE_HARDWARE
7953 */
7954 public int getLayerType() {
7955 return mLayerType;
7956 }
Romain Guy6c319ca2011-01-11 14:29:25 -08007957
7958 /**
7959 * <p>Returns a hardware layer that can be used to draw this view again
7960 * without executing its draw method.</p>
7961 *
7962 * @return A HardwareLayer ready to render, or null if an error occurred.
7963 */
7964 HardwareLayer getHardwareLayer(Canvas currentCanvas) {
7965 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
7966 return null;
7967 }
7968
7969 final int width = mRight - mLeft;
7970 final int height = mBottom - mTop;
7971
7972 if (width == 0 || height == 0) {
7973 return null;
7974 }
7975
7976 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
7977 if (mHardwareLayer == null) {
7978 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
7979 width, height, isOpaque());
7980 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
7981 mHardwareLayer.resize(width, height);
7982 }
7983
7984 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
7985 try {
7986 canvas.setViewport(width, height);
7987 canvas.onPreDraw();
7988
7989 computeScroll();
7990 canvas.translate(-mScrollX, -mScrollY);
7991
7992 final int restoreCount = canvas.save();
7993
7994 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
7995
7996 // Fast path for layouts with no backgrounds
7997 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7998 mPrivateFlags &= ~DIRTY_MASK;
7999 dispatchDraw(canvas);
8000 } else {
8001 draw(canvas);
8002 }
8003
8004 canvas.restoreToCount(restoreCount);
8005 } finally {
8006 canvas.onPostDraw();
8007 mHardwareLayer.end(currentCanvas);
8008 }
8009 }
8010
8011 return mHardwareLayer;
8012 }
Romain Guy171c5922011-01-06 10:04:23 -08008013
8014 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
8016 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
8017 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
8018 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
8019 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
8020 * null.</p>
Romain Guy171c5922011-01-06 10:04:23 -08008021 *
8022 * <p>Enabling the drawing cache is similar to
8023 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
8024 * acceleration is turned off. When hardware acceleration is turned on enabling the
8025 * drawing cache has either no effect or the cache used at drawing time is not a bitmap.
8026 * This API can however be used to manually generate a bitmap copy of this view.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 *
8028 * @param enabled true to enable the drawing cache, false otherwise
8029 *
8030 * @see #isDrawingCacheEnabled()
8031 * @see #getDrawingCache()
8032 * @see #buildDrawingCache()
Romain Guy171c5922011-01-06 10:04:23 -08008033 * @see #setLayerType(int, android.graphics.Paint)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 */
8035 public void setDrawingCacheEnabled(boolean enabled) {
8036 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
8037 }
8038
8039 /**
8040 * <p>Indicates whether the drawing cache is enabled for this view.</p>
8041 *
8042 * @return true if the drawing cache is enabled
8043 *
8044 * @see #setDrawingCacheEnabled(boolean)
8045 * @see #getDrawingCache()
8046 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07008047 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008048 public boolean isDrawingCacheEnabled() {
8049 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
8050 }
8051
8052 /**
Romain Guyb051e892010-09-28 19:09:36 -07008053 * <p>Returns a display list that can be used to draw this view again
8054 * without executing its draw method.</p>
8055 *
8056 * @return A DisplayList ready to replay, or null if caching is not enabled.
8057 */
8058 DisplayList getDisplayList() {
8059 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8060 return null;
8061 }
Romain Guyb051e892010-09-28 19:09:36 -07008062 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8063 return null;
8064 }
8065
8066 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
Chet Haase9e90a992011-01-04 16:23:21 -08008067 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
8068 mDisplayList == null || !mDisplayList.isValid())) {
Romain Guyb051e892010-09-28 19:09:36 -07008069
Chet Haase9e90a992011-01-04 16:23:21 -08008070 if (mDisplayList == null) {
8071 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
8072 }
Romain Guyb051e892010-09-28 19:09:36 -07008073
8074 final HardwareCanvas canvas = mDisplayList.start();
8075 try {
8076 int width = mRight - mLeft;
8077 int height = mBottom - mTop;
8078
8079 canvas.setViewport(width, height);
8080 canvas.onPreDraw();
8081
8082 final int restoreCount = canvas.save();
8083
Romain Guy2fe9a8f2010-10-04 20:17:01 -07008084 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07008085
8086 // Fast path for layouts with no backgrounds
8087 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8088 mPrivateFlags &= ~DIRTY_MASK;
8089 dispatchDraw(canvas);
8090 } else {
8091 draw(canvas);
8092 }
8093
8094 canvas.restoreToCount(restoreCount);
8095 } finally {
8096 canvas.onPostDraw();
8097
8098 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07008099 }
8100 }
8101
8102 return mDisplayList;
8103 }
8104
8105 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008106 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
8107 *
8108 * @return A non-scaled bitmap representing this view or null if cache is disabled.
8109 *
8110 * @see #getDrawingCache(boolean)
8111 */
8112 public Bitmap getDrawingCache() {
8113 return getDrawingCache(false);
8114 }
8115
8116 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
8118 * is null when caching is disabled. If caching is enabled and the cache is not ready,
8119 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
8120 * draw from the cache when the cache is enabled. To benefit from the cache, you must
8121 * request the drawing cache by calling this method and draw it on screen if the
8122 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008123 *
8124 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8125 * this method will create a bitmap of the same size as this view. Because this bitmap
8126 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8127 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8128 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8129 * size than the view. This implies that your application must be able to handle this
8130 * size.</p>
8131 *
8132 * @param autoScale Indicates whether the generated bitmap should be scaled based on
8133 * the current density of the screen when the application is in compatibility
8134 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008136 * @return A bitmap representing this view or null if cache is disabled.
8137 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 * @see #setDrawingCacheEnabled(boolean)
8139 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07008140 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 * @see #destroyDrawingCache()
8142 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008143 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008144 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8145 return null;
8146 }
8147 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008148 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 }
Romain Guy02890fd2010-08-06 17:58:44 -07008150 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 }
8152
8153 /**
8154 * <p>Frees the resources used by the drawing cache. If you call
8155 * {@link #buildDrawingCache()} manually without calling
8156 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8157 * should cleanup the cache with this method afterwards.</p>
8158 *
8159 * @see #setDrawingCacheEnabled(boolean)
8160 * @see #buildDrawingCache()
8161 * @see #getDrawingCache()
8162 */
8163 public void destroyDrawingCache() {
8164 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008165 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008166 mDrawingCache = null;
8167 }
Romain Guyfbd8f692009-06-26 14:51:58 -07008168 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008169 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07008170 mUnscaledDrawingCache = null;
8171 }
Romain Guyb051e892010-09-28 19:09:36 -07008172 if (mDisplayList != null) {
Chet Haase9e90a992011-01-04 16:23:21 -08008173 mDisplayList.invalidate();
Romain Guyb051e892010-09-28 19:09:36 -07008174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 }
8176
8177 /**
8178 * Setting a solid background color for the drawing cache's bitmaps will improve
8179 * perfromance and memory usage. Note, though that this should only be used if this
8180 * view will always be drawn on top of a solid color.
8181 *
8182 * @param color The background color to use for the drawing cache's bitmap
8183 *
8184 * @see #setDrawingCacheEnabled(boolean)
8185 * @see #buildDrawingCache()
8186 * @see #getDrawingCache()
8187 */
8188 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08008189 if (color != mDrawingCacheBackgroundColor) {
8190 mDrawingCacheBackgroundColor = color;
8191 mPrivateFlags &= ~DRAWING_CACHE_VALID;
8192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 }
8194
8195 /**
8196 * @see #setDrawingCacheBackgroundColor(int)
8197 *
8198 * @return The background color to used for the drawing cache's bitmap
8199 */
8200 public int getDrawingCacheBackgroundColor() {
8201 return mDrawingCacheBackgroundColor;
8202 }
8203
8204 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008205 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
8206 *
8207 * @see #buildDrawingCache(boolean)
8208 */
8209 public void buildDrawingCache() {
8210 buildDrawingCache(false);
8211 }
8212
8213 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008214 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
8215 *
8216 * <p>If you call {@link #buildDrawingCache()} manually without calling
8217 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8218 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008219 *
8220 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8221 * this method will create a bitmap of the same size as this view. Because this bitmap
8222 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8223 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8224 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8225 * size than the view. This implies that your application must be able to handle this
8226 * size.</p>
Romain Guy0d9275e2010-10-26 14:22:30 -07008227 *
8228 * <p>You should avoid calling this method when hardware acceleration is enabled. If
8229 * you do not need the drawing cache bitmap, calling this method will increase memory
8230 * usage and cause the view to be rendered in software once, thus negatively impacting
8231 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008232 *
8233 * @see #getDrawingCache()
8234 * @see #destroyDrawingCache()
8235 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008236 public void buildDrawingCache(boolean autoScale) {
8237 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07008238 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008239
8240 if (ViewDebug.TRACE_HIERARCHY) {
8241 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
8242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008243
Romain Guy8506ab42009-06-11 17:35:47 -07008244 int width = mRight - mLeft;
8245 int height = mBottom - mTop;
8246
8247 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07008248 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07008249
Romain Guye1123222009-06-29 14:24:56 -07008250 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008251 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
8252 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07008253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008254
8255 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07008256 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08008257 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008258
8259 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07008260 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08008261 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008262 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
8263 destroyDrawingCache();
8264 return;
8265 }
8266
8267 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07008268 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008269
8270 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008271 Bitmap.Config quality;
8272 if (!opaque) {
8273 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
8274 case DRAWING_CACHE_QUALITY_AUTO:
8275 quality = Bitmap.Config.ARGB_8888;
8276 break;
8277 case DRAWING_CACHE_QUALITY_LOW:
8278 quality = Bitmap.Config.ARGB_4444;
8279 break;
8280 case DRAWING_CACHE_QUALITY_HIGH:
8281 quality = Bitmap.Config.ARGB_8888;
8282 break;
8283 default:
8284 quality = Bitmap.Config.ARGB_8888;
8285 break;
8286 }
8287 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07008288 // Optimization for translucent windows
8289 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08008290 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008291 }
8292
8293 // Try to cleanup memory
8294 if (bitmap != null) bitmap.recycle();
8295
8296 try {
8297 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07008298 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07008299 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07008300 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008301 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07008302 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008303 }
Adam Powell26153a32010-11-08 15:22:27 -08008304 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008305 } catch (OutOfMemoryError e) {
8306 // If there is not enough memory to create the bitmap cache, just
8307 // ignore the issue as bitmap caches are not required to draw the
8308 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07008309 if (autoScale) {
8310 mDrawingCache = null;
8311 } else {
8312 mUnscaledDrawingCache = null;
8313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008314 return;
8315 }
8316
8317 clear = drawingCacheBackgroundColor != 0;
8318 }
8319
8320 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008321 if (attachInfo != null) {
8322 canvas = attachInfo.mCanvas;
8323 if (canvas == null) {
8324 canvas = new Canvas();
8325 }
8326 canvas.setBitmap(bitmap);
8327 // Temporarily clobber the cached Canvas in case one of our children
8328 // is also using a drawing cache. Without this, the children would
8329 // steal the canvas by attaching their own bitmap to it and bad, bad
8330 // thing would happen (invisible views, corrupted drawings, etc.)
8331 attachInfo.mCanvas = null;
8332 } else {
8333 // This case should hopefully never or seldom happen
8334 canvas = new Canvas(bitmap);
8335 }
8336
8337 if (clear) {
8338 bitmap.eraseColor(drawingCacheBackgroundColor);
8339 }
8340
8341 computeScroll();
8342 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07008343
Romain Guye1123222009-06-29 14:24:56 -07008344 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008345 final float scale = attachInfo.mApplicationScale;
8346 canvas.scale(scale, scale);
8347 }
8348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008349 canvas.translate(-mScrollX, -mScrollY);
8350
Romain Guy5bcdff42009-05-14 21:27:18 -07008351 mPrivateFlags |= DRAWN;
Romain Guy171c5922011-01-06 10:04:23 -08008352 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
8353 mLayerType != LAYER_TYPE_NONE) {
Romain Guy0d9275e2010-10-26 14:22:30 -07008354 mPrivateFlags |= DRAWING_CACHE_VALID;
8355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008356
8357 // Fast path for layouts with no backgrounds
8358 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8359 if (ViewDebug.TRACE_HIERARCHY) {
8360 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8361 }
Romain Guy5bcdff42009-05-14 21:27:18 -07008362 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008363 dispatchDraw(canvas);
8364 } else {
8365 draw(canvas);
8366 }
8367
8368 canvas.restoreToCount(restoreCount);
8369
8370 if (attachInfo != null) {
8371 // Restore the cached Canvas for our siblings
8372 attachInfo.mCanvas = canvas;
8373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008374 }
8375 }
8376
8377 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008378 * Create a snapshot of the view into a bitmap. We should probably make
8379 * some form of this public, but should think about the API.
8380 */
Romain Guy223ff5c2010-03-02 17:07:47 -08008381 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008382 int width = mRight - mLeft;
8383 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008384
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008385 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07008386 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008387 width = (int) ((width * scale) + 0.5f);
8388 height = (int) ((height * scale) + 0.5f);
8389
Romain Guy8c11e312009-09-14 15:15:30 -07008390 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008391 if (bitmap == null) {
8392 throw new OutOfMemoryError();
8393 }
8394
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008395 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8396
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008397 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008398 if (attachInfo != null) {
8399 canvas = attachInfo.mCanvas;
8400 if (canvas == null) {
8401 canvas = new Canvas();
8402 }
8403 canvas.setBitmap(bitmap);
8404 // Temporarily clobber the cached Canvas in case one of our children
8405 // is also using a drawing cache. Without this, the children would
8406 // steal the canvas by attaching their own bitmap to it and bad, bad
8407 // things would happen (invisible views, corrupted drawings, etc.)
8408 attachInfo.mCanvas = null;
8409 } else {
8410 // This case should hopefully never or seldom happen
8411 canvas = new Canvas(bitmap);
8412 }
8413
Romain Guy5bcdff42009-05-14 21:27:18 -07008414 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008415 bitmap.eraseColor(backgroundColor);
8416 }
8417
8418 computeScroll();
8419 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008420 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008421 canvas.translate(-mScrollX, -mScrollY);
8422
Romain Guy5bcdff42009-05-14 21:27:18 -07008423 // Temporarily remove the dirty mask
8424 int flags = mPrivateFlags;
8425 mPrivateFlags &= ~DIRTY_MASK;
8426
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008427 // Fast path for layouts with no backgrounds
8428 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8429 dispatchDraw(canvas);
8430 } else {
8431 draw(canvas);
8432 }
8433
Romain Guy5bcdff42009-05-14 21:27:18 -07008434 mPrivateFlags = flags;
8435
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008436 canvas.restoreToCount(restoreCount);
8437
8438 if (attachInfo != null) {
8439 // Restore the cached Canvas for our siblings
8440 attachInfo.mCanvas = canvas;
8441 }
Romain Guy8506ab42009-06-11 17:35:47 -07008442
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008443 return bitmap;
8444 }
8445
8446 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008447 * Indicates whether this View is currently in edit mode. A View is usually
8448 * in edit mode when displayed within a developer tool. For instance, if
8449 * this View is being drawn by a visual user interface builder, this method
8450 * should return true.
8451 *
8452 * Subclasses should check the return value of this method to provide
8453 * different behaviors if their normal behavior might interfere with the
8454 * host environment. For instance: the class spawns a thread in its
8455 * constructor, the drawing code relies on device-specific features, etc.
8456 *
8457 * This method is usually checked in the drawing code of custom widgets.
8458 *
8459 * @return True if this View is in edit mode, false otherwise.
8460 */
8461 public boolean isInEditMode() {
8462 return false;
8463 }
8464
8465 /**
8466 * If the View draws content inside its padding and enables fading edges,
8467 * it needs to support padding offsets. Padding offsets are added to the
8468 * fading edges to extend the length of the fade so that it covers pixels
8469 * drawn inside the padding.
8470 *
8471 * Subclasses of this class should override this method if they need
8472 * to draw content inside the padding.
8473 *
8474 * @return True if padding offset must be applied, false otherwise.
8475 *
8476 * @see #getLeftPaddingOffset()
8477 * @see #getRightPaddingOffset()
8478 * @see #getTopPaddingOffset()
8479 * @see #getBottomPaddingOffset()
8480 *
8481 * @since CURRENT
8482 */
8483 protected boolean isPaddingOffsetRequired() {
8484 return false;
8485 }
8486
8487 /**
8488 * Amount by which to extend the left fading region. Called only when
8489 * {@link #isPaddingOffsetRequired()} returns true.
8490 *
8491 * @return The left padding offset in pixels.
8492 *
8493 * @see #isPaddingOffsetRequired()
8494 *
8495 * @since CURRENT
8496 */
8497 protected int getLeftPaddingOffset() {
8498 return 0;
8499 }
8500
8501 /**
8502 * Amount by which to extend the right fading region. Called only when
8503 * {@link #isPaddingOffsetRequired()} returns true.
8504 *
8505 * @return The right padding offset in pixels.
8506 *
8507 * @see #isPaddingOffsetRequired()
8508 *
8509 * @since CURRENT
8510 */
8511 protected int getRightPaddingOffset() {
8512 return 0;
8513 }
8514
8515 /**
8516 * Amount by which to extend the top fading region. Called only when
8517 * {@link #isPaddingOffsetRequired()} returns true.
8518 *
8519 * @return The top padding offset in pixels.
8520 *
8521 * @see #isPaddingOffsetRequired()
8522 *
8523 * @since CURRENT
8524 */
8525 protected int getTopPaddingOffset() {
8526 return 0;
8527 }
8528
8529 /**
8530 * Amount by which to extend the bottom fading region. Called only when
8531 * {@link #isPaddingOffsetRequired()} returns true.
8532 *
8533 * @return The bottom padding offset in pixels.
8534 *
8535 * @see #isPaddingOffsetRequired()
8536 *
8537 * @since CURRENT
8538 */
8539 protected int getBottomPaddingOffset() {
8540 return 0;
8541 }
8542
8543 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008544 * <p>Indicates whether this view is attached to an hardware accelerated
8545 * window or not.</p>
8546 *
8547 * <p>Even if this method returns true, it does not mean that every call
8548 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8549 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8550 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8551 * window is hardware accelerated,
8552 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8553 * return false, and this method will return true.</p>
8554 *
8555 * @return True if the view is attached to a window and the window is
8556 * hardware accelerated; false in any other case.
8557 */
8558 public boolean isHardwareAccelerated() {
8559 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8560 }
8561
8562 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 * Manually render this view (and all of its children) to the given Canvas.
8564 * The view must have already done a full layout before this function is
Chet Haasec75ec332010-12-17 07:44:30 -08008565 * called. When implementing a view, implement {@link #onDraw} instead of
8566 * overriding this method. If you do need to override this method, call
8567 * the superclass version.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008568 *
8569 * @param canvas The Canvas to which the View is rendered.
8570 */
8571 public void draw(Canvas canvas) {
8572 if (ViewDebug.TRACE_HIERARCHY) {
8573 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8574 }
8575
Romain Guy5bcdff42009-05-14 21:27:18 -07008576 final int privateFlags = mPrivateFlags;
8577 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8578 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8579 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008581 /*
8582 * Draw traversal performs several drawing steps which must be executed
8583 * in the appropriate order:
8584 *
8585 * 1. Draw the background
8586 * 2. If necessary, save the canvas' layers to prepare for fading
8587 * 3. Draw view's content
8588 * 4. Draw children
8589 * 5. If necessary, draw the fading edges and restore layers
8590 * 6. Draw decorations (scrollbars for instance)
8591 */
8592
8593 // Step 1, draw the background, if needed
8594 int saveCount;
8595
Romain Guy24443ea2009-05-11 11:56:30 -07008596 if (!dirtyOpaque) {
8597 final Drawable background = mBGDrawable;
8598 if (background != null) {
8599 final int scrollX = mScrollX;
8600 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601
Romain Guy24443ea2009-05-11 11:56:30 -07008602 if (mBackgroundSizeChanged) {
8603 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8604 mBackgroundSizeChanged = false;
8605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008606
Romain Guy24443ea2009-05-11 11:56:30 -07008607 if ((scrollX | scrollY) == 0) {
8608 background.draw(canvas);
8609 } else {
8610 canvas.translate(scrollX, scrollY);
8611 background.draw(canvas);
8612 canvas.translate(-scrollX, -scrollY);
8613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008614 }
8615 }
8616
8617 // skip step 2 & 5 if possible (common case)
8618 final int viewFlags = mViewFlags;
8619 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8620 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8621 if (!verticalEdges && !horizontalEdges) {
8622 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008623 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008624
8625 // Step 4, draw the children
8626 dispatchDraw(canvas);
8627
8628 // Step 6, draw decorations (scrollbars)
8629 onDrawScrollBars(canvas);
8630
8631 // we're done...
8632 return;
8633 }
8634
8635 /*
8636 * Here we do the full fledged routine...
8637 * (this is an uncommon case where speed matters less,
8638 * this is why we repeat some of the tests that have been
8639 * done above)
8640 */
8641
8642 boolean drawTop = false;
8643 boolean drawBottom = false;
8644 boolean drawLeft = false;
8645 boolean drawRight = false;
8646
8647 float topFadeStrength = 0.0f;
8648 float bottomFadeStrength = 0.0f;
8649 float leftFadeStrength = 0.0f;
8650 float rightFadeStrength = 0.0f;
8651
8652 // Step 2, save the canvas' layers
8653 int paddingLeft = mPaddingLeft;
8654 int paddingTop = mPaddingTop;
8655
8656 final boolean offsetRequired = isPaddingOffsetRequired();
8657 if (offsetRequired) {
8658 paddingLeft += getLeftPaddingOffset();
8659 paddingTop += getTopPaddingOffset();
8660 }
8661
8662 int left = mScrollX + paddingLeft;
8663 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8664 int top = mScrollY + paddingTop;
8665 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8666
8667 if (offsetRequired) {
8668 right += getRightPaddingOffset();
8669 bottom += getBottomPaddingOffset();
8670 }
8671
8672 final ScrollabilityCache scrollabilityCache = mScrollCache;
8673 int length = scrollabilityCache.fadingEdgeLength;
8674
8675 // clip the fade length if top and bottom fades overlap
8676 // overlapping fades produce odd-looking artifacts
8677 if (verticalEdges && (top + length > bottom - length)) {
8678 length = (bottom - top) / 2;
8679 }
8680
8681 // also clip horizontal fades if necessary
8682 if (horizontalEdges && (left + length > right - length)) {
8683 length = (right - left) / 2;
8684 }
8685
8686 if (verticalEdges) {
8687 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008688 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008689 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008690 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008691 }
8692
8693 if (horizontalEdges) {
8694 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008695 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008697 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008698 }
8699
8700 saveCount = canvas.getSaveCount();
8701
8702 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008703 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008704 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8705
8706 if (drawTop) {
8707 canvas.saveLayer(left, top, right, top + length, null, flags);
8708 }
8709
8710 if (drawBottom) {
8711 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8712 }
8713
8714 if (drawLeft) {
8715 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8716 }
8717
8718 if (drawRight) {
8719 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8720 }
8721 } else {
8722 scrollabilityCache.setFadeColor(solidColor);
8723 }
8724
8725 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008726 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008727
8728 // Step 4, draw the children
8729 dispatchDraw(canvas);
8730
8731 // Step 5, draw the fade effect and restore layers
8732 final Paint p = scrollabilityCache.paint;
8733 final Matrix matrix = scrollabilityCache.matrix;
8734 final Shader fade = scrollabilityCache.shader;
8735 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8736
8737 if (drawTop) {
8738 matrix.setScale(1, fadeHeight * topFadeStrength);
8739 matrix.postTranslate(left, top);
8740 fade.setLocalMatrix(matrix);
8741 canvas.drawRect(left, top, right, top + length, p);
8742 }
8743
8744 if (drawBottom) {
8745 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8746 matrix.postRotate(180);
8747 matrix.postTranslate(left, bottom);
8748 fade.setLocalMatrix(matrix);
8749 canvas.drawRect(left, bottom - length, right, bottom, p);
8750 }
8751
8752 if (drawLeft) {
8753 matrix.setScale(1, fadeHeight * leftFadeStrength);
8754 matrix.postRotate(-90);
8755 matrix.postTranslate(left, top);
8756 fade.setLocalMatrix(matrix);
8757 canvas.drawRect(left, top, left + length, bottom, p);
8758 }
8759
8760 if (drawRight) {
8761 matrix.setScale(1, fadeHeight * rightFadeStrength);
8762 matrix.postRotate(90);
8763 matrix.postTranslate(right, top);
8764 fade.setLocalMatrix(matrix);
8765 canvas.drawRect(right - length, top, right, bottom, p);
8766 }
8767
8768 canvas.restoreToCount(saveCount);
8769
8770 // Step 6, draw decorations (scrollbars)
8771 onDrawScrollBars(canvas);
8772 }
8773
8774 /**
8775 * Override this if your view is known to always be drawn on top of a solid color background,
8776 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8777 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8778 * should be set to 0xFF.
8779 *
8780 * @see #setVerticalFadingEdgeEnabled
8781 * @see #setHorizontalFadingEdgeEnabled
8782 *
8783 * @return The known solid color background for this view, or 0 if the color may vary
8784 */
8785 public int getSolidColor() {
8786 return 0;
8787 }
8788
8789 /**
8790 * Build a human readable string representation of the specified view flags.
8791 *
8792 * @param flags the view flags to convert to a string
8793 * @return a String representing the supplied flags
8794 */
8795 private static String printFlags(int flags) {
8796 String output = "";
8797 int numFlags = 0;
8798 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8799 output += "TAKES_FOCUS";
8800 numFlags++;
8801 }
8802
8803 switch (flags & VISIBILITY_MASK) {
8804 case INVISIBLE:
8805 if (numFlags > 0) {
8806 output += " ";
8807 }
8808 output += "INVISIBLE";
8809 // USELESS HERE numFlags++;
8810 break;
8811 case GONE:
8812 if (numFlags > 0) {
8813 output += " ";
8814 }
8815 output += "GONE";
8816 // USELESS HERE numFlags++;
8817 break;
8818 default:
8819 break;
8820 }
8821 return output;
8822 }
8823
8824 /**
8825 * Build a human readable string representation of the specified private
8826 * view flags.
8827 *
8828 * @param privateFlags the private view flags to convert to a string
8829 * @return a String representing the supplied flags
8830 */
8831 private static String printPrivateFlags(int privateFlags) {
8832 String output = "";
8833 int numFlags = 0;
8834
8835 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8836 output += "WANTS_FOCUS";
8837 numFlags++;
8838 }
8839
8840 if ((privateFlags & FOCUSED) == FOCUSED) {
8841 if (numFlags > 0) {
8842 output += " ";
8843 }
8844 output += "FOCUSED";
8845 numFlags++;
8846 }
8847
8848 if ((privateFlags & SELECTED) == SELECTED) {
8849 if (numFlags > 0) {
8850 output += " ";
8851 }
8852 output += "SELECTED";
8853 numFlags++;
8854 }
8855
8856 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8857 if (numFlags > 0) {
8858 output += " ";
8859 }
8860 output += "IS_ROOT_NAMESPACE";
8861 numFlags++;
8862 }
8863
8864 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8865 if (numFlags > 0) {
8866 output += " ";
8867 }
8868 output += "HAS_BOUNDS";
8869 numFlags++;
8870 }
8871
8872 if ((privateFlags & DRAWN) == DRAWN) {
8873 if (numFlags > 0) {
8874 output += " ";
8875 }
8876 output += "DRAWN";
8877 // USELESS HERE numFlags++;
8878 }
8879 return output;
8880 }
8881
8882 /**
8883 * <p>Indicates whether or not this view's layout will be requested during
8884 * the next hierarchy layout pass.</p>
8885 *
8886 * @return true if the layout will be forced during next layout pass
8887 */
8888 public boolean isLayoutRequested() {
8889 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8890 }
8891
8892 /**
8893 * Assign a size and position to a view and all of its
8894 * descendants
8895 *
8896 * <p>This is the second phase of the layout mechanism.
8897 * (The first is measuring). In this phase, each parent calls
8898 * layout on all of its children to position them.
8899 * This is typically done using the child measurements
Chet Haase9c087442011-01-12 16:20:16 -08008900 * that were stored in the measure pass().</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008901 *
Chet Haase9c087442011-01-12 16:20:16 -08008902 * <p>Derived classes should not override this method.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008903 * Derived classes with children should override
8904 * onLayout. In that method, they should
Chet Haase9c087442011-01-12 16:20:16 -08008905 * call layout on each of their children.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 *
8907 * @param l Left position, relative to parent
8908 * @param t Top position, relative to parent
8909 * @param r Right position, relative to parent
8910 * @param b Bottom position, relative to parent
8911 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008912 @SuppressWarnings({"unchecked"})
Chet Haase9c087442011-01-12 16:20:16 -08008913 public void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008914 int oldL = mLeft;
8915 int oldT = mTop;
8916 int oldB = mBottom;
8917 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008918 boolean changed = setFrame(l, t, r, b);
8919 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8920 if (ViewDebug.TRACE_HIERARCHY) {
8921 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8922 }
8923
8924 onLayout(changed, l, t, r, b);
8925 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008926
8927 if (mOnLayoutChangeListeners != null) {
8928 ArrayList<OnLayoutChangeListener> listenersCopy =
8929 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8930 int numListeners = listenersCopy.size();
8931 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07008932 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07008933 }
8934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 }
8936 mPrivateFlags &= ~FORCE_LAYOUT;
8937 }
8938
8939 /**
8940 * Called from layout when this view should
8941 * assign a size and position to each of its children.
8942 *
8943 * Derived classes with children should override
8944 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008945 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008946 * @param changed This is a new size or position for this view
8947 * @param left Left position, relative to parent
8948 * @param top Top position, relative to parent
8949 * @param right Right position, relative to parent
8950 * @param bottom Bottom position, relative to parent
8951 */
8952 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8953 }
8954
8955 /**
8956 * Assign a size and position to this view.
8957 *
8958 * This is called from layout.
8959 *
8960 * @param left Left position, relative to parent
8961 * @param top Top position, relative to parent
8962 * @param right Right position, relative to parent
8963 * @param bottom Bottom position, relative to parent
8964 * @return true if the new size and position are different than the
8965 * previous ones
8966 * {@hide}
8967 */
8968 protected boolean setFrame(int left, int top, int right, int bottom) {
8969 boolean changed = false;
8970
8971 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008972 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008973 + right + "," + bottom + ")");
8974 }
8975
8976 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8977 changed = true;
8978
8979 // Remember our drawn bit
8980 int drawn = mPrivateFlags & DRAWN;
8981
8982 // Invalidate our old position
8983 invalidate();
8984
8985
8986 int oldWidth = mRight - mLeft;
8987 int oldHeight = mBottom - mTop;
8988
8989 mLeft = left;
8990 mTop = top;
8991 mRight = right;
8992 mBottom = bottom;
8993
8994 mPrivateFlags |= HAS_BOUNDS;
8995
8996 int newWidth = right - left;
8997 int newHeight = bottom - top;
8998
8999 if (newWidth != oldWidth || newHeight != oldHeight) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009000 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9001 // A change in dimension means an auto-centered pivot point changes, too
9002 mMatrixDirty = true;
9003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009004 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
9005 }
9006
9007 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
9008 // If we are visible, force the DRAWN bit to on so that
9009 // this invalidate will go through (at least to our parent).
9010 // This is because someone may have invalidated this view
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009011 // before this call to setFrame came in, thereby clearing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009012 // the DRAWN bit.
9013 mPrivateFlags |= DRAWN;
9014 invalidate();
9015 }
9016
9017 // Reset drawn bit to original value (invalidate turns it off)
9018 mPrivateFlags |= drawn;
9019
9020 mBackgroundSizeChanged = true;
9021 }
9022 return changed;
9023 }
9024
9025 /**
9026 * Finalize inflating a view from XML. This is called as the last phase
9027 * of inflation, after all child views have been added.
9028 *
9029 * <p>Even if the subclass overrides onFinishInflate, they should always be
9030 * sure to call the super method, so that we get called.
9031 */
9032 protected void onFinishInflate() {
9033 }
9034
9035 /**
9036 * Returns the resources associated with this view.
9037 *
9038 * @return Resources object.
9039 */
9040 public Resources getResources() {
9041 return mResources;
9042 }
9043
9044 /**
9045 * Invalidates the specified Drawable.
9046 *
9047 * @param drawable the drawable to invalidate
9048 */
9049 public void invalidateDrawable(Drawable drawable) {
9050 if (verifyDrawable(drawable)) {
9051 final Rect dirty = drawable.getBounds();
9052 final int scrollX = mScrollX;
9053 final int scrollY = mScrollY;
9054
9055 invalidate(dirty.left + scrollX, dirty.top + scrollY,
9056 dirty.right + scrollX, dirty.bottom + scrollY);
9057 }
9058 }
9059
9060 /**
9061 * Schedules an action on a drawable to occur at a specified time.
9062 *
9063 * @param who the recipient of the action
9064 * @param what the action to run on the drawable
9065 * @param when the time at which the action must occur. Uses the
9066 * {@link SystemClock#uptimeMillis} timebase.
9067 */
9068 public void scheduleDrawable(Drawable who, Runnable what, long when) {
9069 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9070 mAttachInfo.mHandler.postAtTime(what, who, when);
9071 }
9072 }
9073
9074 /**
9075 * Cancels a scheduled action on a drawable.
9076 *
9077 * @param who the recipient of the action
9078 * @param what the action to cancel
9079 */
9080 public void unscheduleDrawable(Drawable who, Runnable what) {
9081 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9082 mAttachInfo.mHandler.removeCallbacks(what, who);
9083 }
9084 }
9085
9086 /**
9087 * Unschedule any events associated with the given Drawable. This can be
9088 * used when selecting a new Drawable into a view, so that the previous
9089 * one is completely unscheduled.
9090 *
9091 * @param who The Drawable to unschedule.
9092 *
9093 * @see #drawableStateChanged
9094 */
9095 public void unscheduleDrawable(Drawable who) {
9096 if (mAttachInfo != null) {
9097 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
9098 }
9099 }
9100
9101 /**
9102 * If your view subclass is displaying its own Drawable objects, it should
9103 * override this function and return true for any Drawable it is
9104 * displaying. This allows animations for those drawables to be
9105 * scheduled.
9106 *
9107 * <p>Be sure to call through to the super class when overriding this
9108 * function.
9109 *
9110 * @param who The Drawable to verify. Return true if it is one you are
9111 * displaying, else return the result of calling through to the
9112 * super class.
9113 *
9114 * @return boolean If true than the Drawable is being displayed in the
9115 * view; else false and it is not allowed to animate.
9116 *
9117 * @see #unscheduleDrawable
9118 * @see #drawableStateChanged
9119 */
9120 protected boolean verifyDrawable(Drawable who) {
9121 return who == mBGDrawable;
9122 }
9123
9124 /**
9125 * This function is called whenever the state of the view changes in such
9126 * a way that it impacts the state of drawables being shown.
9127 *
9128 * <p>Be sure to call through to the superclass when overriding this
9129 * function.
9130 *
9131 * @see Drawable#setState
9132 */
9133 protected void drawableStateChanged() {
9134 Drawable d = mBGDrawable;
9135 if (d != null && d.isStateful()) {
9136 d.setState(getDrawableState());
9137 }
9138 }
9139
9140 /**
9141 * Call this to force a view to update its drawable state. This will cause
9142 * drawableStateChanged to be called on this view. Views that are interested
9143 * in the new state should call getDrawableState.
9144 *
9145 * @see #drawableStateChanged
9146 * @see #getDrawableState
9147 */
9148 public void refreshDrawableState() {
9149 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9150 drawableStateChanged();
9151
9152 ViewParent parent = mParent;
9153 if (parent != null) {
9154 parent.childDrawableStateChanged(this);
9155 }
9156 }
9157
9158 /**
9159 * Return an array of resource IDs of the drawable states representing the
9160 * current state of the view.
9161 *
9162 * @return The current drawable state
9163 *
9164 * @see Drawable#setState
9165 * @see #drawableStateChanged
9166 * @see #onCreateDrawableState
9167 */
9168 public final int[] getDrawableState() {
9169 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
9170 return mDrawableState;
9171 } else {
9172 mDrawableState = onCreateDrawableState(0);
9173 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
9174 return mDrawableState;
9175 }
9176 }
9177
9178 /**
9179 * Generate the new {@link android.graphics.drawable.Drawable} state for
9180 * this view. This is called by the view
9181 * system when the cached Drawable state is determined to be invalid. To
9182 * retrieve the current state, you should use {@link #getDrawableState}.
9183 *
9184 * @param extraSpace if non-zero, this is the number of extra entries you
9185 * would like in the returned array in which you can place your own
9186 * states.
9187 *
9188 * @return Returns an array holding the current {@link Drawable} state of
9189 * the view.
9190 *
9191 * @see #mergeDrawableStates
9192 */
9193 protected int[] onCreateDrawableState(int extraSpace) {
9194 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
9195 mParent instanceof View) {
9196 return ((View) mParent).onCreateDrawableState(extraSpace);
9197 }
9198
9199 int[] drawableState;
9200
9201 int privateFlags = mPrivateFlags;
9202
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009203 int viewStateIndex = 0;
9204 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
9205 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
9206 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07009207 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009208 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
9209 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08009210 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
9211 // This is set if HW acceleration is requested, even if the current
9212 // process doesn't allow it. This is just to allow app preview
9213 // windows to better match their app.
9214 viewStateIndex |= VIEW_STATE_ACCELERATED;
9215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009216
9217 drawableState = VIEW_STATE_SETS[viewStateIndex];
9218
9219 //noinspection ConstantIfStatement
9220 if (false) {
9221 Log.i("View", "drawableStateIndex=" + viewStateIndex);
9222 Log.i("View", toString()
9223 + " pressed=" + ((privateFlags & PRESSED) != 0)
9224 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
9225 + " fo=" + hasFocus()
9226 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009227 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009228 + ": " + Arrays.toString(drawableState));
9229 }
9230
9231 if (extraSpace == 0) {
9232 return drawableState;
9233 }
9234
9235 final int[] fullState;
9236 if (drawableState != null) {
9237 fullState = new int[drawableState.length + extraSpace];
9238 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
9239 } else {
9240 fullState = new int[extraSpace];
9241 }
9242
9243 return fullState;
9244 }
9245
9246 /**
9247 * Merge your own state values in <var>additionalState</var> into the base
9248 * state values <var>baseState</var> that were returned by
9249 * {@link #onCreateDrawableState}.
9250 *
9251 * @param baseState The base state values returned by
9252 * {@link #onCreateDrawableState}, which will be modified to also hold your
9253 * own additional state values.
9254 *
9255 * @param additionalState The additional state values you would like
9256 * added to <var>baseState</var>; this array is not modified.
9257 *
9258 * @return As a convenience, the <var>baseState</var> array you originally
9259 * passed into the function is returned.
9260 *
9261 * @see #onCreateDrawableState
9262 */
9263 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
9264 final int N = baseState.length;
9265 int i = N - 1;
9266 while (i >= 0 && baseState[i] == 0) {
9267 i--;
9268 }
9269 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
9270 return baseState;
9271 }
9272
9273 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07009274 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
9275 * on all Drawable objects associated with this view.
9276 */
9277 public void jumpDrawablesToCurrentState() {
9278 if (mBGDrawable != null) {
9279 mBGDrawable.jumpToCurrentState();
9280 }
9281 }
9282
9283 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009284 * Sets the background color for this view.
9285 * @param color the color of the background
9286 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009287 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009288 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07009289 if (mBGDrawable instanceof ColorDrawable) {
9290 ((ColorDrawable) mBGDrawable).setColor(color);
9291 } else {
9292 setBackgroundDrawable(new ColorDrawable(color));
9293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009294 }
9295
9296 /**
9297 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07009298 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009299 * @param resid The identifier of the resource.
9300 * @attr ref android.R.styleable#View_background
9301 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009302 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303 public void setBackgroundResource(int resid) {
9304 if (resid != 0 && resid == mBackgroundResource) {
9305 return;
9306 }
9307
9308 Drawable d= null;
9309 if (resid != 0) {
9310 d = mResources.getDrawable(resid);
9311 }
9312 setBackgroundDrawable(d);
9313
9314 mBackgroundResource = resid;
9315 }
9316
9317 /**
9318 * Set the background to a given Drawable, or remove the background. If the
9319 * background has padding, this View's padding is set to the background's
9320 * padding. However, when a background is removed, this View's padding isn't
9321 * touched. If setting the padding is desired, please use
9322 * {@link #setPadding(int, int, int, int)}.
9323 *
9324 * @param d The Drawable to use as the background, or null to remove the
9325 * background
9326 */
9327 public void setBackgroundDrawable(Drawable d) {
9328 boolean requestLayout = false;
9329
9330 mBackgroundResource = 0;
9331
9332 /*
9333 * Regardless of whether we're setting a new background or not, we want
9334 * to clear the previous drawable.
9335 */
9336 if (mBGDrawable != null) {
9337 mBGDrawable.setCallback(null);
9338 unscheduleDrawable(mBGDrawable);
9339 }
9340
9341 if (d != null) {
9342 Rect padding = sThreadLocal.get();
9343 if (padding == null) {
9344 padding = new Rect();
9345 sThreadLocal.set(padding);
9346 }
9347 if (d.getPadding(padding)) {
9348 setPadding(padding.left, padding.top, padding.right, padding.bottom);
9349 }
9350
9351 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
9352 // if it has a different minimum size, we should layout again
9353 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9354 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9355 requestLayout = true;
9356 }
9357
9358 d.setCallback(this);
9359 if (d.isStateful()) {
9360 d.setState(getDrawableState());
9361 }
9362 d.setVisible(getVisibility() == VISIBLE, false);
9363 mBGDrawable = d;
9364
9365 if ((mPrivateFlags & SKIP_DRAW) != 0) {
9366 mPrivateFlags &= ~SKIP_DRAW;
9367 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9368 requestLayout = true;
9369 }
9370 } else {
9371 /* Remove the background */
9372 mBGDrawable = null;
9373
9374 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9375 /*
9376 * This view ONLY drew the background before and we're removing
9377 * the background, so now it won't draw anything
9378 * (hence we SKIP_DRAW)
9379 */
9380 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9381 mPrivateFlags |= SKIP_DRAW;
9382 }
9383
9384 /*
9385 * When the background is set, we try to apply its padding to this
9386 * View. When the background is removed, we don't touch this View's
9387 * padding. This is noted in the Javadocs. Hence, we don't need to
9388 * requestLayout(), the invalidate() below is sufficient.
9389 */
9390
9391 // The old background's minimum size could have affected this
9392 // View's layout, so let's requestLayout
9393 requestLayout = true;
9394 }
9395
Romain Guy8f1344f52009-05-15 16:03:59 -07009396 computeOpaqueFlags();
9397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009398 if (requestLayout) {
9399 requestLayout();
9400 }
9401
9402 mBackgroundSizeChanged = true;
9403 invalidate();
9404 }
9405
9406 /**
9407 * Gets the background drawable
9408 * @return The drawable used as the background for this view, if any.
9409 */
9410 public Drawable getBackground() {
9411 return mBGDrawable;
9412 }
9413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009414 /**
9415 * Sets the padding. The view may add on the space required to display
9416 * the scrollbars, depending on the style and visibility of the scrollbars.
9417 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9418 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9419 * from the values set in this call.
9420 *
9421 * @attr ref android.R.styleable#View_padding
9422 * @attr ref android.R.styleable#View_paddingBottom
9423 * @attr ref android.R.styleable#View_paddingLeft
9424 * @attr ref android.R.styleable#View_paddingRight
9425 * @attr ref android.R.styleable#View_paddingTop
9426 * @param left the left padding in pixels
9427 * @param top the top padding in pixels
9428 * @param right the right padding in pixels
9429 * @param bottom the bottom padding in pixels
9430 */
9431 public void setPadding(int left, int top, int right, int bottom) {
9432 boolean changed = false;
9433
Adam Powell20232d02010-12-08 21:08:53 -08009434 mUserPaddingLeft = left;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009435 mUserPaddingRight = right;
9436 mUserPaddingBottom = bottom;
9437
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009438 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07009439
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009440 // Common case is there are no scroll bars.
9441 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009442 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
Adam Powell20232d02010-12-08 21:08:53 -08009443 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9444 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009445 ? 0 : getVerticalScrollbarWidth();
Adam Powell20232d02010-12-08 21:08:53 -08009446 switch (mVerticalScrollbarPosition) {
9447 case SCROLLBAR_POSITION_DEFAULT:
9448 case SCROLLBAR_POSITION_RIGHT:
9449 right += offset;
9450 break;
9451 case SCROLLBAR_POSITION_LEFT:
9452 left += offset;
9453 break;
9454 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009455 }
Adam Powell20232d02010-12-08 21:08:53 -08009456 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009457 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9458 ? 0 : getHorizontalScrollbarHeight();
9459 }
9460 }
Romain Guy8506ab42009-06-11 17:35:47 -07009461
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009462 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009463 changed = true;
9464 mPaddingLeft = left;
9465 }
9466 if (mPaddingTop != top) {
9467 changed = true;
9468 mPaddingTop = top;
9469 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009470 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009471 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009472 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009473 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009474 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009475 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009476 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009477 }
9478
9479 if (changed) {
9480 requestLayout();
9481 }
9482 }
9483
9484 /**
9485 * Returns the top padding of this view.
9486 *
9487 * @return the top padding in pixels
9488 */
9489 public int getPaddingTop() {
9490 return mPaddingTop;
9491 }
9492
9493 /**
9494 * Returns the bottom padding of this view. If there are inset and enabled
9495 * scrollbars, this value may include the space required to display the
9496 * scrollbars as well.
9497 *
9498 * @return the bottom padding in pixels
9499 */
9500 public int getPaddingBottom() {
9501 return mPaddingBottom;
9502 }
9503
9504 /**
9505 * Returns the left padding of this view. If there are inset and enabled
9506 * scrollbars, this value may include the space required to display the
9507 * scrollbars as well.
9508 *
9509 * @return the left padding in pixels
9510 */
9511 public int getPaddingLeft() {
9512 return mPaddingLeft;
9513 }
9514
9515 /**
9516 * Returns the right padding of this view. If there are inset and enabled
9517 * scrollbars, this value may include the space required to display the
9518 * scrollbars as well.
9519 *
9520 * @return the right padding in pixels
9521 */
9522 public int getPaddingRight() {
9523 return mPaddingRight;
9524 }
9525
9526 /**
9527 * Changes the selection state of this view. A view can be selected or not.
9528 * Note that selection is not the same as focus. Views are typically
9529 * selected in the context of an AdapterView like ListView or GridView;
9530 * the selected view is the view that is highlighted.
9531 *
9532 * @param selected true if the view must be selected, false otherwise
9533 */
9534 public void setSelected(boolean selected) {
9535 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9536 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009537 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009538 invalidate();
9539 refreshDrawableState();
9540 dispatchSetSelected(selected);
9541 }
9542 }
9543
9544 /**
9545 * Dispatch setSelected to all of this View's children.
9546 *
9547 * @see #setSelected(boolean)
9548 *
9549 * @param selected The new selected state
9550 */
9551 protected void dispatchSetSelected(boolean selected) {
9552 }
9553
9554 /**
9555 * Indicates the selection state of this view.
9556 *
9557 * @return true if the view is selected, false otherwise
9558 */
9559 @ViewDebug.ExportedProperty
9560 public boolean isSelected() {
9561 return (mPrivateFlags & SELECTED) != 0;
9562 }
9563
9564 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009565 * Changes the activated state of this view. A view can be activated or not.
9566 * Note that activation is not the same as selection. Selection is
9567 * a transient property, representing the view (hierarchy) the user is
9568 * currently interacting with. Activation is a longer-term state that the
9569 * user can move views in and out of. For example, in a list view with
9570 * single or multiple selection enabled, the views in the current selection
9571 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9572 * here.) The activated state is propagated down to children of the view it
9573 * is set on.
9574 *
9575 * @param activated true if the view must be activated, false otherwise
9576 */
9577 public void setActivated(boolean activated) {
9578 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9579 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
9580 invalidate();
9581 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009582 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009583 }
9584 }
9585
9586 /**
9587 * Dispatch setActivated to all of this View's children.
9588 *
9589 * @see #setActivated(boolean)
9590 *
9591 * @param activated The new activated state
9592 */
9593 protected void dispatchSetActivated(boolean activated) {
9594 }
9595
9596 /**
9597 * Indicates the activation state of this view.
9598 *
9599 * @return true if the view is activated, false otherwise
9600 */
9601 @ViewDebug.ExportedProperty
9602 public boolean isActivated() {
9603 return (mPrivateFlags & ACTIVATED) != 0;
9604 }
9605
9606 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009607 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9608 * observer can be used to get notifications when global events, like
9609 * layout, happen.
9610 *
9611 * The returned ViewTreeObserver observer is not guaranteed to remain
9612 * valid for the lifetime of this View. If the caller of this method keeps
9613 * a long-lived reference to ViewTreeObserver, it should always check for
9614 * the return value of {@link ViewTreeObserver#isAlive()}.
9615 *
9616 * @return The ViewTreeObserver for this view's hierarchy.
9617 */
9618 public ViewTreeObserver getViewTreeObserver() {
9619 if (mAttachInfo != null) {
9620 return mAttachInfo.mTreeObserver;
9621 }
9622 if (mFloatingTreeObserver == null) {
9623 mFloatingTreeObserver = new ViewTreeObserver();
9624 }
9625 return mFloatingTreeObserver;
9626 }
9627
9628 /**
9629 * <p>Finds the topmost view in the current view hierarchy.</p>
9630 *
9631 * @return the topmost view containing this view
9632 */
9633 public View getRootView() {
9634 if (mAttachInfo != null) {
9635 final View v = mAttachInfo.mRootView;
9636 if (v != null) {
9637 return v;
9638 }
9639 }
Romain Guy8506ab42009-06-11 17:35:47 -07009640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009641 View parent = this;
9642
9643 while (parent.mParent != null && parent.mParent instanceof View) {
9644 parent = (View) parent.mParent;
9645 }
9646
9647 return parent;
9648 }
9649
9650 /**
9651 * <p>Computes the coordinates of this view on the screen. The argument
9652 * must be an array of two integers. After the method returns, the array
9653 * contains the x and y location in that order.</p>
9654 *
9655 * @param location an array of two integers in which to hold the coordinates
9656 */
9657 public void getLocationOnScreen(int[] location) {
9658 getLocationInWindow(location);
9659
9660 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009661 if (info != null) {
9662 location[0] += info.mWindowLeft;
9663 location[1] += info.mWindowTop;
9664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009665 }
9666
9667 /**
9668 * <p>Computes the coordinates of this view in its window. The argument
9669 * must be an array of two integers. After the method returns, the array
9670 * contains the x and y location in that order.</p>
9671 *
9672 * @param location an array of two integers in which to hold the coordinates
9673 */
9674 public void getLocationInWindow(int[] location) {
9675 if (location == null || location.length < 2) {
9676 throw new IllegalArgumentException("location must be an array of "
9677 + "two integers");
9678 }
9679
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009680 location[0] = mLeft + (int) (mTranslationX + 0.5f);
9681 location[1] = mTop + (int) (mTranslationY + 0.5f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009682
9683 ViewParent viewParent = mParent;
9684 while (viewParent instanceof View) {
9685 final View view = (View)viewParent;
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009686 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
9687 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009688 viewParent = view.mParent;
9689 }
Romain Guy8506ab42009-06-11 17:35:47 -07009690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009691 if (viewParent instanceof ViewRoot) {
9692 // *cough*
9693 final ViewRoot vr = (ViewRoot)viewParent;
9694 location[1] -= vr.mCurScrollY;
9695 }
9696 }
9697
9698 /**
9699 * {@hide}
9700 * @param id the id of the view to be found
9701 * @return the view of the specified id, null if cannot be found
9702 */
9703 protected View findViewTraversal(int id) {
9704 if (id == mID) {
9705 return this;
9706 }
9707 return null;
9708 }
9709
9710 /**
9711 * {@hide}
9712 * @param tag the tag of the view to be found
9713 * @return the view of specified tag, null if cannot be found
9714 */
9715 protected View findViewWithTagTraversal(Object tag) {
9716 if (tag != null && tag.equals(mTag)) {
9717 return this;
9718 }
9719 return null;
9720 }
9721
9722 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009723 * {@hide}
9724 * @param predicate The predicate to evaluate.
9725 * @return The first view that matches the predicate or null.
9726 */
9727 protected View findViewByPredicateTraversal(Predicate<View> predicate) {
9728 if (predicate.apply(this)) {
9729 return this;
9730 }
9731 return null;
9732 }
9733
9734 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009735 * Look for a child view with the given id. If this view has the given
9736 * id, return this view.
9737 *
9738 * @param id The id to search for.
9739 * @return The view that has the given id in the hierarchy or null
9740 */
9741 public final View findViewById(int id) {
9742 if (id < 0) {
9743 return null;
9744 }
9745 return findViewTraversal(id);
9746 }
9747
9748 /**
9749 * Look for a child view with the given tag. If this view has the given
9750 * tag, return this view.
9751 *
9752 * @param tag The tag to search for, using "tag.equals(getTag())".
9753 * @return The View that has the given tag in the hierarchy or null
9754 */
9755 public final View findViewWithTag(Object tag) {
9756 if (tag == null) {
9757 return null;
9758 }
9759 return findViewWithTagTraversal(tag);
9760 }
9761
9762 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009763 * {@hide}
9764 * Look for a child view that matches the specified predicate.
9765 * If this view matches the predicate, return this view.
9766 *
9767 * @param predicate The predicate to evaluate.
9768 * @return The first view that matches the predicate or null.
9769 */
9770 public final View findViewByPredicate(Predicate<View> predicate) {
9771 return findViewByPredicateTraversal(predicate);
9772 }
9773
9774 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009775 * Sets the identifier for this view. The identifier does not have to be
9776 * unique in this view's hierarchy. The identifier should be a positive
9777 * number.
9778 *
9779 * @see #NO_ID
9780 * @see #getId
9781 * @see #findViewById
9782 *
9783 * @param id a number used to identify the view
9784 *
9785 * @attr ref android.R.styleable#View_id
9786 */
9787 public void setId(int id) {
9788 mID = id;
9789 }
9790
9791 /**
9792 * {@hide}
9793 *
9794 * @param isRoot true if the view belongs to the root namespace, false
9795 * otherwise
9796 */
9797 public void setIsRootNamespace(boolean isRoot) {
9798 if (isRoot) {
9799 mPrivateFlags |= IS_ROOT_NAMESPACE;
9800 } else {
9801 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9802 }
9803 }
9804
9805 /**
9806 * {@hide}
9807 *
9808 * @return true if the view belongs to the root namespace, false otherwise
9809 */
9810 public boolean isRootNamespace() {
9811 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9812 }
9813
9814 /**
9815 * Returns this view's identifier.
9816 *
9817 * @return a positive integer used to identify the view or {@link #NO_ID}
9818 * if the view has no ID
9819 *
9820 * @see #setId
9821 * @see #findViewById
9822 * @attr ref android.R.styleable#View_id
9823 */
9824 @ViewDebug.CapturedViewProperty
9825 public int getId() {
9826 return mID;
9827 }
9828
9829 /**
9830 * Returns this view's tag.
9831 *
9832 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07009833 *
9834 * @see #setTag(Object)
9835 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009836 */
9837 @ViewDebug.ExportedProperty
9838 public Object getTag() {
9839 return mTag;
9840 }
9841
9842 /**
9843 * Sets the tag associated with this view. A tag can be used to mark
9844 * a view in its hierarchy and does not have to be unique within the
9845 * hierarchy. Tags can also be used to store data within a view without
9846 * resorting to another data structure.
9847 *
9848 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07009849 *
9850 * @see #getTag()
9851 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009852 */
9853 public void setTag(final Object tag) {
9854 mTag = tag;
9855 }
9856
9857 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009858 * Returns the tag associated with this view and the specified key.
9859 *
9860 * @param key The key identifying the tag
9861 *
9862 * @return the Object stored in this view as a tag
9863 *
9864 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009865 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009866 */
9867 public Object getTag(int key) {
9868 SparseArray<Object> tags = null;
9869 synchronized (sTagsLock) {
9870 if (sTags != null) {
9871 tags = sTags.get(this);
9872 }
9873 }
9874
9875 if (tags != null) return tags.get(key);
9876 return null;
9877 }
9878
9879 /**
9880 * Sets a tag associated with this view and a key. A tag can be used
9881 * to mark a view in its hierarchy and does not have to be unique within
9882 * the hierarchy. Tags can also be used to store data within a view
9883 * without resorting to another data structure.
9884 *
9885 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009886 * application to ensure it is unique (see the <a
9887 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9888 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009889 * the Android framework or not associated with any package will cause
9890 * an {@link IllegalArgumentException} to be thrown.
9891 *
9892 * @param key The key identifying the tag
9893 * @param tag An Object to tag the view with
9894 *
9895 * @throws IllegalArgumentException If they specified key is not valid
9896 *
9897 * @see #setTag(Object)
9898 * @see #getTag(int)
9899 */
9900 public void setTag(int key, final Object tag) {
9901 // If the package id is 0x00 or 0x01, it's either an undefined package
9902 // or a framework id
9903 if ((key >>> 24) < 2) {
9904 throw new IllegalArgumentException("The key must be an application-specific "
9905 + "resource id.");
9906 }
9907
9908 setTagInternal(this, key, tag);
9909 }
9910
9911 /**
9912 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9913 * framework id.
9914 *
9915 * @hide
9916 */
9917 public void setTagInternal(int key, Object tag) {
9918 if ((key >>> 24) != 0x1) {
9919 throw new IllegalArgumentException("The key must be a framework-specific "
9920 + "resource id.");
9921 }
9922
Romain Guy8506ab42009-06-11 17:35:47 -07009923 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009924 }
9925
9926 private static void setTagInternal(View view, int key, Object tag) {
9927 SparseArray<Object> tags = null;
9928 synchronized (sTagsLock) {
9929 if (sTags == null) {
9930 sTags = new WeakHashMap<View, SparseArray<Object>>();
9931 } else {
9932 tags = sTags.get(view);
9933 }
9934 }
9935
9936 if (tags == null) {
9937 tags = new SparseArray<Object>(2);
9938 synchronized (sTagsLock) {
9939 sTags.put(view, tags);
9940 }
9941 }
9942
9943 tags.put(key, tag);
9944 }
9945
9946 /**
Romain Guy13922e02009-05-12 17:56:14 -07009947 * @param consistency The type of consistency. See ViewDebug for more information.
9948 *
9949 * @hide
9950 */
9951 protected boolean dispatchConsistencyCheck(int consistency) {
9952 return onConsistencyCheck(consistency);
9953 }
9954
9955 /**
9956 * Method that subclasses should implement to check their consistency. The type of
9957 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009958 *
Romain Guy13922e02009-05-12 17:56:14 -07009959 * @param consistency The type of consistency. See ViewDebug for more information.
9960 *
9961 * @throws IllegalStateException if the view is in an inconsistent state.
9962 *
9963 * @hide
9964 */
9965 protected boolean onConsistencyCheck(int consistency) {
9966 boolean result = true;
9967
9968 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9969 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9970
9971 if (checkLayout) {
9972 if (getParent() == null) {
9973 result = false;
9974 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9975 "View " + this + " does not have a parent.");
9976 }
9977
9978 if (mAttachInfo == null) {
9979 result = false;
9980 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9981 "View " + this + " is not attached to a window.");
9982 }
9983 }
9984
9985 if (checkDrawing) {
9986 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9987 // from their draw() method
9988
9989 if ((mPrivateFlags & DRAWN) != DRAWN &&
9990 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9991 result = false;
9992 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9993 "View " + this + " was invalidated but its drawing cache is valid.");
9994 }
9995 }
9996
9997 return result;
9998 }
9999
10000 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010001 * Prints information about this view in the log output, with the tag
10002 * {@link #VIEW_LOG_TAG}.
10003 *
10004 * @hide
10005 */
10006 public void debug() {
10007 debug(0);
10008 }
10009
10010 /**
10011 * Prints information about this view in the log output, with the tag
10012 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
10013 * indentation defined by the <code>depth</code>.
10014 *
10015 * @param depth the indentation level
10016 *
10017 * @hide
10018 */
10019 protected void debug(int depth) {
10020 String output = debugIndent(depth - 1);
10021
10022 output += "+ " + this;
10023 int id = getId();
10024 if (id != -1) {
10025 output += " (id=" + id + ")";
10026 }
10027 Object tag = getTag();
10028 if (tag != null) {
10029 output += " (tag=" + tag + ")";
10030 }
10031 Log.d(VIEW_LOG_TAG, output);
10032
10033 if ((mPrivateFlags & FOCUSED) != 0) {
10034 output = debugIndent(depth) + " FOCUSED";
10035 Log.d(VIEW_LOG_TAG, output);
10036 }
10037
10038 output = debugIndent(depth);
10039 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
10040 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
10041 + "} ";
10042 Log.d(VIEW_LOG_TAG, output);
10043
10044 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
10045 || mPaddingBottom != 0) {
10046 output = debugIndent(depth);
10047 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
10048 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
10049 Log.d(VIEW_LOG_TAG, output);
10050 }
10051
10052 output = debugIndent(depth);
10053 output += "mMeasureWidth=" + mMeasuredWidth +
10054 " mMeasureHeight=" + mMeasuredHeight;
10055 Log.d(VIEW_LOG_TAG, output);
10056
10057 output = debugIndent(depth);
10058 if (mLayoutParams == null) {
10059 output += "BAD! no layout params";
10060 } else {
10061 output = mLayoutParams.debug(output);
10062 }
10063 Log.d(VIEW_LOG_TAG, output);
10064
10065 output = debugIndent(depth);
10066 output += "flags={";
10067 output += View.printFlags(mViewFlags);
10068 output += "}";
10069 Log.d(VIEW_LOG_TAG, output);
10070
10071 output = debugIndent(depth);
10072 output += "privateFlags={";
10073 output += View.printPrivateFlags(mPrivateFlags);
10074 output += "}";
10075 Log.d(VIEW_LOG_TAG, output);
10076 }
10077
10078 /**
10079 * Creates an string of whitespaces used for indentation.
10080 *
10081 * @param depth the indentation level
10082 * @return a String containing (depth * 2 + 3) * 2 white spaces
10083 *
10084 * @hide
10085 */
10086 protected static String debugIndent(int depth) {
10087 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
10088 for (int i = 0; i < (depth * 2) + 3; i++) {
10089 spaces.append(' ').append(' ');
10090 }
10091 return spaces.toString();
10092 }
10093
10094 /**
10095 * <p>Return the offset of the widget's text baseline from the widget's top
10096 * boundary. If this widget does not support baseline alignment, this
10097 * method returns -1. </p>
10098 *
10099 * @return the offset of the baseline within the widget's bounds or -1
10100 * if baseline alignment is not supported
10101 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -070010102 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010103 public int getBaseline() {
10104 return -1;
10105 }
10106
10107 /**
10108 * Call this when something has changed which has invalidated the
10109 * layout of this view. This will schedule a layout pass of the view
10110 * tree.
10111 */
10112 public void requestLayout() {
10113 if (ViewDebug.TRACE_HIERARCHY) {
10114 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
10115 }
10116
10117 mPrivateFlags |= FORCE_LAYOUT;
10118
10119 if (mParent != null && !mParent.isLayoutRequested()) {
10120 mParent.requestLayout();
10121 }
10122 }
10123
10124 /**
10125 * Forces this view to be laid out during the next layout pass.
10126 * This method does not call requestLayout() or forceLayout()
10127 * on the parent.
10128 */
10129 public void forceLayout() {
10130 mPrivateFlags |= FORCE_LAYOUT;
10131 }
10132
10133 /**
10134 * <p>
10135 * This is called to find out how big a view should be. The parent
10136 * supplies constraint information in the width and height parameters.
10137 * </p>
10138 *
10139 * <p>
10140 * The actual mesurement work of a view is performed in
10141 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
10142 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
10143 * </p>
10144 *
10145 *
10146 * @param widthMeasureSpec Horizontal space requirements as imposed by the
10147 * parent
10148 * @param heightMeasureSpec Vertical space requirements as imposed by the
10149 * parent
10150 *
10151 * @see #onMeasure(int, int)
10152 */
10153 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
10154 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
10155 widthMeasureSpec != mOldWidthMeasureSpec ||
10156 heightMeasureSpec != mOldHeightMeasureSpec) {
10157
10158 // first clears the measured dimension flag
10159 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
10160
10161 if (ViewDebug.TRACE_HIERARCHY) {
10162 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
10163 }
10164
10165 // measure ourselves, this should set the measured dimension flag back
10166 onMeasure(widthMeasureSpec, heightMeasureSpec);
10167
10168 // flag not set, setMeasuredDimension() was not invoked, we raise
10169 // an exception to warn the developer
10170 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
10171 throw new IllegalStateException("onMeasure() did not set the"
10172 + " measured dimension by calling"
10173 + " setMeasuredDimension()");
10174 }
10175
10176 mPrivateFlags |= LAYOUT_REQUIRED;
10177 }
10178
10179 mOldWidthMeasureSpec = widthMeasureSpec;
10180 mOldHeightMeasureSpec = heightMeasureSpec;
10181 }
10182
10183 /**
10184 * <p>
10185 * Measure the view and its content to determine the measured width and the
10186 * measured height. This method is invoked by {@link #measure(int, int)} and
10187 * should be overriden by subclasses to provide accurate and efficient
10188 * measurement of their contents.
10189 * </p>
10190 *
10191 * <p>
10192 * <strong>CONTRACT:</strong> When overriding this method, you
10193 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
10194 * measured width and height of this view. Failure to do so will trigger an
10195 * <code>IllegalStateException</code>, thrown by
10196 * {@link #measure(int, int)}. Calling the superclass'
10197 * {@link #onMeasure(int, int)} is a valid use.
10198 * </p>
10199 *
10200 * <p>
10201 * The base class implementation of measure defaults to the background size,
10202 * unless a larger size is allowed by the MeasureSpec. Subclasses should
10203 * override {@link #onMeasure(int, int)} to provide better measurements of
10204 * their content.
10205 * </p>
10206 *
10207 * <p>
10208 * If this method is overridden, it is the subclass's responsibility to make
10209 * sure the measured height and width are at least the view's minimum height
10210 * and width ({@link #getSuggestedMinimumHeight()} and
10211 * {@link #getSuggestedMinimumWidth()}).
10212 * </p>
10213 *
10214 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
10215 * The requirements are encoded with
10216 * {@link android.view.View.MeasureSpec}.
10217 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
10218 * The requirements are encoded with
10219 * {@link android.view.View.MeasureSpec}.
10220 *
10221 * @see #getMeasuredWidth()
10222 * @see #getMeasuredHeight()
10223 * @see #setMeasuredDimension(int, int)
10224 * @see #getSuggestedMinimumHeight()
10225 * @see #getSuggestedMinimumWidth()
10226 * @see android.view.View.MeasureSpec#getMode(int)
10227 * @see android.view.View.MeasureSpec#getSize(int)
10228 */
10229 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10230 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
10231 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
10232 }
10233
10234 /**
10235 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
10236 * measured width and measured height. Failing to do so will trigger an
10237 * exception at measurement time.</p>
10238 *
Dianne Hackborn189ee182010-12-02 21:48:53 -080010239 * @param measuredWidth The measured width of this view. May be a complex
10240 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10241 * {@link #MEASURED_STATE_TOO_SMALL}.
10242 * @param measuredHeight The measured height of this view. May be a complex
10243 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10244 * {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010245 */
10246 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
10247 mMeasuredWidth = measuredWidth;
10248 mMeasuredHeight = measuredHeight;
10249
10250 mPrivateFlags |= MEASURED_DIMENSION_SET;
10251 }
10252
10253 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -080010254 * Merge two states as returned by {@link #getMeasuredState()}.
10255 * @param curState The current state as returned from a view or the result
10256 * of combining multiple views.
10257 * @param newState The new view state to combine.
10258 * @return Returns a new integer reflecting the combination of the two
10259 * states.
10260 */
10261 public static int combineMeasuredStates(int curState, int newState) {
10262 return curState | newState;
10263 }
10264
10265 /**
10266 * Version of {@link #resolveSizeAndState(int, int, int)}
10267 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
10268 */
10269 public static int resolveSize(int size, int measureSpec) {
10270 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
10271 }
10272
10273 /**
10274 * Utility to reconcile a desired size and state, with constraints imposed
10275 * by a MeasureSpec. Will take the desired size, unless a different size
10276 * is imposed by the constraints. The returned value is a compound integer,
10277 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
10278 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
10279 * size is smaller than the size the view wants to be.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010280 *
10281 * @param size How big the view wants to be
10282 * @param measureSpec Constraints imposed by the parent
Dianne Hackborn189ee182010-12-02 21:48:53 -080010283 * @return Size information bit mask as defined by
10284 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010285 */
Dianne Hackborn189ee182010-12-02 21:48:53 -080010286 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010287 int result = size;
10288 int specMode = MeasureSpec.getMode(measureSpec);
10289 int specSize = MeasureSpec.getSize(measureSpec);
10290 switch (specMode) {
10291 case MeasureSpec.UNSPECIFIED:
10292 result = size;
10293 break;
10294 case MeasureSpec.AT_MOST:
Dianne Hackborn189ee182010-12-02 21:48:53 -080010295 if (specSize < size) {
10296 result = specSize | MEASURED_STATE_TOO_SMALL;
10297 } else {
10298 result = size;
10299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010300 break;
10301 case MeasureSpec.EXACTLY:
10302 result = specSize;
10303 break;
10304 }
Dianne Hackborn189ee182010-12-02 21:48:53 -080010305 return result | (childMeasuredState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010306 }
10307
10308 /**
10309 * Utility to return a default size. Uses the supplied size if the
10310 * MeasureSpec imposed no contraints. Will get larger if allowed
10311 * by the MeasureSpec.
10312 *
10313 * @param size Default size for this view
10314 * @param measureSpec Constraints imposed by the parent
10315 * @return The size this view should be.
10316 */
10317 public static int getDefaultSize(int size, int measureSpec) {
10318 int result = size;
10319 int specMode = MeasureSpec.getMode(measureSpec);
10320 int specSize = MeasureSpec.getSize(measureSpec);
10321
10322 switch (specMode) {
10323 case MeasureSpec.UNSPECIFIED:
10324 result = size;
10325 break;
10326 case MeasureSpec.AT_MOST:
10327 case MeasureSpec.EXACTLY:
10328 result = specSize;
10329 break;
10330 }
10331 return result;
10332 }
10333
10334 /**
10335 * Returns the suggested minimum height that the view should use. This
10336 * returns the maximum of the view's minimum height
10337 * and the background's minimum height
10338 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10339 * <p>
10340 * When being used in {@link #onMeasure(int, int)}, the caller should still
10341 * ensure the returned height is within the requirements of the parent.
10342 *
10343 * @return The suggested minimum height of the view.
10344 */
10345 protected int getSuggestedMinimumHeight() {
10346 int suggestedMinHeight = mMinHeight;
10347
10348 if (mBGDrawable != null) {
10349 final int bgMinHeight = mBGDrawable.getMinimumHeight();
10350 if (suggestedMinHeight < bgMinHeight) {
10351 suggestedMinHeight = bgMinHeight;
10352 }
10353 }
10354
10355 return suggestedMinHeight;
10356 }
10357
10358 /**
10359 * Returns the suggested minimum width that the view should use. This
10360 * returns the maximum of the view's minimum width)
10361 * and the background's minimum width
10362 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10363 * <p>
10364 * When being used in {@link #onMeasure(int, int)}, the caller should still
10365 * ensure the returned width is within the requirements of the parent.
10366 *
10367 * @return The suggested minimum width of the view.
10368 */
10369 protected int getSuggestedMinimumWidth() {
10370 int suggestedMinWidth = mMinWidth;
10371
10372 if (mBGDrawable != null) {
10373 final int bgMinWidth = mBGDrawable.getMinimumWidth();
10374 if (suggestedMinWidth < bgMinWidth) {
10375 suggestedMinWidth = bgMinWidth;
10376 }
10377 }
10378
10379 return suggestedMinWidth;
10380 }
10381
10382 /**
10383 * Sets the minimum height of the view. It is not guaranteed the view will
10384 * be able to achieve this minimum height (for example, if its parent layout
10385 * constrains it with less available height).
10386 *
10387 * @param minHeight The minimum height the view will try to be.
10388 */
10389 public void setMinimumHeight(int minHeight) {
10390 mMinHeight = minHeight;
10391 }
10392
10393 /**
10394 * Sets the minimum width of the view. It is not guaranteed the view will
10395 * be able to achieve this minimum width (for example, if its parent layout
10396 * constrains it with less available width).
10397 *
10398 * @param minWidth The minimum width the view will try to be.
10399 */
10400 public void setMinimumWidth(int minWidth) {
10401 mMinWidth = minWidth;
10402 }
10403
10404 /**
10405 * Get the animation currently associated with this view.
10406 *
10407 * @return The animation that is currently playing or
10408 * scheduled to play for this view.
10409 */
10410 public Animation getAnimation() {
10411 return mCurrentAnimation;
10412 }
10413
10414 /**
10415 * Start the specified animation now.
10416 *
10417 * @param animation the animation to start now
10418 */
10419 public void startAnimation(Animation animation) {
10420 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10421 setAnimation(animation);
10422 invalidate();
10423 }
10424
10425 /**
10426 * Cancels any animations for this view.
10427 */
10428 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -080010429 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -080010430 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -080010431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010432 mCurrentAnimation = null;
10433 }
10434
10435 /**
10436 * Sets the next animation to play for this view.
10437 * If you want the animation to play immediately, use
10438 * startAnimation. This method provides allows fine-grained
10439 * control over the start time and invalidation, but you
10440 * must make sure that 1) the animation has a start time set, and
10441 * 2) the view will be invalidated when the animation is supposed to
10442 * start.
10443 *
10444 * @param animation The next animation, or null.
10445 */
10446 public void setAnimation(Animation animation) {
10447 mCurrentAnimation = animation;
10448 if (animation != null) {
10449 animation.reset();
10450 }
10451 }
10452
10453 /**
10454 * Invoked by a parent ViewGroup to notify the start of the animation
10455 * currently associated with this view. If you override this method,
10456 * always call super.onAnimationStart();
10457 *
10458 * @see #setAnimation(android.view.animation.Animation)
10459 * @see #getAnimation()
10460 */
10461 protected void onAnimationStart() {
10462 mPrivateFlags |= ANIMATION_STARTED;
10463 }
10464
10465 /**
10466 * Invoked by a parent ViewGroup to notify the end of the animation
10467 * currently associated with this view. If you override this method,
10468 * always call super.onAnimationEnd();
10469 *
10470 * @see #setAnimation(android.view.animation.Animation)
10471 * @see #getAnimation()
10472 */
10473 protected void onAnimationEnd() {
10474 mPrivateFlags &= ~ANIMATION_STARTED;
10475 }
10476
10477 /**
10478 * Invoked if there is a Transform that involves alpha. Subclass that can
10479 * draw themselves with the specified alpha should return true, and then
10480 * respect that alpha when their onDraw() is called. If this returns false
10481 * then the view may be redirected to draw into an offscreen buffer to
10482 * fulfill the request, which will look fine, but may be slower than if the
10483 * subclass handles it internally. The default implementation returns false.
10484 *
10485 * @param alpha The alpha (0..255) to apply to the view's drawing
10486 * @return true if the view can draw with the specified alpha.
10487 */
10488 protected boolean onSetAlpha(int alpha) {
10489 return false;
10490 }
10491
10492 /**
10493 * This is used by the RootView to perform an optimization when
10494 * the view hierarchy contains one or several SurfaceView.
10495 * SurfaceView is always considered transparent, but its children are not,
10496 * therefore all View objects remove themselves from the global transparent
10497 * region (passed as a parameter to this function).
10498 *
10499 * @param region The transparent region for this ViewRoot (window).
10500 *
10501 * @return Returns true if the effective visibility of the view at this
10502 * point is opaque, regardless of the transparent region; returns false
10503 * if it is possible for underlying windows to be seen behind the view.
10504 *
10505 * {@hide}
10506 */
10507 public boolean gatherTransparentRegion(Region region) {
10508 final AttachInfo attachInfo = mAttachInfo;
10509 if (region != null && attachInfo != null) {
10510 final int pflags = mPrivateFlags;
10511 if ((pflags & SKIP_DRAW) == 0) {
10512 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10513 // remove it from the transparent region.
10514 final int[] location = attachInfo.mTransparentLocation;
10515 getLocationInWindow(location);
10516 region.op(location[0], location[1], location[0] + mRight - mLeft,
10517 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10518 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10519 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10520 // exists, so we remove the background drawable's non-transparent
10521 // parts from this transparent region.
10522 applyDrawableToTransparentRegion(mBGDrawable, region);
10523 }
10524 }
10525 return true;
10526 }
10527
10528 /**
10529 * Play a sound effect for this view.
10530 *
10531 * <p>The framework will play sound effects for some built in actions, such as
10532 * clicking, but you may wish to play these effects in your widget,
10533 * for instance, for internal navigation.
10534 *
10535 * <p>The sound effect will only be played if sound effects are enabled by the user, and
10536 * {@link #isSoundEffectsEnabled()} is true.
10537 *
10538 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10539 */
10540 public void playSoundEffect(int soundConstant) {
10541 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10542 return;
10543 }
10544 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10545 }
10546
10547 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010548 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010549 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010550 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010551 *
10552 * <p>The framework will provide haptic feedback for some built in actions,
10553 * such as long presses, but you may wish to provide feedback for your
10554 * own widget.
10555 *
10556 * <p>The feedback will only be performed if
10557 * {@link #isHapticFeedbackEnabled()} is true.
10558 *
10559 * @param feedbackConstant One of the constants defined in
10560 * {@link HapticFeedbackConstants}
10561 */
10562 public boolean performHapticFeedback(int feedbackConstant) {
10563 return performHapticFeedback(feedbackConstant, 0);
10564 }
10565
10566 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010567 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010568 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010569 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010570 *
10571 * @param feedbackConstant One of the constants defined in
10572 * {@link HapticFeedbackConstants}
10573 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10574 */
10575 public boolean performHapticFeedback(int feedbackConstant, int flags) {
10576 if (mAttachInfo == null) {
10577 return false;
10578 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010579 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010580 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010581 && !isHapticFeedbackEnabled()) {
10582 return false;
10583 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010584 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10585 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010586 }
10587
10588 /**
Christopher Tate2c095f32010-10-04 14:13:40 -070010589 * !!! TODO: real docs
10590 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010591 * The base class implementation makes the shadow the same size and appearance
Christopher Tate2c095f32010-10-04 14:13:40 -070010592 * as the view itself, and positions it with its center at the touch point.
10593 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010594 public static class DragShadowBuilder {
Christopher Tatea0374192010-10-05 13:06:41 -070010595 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010596
10597 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010598 * Construct a shadow builder object for use with the given view.
Christopher Tate2c095f32010-10-04 14:13:40 -070010599 * @param view
10600 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010601 public DragShadowBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010602 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010603 }
10604
Chris Tate6b391282010-10-14 15:48:59 -070010605 final public View getView() {
10606 return mView.get();
10607 }
10608
Christopher Tate2c095f32010-10-04 14:13:40 -070010609 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010610 * Provide the draggable-shadow metrics for the operation: the dimensions of
10611 * the shadow image itself, and the point within that shadow that should
Christopher Tate2c095f32010-10-04 14:13:40 -070010612 * be centered under the touch location while dragging.
10613 * <p>
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010614 * The default implementation sets the dimensions of the shadow to be the
10615 * same as the dimensions of the View itself and centers the shadow under
Christopher Tate2c095f32010-10-04 14:13:40 -070010616 * the touch point.
10617 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010618 * @param shadowSize The application should set the {@code x} member of this
10619 * parameter to the desired shadow width, and the {@code y} member to
Christopher Tate2c095f32010-10-04 14:13:40 -070010620 * the desired height.
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010621 * @param shadowTouchPoint The application should set this point to be the
10622 * location within the shadow that should track directly underneath
Christopher Tate2c095f32010-10-04 14:13:40 -070010623 * the touch point on the screen during a drag.
10624 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010625 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070010626 final View view = mView.get();
10627 if (view != null) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010628 shadowSize.set(view.getWidth(), view.getHeight());
10629 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
Christopher Tatea0374192010-10-05 13:06:41 -070010630 } else {
10631 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10632 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010633 }
10634
10635 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010636 * Draw the shadow image for the upcoming drag. The shadow canvas was
10637 * created with the dimensions supplied by the
10638 * {@link #onProvideShadowMetrics(Point, Point)} callback.
Christopher Tate2c095f32010-10-04 14:13:40 -070010639 *
10640 * @param canvas
10641 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010642 public void onDrawShadow(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070010643 final View view = mView.get();
10644 if (view != null) {
10645 view.draw(canvas);
10646 } else {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010647 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
Christopher Tatea0374192010-10-05 13:06:41 -070010648 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010649 }
10650 }
10651
10652 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010653 * Drag and drop. App calls startDrag(), then callbacks to the shadow builder's
10654 * {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} and
10655 * {@link DragShadowBuilder#onDrawShadow(Canvas)} methods happen, then the drag
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010656 * operation is handed over to the OS.
Christopher Tatea53146c2010-09-07 11:57:52 -070010657 * !!! TODO: real docs
Christopher Tate407b4e92010-11-30 17:14:08 -080010658 *
10659 * @param data !!! TODO
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010660 * @param shadowBuilder !!! TODO
Christopher Tate407b4e92010-11-30 17:14:08 -080010661 * @param myLocalState An arbitrary object that will be passed as part of every DragEvent
10662 * delivered to the calling application during the course of the current drag operation.
10663 * This object is private to the application that called startDrag(), and is not
10664 * visible to other applications. It provides a lightweight way for the application to
10665 * propagate information from the initiator to the recipient of a drag within its own
10666 * application; for example, to help disambiguate between 'copy' and 'move' semantics.
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010667 * @param flags Flags affecting the drag operation. At present no flags are defined;
10668 * pass 0 for this parameter.
Christopher Tate407b4e92010-11-30 17:14:08 -080010669 * @return {@code true} if the drag operation was initiated successfully; {@code false} if
10670 * an error prevented the drag from taking place.
Christopher Tatea53146c2010-09-07 11:57:52 -070010671 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010672 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010673 Object myLocalState, int flags) {
Christopher Tate2c095f32010-10-04 14:13:40 -070010674 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010675 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
Christopher Tatea53146c2010-09-07 11:57:52 -070010676 }
10677 boolean okay = false;
10678
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010679 Point shadowSize = new Point();
10680 Point shadowTouchPoint = new Point();
10681 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
Christopher Tate2c095f32010-10-04 14:13:40 -070010682
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010683 if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
10684 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
10685 throw new IllegalStateException("Drag shadow dimensions must not be negative");
Christopher Tate2c095f32010-10-04 14:13:40 -070010686 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010687
Chris Tatea32dcf72010-10-14 12:13:50 -070010688 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010689 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
10690 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
Chris Tatea32dcf72010-10-14 12:13:50 -070010691 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010692 Surface surface = new Surface();
10693 try {
10694 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010695 flags, shadowSize.x, shadowSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070010696 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070010697 + " surface=" + surface);
10698 if (token != null) {
10699 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070010700 try {
Chris Tate6b391282010-10-14 15:48:59 -070010701 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010702 shadowBuilder.onDrawShadow(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070010703 } finally {
10704 surface.unlockCanvasAndPost(canvas);
10705 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010706
Christopher Tate407b4e92010-11-30 17:14:08 -080010707 final ViewRoot root = getViewRoot();
10708
10709 // Cache the local state object for delivery with DragEvents
10710 root.setLocalDragState(myLocalState);
10711
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010712 // repurpose 'shadowSize' for the last touch point
10713 root.getLastTouchPoint(shadowSize);
Christopher Tate2c095f32010-10-04 14:13:40 -070010714
Christopher Tatea53146c2010-09-07 11:57:52 -070010715 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010716 shadowSize.x, shadowSize.y,
10717 shadowTouchPoint.x, shadowTouchPoint.y, data);
Christopher Tate2c095f32010-10-04 14:13:40 -070010718 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070010719 }
10720 } catch (Exception e) {
10721 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
10722 surface.destroy();
10723 }
10724
10725 return okay;
10726 }
10727
Christopher Tatea53146c2010-09-07 11:57:52 -070010728 /**
10729 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
10730 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
10731 *
10732 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
10733 * being dragged. onDragEvent() should return 'true' if the view can handle
10734 * a drop of that content. A view that returns 'false' here will receive no
10735 * further calls to onDragEvent() about the drag/drop operation.
10736 *
10737 * For DRAG_ENTERED, event.getClipDescription() describes the content being
10738 * dragged. This will be the same content description passed in the
10739 * DRAG_STARTED_EVENT invocation.
10740 *
10741 * For DRAG_EXITED, event.getClipDescription() describes the content being
10742 * dragged. This will be the same content description passed in the
10743 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
10744 * drag-acceptance visual state.
10745 *
10746 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10747 * coordinates of the current drag point. The view must return 'true' if it
10748 * can accept a drop of the current drag content, false otherwise.
10749 *
10750 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10751 * within the view; also, event.getClipData() returns the full data payload
10752 * being dropped. The view should return 'true' if it consumed the dropped
10753 * content, 'false' if it did not.
10754 *
10755 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
10756 * to its normal visual state.
10757 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010758 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070010759 return false;
10760 }
10761
10762 /**
10763 * Views typically don't need to override dispatchDragEvent(); it just calls
Chris Tate32affef2010-10-18 15:29:21 -070010764 * onDragEvent(event) and passes the result up appropriately.
Christopher Tatea53146c2010-09-07 11:57:52 -070010765 */
10766 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070010767 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10768 && mOnDragListener.onDrag(this, event)) {
10769 return true;
10770 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010771 return onDragEvent(event);
10772 }
10773
10774 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070010775 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
10776 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070010777 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070010778 */
10779 public void onCloseSystemDialogs(String reason) {
10780 }
10781
10782 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010783 * Given a Drawable whose bounds have been set to draw into this view,
10784 * update a Region being computed for {@link #gatherTransparentRegion} so
10785 * that any non-transparent parts of the Drawable are removed from the
10786 * given transparent region.
10787 *
10788 * @param dr The Drawable whose transparency is to be applied to the region.
10789 * @param region A Region holding the current transparency information,
10790 * where any parts of the region that are set are considered to be
10791 * transparent. On return, this region will be modified to have the
10792 * transparency information reduced by the corresponding parts of the
10793 * Drawable that are not transparent.
10794 * {@hide}
10795 */
10796 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
10797 if (DBG) {
10798 Log.i("View", "Getting transparent region for: " + this);
10799 }
10800 final Region r = dr.getTransparentRegion();
10801 final Rect db = dr.getBounds();
10802 final AttachInfo attachInfo = mAttachInfo;
10803 if (r != null && attachInfo != null) {
10804 final int w = getRight()-getLeft();
10805 final int h = getBottom()-getTop();
10806 if (db.left > 0) {
10807 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
10808 r.op(0, 0, db.left, h, Region.Op.UNION);
10809 }
10810 if (db.right < w) {
10811 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
10812 r.op(db.right, 0, w, h, Region.Op.UNION);
10813 }
10814 if (db.top > 0) {
10815 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
10816 r.op(0, 0, w, db.top, Region.Op.UNION);
10817 }
10818 if (db.bottom < h) {
10819 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
10820 r.op(0, db.bottom, w, h, Region.Op.UNION);
10821 }
10822 final int[] location = attachInfo.mTransparentLocation;
10823 getLocationInWindow(location);
10824 r.translate(location[0], location[1]);
10825 region.op(r, Region.Op.INTERSECT);
10826 } else {
10827 region.op(db, Region.Op.DIFFERENCE);
10828 }
10829 }
10830
Adam Powelle14579b2009-12-16 18:39:52 -080010831 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010832 mHasPerformedLongPress = false;
10833
10834 if (mPendingCheckForLongPress == null) {
10835 mPendingCheckForLongPress = new CheckForLongPress();
10836 }
10837 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080010838 postDelayed(mPendingCheckForLongPress,
10839 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010840 }
10841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010842 /**
10843 * Inflate a view from an XML resource. This convenience method wraps the {@link
10844 * LayoutInflater} class, which provides a full range of options for view inflation.
10845 *
10846 * @param context The Context object for your activity or application.
10847 * @param resource The resource ID to inflate
10848 * @param root A view group that will be the parent. Used to properly inflate the
10849 * layout_* parameters.
10850 * @see LayoutInflater
10851 */
10852 public static View inflate(Context context, int resource, ViewGroup root) {
10853 LayoutInflater factory = LayoutInflater.from(context);
10854 return factory.inflate(resource, root);
10855 }
Romain Guy33e72ae2010-07-17 12:40:29 -070010856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010857 /**
Adam Powell637d3372010-08-25 14:37:03 -070010858 * Scroll the view with standard behavior for scrolling beyond the normal
10859 * content boundaries. Views that call this method should override
10860 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
10861 * results of an over-scroll operation.
10862 *
10863 * Views can use this method to handle any touch or fling-based scrolling.
10864 *
10865 * @param deltaX Change in X in pixels
10866 * @param deltaY Change in Y in pixels
10867 * @param scrollX Current X scroll value in pixels before applying deltaX
10868 * @param scrollY Current Y scroll value in pixels before applying deltaY
10869 * @param scrollRangeX Maximum content scroll range along the X axis
10870 * @param scrollRangeY Maximum content scroll range along the Y axis
10871 * @param maxOverScrollX Number of pixels to overscroll by in either direction
10872 * along the X axis.
10873 * @param maxOverScrollY Number of pixels to overscroll by in either direction
10874 * along the Y axis.
10875 * @param isTouchEvent true if this scroll operation is the result of a touch event.
10876 * @return true if scrolling was clamped to an over-scroll boundary along either
10877 * axis, false otherwise.
10878 */
10879 protected boolean overScrollBy(int deltaX, int deltaY,
10880 int scrollX, int scrollY,
10881 int scrollRangeX, int scrollRangeY,
10882 int maxOverScrollX, int maxOverScrollY,
10883 boolean isTouchEvent) {
10884 final int overScrollMode = mOverScrollMode;
10885 final boolean canScrollHorizontal =
10886 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
10887 final boolean canScrollVertical =
10888 computeVerticalScrollRange() > computeVerticalScrollExtent();
10889 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
10890 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
10891 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
10892 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
10893
10894 int newScrollX = scrollX + deltaX;
10895 if (!overScrollHorizontal) {
10896 maxOverScrollX = 0;
10897 }
10898
10899 int newScrollY = scrollY + deltaY;
10900 if (!overScrollVertical) {
10901 maxOverScrollY = 0;
10902 }
10903
10904 // Clamp values if at the limits and record
10905 final int left = -maxOverScrollX;
10906 final int right = maxOverScrollX + scrollRangeX;
10907 final int top = -maxOverScrollY;
10908 final int bottom = maxOverScrollY + scrollRangeY;
10909
10910 boolean clampedX = false;
10911 if (newScrollX > right) {
10912 newScrollX = right;
10913 clampedX = true;
10914 } else if (newScrollX < left) {
10915 newScrollX = left;
10916 clampedX = true;
10917 }
10918
10919 boolean clampedY = false;
10920 if (newScrollY > bottom) {
10921 newScrollY = bottom;
10922 clampedY = true;
10923 } else if (newScrollY < top) {
10924 newScrollY = top;
10925 clampedY = true;
10926 }
10927
10928 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
10929
10930 return clampedX || clampedY;
10931 }
10932
10933 /**
10934 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
10935 * respond to the results of an over-scroll operation.
10936 *
10937 * @param scrollX New X scroll value in pixels
10938 * @param scrollY New Y scroll value in pixels
10939 * @param clampedX True if scrollX was clamped to an over-scroll boundary
10940 * @param clampedY True if scrollY was clamped to an over-scroll boundary
10941 */
10942 protected void onOverScrolled(int scrollX, int scrollY,
10943 boolean clampedX, boolean clampedY) {
10944 // Intentionally empty.
10945 }
10946
10947 /**
10948 * Returns the over-scroll mode for this view. The result will be
10949 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10950 * (allow over-scrolling only if the view content is larger than the container),
10951 * or {@link #OVER_SCROLL_NEVER}.
10952 *
10953 * @return This view's over-scroll mode.
10954 */
10955 public int getOverScrollMode() {
10956 return mOverScrollMode;
10957 }
10958
10959 /**
10960 * Set the over-scroll mode for this view. Valid over-scroll modes are
10961 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10962 * (allow over-scrolling only if the view content is larger than the container),
10963 * or {@link #OVER_SCROLL_NEVER}.
10964 *
10965 * Setting the over-scroll mode of a view will have an effect only if the
10966 * view is capable of scrolling.
10967 *
10968 * @param overScrollMode The new over-scroll mode for this view.
10969 */
10970 public void setOverScrollMode(int overScrollMode) {
10971 if (overScrollMode != OVER_SCROLL_ALWAYS &&
10972 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
10973 overScrollMode != OVER_SCROLL_NEVER) {
10974 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
10975 }
10976 mOverScrollMode = overScrollMode;
10977 }
10978
10979 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010980 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
10981 * Each MeasureSpec represents a requirement for either the width or the height.
10982 * A MeasureSpec is comprised of a size and a mode. There are three possible
10983 * modes:
10984 * <dl>
10985 * <dt>UNSPECIFIED</dt>
10986 * <dd>
10987 * The parent has not imposed any constraint on the child. It can be whatever size
10988 * it wants.
10989 * </dd>
10990 *
10991 * <dt>EXACTLY</dt>
10992 * <dd>
10993 * The parent has determined an exact size for the child. The child is going to be
10994 * given those bounds regardless of how big it wants to be.
10995 * </dd>
10996 *
10997 * <dt>AT_MOST</dt>
10998 * <dd>
10999 * The child can be as large as it wants up to the specified size.
11000 * </dd>
11001 * </dl>
11002 *
11003 * MeasureSpecs are implemented as ints to reduce object allocation. This class
11004 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
11005 */
11006 public static class MeasureSpec {
11007 private static final int MODE_SHIFT = 30;
11008 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
11009
11010 /**
11011 * Measure specification mode: The parent has not imposed any constraint
11012 * on the child. It can be whatever size it wants.
11013 */
11014 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
11015
11016 /**
11017 * Measure specification mode: The parent has determined an exact size
11018 * for the child. The child is going to be given those bounds regardless
11019 * of how big it wants to be.
11020 */
11021 public static final int EXACTLY = 1 << MODE_SHIFT;
11022
11023 /**
11024 * Measure specification mode: The child can be as large as it wants up
11025 * to the specified size.
11026 */
11027 public static final int AT_MOST = 2 << MODE_SHIFT;
11028
11029 /**
11030 * Creates a measure specification based on the supplied size and mode.
11031 *
11032 * The mode must always be one of the following:
11033 * <ul>
11034 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
11035 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
11036 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
11037 * </ul>
11038 *
11039 * @param size the size of the measure specification
11040 * @param mode the mode of the measure specification
11041 * @return the measure specification based on size and mode
11042 */
11043 public static int makeMeasureSpec(int size, int mode) {
11044 return size + mode;
11045 }
11046
11047 /**
11048 * Extracts the mode from the supplied measure specification.
11049 *
11050 * @param measureSpec the measure specification to extract the mode from
11051 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
11052 * {@link android.view.View.MeasureSpec#AT_MOST} or
11053 * {@link android.view.View.MeasureSpec#EXACTLY}
11054 */
11055 public static int getMode(int measureSpec) {
11056 return (measureSpec & MODE_MASK);
11057 }
11058
11059 /**
11060 * Extracts the size from the supplied measure specification.
11061 *
11062 * @param measureSpec the measure specification to extract the size from
11063 * @return the size in pixels defined in the supplied measure specification
11064 */
11065 public static int getSize(int measureSpec) {
11066 return (measureSpec & ~MODE_MASK);
11067 }
11068
11069 /**
11070 * Returns a String representation of the specified measure
11071 * specification.
11072 *
11073 * @param measureSpec the measure specification to convert to a String
11074 * @return a String with the following format: "MeasureSpec: MODE SIZE"
11075 */
11076 public static String toString(int measureSpec) {
11077 int mode = getMode(measureSpec);
11078 int size = getSize(measureSpec);
11079
11080 StringBuilder sb = new StringBuilder("MeasureSpec: ");
11081
11082 if (mode == UNSPECIFIED)
11083 sb.append("UNSPECIFIED ");
11084 else if (mode == EXACTLY)
11085 sb.append("EXACTLY ");
11086 else if (mode == AT_MOST)
11087 sb.append("AT_MOST ");
11088 else
11089 sb.append(mode).append(" ");
11090
11091 sb.append(size);
11092 return sb.toString();
11093 }
11094 }
11095
11096 class CheckForLongPress implements Runnable {
11097
11098 private int mOriginalWindowAttachCount;
11099
11100 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011101 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 && mOriginalWindowAttachCount == mWindowAttachCount) {
11103 if (performLongClick()) {
11104 mHasPerformedLongPress = true;
11105 }
11106 }
11107 }
11108
11109 public void rememberWindowAttachCount() {
11110 mOriginalWindowAttachCount = mWindowAttachCount;
11111 }
11112 }
Adam Powelle14579b2009-12-16 18:39:52 -080011113
11114 private final class CheckForTap implements Runnable {
11115 public void run() {
11116 mPrivateFlags &= ~PREPRESSED;
11117 mPrivateFlags |= PRESSED;
11118 refreshDrawableState();
11119 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
11120 postCheckForLongClick(ViewConfiguration.getTapTimeout());
11121 }
11122 }
11123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011124
Adam Powella35d7682010-03-12 14:48:13 -080011125 private final class PerformClick implements Runnable {
11126 public void run() {
11127 performClick();
11128 }
11129 }
11130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011131 /**
11132 * Interface definition for a callback to be invoked when a key event is
11133 * dispatched to this view. The callback will be invoked before the key
11134 * event is given to the view.
11135 */
11136 public interface OnKeyListener {
11137 /**
11138 * Called when a key is dispatched to a view. This allows listeners to
11139 * get a chance to respond before the target view.
11140 *
11141 * @param v The view the key has been dispatched to.
11142 * @param keyCode The code for the physical key that was pressed
11143 * @param event The KeyEvent object containing full information about
11144 * the event.
11145 * @return True if the listener has consumed the event, false otherwise.
11146 */
11147 boolean onKey(View v, int keyCode, KeyEvent event);
11148 }
11149
11150 /**
11151 * Interface definition for a callback to be invoked when a touch event is
11152 * dispatched to this view. The callback will be invoked before the touch
11153 * event is given to the view.
11154 */
11155 public interface OnTouchListener {
11156 /**
11157 * Called when a touch event is dispatched to a view. This allows listeners to
11158 * get a chance to respond before the target view.
11159 *
11160 * @param v The view the touch event has been dispatched to.
11161 * @param event The MotionEvent object containing full information about
11162 * the event.
11163 * @return True if the listener has consumed the event, false otherwise.
11164 */
11165 boolean onTouch(View v, MotionEvent event);
11166 }
11167
11168 /**
11169 * Interface definition for a callback to be invoked when a view has been clicked and held.
11170 */
11171 public interface OnLongClickListener {
11172 /**
11173 * Called when a view has been clicked and held.
11174 *
11175 * @param v The view that was clicked and held.
11176 *
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -080011177 * @return true if the callback consumed the long click, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011178 */
11179 boolean onLongClick(View v);
11180 }
11181
11182 /**
Chris Tate32affef2010-10-18 15:29:21 -070011183 * Interface definition for a callback to be invoked when a drag is being dispatched
11184 * to this view. The callback will be invoked before the hosting view's own
11185 * onDrag(event) method. If the listener wants to fall back to the hosting view's
11186 * onDrag(event) behavior, it should return 'false' from this callback.
11187 */
11188 public interface OnDragListener {
11189 /**
11190 * Called when a drag event is dispatched to a view. This allows listeners
11191 * to get a chance to override base View behavior.
11192 *
11193 * @param v The view the drag has been dispatched to.
11194 * @param event The DragEvent object containing full information
11195 * about the event.
11196 * @return true if the listener consumed the DragEvent, false in order to fall
11197 * back to the view's default handling.
11198 */
11199 boolean onDrag(View v, DragEvent event);
11200 }
11201
11202 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011203 * Interface definition for a callback to be invoked when the focus state of
11204 * a view changed.
11205 */
11206 public interface OnFocusChangeListener {
11207 /**
11208 * Called when the focus state of a view has changed.
11209 *
11210 * @param v The view whose state has changed.
11211 * @param hasFocus The new focus state of v.
11212 */
11213 void onFocusChange(View v, boolean hasFocus);
11214 }
11215
11216 /**
11217 * Interface definition for a callback to be invoked when a view is clicked.
11218 */
11219 public interface OnClickListener {
11220 /**
11221 * Called when a view has been clicked.
11222 *
11223 * @param v The view that was clicked.
11224 */
11225 void onClick(View v);
11226 }
11227
11228 /**
11229 * Interface definition for a callback to be invoked when the context menu
11230 * for this view is being built.
11231 */
11232 public interface OnCreateContextMenuListener {
11233 /**
11234 * Called when the context menu for this view is being built. It is not
11235 * safe to hold onto the menu after this method returns.
11236 *
11237 * @param menu The context menu that is being built
11238 * @param v The view for which the context menu is being built
11239 * @param menuInfo Extra information about the item for which the
11240 * context menu should be shown. This information will vary
11241 * depending on the class of v.
11242 */
11243 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
11244 }
11245
11246 private final class UnsetPressedState implements Runnable {
11247 public void run() {
11248 setPressed(false);
11249 }
11250 }
11251
11252 /**
11253 * Base class for derived classes that want to save and restore their own
11254 * state in {@link android.view.View#onSaveInstanceState()}.
11255 */
11256 public static class BaseSavedState extends AbsSavedState {
11257 /**
11258 * Constructor used when reading from a parcel. Reads the state of the superclass.
11259 *
11260 * @param source
11261 */
11262 public BaseSavedState(Parcel source) {
11263 super(source);
11264 }
11265
11266 /**
11267 * Constructor called by derived classes when creating their SavedState objects
11268 *
11269 * @param superState The state of the superclass of this view
11270 */
11271 public BaseSavedState(Parcelable superState) {
11272 super(superState);
11273 }
11274
11275 public static final Parcelable.Creator<BaseSavedState> CREATOR =
11276 new Parcelable.Creator<BaseSavedState>() {
11277 public BaseSavedState createFromParcel(Parcel in) {
11278 return new BaseSavedState(in);
11279 }
11280
11281 public BaseSavedState[] newArray(int size) {
11282 return new BaseSavedState[size];
11283 }
11284 };
11285 }
11286
11287 /**
11288 * A set of information given to a view when it is attached to its parent
11289 * window.
11290 */
11291 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011292 interface Callbacks {
11293 void playSoundEffect(int effectId);
11294 boolean performHapticFeedback(int effectId, boolean always);
11295 }
11296
11297 /**
11298 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11299 * to a Handler. This class contains the target (View) to invalidate and
11300 * the coordinates of the dirty rectangle.
11301 *
11302 * For performance purposes, this class also implements a pool of up to
11303 * POOL_LIMIT objects that get reused. This reduces memory allocations
11304 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011305 */
Romain Guyd928d682009-03-31 17:52:16 -070011306 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011307 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070011308 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11309 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070011310 public InvalidateInfo newInstance() {
11311 return new InvalidateInfo();
11312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313
Romain Guyd928d682009-03-31 17:52:16 -070011314 public void onAcquired(InvalidateInfo element) {
11315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011316
Romain Guyd928d682009-03-31 17:52:16 -070011317 public void onReleased(InvalidateInfo element) {
11318 }
11319 }, POOL_LIMIT)
11320 );
11321
11322 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011323
11324 View target;
11325
11326 int left;
11327 int top;
11328 int right;
11329 int bottom;
11330
Romain Guyd928d682009-03-31 17:52:16 -070011331 public void setNextPoolable(InvalidateInfo element) {
11332 mNext = element;
11333 }
11334
11335 public InvalidateInfo getNextPoolable() {
11336 return mNext;
11337 }
11338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011339 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070011340 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011341 }
11342
11343 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070011344 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011345 }
11346 }
11347
11348 final IWindowSession mSession;
11349
11350 final IWindow mWindow;
11351
11352 final IBinder mWindowToken;
11353
11354 final Callbacks mRootCallbacks;
11355
11356 /**
11357 * The top view of the hierarchy.
11358 */
11359 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070011360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011361 IBinder mPanelParentWindowToken;
11362 Surface mSurface;
11363
Romain Guyb051e892010-09-28 19:09:36 -070011364 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080011365 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070011366 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070011367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011368 /**
Romain Guy8506ab42009-06-11 17:35:47 -070011369 * Scale factor used by the compatibility mode
11370 */
11371 float mApplicationScale;
11372
11373 /**
11374 * Indicates whether the application is in compatibility mode
11375 */
11376 boolean mScalingRequired;
11377
11378 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 * Left position of this view's window
11380 */
11381 int mWindowLeft;
11382
11383 /**
11384 * Top position of this view's window
11385 */
11386 int mWindowTop;
11387
11388 /**
Adam Powell26153a32010-11-08 15:22:27 -080011389 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070011390 */
Adam Powell26153a32010-11-08 15:22:27 -080011391 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070011392
11393 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011394 * For windows that are full-screen but using insets to layout inside
11395 * of the screen decorations, these are the current insets for the
11396 * content of the window.
11397 */
11398 final Rect mContentInsets = new Rect();
11399
11400 /**
11401 * For windows that are full-screen but using insets to layout inside
11402 * of the screen decorations, these are the current insets for the
11403 * actual visible parts of the window.
11404 */
11405 final Rect mVisibleInsets = new Rect();
11406
11407 /**
11408 * The internal insets given by this window. This value is
11409 * supplied by the client (through
11410 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11411 * be given to the window manager when changed to be used in laying
11412 * out windows behind it.
11413 */
11414 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11415 = new ViewTreeObserver.InternalInsetsInfo();
11416
11417 /**
11418 * All views in the window's hierarchy that serve as scroll containers,
11419 * used to determine if the window can be resized or must be panned
11420 * to adjust for a soft input area.
11421 */
11422 final ArrayList<View> mScrollContainers = new ArrayList<View>();
11423
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070011424 final KeyEvent.DispatcherState mKeyDispatchState
11425 = new KeyEvent.DispatcherState();
11426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011427 /**
11428 * Indicates whether the view's window currently has the focus.
11429 */
11430 boolean mHasWindowFocus;
11431
11432 /**
11433 * The current visibility of the window.
11434 */
11435 int mWindowVisibility;
11436
11437 /**
11438 * Indicates the time at which drawing started to occur.
11439 */
11440 long mDrawingTime;
11441
11442 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070011443 * Indicates whether or not ignoring the DIRTY_MASK flags.
11444 */
11445 boolean mIgnoreDirtyState;
11446
11447 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011448 * Indicates whether the view's window is currently in touch mode.
11449 */
11450 boolean mInTouchMode;
11451
11452 /**
11453 * Indicates that ViewRoot should trigger a global layout change
11454 * the next time it performs a traversal
11455 */
11456 boolean mRecomputeGlobalAttributes;
11457
11458 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011459 * Set during a traveral if any views want to keep the screen on.
11460 */
11461 boolean mKeepScreenOn;
11462
11463 /**
11464 * Set if the visibility of any views has changed.
11465 */
11466 boolean mViewVisibilityChanged;
11467
11468 /**
11469 * Set to true if a view has been scrolled.
11470 */
11471 boolean mViewScrollChanged;
11472
11473 /**
11474 * Global to the view hierarchy used as a temporary for dealing with
11475 * x/y points in the transparent region computations.
11476 */
11477 final int[] mTransparentLocation = new int[2];
11478
11479 /**
11480 * Global to the view hierarchy used as a temporary for dealing with
11481 * x/y points in the ViewGroup.invalidateChild implementation.
11482 */
11483 final int[] mInvalidateChildLocation = new int[2];
11484
Chet Haasec3aa3612010-06-17 08:50:37 -070011485
11486 /**
11487 * Global to the view hierarchy used as a temporary for dealing with
11488 * x/y location when view is transformed.
11489 */
11490 final float[] mTmpTransformLocation = new float[2];
11491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011492 /**
11493 * The view tree observer used to dispatch global events like
11494 * layout, pre-draw, touch mode change, etc.
11495 */
11496 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11497
11498 /**
11499 * A Canvas used by the view hierarchy to perform bitmap caching.
11500 */
11501 Canvas mCanvas;
11502
11503 /**
11504 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11505 * handler can be used to pump events in the UI events queue.
11506 */
11507 final Handler mHandler;
11508
11509 /**
11510 * Identifier for messages requesting the view to be invalidated.
11511 * Such messages should be sent to {@link #mHandler}.
11512 */
11513 static final int INVALIDATE_MSG = 0x1;
11514
11515 /**
11516 * Identifier for messages requesting the view to invalidate a region.
11517 * Such messages should be sent to {@link #mHandler}.
11518 */
11519 static final int INVALIDATE_RECT_MSG = 0x2;
11520
11521 /**
11522 * Temporary for use in computing invalidate rectangles while
11523 * calling up the hierarchy.
11524 */
11525 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070011526
11527 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070011528 * Temporary for use in computing hit areas with transformed views
11529 */
11530 final RectF mTmpTransformRect = new RectF();
11531
11532 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070011533 * Temporary list for use in collecting focusable descendents of a view.
11534 */
11535 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011537 /**
11538 * Creates a new set of attachment information with the specified
11539 * events handler and thread.
11540 *
11541 * @param handler the events handler the view must use
11542 */
11543 AttachInfo(IWindowSession session, IWindow window,
11544 Handler handler, Callbacks effectPlayer) {
11545 mSession = session;
11546 mWindow = window;
11547 mWindowToken = window.asBinder();
11548 mHandler = handler;
11549 mRootCallbacks = effectPlayer;
11550 }
11551 }
11552
11553 /**
11554 * <p>ScrollabilityCache holds various fields used by a View when scrolling
11555 * is supported. This avoids keeping too many unused fields in most
11556 * instances of View.</p>
11557 */
Mike Cleronf116bf82009-09-27 19:14:12 -070011558 private static class ScrollabilityCache implements Runnable {
11559
11560 /**
11561 * Scrollbars are not visible
11562 */
11563 public static final int OFF = 0;
11564
11565 /**
11566 * Scrollbars are visible
11567 */
11568 public static final int ON = 1;
11569
11570 /**
11571 * Scrollbars are fading away
11572 */
11573 public static final int FADING = 2;
11574
11575 public boolean fadeScrollBars;
11576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011577 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070011578 public int scrollBarDefaultDelayBeforeFade;
11579 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011580
11581 public int scrollBarSize;
11582 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070011583 public float[] interpolatorValues;
11584 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011585
11586 public final Paint paint;
11587 public final Matrix matrix;
11588 public Shader shader;
11589
Mike Cleronf116bf82009-09-27 19:14:12 -070011590 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11591
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011592 private static final float[] OPAQUE = { 255 };
11593 private static final float[] TRANSPARENT = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070011594
11595 /**
11596 * When fading should start. This time moves into the future every time
11597 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11598 */
11599 public long fadeStartTime;
11600
11601
11602 /**
11603 * The current state of the scrollbars: ON, OFF, or FADING
11604 */
11605 public int state = OFF;
11606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011607 private int mLastColor;
11608
Mike Cleronf116bf82009-09-27 19:14:12 -070011609 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011610 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11611 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070011612 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11613 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011614
11615 paint = new Paint();
11616 matrix = new Matrix();
11617 // use use a height of 1, and then wack the matrix each time we
11618 // actually use it.
11619 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011621 paint.setShader(shader);
11622 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070011623 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011624 }
Romain Guy8506ab42009-06-11 17:35:47 -070011625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011626 public void setFadeColor(int color) {
11627 if (color != 0 && color != mLastColor) {
11628 mLastColor = color;
11629 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070011630
Romain Guye55e1a72009-08-27 10:42:26 -070011631 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11632 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011634 paint.setShader(shader);
11635 // Restore the default transfer mode (src_over)
11636 paint.setXfermode(null);
11637 }
11638 }
Mike Cleronf116bf82009-09-27 19:14:12 -070011639
11640 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070011641 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070011642 if (now >= fadeStartTime) {
11643
11644 // the animation fades the scrollbars out by changing
11645 // the opacity (alpha) from fully opaque to fully
11646 // transparent
11647 int nextFrame = (int) now;
11648 int framesCount = 0;
11649
11650 Interpolator interpolator = scrollBarInterpolator;
11651
11652 // Start opaque
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011653 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
Mike Cleronf116bf82009-09-27 19:14:12 -070011654
11655 // End transparent
11656 nextFrame += scrollBarFadeDuration;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011657 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
Mike Cleronf116bf82009-09-27 19:14:12 -070011658
11659 state = FADING;
11660
11661 // Kick off the fade animation
11662 host.invalidate();
11663 }
11664 }
11665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011666 }
11667}