blob: 270ea7689e1a1ff5734e588a7fb1ed84d4cfae31 [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
Romain Guyd6cd5722011-01-17 14:42:41 -08007908 if (layerType == mLayerType) {
7909 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
7910 mLayerPaint = paint == null ? new Paint() : paint;
7911 if (mParent instanceof ViewGroup) {
7912 ((ViewGroup) mParent).invalidate();
7913 }
7914 invalidate();
7915 }
7916 return;
7917 }
Romain Guy171c5922011-01-06 10:04:23 -08007918
7919 // Destroy any previous software drawing cache if needed
Romain Guy6c319ca2011-01-11 14:29:25 -08007920 switch (mLayerType) {
7921 case LAYER_TYPE_SOFTWARE:
7922 if (mDrawingCache != null) {
7923 mDrawingCache.recycle();
7924 mDrawingCache = null;
7925 }
7926
7927 if (mUnscaledDrawingCache != null) {
7928 mUnscaledDrawingCache.recycle();
7929 mUnscaledDrawingCache = null;
7930 }
7931 break;
7932 case LAYER_TYPE_HARDWARE:
7933 if (mHardwareLayer != null) {
7934 mHardwareLayer.destroy();
7935 mHardwareLayer = null;
7936 }
7937 break;
7938 default:
7939 break;
Romain Guy171c5922011-01-06 10:04:23 -08007940 }
7941
7942 mLayerType = layerType;
Romain Guyd6cd5722011-01-17 14:42:41 -08007943 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : (paint == null ? new Paint() : paint);
Romain Guy171c5922011-01-06 10:04:23 -08007944
Romain Guyd6cd5722011-01-17 14:42:41 -08007945 if (mParent instanceof ViewGroup) {
7946 ((ViewGroup) mParent).invalidate();
7947 }
Romain Guy171c5922011-01-06 10:04:23 -08007948 invalidate();
7949 }
7950
7951 /**
7952 * Indicates what type of layer is currently associated with this view. By default
7953 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
7954 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
7955 * for more information on the different types of layers.
7956 *
7957 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
7958 * {@link #LAYER_TYPE_HARDWARE}
7959 *
7960 * @see #setLayerType(int, android.graphics.Paint)
7961 * @see #LAYER_TYPE_NONE
7962 * @see #LAYER_TYPE_SOFTWARE
7963 * @see #LAYER_TYPE_HARDWARE
7964 */
7965 public int getLayerType() {
7966 return mLayerType;
7967 }
Romain Guy6c319ca2011-01-11 14:29:25 -08007968
7969 /**
7970 * <p>Returns a hardware layer that can be used to draw this view again
7971 * without executing its draw method.</p>
7972 *
7973 * @return A HardwareLayer ready to render, or null if an error occurred.
7974 */
7975 HardwareLayer getHardwareLayer(Canvas currentCanvas) {
7976 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
7977 return null;
7978 }
7979
7980 final int width = mRight - mLeft;
7981 final int height = mBottom - mTop;
7982
7983 if (width == 0 || height == 0) {
7984 return null;
7985 }
7986
7987 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
7988 if (mHardwareLayer == null) {
7989 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
7990 width, height, isOpaque());
7991 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
7992 mHardwareLayer.resize(width, height);
7993 }
7994
7995 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
7996 try {
7997 canvas.setViewport(width, height);
7998 canvas.onPreDraw();
7999
8000 computeScroll();
8001 canvas.translate(-mScrollX, -mScrollY);
8002
8003 final int restoreCount = canvas.save();
8004
8005 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8006
8007 // Fast path for layouts with no backgrounds
8008 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8009 mPrivateFlags &= ~DIRTY_MASK;
8010 dispatchDraw(canvas);
8011 } else {
8012 draw(canvas);
8013 }
8014
8015 canvas.restoreToCount(restoreCount);
8016 } finally {
8017 canvas.onPostDraw();
8018 mHardwareLayer.end(currentCanvas);
8019 }
8020 }
8021
8022 return mHardwareLayer;
8023 }
Romain Guy171c5922011-01-06 10:04:23 -08008024
8025 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
8027 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
8028 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
8029 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
8030 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
8031 * null.</p>
Romain Guy171c5922011-01-06 10:04:23 -08008032 *
8033 * <p>Enabling the drawing cache is similar to
8034 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
8035 * acceleration is turned off. When hardware acceleration is turned on enabling the
8036 * drawing cache has either no effect or the cache used at drawing time is not a bitmap.
8037 * 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 -08008038 *
8039 * @param enabled true to enable the drawing cache, false otherwise
8040 *
8041 * @see #isDrawingCacheEnabled()
8042 * @see #getDrawingCache()
8043 * @see #buildDrawingCache()
Romain Guy171c5922011-01-06 10:04:23 -08008044 * @see #setLayerType(int, android.graphics.Paint)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008045 */
8046 public void setDrawingCacheEnabled(boolean enabled) {
8047 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
8048 }
8049
8050 /**
8051 * <p>Indicates whether the drawing cache is enabled for this view.</p>
8052 *
8053 * @return true if the drawing cache is enabled
8054 *
8055 * @see #setDrawingCacheEnabled(boolean)
8056 * @see #getDrawingCache()
8057 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07008058 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008059 public boolean isDrawingCacheEnabled() {
8060 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
8061 }
8062
8063 /**
Romain Guyb051e892010-09-28 19:09:36 -07008064 * <p>Returns a display list that can be used to draw this view again
8065 * without executing its draw method.</p>
8066 *
8067 * @return A DisplayList ready to replay, or null if caching is not enabled.
8068 */
8069 DisplayList getDisplayList() {
8070 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8071 return null;
8072 }
Romain Guyb051e892010-09-28 19:09:36 -07008073 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8074 return null;
8075 }
8076
8077 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
Chet Haase9e90a992011-01-04 16:23:21 -08008078 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
8079 mDisplayList == null || !mDisplayList.isValid())) {
Romain Guyb051e892010-09-28 19:09:36 -07008080
Chet Haase9e90a992011-01-04 16:23:21 -08008081 if (mDisplayList == null) {
8082 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
8083 }
Romain Guyb051e892010-09-28 19:09:36 -07008084
8085 final HardwareCanvas canvas = mDisplayList.start();
8086 try {
8087 int width = mRight - mLeft;
8088 int height = mBottom - mTop;
8089
8090 canvas.setViewport(width, height);
8091 canvas.onPreDraw();
8092
8093 final int restoreCount = canvas.save();
8094
Romain Guy2fe9a8f2010-10-04 20:17:01 -07008095 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07008096
8097 // Fast path for layouts with no backgrounds
8098 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8099 mPrivateFlags &= ~DIRTY_MASK;
8100 dispatchDraw(canvas);
8101 } else {
8102 draw(canvas);
8103 }
8104
8105 canvas.restoreToCount(restoreCount);
8106 } finally {
8107 canvas.onPostDraw();
8108
8109 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07008110 }
8111 }
8112
8113 return mDisplayList;
8114 }
8115
8116 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008117 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
8118 *
8119 * @return A non-scaled bitmap representing this view or null if cache is disabled.
8120 *
8121 * @see #getDrawingCache(boolean)
8122 */
8123 public Bitmap getDrawingCache() {
8124 return getDrawingCache(false);
8125 }
8126
8127 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
8129 * is null when caching is disabled. If caching is enabled and the cache is not ready,
8130 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
8131 * draw from the cache when the cache is enabled. To benefit from the cache, you must
8132 * request the drawing cache by calling this method and draw it on screen if the
8133 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008134 *
8135 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8136 * this method will create a bitmap of the same size as this view. Because this bitmap
8137 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8138 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8139 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8140 * size than the view. This implies that your application must be able to handle this
8141 * size.</p>
8142 *
8143 * @param autoScale Indicates whether the generated bitmap should be scaled based on
8144 * the current density of the screen when the application is in compatibility
8145 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008146 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008147 * @return A bitmap representing this view or null if cache is disabled.
8148 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 * @see #setDrawingCacheEnabled(boolean)
8150 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07008151 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008152 * @see #destroyDrawingCache()
8153 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008154 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008155 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8156 return null;
8157 }
8158 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008159 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 }
Romain Guy02890fd2010-08-06 17:58:44 -07008161 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 }
8163
8164 /**
8165 * <p>Frees the resources used by the drawing cache. If you call
8166 * {@link #buildDrawingCache()} manually without calling
8167 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8168 * should cleanup the cache with this method afterwards.</p>
8169 *
8170 * @see #setDrawingCacheEnabled(boolean)
8171 * @see #buildDrawingCache()
8172 * @see #getDrawingCache()
8173 */
8174 public void destroyDrawingCache() {
8175 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008176 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 mDrawingCache = null;
8178 }
Romain Guyfbd8f692009-06-26 14:51:58 -07008179 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008180 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07008181 mUnscaledDrawingCache = null;
8182 }
Romain Guyb051e892010-09-28 19:09:36 -07008183 if (mDisplayList != null) {
Chet Haase9e90a992011-01-04 16:23:21 -08008184 mDisplayList.invalidate();
Romain Guyb051e892010-09-28 19:09:36 -07008185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008186 }
8187
8188 /**
8189 * Setting a solid background color for the drawing cache's bitmaps will improve
8190 * perfromance and memory usage. Note, though that this should only be used if this
8191 * view will always be drawn on top of a solid color.
8192 *
8193 * @param color The background color to use for the drawing cache's bitmap
8194 *
8195 * @see #setDrawingCacheEnabled(boolean)
8196 * @see #buildDrawingCache()
8197 * @see #getDrawingCache()
8198 */
8199 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08008200 if (color != mDrawingCacheBackgroundColor) {
8201 mDrawingCacheBackgroundColor = color;
8202 mPrivateFlags &= ~DRAWING_CACHE_VALID;
8203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008204 }
8205
8206 /**
8207 * @see #setDrawingCacheBackgroundColor(int)
8208 *
8209 * @return The background color to used for the drawing cache's bitmap
8210 */
8211 public int getDrawingCacheBackgroundColor() {
8212 return mDrawingCacheBackgroundColor;
8213 }
8214
8215 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008216 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
8217 *
8218 * @see #buildDrawingCache(boolean)
8219 */
8220 public void buildDrawingCache() {
8221 buildDrawingCache(false);
8222 }
8223
8224 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
8226 *
8227 * <p>If you call {@link #buildDrawingCache()} manually without calling
8228 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8229 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008230 *
8231 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8232 * this method will create a bitmap of the same size as this view. Because this bitmap
8233 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8234 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8235 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8236 * size than the view. This implies that your application must be able to handle this
8237 * size.</p>
Romain Guy0d9275e2010-10-26 14:22:30 -07008238 *
8239 * <p>You should avoid calling this method when hardware acceleration is enabled. If
8240 * you do not need the drawing cache bitmap, calling this method will increase memory
8241 * usage and cause the view to be rendered in software once, thus negatively impacting
8242 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008243 *
8244 * @see #getDrawingCache()
8245 * @see #destroyDrawingCache()
8246 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008247 public void buildDrawingCache(boolean autoScale) {
8248 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07008249 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008250
8251 if (ViewDebug.TRACE_HIERARCHY) {
8252 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
8253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008254
Romain Guy8506ab42009-06-11 17:35:47 -07008255 int width = mRight - mLeft;
8256 int height = mBottom - mTop;
8257
8258 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07008259 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07008260
Romain Guye1123222009-06-29 14:24:56 -07008261 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008262 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
8263 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07008264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008265
8266 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07008267 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08008268 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008269
8270 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07008271 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08008272 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008273 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
8274 destroyDrawingCache();
8275 return;
8276 }
8277
8278 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07008279 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280
8281 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 Bitmap.Config quality;
8283 if (!opaque) {
8284 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
8285 case DRAWING_CACHE_QUALITY_AUTO:
8286 quality = Bitmap.Config.ARGB_8888;
8287 break;
8288 case DRAWING_CACHE_QUALITY_LOW:
8289 quality = Bitmap.Config.ARGB_4444;
8290 break;
8291 case DRAWING_CACHE_QUALITY_HIGH:
8292 quality = Bitmap.Config.ARGB_8888;
8293 break;
8294 default:
8295 quality = Bitmap.Config.ARGB_8888;
8296 break;
8297 }
8298 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07008299 // Optimization for translucent windows
8300 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08008301 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 }
8303
8304 // Try to cleanup memory
8305 if (bitmap != null) bitmap.recycle();
8306
8307 try {
8308 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07008309 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07008310 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07008311 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008312 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07008313 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008314 }
Adam Powell26153a32010-11-08 15:22:27 -08008315 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008316 } catch (OutOfMemoryError e) {
8317 // If there is not enough memory to create the bitmap cache, just
8318 // ignore the issue as bitmap caches are not required to draw the
8319 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07008320 if (autoScale) {
8321 mDrawingCache = null;
8322 } else {
8323 mUnscaledDrawingCache = null;
8324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008325 return;
8326 }
8327
8328 clear = drawingCacheBackgroundColor != 0;
8329 }
8330
8331 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008332 if (attachInfo != null) {
8333 canvas = attachInfo.mCanvas;
8334 if (canvas == null) {
8335 canvas = new Canvas();
8336 }
8337 canvas.setBitmap(bitmap);
8338 // Temporarily clobber the cached Canvas in case one of our children
8339 // is also using a drawing cache. Without this, the children would
8340 // steal the canvas by attaching their own bitmap to it and bad, bad
8341 // thing would happen (invisible views, corrupted drawings, etc.)
8342 attachInfo.mCanvas = null;
8343 } else {
8344 // This case should hopefully never or seldom happen
8345 canvas = new Canvas(bitmap);
8346 }
8347
8348 if (clear) {
8349 bitmap.eraseColor(drawingCacheBackgroundColor);
8350 }
8351
8352 computeScroll();
8353 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07008354
Romain Guye1123222009-06-29 14:24:56 -07008355 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008356 final float scale = attachInfo.mApplicationScale;
8357 canvas.scale(scale, scale);
8358 }
8359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008360 canvas.translate(-mScrollX, -mScrollY);
8361
Romain Guy5bcdff42009-05-14 21:27:18 -07008362 mPrivateFlags |= DRAWN;
Romain Guy171c5922011-01-06 10:04:23 -08008363 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
8364 mLayerType != LAYER_TYPE_NONE) {
Romain Guy0d9275e2010-10-26 14:22:30 -07008365 mPrivateFlags |= DRAWING_CACHE_VALID;
8366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008367
8368 // Fast path for layouts with no backgrounds
8369 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8370 if (ViewDebug.TRACE_HIERARCHY) {
8371 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8372 }
Romain Guy5bcdff42009-05-14 21:27:18 -07008373 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008374 dispatchDraw(canvas);
8375 } else {
8376 draw(canvas);
8377 }
8378
8379 canvas.restoreToCount(restoreCount);
8380
8381 if (attachInfo != null) {
8382 // Restore the cached Canvas for our siblings
8383 attachInfo.mCanvas = canvas;
8384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008385 }
8386 }
8387
8388 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008389 * Create a snapshot of the view into a bitmap. We should probably make
8390 * some form of this public, but should think about the API.
8391 */
Romain Guy223ff5c2010-03-02 17:07:47 -08008392 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008393 int width = mRight - mLeft;
8394 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008395
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008396 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07008397 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008398 width = (int) ((width * scale) + 0.5f);
8399 height = (int) ((height * scale) + 0.5f);
8400
Romain Guy8c11e312009-09-14 15:15:30 -07008401 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008402 if (bitmap == null) {
8403 throw new OutOfMemoryError();
8404 }
8405
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008406 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8407
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008408 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008409 if (attachInfo != null) {
8410 canvas = attachInfo.mCanvas;
8411 if (canvas == null) {
8412 canvas = new Canvas();
8413 }
8414 canvas.setBitmap(bitmap);
8415 // Temporarily clobber the cached Canvas in case one of our children
8416 // is also using a drawing cache. Without this, the children would
8417 // steal the canvas by attaching their own bitmap to it and bad, bad
8418 // things would happen (invisible views, corrupted drawings, etc.)
8419 attachInfo.mCanvas = null;
8420 } else {
8421 // This case should hopefully never or seldom happen
8422 canvas = new Canvas(bitmap);
8423 }
8424
Romain Guy5bcdff42009-05-14 21:27:18 -07008425 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008426 bitmap.eraseColor(backgroundColor);
8427 }
8428
8429 computeScroll();
8430 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008431 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008432 canvas.translate(-mScrollX, -mScrollY);
8433
Romain Guy5bcdff42009-05-14 21:27:18 -07008434 // Temporarily remove the dirty mask
8435 int flags = mPrivateFlags;
8436 mPrivateFlags &= ~DIRTY_MASK;
8437
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008438 // Fast path for layouts with no backgrounds
8439 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8440 dispatchDraw(canvas);
8441 } else {
8442 draw(canvas);
8443 }
8444
Romain Guy5bcdff42009-05-14 21:27:18 -07008445 mPrivateFlags = flags;
8446
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008447 canvas.restoreToCount(restoreCount);
8448
8449 if (attachInfo != null) {
8450 // Restore the cached Canvas for our siblings
8451 attachInfo.mCanvas = canvas;
8452 }
Romain Guy8506ab42009-06-11 17:35:47 -07008453
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008454 return bitmap;
8455 }
8456
8457 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458 * Indicates whether this View is currently in edit mode. A View is usually
8459 * in edit mode when displayed within a developer tool. For instance, if
8460 * this View is being drawn by a visual user interface builder, this method
8461 * should return true.
8462 *
8463 * Subclasses should check the return value of this method to provide
8464 * different behaviors if their normal behavior might interfere with the
8465 * host environment. For instance: the class spawns a thread in its
8466 * constructor, the drawing code relies on device-specific features, etc.
8467 *
8468 * This method is usually checked in the drawing code of custom widgets.
8469 *
8470 * @return True if this View is in edit mode, false otherwise.
8471 */
8472 public boolean isInEditMode() {
8473 return false;
8474 }
8475
8476 /**
8477 * If the View draws content inside its padding and enables fading edges,
8478 * it needs to support padding offsets. Padding offsets are added to the
8479 * fading edges to extend the length of the fade so that it covers pixels
8480 * drawn inside the padding.
8481 *
8482 * Subclasses of this class should override this method if they need
8483 * to draw content inside the padding.
8484 *
8485 * @return True if padding offset must be applied, false otherwise.
8486 *
8487 * @see #getLeftPaddingOffset()
8488 * @see #getRightPaddingOffset()
8489 * @see #getTopPaddingOffset()
8490 * @see #getBottomPaddingOffset()
8491 *
8492 * @since CURRENT
8493 */
8494 protected boolean isPaddingOffsetRequired() {
8495 return false;
8496 }
8497
8498 /**
8499 * Amount by which to extend the left fading region. Called only when
8500 * {@link #isPaddingOffsetRequired()} returns true.
8501 *
8502 * @return The left padding offset in pixels.
8503 *
8504 * @see #isPaddingOffsetRequired()
8505 *
8506 * @since CURRENT
8507 */
8508 protected int getLeftPaddingOffset() {
8509 return 0;
8510 }
8511
8512 /**
8513 * Amount by which to extend the right fading region. Called only when
8514 * {@link #isPaddingOffsetRequired()} returns true.
8515 *
8516 * @return The right padding offset in pixels.
8517 *
8518 * @see #isPaddingOffsetRequired()
8519 *
8520 * @since CURRENT
8521 */
8522 protected int getRightPaddingOffset() {
8523 return 0;
8524 }
8525
8526 /**
8527 * Amount by which to extend the top fading region. Called only when
8528 * {@link #isPaddingOffsetRequired()} returns true.
8529 *
8530 * @return The top padding offset in pixels.
8531 *
8532 * @see #isPaddingOffsetRequired()
8533 *
8534 * @since CURRENT
8535 */
8536 protected int getTopPaddingOffset() {
8537 return 0;
8538 }
8539
8540 /**
8541 * Amount by which to extend the bottom fading region. Called only when
8542 * {@link #isPaddingOffsetRequired()} returns true.
8543 *
8544 * @return The bottom padding offset in pixels.
8545 *
8546 * @see #isPaddingOffsetRequired()
8547 *
8548 * @since CURRENT
8549 */
8550 protected int getBottomPaddingOffset() {
8551 return 0;
8552 }
8553
8554 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008555 * <p>Indicates whether this view is attached to an hardware accelerated
8556 * window or not.</p>
8557 *
8558 * <p>Even if this method returns true, it does not mean that every call
8559 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8560 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8561 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8562 * window is hardware accelerated,
8563 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8564 * return false, and this method will return true.</p>
8565 *
8566 * @return True if the view is attached to a window and the window is
8567 * hardware accelerated; false in any other case.
8568 */
8569 public boolean isHardwareAccelerated() {
8570 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8571 }
8572
8573 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 * Manually render this view (and all of its children) to the given Canvas.
8575 * The view must have already done a full layout before this function is
Chet Haasec75ec332010-12-17 07:44:30 -08008576 * called. When implementing a view, implement {@link #onDraw} instead of
8577 * overriding this method. If you do need to override this method, call
8578 * the superclass version.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 *
8580 * @param canvas The Canvas to which the View is rendered.
8581 */
8582 public void draw(Canvas canvas) {
8583 if (ViewDebug.TRACE_HIERARCHY) {
8584 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8585 }
8586
Romain Guy5bcdff42009-05-14 21:27:18 -07008587 final int privateFlags = mPrivateFlags;
8588 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8589 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8590 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 /*
8593 * Draw traversal performs several drawing steps which must be executed
8594 * in the appropriate order:
8595 *
8596 * 1. Draw the background
8597 * 2. If necessary, save the canvas' layers to prepare for fading
8598 * 3. Draw view's content
8599 * 4. Draw children
8600 * 5. If necessary, draw the fading edges and restore layers
8601 * 6. Draw decorations (scrollbars for instance)
8602 */
8603
8604 // Step 1, draw the background, if needed
8605 int saveCount;
8606
Romain Guy24443ea2009-05-11 11:56:30 -07008607 if (!dirtyOpaque) {
8608 final Drawable background = mBGDrawable;
8609 if (background != null) {
8610 final int scrollX = mScrollX;
8611 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612
Romain Guy24443ea2009-05-11 11:56:30 -07008613 if (mBackgroundSizeChanged) {
8614 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8615 mBackgroundSizeChanged = false;
8616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008617
Romain Guy24443ea2009-05-11 11:56:30 -07008618 if ((scrollX | scrollY) == 0) {
8619 background.draw(canvas);
8620 } else {
8621 canvas.translate(scrollX, scrollY);
8622 background.draw(canvas);
8623 canvas.translate(-scrollX, -scrollY);
8624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625 }
8626 }
8627
8628 // skip step 2 & 5 if possible (common case)
8629 final int viewFlags = mViewFlags;
8630 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8631 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8632 if (!verticalEdges && !horizontalEdges) {
8633 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008634 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008635
8636 // Step 4, draw the children
8637 dispatchDraw(canvas);
8638
8639 // Step 6, draw decorations (scrollbars)
8640 onDrawScrollBars(canvas);
8641
8642 // we're done...
8643 return;
8644 }
8645
8646 /*
8647 * Here we do the full fledged routine...
8648 * (this is an uncommon case where speed matters less,
8649 * this is why we repeat some of the tests that have been
8650 * done above)
8651 */
8652
8653 boolean drawTop = false;
8654 boolean drawBottom = false;
8655 boolean drawLeft = false;
8656 boolean drawRight = false;
8657
8658 float topFadeStrength = 0.0f;
8659 float bottomFadeStrength = 0.0f;
8660 float leftFadeStrength = 0.0f;
8661 float rightFadeStrength = 0.0f;
8662
8663 // Step 2, save the canvas' layers
8664 int paddingLeft = mPaddingLeft;
8665 int paddingTop = mPaddingTop;
8666
8667 final boolean offsetRequired = isPaddingOffsetRequired();
8668 if (offsetRequired) {
8669 paddingLeft += getLeftPaddingOffset();
8670 paddingTop += getTopPaddingOffset();
8671 }
8672
8673 int left = mScrollX + paddingLeft;
8674 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8675 int top = mScrollY + paddingTop;
8676 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8677
8678 if (offsetRequired) {
8679 right += getRightPaddingOffset();
8680 bottom += getBottomPaddingOffset();
8681 }
8682
8683 final ScrollabilityCache scrollabilityCache = mScrollCache;
8684 int length = scrollabilityCache.fadingEdgeLength;
8685
8686 // clip the fade length if top and bottom fades overlap
8687 // overlapping fades produce odd-looking artifacts
8688 if (verticalEdges && (top + length > bottom - length)) {
8689 length = (bottom - top) / 2;
8690 }
8691
8692 // also clip horizontal fades if necessary
8693 if (horizontalEdges && (left + length > right - length)) {
8694 length = (right - left) / 2;
8695 }
8696
8697 if (verticalEdges) {
8698 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008699 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008700 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008701 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008702 }
8703
8704 if (horizontalEdges) {
8705 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008706 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008707 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008708 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 }
8710
8711 saveCount = canvas.getSaveCount();
8712
8713 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008714 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008715 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8716
8717 if (drawTop) {
8718 canvas.saveLayer(left, top, right, top + length, null, flags);
8719 }
8720
8721 if (drawBottom) {
8722 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8723 }
8724
8725 if (drawLeft) {
8726 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8727 }
8728
8729 if (drawRight) {
8730 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8731 }
8732 } else {
8733 scrollabilityCache.setFadeColor(solidColor);
8734 }
8735
8736 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008737 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008738
8739 // Step 4, draw the children
8740 dispatchDraw(canvas);
8741
8742 // Step 5, draw the fade effect and restore layers
8743 final Paint p = scrollabilityCache.paint;
8744 final Matrix matrix = scrollabilityCache.matrix;
8745 final Shader fade = scrollabilityCache.shader;
8746 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8747
8748 if (drawTop) {
8749 matrix.setScale(1, fadeHeight * topFadeStrength);
8750 matrix.postTranslate(left, top);
8751 fade.setLocalMatrix(matrix);
8752 canvas.drawRect(left, top, right, top + length, p);
8753 }
8754
8755 if (drawBottom) {
8756 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8757 matrix.postRotate(180);
8758 matrix.postTranslate(left, bottom);
8759 fade.setLocalMatrix(matrix);
8760 canvas.drawRect(left, bottom - length, right, bottom, p);
8761 }
8762
8763 if (drawLeft) {
8764 matrix.setScale(1, fadeHeight * leftFadeStrength);
8765 matrix.postRotate(-90);
8766 matrix.postTranslate(left, top);
8767 fade.setLocalMatrix(matrix);
8768 canvas.drawRect(left, top, left + length, bottom, p);
8769 }
8770
8771 if (drawRight) {
8772 matrix.setScale(1, fadeHeight * rightFadeStrength);
8773 matrix.postRotate(90);
8774 matrix.postTranslate(right, top);
8775 fade.setLocalMatrix(matrix);
8776 canvas.drawRect(right - length, top, right, bottom, p);
8777 }
8778
8779 canvas.restoreToCount(saveCount);
8780
8781 // Step 6, draw decorations (scrollbars)
8782 onDrawScrollBars(canvas);
8783 }
8784
8785 /**
8786 * Override this if your view is known to always be drawn on top of a solid color background,
8787 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8788 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8789 * should be set to 0xFF.
8790 *
8791 * @see #setVerticalFadingEdgeEnabled
8792 * @see #setHorizontalFadingEdgeEnabled
8793 *
8794 * @return The known solid color background for this view, or 0 if the color may vary
8795 */
8796 public int getSolidColor() {
8797 return 0;
8798 }
8799
8800 /**
8801 * Build a human readable string representation of the specified view flags.
8802 *
8803 * @param flags the view flags to convert to a string
8804 * @return a String representing the supplied flags
8805 */
8806 private static String printFlags(int flags) {
8807 String output = "";
8808 int numFlags = 0;
8809 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8810 output += "TAKES_FOCUS";
8811 numFlags++;
8812 }
8813
8814 switch (flags & VISIBILITY_MASK) {
8815 case INVISIBLE:
8816 if (numFlags > 0) {
8817 output += " ";
8818 }
8819 output += "INVISIBLE";
8820 // USELESS HERE numFlags++;
8821 break;
8822 case GONE:
8823 if (numFlags > 0) {
8824 output += " ";
8825 }
8826 output += "GONE";
8827 // USELESS HERE numFlags++;
8828 break;
8829 default:
8830 break;
8831 }
8832 return output;
8833 }
8834
8835 /**
8836 * Build a human readable string representation of the specified private
8837 * view flags.
8838 *
8839 * @param privateFlags the private view flags to convert to a string
8840 * @return a String representing the supplied flags
8841 */
8842 private static String printPrivateFlags(int privateFlags) {
8843 String output = "";
8844 int numFlags = 0;
8845
8846 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8847 output += "WANTS_FOCUS";
8848 numFlags++;
8849 }
8850
8851 if ((privateFlags & FOCUSED) == FOCUSED) {
8852 if (numFlags > 0) {
8853 output += " ";
8854 }
8855 output += "FOCUSED";
8856 numFlags++;
8857 }
8858
8859 if ((privateFlags & SELECTED) == SELECTED) {
8860 if (numFlags > 0) {
8861 output += " ";
8862 }
8863 output += "SELECTED";
8864 numFlags++;
8865 }
8866
8867 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8868 if (numFlags > 0) {
8869 output += " ";
8870 }
8871 output += "IS_ROOT_NAMESPACE";
8872 numFlags++;
8873 }
8874
8875 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8876 if (numFlags > 0) {
8877 output += " ";
8878 }
8879 output += "HAS_BOUNDS";
8880 numFlags++;
8881 }
8882
8883 if ((privateFlags & DRAWN) == DRAWN) {
8884 if (numFlags > 0) {
8885 output += " ";
8886 }
8887 output += "DRAWN";
8888 // USELESS HERE numFlags++;
8889 }
8890 return output;
8891 }
8892
8893 /**
8894 * <p>Indicates whether or not this view's layout will be requested during
8895 * the next hierarchy layout pass.</p>
8896 *
8897 * @return true if the layout will be forced during next layout pass
8898 */
8899 public boolean isLayoutRequested() {
8900 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8901 }
8902
8903 /**
8904 * Assign a size and position to a view and all of its
8905 * descendants
8906 *
8907 * <p>This is the second phase of the layout mechanism.
8908 * (The first is measuring). In this phase, each parent calls
8909 * layout on all of its children to position them.
8910 * This is typically done using the child measurements
Chet Haase9c087442011-01-12 16:20:16 -08008911 * that were stored in the measure pass().</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008912 *
Chet Haase9c087442011-01-12 16:20:16 -08008913 * <p>Derived classes should not override this method.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008914 * Derived classes with children should override
8915 * onLayout. In that method, they should
Chet Haase9c087442011-01-12 16:20:16 -08008916 * call layout on each of their children.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008917 *
8918 * @param l Left position, relative to parent
8919 * @param t Top position, relative to parent
8920 * @param r Right position, relative to parent
8921 * @param b Bottom position, relative to parent
8922 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008923 @SuppressWarnings({"unchecked"})
Chet Haase9c087442011-01-12 16:20:16 -08008924 public void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008925 int oldL = mLeft;
8926 int oldT = mTop;
8927 int oldB = mBottom;
8928 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008929 boolean changed = setFrame(l, t, r, b);
8930 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8931 if (ViewDebug.TRACE_HIERARCHY) {
8932 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8933 }
8934
8935 onLayout(changed, l, t, r, b);
8936 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008937
8938 if (mOnLayoutChangeListeners != null) {
8939 ArrayList<OnLayoutChangeListener> listenersCopy =
8940 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8941 int numListeners = listenersCopy.size();
8942 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07008943 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07008944 }
8945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008946 }
8947 mPrivateFlags &= ~FORCE_LAYOUT;
8948 }
8949
8950 /**
8951 * Called from layout when this view should
8952 * assign a size and position to each of its children.
8953 *
8954 * Derived classes with children should override
8955 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008956 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 * @param changed This is a new size or position for this view
8958 * @param left Left position, relative to parent
8959 * @param top Top position, relative to parent
8960 * @param right Right position, relative to parent
8961 * @param bottom Bottom position, relative to parent
8962 */
8963 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8964 }
8965
8966 /**
8967 * Assign a size and position to this view.
8968 *
8969 * This is called from layout.
8970 *
8971 * @param left Left position, relative to parent
8972 * @param top Top position, relative to parent
8973 * @param right Right position, relative to parent
8974 * @param bottom Bottom position, relative to parent
8975 * @return true if the new size and position are different than the
8976 * previous ones
8977 * {@hide}
8978 */
8979 protected boolean setFrame(int left, int top, int right, int bottom) {
8980 boolean changed = false;
8981
8982 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008983 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008984 + right + "," + bottom + ")");
8985 }
8986
8987 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8988 changed = true;
8989
8990 // Remember our drawn bit
8991 int drawn = mPrivateFlags & DRAWN;
8992
8993 // Invalidate our old position
8994 invalidate();
8995
8996
8997 int oldWidth = mRight - mLeft;
8998 int oldHeight = mBottom - mTop;
8999
9000 mLeft = left;
9001 mTop = top;
9002 mRight = right;
9003 mBottom = bottom;
9004
9005 mPrivateFlags |= HAS_BOUNDS;
9006
9007 int newWidth = right - left;
9008 int newHeight = bottom - top;
9009
9010 if (newWidth != oldWidth || newHeight != oldHeight) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009011 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9012 // A change in dimension means an auto-centered pivot point changes, too
9013 mMatrixDirty = true;
9014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009015 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
9016 }
9017
9018 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
9019 // If we are visible, force the DRAWN bit to on so that
9020 // this invalidate will go through (at least to our parent).
9021 // This is because someone may have invalidated this view
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009022 // before this call to setFrame came in, thereby clearing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 // the DRAWN bit.
9024 mPrivateFlags |= DRAWN;
9025 invalidate();
9026 }
9027
9028 // Reset drawn bit to original value (invalidate turns it off)
9029 mPrivateFlags |= drawn;
9030
9031 mBackgroundSizeChanged = true;
9032 }
9033 return changed;
9034 }
9035
9036 /**
9037 * Finalize inflating a view from XML. This is called as the last phase
9038 * of inflation, after all child views have been added.
9039 *
9040 * <p>Even if the subclass overrides onFinishInflate, they should always be
9041 * sure to call the super method, so that we get called.
9042 */
9043 protected void onFinishInflate() {
9044 }
9045
9046 /**
9047 * Returns the resources associated with this view.
9048 *
9049 * @return Resources object.
9050 */
9051 public Resources getResources() {
9052 return mResources;
9053 }
9054
9055 /**
9056 * Invalidates the specified Drawable.
9057 *
9058 * @param drawable the drawable to invalidate
9059 */
9060 public void invalidateDrawable(Drawable drawable) {
9061 if (verifyDrawable(drawable)) {
9062 final Rect dirty = drawable.getBounds();
9063 final int scrollX = mScrollX;
9064 final int scrollY = mScrollY;
9065
9066 invalidate(dirty.left + scrollX, dirty.top + scrollY,
9067 dirty.right + scrollX, dirty.bottom + scrollY);
9068 }
9069 }
9070
9071 /**
9072 * Schedules an action on a drawable to occur at a specified time.
9073 *
9074 * @param who the recipient of the action
9075 * @param what the action to run on the drawable
9076 * @param when the time at which the action must occur. Uses the
9077 * {@link SystemClock#uptimeMillis} timebase.
9078 */
9079 public void scheduleDrawable(Drawable who, Runnable what, long when) {
9080 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9081 mAttachInfo.mHandler.postAtTime(what, who, when);
9082 }
9083 }
9084
9085 /**
9086 * Cancels a scheduled action on a drawable.
9087 *
9088 * @param who the recipient of the action
9089 * @param what the action to cancel
9090 */
9091 public void unscheduleDrawable(Drawable who, Runnable what) {
9092 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9093 mAttachInfo.mHandler.removeCallbacks(what, who);
9094 }
9095 }
9096
9097 /**
9098 * Unschedule any events associated with the given Drawable. This can be
9099 * used when selecting a new Drawable into a view, so that the previous
9100 * one is completely unscheduled.
9101 *
9102 * @param who The Drawable to unschedule.
9103 *
9104 * @see #drawableStateChanged
9105 */
9106 public void unscheduleDrawable(Drawable who) {
9107 if (mAttachInfo != null) {
9108 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
9109 }
9110 }
9111
9112 /**
9113 * If your view subclass is displaying its own Drawable objects, it should
9114 * override this function and return true for any Drawable it is
9115 * displaying. This allows animations for those drawables to be
9116 * scheduled.
9117 *
9118 * <p>Be sure to call through to the super class when overriding this
9119 * function.
9120 *
9121 * @param who The Drawable to verify. Return true if it is one you are
9122 * displaying, else return the result of calling through to the
9123 * super class.
9124 *
9125 * @return boolean If true than the Drawable is being displayed in the
9126 * view; else false and it is not allowed to animate.
9127 *
9128 * @see #unscheduleDrawable
9129 * @see #drawableStateChanged
9130 */
9131 protected boolean verifyDrawable(Drawable who) {
9132 return who == mBGDrawable;
9133 }
9134
9135 /**
9136 * This function is called whenever the state of the view changes in such
9137 * a way that it impacts the state of drawables being shown.
9138 *
9139 * <p>Be sure to call through to the superclass when overriding this
9140 * function.
9141 *
9142 * @see Drawable#setState
9143 */
9144 protected void drawableStateChanged() {
9145 Drawable d = mBGDrawable;
9146 if (d != null && d.isStateful()) {
9147 d.setState(getDrawableState());
9148 }
9149 }
9150
9151 /**
9152 * Call this to force a view to update its drawable state. This will cause
9153 * drawableStateChanged to be called on this view. Views that are interested
9154 * in the new state should call getDrawableState.
9155 *
9156 * @see #drawableStateChanged
9157 * @see #getDrawableState
9158 */
9159 public void refreshDrawableState() {
9160 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9161 drawableStateChanged();
9162
9163 ViewParent parent = mParent;
9164 if (parent != null) {
9165 parent.childDrawableStateChanged(this);
9166 }
9167 }
9168
9169 /**
9170 * Return an array of resource IDs of the drawable states representing the
9171 * current state of the view.
9172 *
9173 * @return The current drawable state
9174 *
9175 * @see Drawable#setState
9176 * @see #drawableStateChanged
9177 * @see #onCreateDrawableState
9178 */
9179 public final int[] getDrawableState() {
9180 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
9181 return mDrawableState;
9182 } else {
9183 mDrawableState = onCreateDrawableState(0);
9184 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
9185 return mDrawableState;
9186 }
9187 }
9188
9189 /**
9190 * Generate the new {@link android.graphics.drawable.Drawable} state for
9191 * this view. This is called by the view
9192 * system when the cached Drawable state is determined to be invalid. To
9193 * retrieve the current state, you should use {@link #getDrawableState}.
9194 *
9195 * @param extraSpace if non-zero, this is the number of extra entries you
9196 * would like in the returned array in which you can place your own
9197 * states.
9198 *
9199 * @return Returns an array holding the current {@link Drawable} state of
9200 * the view.
9201 *
9202 * @see #mergeDrawableStates
9203 */
9204 protected int[] onCreateDrawableState(int extraSpace) {
9205 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
9206 mParent instanceof View) {
9207 return ((View) mParent).onCreateDrawableState(extraSpace);
9208 }
9209
9210 int[] drawableState;
9211
9212 int privateFlags = mPrivateFlags;
9213
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009214 int viewStateIndex = 0;
9215 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
9216 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
9217 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07009218 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009219 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
9220 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08009221 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
9222 // This is set if HW acceleration is requested, even if the current
9223 // process doesn't allow it. This is just to allow app preview
9224 // windows to better match their app.
9225 viewStateIndex |= VIEW_STATE_ACCELERATED;
9226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009227
9228 drawableState = VIEW_STATE_SETS[viewStateIndex];
9229
9230 //noinspection ConstantIfStatement
9231 if (false) {
9232 Log.i("View", "drawableStateIndex=" + viewStateIndex);
9233 Log.i("View", toString()
9234 + " pressed=" + ((privateFlags & PRESSED) != 0)
9235 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
9236 + " fo=" + hasFocus()
9237 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009238 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009239 + ": " + Arrays.toString(drawableState));
9240 }
9241
9242 if (extraSpace == 0) {
9243 return drawableState;
9244 }
9245
9246 final int[] fullState;
9247 if (drawableState != null) {
9248 fullState = new int[drawableState.length + extraSpace];
9249 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
9250 } else {
9251 fullState = new int[extraSpace];
9252 }
9253
9254 return fullState;
9255 }
9256
9257 /**
9258 * Merge your own state values in <var>additionalState</var> into the base
9259 * state values <var>baseState</var> that were returned by
9260 * {@link #onCreateDrawableState}.
9261 *
9262 * @param baseState The base state values returned by
9263 * {@link #onCreateDrawableState}, which will be modified to also hold your
9264 * own additional state values.
9265 *
9266 * @param additionalState The additional state values you would like
9267 * added to <var>baseState</var>; this array is not modified.
9268 *
9269 * @return As a convenience, the <var>baseState</var> array you originally
9270 * passed into the function is returned.
9271 *
9272 * @see #onCreateDrawableState
9273 */
9274 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
9275 final int N = baseState.length;
9276 int i = N - 1;
9277 while (i >= 0 && baseState[i] == 0) {
9278 i--;
9279 }
9280 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
9281 return baseState;
9282 }
9283
9284 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07009285 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
9286 * on all Drawable objects associated with this view.
9287 */
9288 public void jumpDrawablesToCurrentState() {
9289 if (mBGDrawable != null) {
9290 mBGDrawable.jumpToCurrentState();
9291 }
9292 }
9293
9294 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009295 * Sets the background color for this view.
9296 * @param color the color of the background
9297 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009298 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009299 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07009300 if (mBGDrawable instanceof ColorDrawable) {
9301 ((ColorDrawable) mBGDrawable).setColor(color);
9302 } else {
9303 setBackgroundDrawable(new ColorDrawable(color));
9304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009305 }
9306
9307 /**
9308 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07009309 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009310 * @param resid The identifier of the resource.
9311 * @attr ref android.R.styleable#View_background
9312 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009313 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009314 public void setBackgroundResource(int resid) {
9315 if (resid != 0 && resid == mBackgroundResource) {
9316 return;
9317 }
9318
9319 Drawable d= null;
9320 if (resid != 0) {
9321 d = mResources.getDrawable(resid);
9322 }
9323 setBackgroundDrawable(d);
9324
9325 mBackgroundResource = resid;
9326 }
9327
9328 /**
9329 * Set the background to a given Drawable, or remove the background. If the
9330 * background has padding, this View's padding is set to the background's
9331 * padding. However, when a background is removed, this View's padding isn't
9332 * touched. If setting the padding is desired, please use
9333 * {@link #setPadding(int, int, int, int)}.
9334 *
9335 * @param d The Drawable to use as the background, or null to remove the
9336 * background
9337 */
9338 public void setBackgroundDrawable(Drawable d) {
9339 boolean requestLayout = false;
9340
9341 mBackgroundResource = 0;
9342
9343 /*
9344 * Regardless of whether we're setting a new background or not, we want
9345 * to clear the previous drawable.
9346 */
9347 if (mBGDrawable != null) {
9348 mBGDrawable.setCallback(null);
9349 unscheduleDrawable(mBGDrawable);
9350 }
9351
9352 if (d != null) {
9353 Rect padding = sThreadLocal.get();
9354 if (padding == null) {
9355 padding = new Rect();
9356 sThreadLocal.set(padding);
9357 }
9358 if (d.getPadding(padding)) {
9359 setPadding(padding.left, padding.top, padding.right, padding.bottom);
9360 }
9361
9362 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
9363 // if it has a different minimum size, we should layout again
9364 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9365 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9366 requestLayout = true;
9367 }
9368
9369 d.setCallback(this);
9370 if (d.isStateful()) {
9371 d.setState(getDrawableState());
9372 }
9373 d.setVisible(getVisibility() == VISIBLE, false);
9374 mBGDrawable = d;
9375
9376 if ((mPrivateFlags & SKIP_DRAW) != 0) {
9377 mPrivateFlags &= ~SKIP_DRAW;
9378 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9379 requestLayout = true;
9380 }
9381 } else {
9382 /* Remove the background */
9383 mBGDrawable = null;
9384
9385 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9386 /*
9387 * This view ONLY drew the background before and we're removing
9388 * the background, so now it won't draw anything
9389 * (hence we SKIP_DRAW)
9390 */
9391 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9392 mPrivateFlags |= SKIP_DRAW;
9393 }
9394
9395 /*
9396 * When the background is set, we try to apply its padding to this
9397 * View. When the background is removed, we don't touch this View's
9398 * padding. This is noted in the Javadocs. Hence, we don't need to
9399 * requestLayout(), the invalidate() below is sufficient.
9400 */
9401
9402 // The old background's minimum size could have affected this
9403 // View's layout, so let's requestLayout
9404 requestLayout = true;
9405 }
9406
Romain Guy8f1344f52009-05-15 16:03:59 -07009407 computeOpaqueFlags();
9408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009409 if (requestLayout) {
9410 requestLayout();
9411 }
9412
9413 mBackgroundSizeChanged = true;
9414 invalidate();
9415 }
9416
9417 /**
9418 * Gets the background drawable
9419 * @return The drawable used as the background for this view, if any.
9420 */
9421 public Drawable getBackground() {
9422 return mBGDrawable;
9423 }
9424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009425 /**
9426 * Sets the padding. The view may add on the space required to display
9427 * the scrollbars, depending on the style and visibility of the scrollbars.
9428 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9429 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9430 * from the values set in this call.
9431 *
9432 * @attr ref android.R.styleable#View_padding
9433 * @attr ref android.R.styleable#View_paddingBottom
9434 * @attr ref android.R.styleable#View_paddingLeft
9435 * @attr ref android.R.styleable#View_paddingRight
9436 * @attr ref android.R.styleable#View_paddingTop
9437 * @param left the left padding in pixels
9438 * @param top the top padding in pixels
9439 * @param right the right padding in pixels
9440 * @param bottom the bottom padding in pixels
9441 */
9442 public void setPadding(int left, int top, int right, int bottom) {
9443 boolean changed = false;
9444
Adam Powell20232d02010-12-08 21:08:53 -08009445 mUserPaddingLeft = left;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009446 mUserPaddingRight = right;
9447 mUserPaddingBottom = bottom;
9448
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009449 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07009450
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009451 // Common case is there are no scroll bars.
9452 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009453 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
Adam Powell20232d02010-12-08 21:08:53 -08009454 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9455 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009456 ? 0 : getVerticalScrollbarWidth();
Adam Powell20232d02010-12-08 21:08:53 -08009457 switch (mVerticalScrollbarPosition) {
9458 case SCROLLBAR_POSITION_DEFAULT:
9459 case SCROLLBAR_POSITION_RIGHT:
9460 right += offset;
9461 break;
9462 case SCROLLBAR_POSITION_LEFT:
9463 left += offset;
9464 break;
9465 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009466 }
Adam Powell20232d02010-12-08 21:08:53 -08009467 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009468 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9469 ? 0 : getHorizontalScrollbarHeight();
9470 }
9471 }
Romain Guy8506ab42009-06-11 17:35:47 -07009472
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009473 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009474 changed = true;
9475 mPaddingLeft = left;
9476 }
9477 if (mPaddingTop != top) {
9478 changed = true;
9479 mPaddingTop = top;
9480 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009481 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009482 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009483 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009484 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009485 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009487 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009488 }
9489
9490 if (changed) {
9491 requestLayout();
9492 }
9493 }
9494
9495 /**
9496 * Returns the top padding of this view.
9497 *
9498 * @return the top padding in pixels
9499 */
9500 public int getPaddingTop() {
9501 return mPaddingTop;
9502 }
9503
9504 /**
9505 * Returns the bottom 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 bottom padding in pixels
9510 */
9511 public int getPaddingBottom() {
9512 return mPaddingBottom;
9513 }
9514
9515 /**
9516 * Returns the left 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 left padding in pixels
9521 */
9522 public int getPaddingLeft() {
9523 return mPaddingLeft;
9524 }
9525
9526 /**
9527 * Returns the right padding of this view. If there are inset and enabled
9528 * scrollbars, this value may include the space required to display the
9529 * scrollbars as well.
9530 *
9531 * @return the right padding in pixels
9532 */
9533 public int getPaddingRight() {
9534 return mPaddingRight;
9535 }
9536
9537 /**
9538 * Changes the selection state of this view. A view can be selected or not.
9539 * Note that selection is not the same as focus. Views are typically
9540 * selected in the context of an AdapterView like ListView or GridView;
9541 * the selected view is the view that is highlighted.
9542 *
9543 * @param selected true if the view must be selected, false otherwise
9544 */
9545 public void setSelected(boolean selected) {
9546 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9547 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009548 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009549 invalidate();
9550 refreshDrawableState();
9551 dispatchSetSelected(selected);
9552 }
9553 }
9554
9555 /**
9556 * Dispatch setSelected to all of this View's children.
9557 *
9558 * @see #setSelected(boolean)
9559 *
9560 * @param selected The new selected state
9561 */
9562 protected void dispatchSetSelected(boolean selected) {
9563 }
9564
9565 /**
9566 * Indicates the selection state of this view.
9567 *
9568 * @return true if the view is selected, false otherwise
9569 */
9570 @ViewDebug.ExportedProperty
9571 public boolean isSelected() {
9572 return (mPrivateFlags & SELECTED) != 0;
9573 }
9574
9575 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009576 * Changes the activated state of this view. A view can be activated or not.
9577 * Note that activation is not the same as selection. Selection is
9578 * a transient property, representing the view (hierarchy) the user is
9579 * currently interacting with. Activation is a longer-term state that the
9580 * user can move views in and out of. For example, in a list view with
9581 * single or multiple selection enabled, the views in the current selection
9582 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9583 * here.) The activated state is propagated down to children of the view it
9584 * is set on.
9585 *
9586 * @param activated true if the view must be activated, false otherwise
9587 */
9588 public void setActivated(boolean activated) {
9589 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9590 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
9591 invalidate();
9592 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009593 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009594 }
9595 }
9596
9597 /**
9598 * Dispatch setActivated to all of this View's children.
9599 *
9600 * @see #setActivated(boolean)
9601 *
9602 * @param activated The new activated state
9603 */
9604 protected void dispatchSetActivated(boolean activated) {
9605 }
9606
9607 /**
9608 * Indicates the activation state of this view.
9609 *
9610 * @return true if the view is activated, false otherwise
9611 */
9612 @ViewDebug.ExportedProperty
9613 public boolean isActivated() {
9614 return (mPrivateFlags & ACTIVATED) != 0;
9615 }
9616
9617 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009618 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9619 * observer can be used to get notifications when global events, like
9620 * layout, happen.
9621 *
9622 * The returned ViewTreeObserver observer is not guaranteed to remain
9623 * valid for the lifetime of this View. If the caller of this method keeps
9624 * a long-lived reference to ViewTreeObserver, it should always check for
9625 * the return value of {@link ViewTreeObserver#isAlive()}.
9626 *
9627 * @return The ViewTreeObserver for this view's hierarchy.
9628 */
9629 public ViewTreeObserver getViewTreeObserver() {
9630 if (mAttachInfo != null) {
9631 return mAttachInfo.mTreeObserver;
9632 }
9633 if (mFloatingTreeObserver == null) {
9634 mFloatingTreeObserver = new ViewTreeObserver();
9635 }
9636 return mFloatingTreeObserver;
9637 }
9638
9639 /**
9640 * <p>Finds the topmost view in the current view hierarchy.</p>
9641 *
9642 * @return the topmost view containing this view
9643 */
9644 public View getRootView() {
9645 if (mAttachInfo != null) {
9646 final View v = mAttachInfo.mRootView;
9647 if (v != null) {
9648 return v;
9649 }
9650 }
Romain Guy8506ab42009-06-11 17:35:47 -07009651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009652 View parent = this;
9653
9654 while (parent.mParent != null && parent.mParent instanceof View) {
9655 parent = (View) parent.mParent;
9656 }
9657
9658 return parent;
9659 }
9660
9661 /**
9662 * <p>Computes the coordinates of this view on the screen. The argument
9663 * must be an array of two integers. After the method returns, the array
9664 * contains the x and y location in that order.</p>
9665 *
9666 * @param location an array of two integers in which to hold the coordinates
9667 */
9668 public void getLocationOnScreen(int[] location) {
9669 getLocationInWindow(location);
9670
9671 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009672 if (info != null) {
9673 location[0] += info.mWindowLeft;
9674 location[1] += info.mWindowTop;
9675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009676 }
9677
9678 /**
9679 * <p>Computes the coordinates of this view in its window. The argument
9680 * must be an array of two integers. After the method returns, the array
9681 * contains the x and y location in that order.</p>
9682 *
9683 * @param location an array of two integers in which to hold the coordinates
9684 */
9685 public void getLocationInWindow(int[] location) {
9686 if (location == null || location.length < 2) {
9687 throw new IllegalArgumentException("location must be an array of "
9688 + "two integers");
9689 }
9690
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009691 location[0] = mLeft + (int) (mTranslationX + 0.5f);
9692 location[1] = mTop + (int) (mTranslationY + 0.5f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009693
9694 ViewParent viewParent = mParent;
9695 while (viewParent instanceof View) {
9696 final View view = (View)viewParent;
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009697 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
9698 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009699 viewParent = view.mParent;
9700 }
Romain Guy8506ab42009-06-11 17:35:47 -07009701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009702 if (viewParent instanceof ViewRoot) {
9703 // *cough*
9704 final ViewRoot vr = (ViewRoot)viewParent;
9705 location[1] -= vr.mCurScrollY;
9706 }
9707 }
9708
9709 /**
9710 * {@hide}
9711 * @param id the id of the view to be found
9712 * @return the view of the specified id, null if cannot be found
9713 */
9714 protected View findViewTraversal(int id) {
9715 if (id == mID) {
9716 return this;
9717 }
9718 return null;
9719 }
9720
9721 /**
9722 * {@hide}
9723 * @param tag the tag of the view to be found
9724 * @return the view of specified tag, null if cannot be found
9725 */
9726 protected View findViewWithTagTraversal(Object tag) {
9727 if (tag != null && tag.equals(mTag)) {
9728 return this;
9729 }
9730 return null;
9731 }
9732
9733 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009734 * {@hide}
9735 * @param predicate The predicate to evaluate.
9736 * @return The first view that matches the predicate or null.
9737 */
9738 protected View findViewByPredicateTraversal(Predicate<View> predicate) {
9739 if (predicate.apply(this)) {
9740 return this;
9741 }
9742 return null;
9743 }
9744
9745 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009746 * Look for a child view with the given id. If this view has the given
9747 * id, return this view.
9748 *
9749 * @param id The id to search for.
9750 * @return The view that has the given id in the hierarchy or null
9751 */
9752 public final View findViewById(int id) {
9753 if (id < 0) {
9754 return null;
9755 }
9756 return findViewTraversal(id);
9757 }
9758
9759 /**
9760 * Look for a child view with the given tag. If this view has the given
9761 * tag, return this view.
9762 *
9763 * @param tag The tag to search for, using "tag.equals(getTag())".
9764 * @return The View that has the given tag in the hierarchy or null
9765 */
9766 public final View findViewWithTag(Object tag) {
9767 if (tag == null) {
9768 return null;
9769 }
9770 return findViewWithTagTraversal(tag);
9771 }
9772
9773 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009774 * {@hide}
9775 * Look for a child view that matches the specified predicate.
9776 * If this view matches the predicate, return this view.
9777 *
9778 * @param predicate The predicate to evaluate.
9779 * @return The first view that matches the predicate or null.
9780 */
9781 public final View findViewByPredicate(Predicate<View> predicate) {
9782 return findViewByPredicateTraversal(predicate);
9783 }
9784
9785 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009786 * Sets the identifier for this view. The identifier does not have to be
9787 * unique in this view's hierarchy. The identifier should be a positive
9788 * number.
9789 *
9790 * @see #NO_ID
9791 * @see #getId
9792 * @see #findViewById
9793 *
9794 * @param id a number used to identify the view
9795 *
9796 * @attr ref android.R.styleable#View_id
9797 */
9798 public void setId(int id) {
9799 mID = id;
9800 }
9801
9802 /**
9803 * {@hide}
9804 *
9805 * @param isRoot true if the view belongs to the root namespace, false
9806 * otherwise
9807 */
9808 public void setIsRootNamespace(boolean isRoot) {
9809 if (isRoot) {
9810 mPrivateFlags |= IS_ROOT_NAMESPACE;
9811 } else {
9812 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9813 }
9814 }
9815
9816 /**
9817 * {@hide}
9818 *
9819 * @return true if the view belongs to the root namespace, false otherwise
9820 */
9821 public boolean isRootNamespace() {
9822 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9823 }
9824
9825 /**
9826 * Returns this view's identifier.
9827 *
9828 * @return a positive integer used to identify the view or {@link #NO_ID}
9829 * if the view has no ID
9830 *
9831 * @see #setId
9832 * @see #findViewById
9833 * @attr ref android.R.styleable#View_id
9834 */
9835 @ViewDebug.CapturedViewProperty
9836 public int getId() {
9837 return mID;
9838 }
9839
9840 /**
9841 * Returns this view's tag.
9842 *
9843 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07009844 *
9845 * @see #setTag(Object)
9846 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009847 */
9848 @ViewDebug.ExportedProperty
9849 public Object getTag() {
9850 return mTag;
9851 }
9852
9853 /**
9854 * Sets the tag associated with this view. A tag can be used to mark
9855 * a view in its hierarchy and does not have to be unique within the
9856 * hierarchy. Tags can also be used to store data within a view without
9857 * resorting to another data structure.
9858 *
9859 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07009860 *
9861 * @see #getTag()
9862 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009863 */
9864 public void setTag(final Object tag) {
9865 mTag = tag;
9866 }
9867
9868 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009869 * Returns the tag associated with this view and the specified key.
9870 *
9871 * @param key The key identifying the tag
9872 *
9873 * @return the Object stored in this view as a tag
9874 *
9875 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009876 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009877 */
9878 public Object getTag(int key) {
9879 SparseArray<Object> tags = null;
9880 synchronized (sTagsLock) {
9881 if (sTags != null) {
9882 tags = sTags.get(this);
9883 }
9884 }
9885
9886 if (tags != null) return tags.get(key);
9887 return null;
9888 }
9889
9890 /**
9891 * Sets a tag associated with this view and a key. A tag can be used
9892 * to mark a view in its hierarchy and does not have to be unique within
9893 * the hierarchy. Tags can also be used to store data within a view
9894 * without resorting to another data structure.
9895 *
9896 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009897 * application to ensure it is unique (see the <a
9898 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9899 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009900 * the Android framework or not associated with any package will cause
9901 * an {@link IllegalArgumentException} to be thrown.
9902 *
9903 * @param key The key identifying the tag
9904 * @param tag An Object to tag the view with
9905 *
9906 * @throws IllegalArgumentException If they specified key is not valid
9907 *
9908 * @see #setTag(Object)
9909 * @see #getTag(int)
9910 */
9911 public void setTag(int key, final Object tag) {
9912 // If the package id is 0x00 or 0x01, it's either an undefined package
9913 // or a framework id
9914 if ((key >>> 24) < 2) {
9915 throw new IllegalArgumentException("The key must be an application-specific "
9916 + "resource id.");
9917 }
9918
9919 setTagInternal(this, key, tag);
9920 }
9921
9922 /**
9923 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9924 * framework id.
9925 *
9926 * @hide
9927 */
9928 public void setTagInternal(int key, Object tag) {
9929 if ((key >>> 24) != 0x1) {
9930 throw new IllegalArgumentException("The key must be a framework-specific "
9931 + "resource id.");
9932 }
9933
Romain Guy8506ab42009-06-11 17:35:47 -07009934 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009935 }
9936
9937 private static void setTagInternal(View view, int key, Object tag) {
9938 SparseArray<Object> tags = null;
9939 synchronized (sTagsLock) {
9940 if (sTags == null) {
9941 sTags = new WeakHashMap<View, SparseArray<Object>>();
9942 } else {
9943 tags = sTags.get(view);
9944 }
9945 }
9946
9947 if (tags == null) {
9948 tags = new SparseArray<Object>(2);
9949 synchronized (sTagsLock) {
9950 sTags.put(view, tags);
9951 }
9952 }
9953
9954 tags.put(key, tag);
9955 }
9956
9957 /**
Romain Guy13922e02009-05-12 17:56:14 -07009958 * @param consistency The type of consistency. See ViewDebug for more information.
9959 *
9960 * @hide
9961 */
9962 protected boolean dispatchConsistencyCheck(int consistency) {
9963 return onConsistencyCheck(consistency);
9964 }
9965
9966 /**
9967 * Method that subclasses should implement to check their consistency. The type of
9968 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009969 *
Romain Guy13922e02009-05-12 17:56:14 -07009970 * @param consistency The type of consistency. See ViewDebug for more information.
9971 *
9972 * @throws IllegalStateException if the view is in an inconsistent state.
9973 *
9974 * @hide
9975 */
9976 protected boolean onConsistencyCheck(int consistency) {
9977 boolean result = true;
9978
9979 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9980 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9981
9982 if (checkLayout) {
9983 if (getParent() == null) {
9984 result = false;
9985 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9986 "View " + this + " does not have a parent.");
9987 }
9988
9989 if (mAttachInfo == null) {
9990 result = false;
9991 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9992 "View " + this + " is not attached to a window.");
9993 }
9994 }
9995
9996 if (checkDrawing) {
9997 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9998 // from their draw() method
9999
10000 if ((mPrivateFlags & DRAWN) != DRAWN &&
10001 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
10002 result = false;
10003 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10004 "View " + this + " was invalidated but its drawing cache is valid.");
10005 }
10006 }
10007
10008 return result;
10009 }
10010
10011 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010012 * Prints information about this view in the log output, with the tag
10013 * {@link #VIEW_LOG_TAG}.
10014 *
10015 * @hide
10016 */
10017 public void debug() {
10018 debug(0);
10019 }
10020
10021 /**
10022 * Prints information about this view in the log output, with the tag
10023 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
10024 * indentation defined by the <code>depth</code>.
10025 *
10026 * @param depth the indentation level
10027 *
10028 * @hide
10029 */
10030 protected void debug(int depth) {
10031 String output = debugIndent(depth - 1);
10032
10033 output += "+ " + this;
10034 int id = getId();
10035 if (id != -1) {
10036 output += " (id=" + id + ")";
10037 }
10038 Object tag = getTag();
10039 if (tag != null) {
10040 output += " (tag=" + tag + ")";
10041 }
10042 Log.d(VIEW_LOG_TAG, output);
10043
10044 if ((mPrivateFlags & FOCUSED) != 0) {
10045 output = debugIndent(depth) + " FOCUSED";
10046 Log.d(VIEW_LOG_TAG, output);
10047 }
10048
10049 output = debugIndent(depth);
10050 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
10051 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
10052 + "} ";
10053 Log.d(VIEW_LOG_TAG, output);
10054
10055 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
10056 || mPaddingBottom != 0) {
10057 output = debugIndent(depth);
10058 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
10059 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
10060 Log.d(VIEW_LOG_TAG, output);
10061 }
10062
10063 output = debugIndent(depth);
10064 output += "mMeasureWidth=" + mMeasuredWidth +
10065 " mMeasureHeight=" + mMeasuredHeight;
10066 Log.d(VIEW_LOG_TAG, output);
10067
10068 output = debugIndent(depth);
10069 if (mLayoutParams == null) {
10070 output += "BAD! no layout params";
10071 } else {
10072 output = mLayoutParams.debug(output);
10073 }
10074 Log.d(VIEW_LOG_TAG, output);
10075
10076 output = debugIndent(depth);
10077 output += "flags={";
10078 output += View.printFlags(mViewFlags);
10079 output += "}";
10080 Log.d(VIEW_LOG_TAG, output);
10081
10082 output = debugIndent(depth);
10083 output += "privateFlags={";
10084 output += View.printPrivateFlags(mPrivateFlags);
10085 output += "}";
10086 Log.d(VIEW_LOG_TAG, output);
10087 }
10088
10089 /**
10090 * Creates an string of whitespaces used for indentation.
10091 *
10092 * @param depth the indentation level
10093 * @return a String containing (depth * 2 + 3) * 2 white spaces
10094 *
10095 * @hide
10096 */
10097 protected static String debugIndent(int depth) {
10098 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
10099 for (int i = 0; i < (depth * 2) + 3; i++) {
10100 spaces.append(' ').append(' ');
10101 }
10102 return spaces.toString();
10103 }
10104
10105 /**
10106 * <p>Return the offset of the widget's text baseline from the widget's top
10107 * boundary. If this widget does not support baseline alignment, this
10108 * method returns -1. </p>
10109 *
10110 * @return the offset of the baseline within the widget's bounds or -1
10111 * if baseline alignment is not supported
10112 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -070010113 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010114 public int getBaseline() {
10115 return -1;
10116 }
10117
10118 /**
10119 * Call this when something has changed which has invalidated the
10120 * layout of this view. This will schedule a layout pass of the view
10121 * tree.
10122 */
10123 public void requestLayout() {
10124 if (ViewDebug.TRACE_HIERARCHY) {
10125 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
10126 }
10127
10128 mPrivateFlags |= FORCE_LAYOUT;
10129
10130 if (mParent != null && !mParent.isLayoutRequested()) {
10131 mParent.requestLayout();
10132 }
10133 }
10134
10135 /**
10136 * Forces this view to be laid out during the next layout pass.
10137 * This method does not call requestLayout() or forceLayout()
10138 * on the parent.
10139 */
10140 public void forceLayout() {
10141 mPrivateFlags |= FORCE_LAYOUT;
10142 }
10143
10144 /**
10145 * <p>
10146 * This is called to find out how big a view should be. The parent
10147 * supplies constraint information in the width and height parameters.
10148 * </p>
10149 *
10150 * <p>
10151 * The actual mesurement work of a view is performed in
10152 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
10153 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
10154 * </p>
10155 *
10156 *
10157 * @param widthMeasureSpec Horizontal space requirements as imposed by the
10158 * parent
10159 * @param heightMeasureSpec Vertical space requirements as imposed by the
10160 * parent
10161 *
10162 * @see #onMeasure(int, int)
10163 */
10164 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
10165 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
10166 widthMeasureSpec != mOldWidthMeasureSpec ||
10167 heightMeasureSpec != mOldHeightMeasureSpec) {
10168
10169 // first clears the measured dimension flag
10170 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
10171
10172 if (ViewDebug.TRACE_HIERARCHY) {
10173 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
10174 }
10175
10176 // measure ourselves, this should set the measured dimension flag back
10177 onMeasure(widthMeasureSpec, heightMeasureSpec);
10178
10179 // flag not set, setMeasuredDimension() was not invoked, we raise
10180 // an exception to warn the developer
10181 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
10182 throw new IllegalStateException("onMeasure() did not set the"
10183 + " measured dimension by calling"
10184 + " setMeasuredDimension()");
10185 }
10186
10187 mPrivateFlags |= LAYOUT_REQUIRED;
10188 }
10189
10190 mOldWidthMeasureSpec = widthMeasureSpec;
10191 mOldHeightMeasureSpec = heightMeasureSpec;
10192 }
10193
10194 /**
10195 * <p>
10196 * Measure the view and its content to determine the measured width and the
10197 * measured height. This method is invoked by {@link #measure(int, int)} and
10198 * should be overriden by subclasses to provide accurate and efficient
10199 * measurement of their contents.
10200 * </p>
10201 *
10202 * <p>
10203 * <strong>CONTRACT:</strong> When overriding this method, you
10204 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
10205 * measured width and height of this view. Failure to do so will trigger an
10206 * <code>IllegalStateException</code>, thrown by
10207 * {@link #measure(int, int)}. Calling the superclass'
10208 * {@link #onMeasure(int, int)} is a valid use.
10209 * </p>
10210 *
10211 * <p>
10212 * The base class implementation of measure defaults to the background size,
10213 * unless a larger size is allowed by the MeasureSpec. Subclasses should
10214 * override {@link #onMeasure(int, int)} to provide better measurements of
10215 * their content.
10216 * </p>
10217 *
10218 * <p>
10219 * If this method is overridden, it is the subclass's responsibility to make
10220 * sure the measured height and width are at least the view's minimum height
10221 * and width ({@link #getSuggestedMinimumHeight()} and
10222 * {@link #getSuggestedMinimumWidth()}).
10223 * </p>
10224 *
10225 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
10226 * The requirements are encoded with
10227 * {@link android.view.View.MeasureSpec}.
10228 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
10229 * The requirements are encoded with
10230 * {@link android.view.View.MeasureSpec}.
10231 *
10232 * @see #getMeasuredWidth()
10233 * @see #getMeasuredHeight()
10234 * @see #setMeasuredDimension(int, int)
10235 * @see #getSuggestedMinimumHeight()
10236 * @see #getSuggestedMinimumWidth()
10237 * @see android.view.View.MeasureSpec#getMode(int)
10238 * @see android.view.View.MeasureSpec#getSize(int)
10239 */
10240 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10241 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
10242 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
10243 }
10244
10245 /**
10246 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
10247 * measured width and measured height. Failing to do so will trigger an
10248 * exception at measurement time.</p>
10249 *
Dianne Hackborn189ee182010-12-02 21:48:53 -080010250 * @param measuredWidth The measured width of this view. May be a complex
10251 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10252 * {@link #MEASURED_STATE_TOO_SMALL}.
10253 * @param measuredHeight The measured height of this view. May be a complex
10254 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10255 * {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010256 */
10257 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
10258 mMeasuredWidth = measuredWidth;
10259 mMeasuredHeight = measuredHeight;
10260
10261 mPrivateFlags |= MEASURED_DIMENSION_SET;
10262 }
10263
10264 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -080010265 * Merge two states as returned by {@link #getMeasuredState()}.
10266 * @param curState The current state as returned from a view or the result
10267 * of combining multiple views.
10268 * @param newState The new view state to combine.
10269 * @return Returns a new integer reflecting the combination of the two
10270 * states.
10271 */
10272 public static int combineMeasuredStates(int curState, int newState) {
10273 return curState | newState;
10274 }
10275
10276 /**
10277 * Version of {@link #resolveSizeAndState(int, int, int)}
10278 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
10279 */
10280 public static int resolveSize(int size, int measureSpec) {
10281 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
10282 }
10283
10284 /**
10285 * Utility to reconcile a desired size and state, with constraints imposed
10286 * by a MeasureSpec. Will take the desired size, unless a different size
10287 * is imposed by the constraints. The returned value is a compound integer,
10288 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
10289 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
10290 * size is smaller than the size the view wants to be.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010291 *
10292 * @param size How big the view wants to be
10293 * @param measureSpec Constraints imposed by the parent
Dianne Hackborn189ee182010-12-02 21:48:53 -080010294 * @return Size information bit mask as defined by
10295 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010296 */
Dianne Hackborn189ee182010-12-02 21:48:53 -080010297 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010298 int result = size;
10299 int specMode = MeasureSpec.getMode(measureSpec);
10300 int specSize = MeasureSpec.getSize(measureSpec);
10301 switch (specMode) {
10302 case MeasureSpec.UNSPECIFIED:
10303 result = size;
10304 break;
10305 case MeasureSpec.AT_MOST:
Dianne Hackborn189ee182010-12-02 21:48:53 -080010306 if (specSize < size) {
10307 result = specSize | MEASURED_STATE_TOO_SMALL;
10308 } else {
10309 result = size;
10310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010311 break;
10312 case MeasureSpec.EXACTLY:
10313 result = specSize;
10314 break;
10315 }
Dianne Hackborn189ee182010-12-02 21:48:53 -080010316 return result | (childMeasuredState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010317 }
10318
10319 /**
10320 * Utility to return a default size. Uses the supplied size if the
10321 * MeasureSpec imposed no contraints. Will get larger if allowed
10322 * by the MeasureSpec.
10323 *
10324 * @param size Default size for this view
10325 * @param measureSpec Constraints imposed by the parent
10326 * @return The size this view should be.
10327 */
10328 public static int getDefaultSize(int size, int measureSpec) {
10329 int result = size;
10330 int specMode = MeasureSpec.getMode(measureSpec);
10331 int specSize = MeasureSpec.getSize(measureSpec);
10332
10333 switch (specMode) {
10334 case MeasureSpec.UNSPECIFIED:
10335 result = size;
10336 break;
10337 case MeasureSpec.AT_MOST:
10338 case MeasureSpec.EXACTLY:
10339 result = specSize;
10340 break;
10341 }
10342 return result;
10343 }
10344
10345 /**
10346 * Returns the suggested minimum height that the view should use. This
10347 * returns the maximum of the view's minimum height
10348 * and the background's minimum height
10349 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10350 * <p>
10351 * When being used in {@link #onMeasure(int, int)}, the caller should still
10352 * ensure the returned height is within the requirements of the parent.
10353 *
10354 * @return The suggested minimum height of the view.
10355 */
10356 protected int getSuggestedMinimumHeight() {
10357 int suggestedMinHeight = mMinHeight;
10358
10359 if (mBGDrawable != null) {
10360 final int bgMinHeight = mBGDrawable.getMinimumHeight();
10361 if (suggestedMinHeight < bgMinHeight) {
10362 suggestedMinHeight = bgMinHeight;
10363 }
10364 }
10365
10366 return suggestedMinHeight;
10367 }
10368
10369 /**
10370 * Returns the suggested minimum width that the view should use. This
10371 * returns the maximum of the view's minimum width)
10372 * and the background's minimum width
10373 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10374 * <p>
10375 * When being used in {@link #onMeasure(int, int)}, the caller should still
10376 * ensure the returned width is within the requirements of the parent.
10377 *
10378 * @return The suggested minimum width of the view.
10379 */
10380 protected int getSuggestedMinimumWidth() {
10381 int suggestedMinWidth = mMinWidth;
10382
10383 if (mBGDrawable != null) {
10384 final int bgMinWidth = mBGDrawable.getMinimumWidth();
10385 if (suggestedMinWidth < bgMinWidth) {
10386 suggestedMinWidth = bgMinWidth;
10387 }
10388 }
10389
10390 return suggestedMinWidth;
10391 }
10392
10393 /**
10394 * Sets the minimum height of the view. It is not guaranteed the view will
10395 * be able to achieve this minimum height (for example, if its parent layout
10396 * constrains it with less available height).
10397 *
10398 * @param minHeight The minimum height the view will try to be.
10399 */
10400 public void setMinimumHeight(int minHeight) {
10401 mMinHeight = minHeight;
10402 }
10403
10404 /**
10405 * Sets the minimum width of the view. It is not guaranteed the view will
10406 * be able to achieve this minimum width (for example, if its parent layout
10407 * constrains it with less available width).
10408 *
10409 * @param minWidth The minimum width the view will try to be.
10410 */
10411 public void setMinimumWidth(int minWidth) {
10412 mMinWidth = minWidth;
10413 }
10414
10415 /**
10416 * Get the animation currently associated with this view.
10417 *
10418 * @return The animation that is currently playing or
10419 * scheduled to play for this view.
10420 */
10421 public Animation getAnimation() {
10422 return mCurrentAnimation;
10423 }
10424
10425 /**
10426 * Start the specified animation now.
10427 *
10428 * @param animation the animation to start now
10429 */
10430 public void startAnimation(Animation animation) {
10431 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10432 setAnimation(animation);
10433 invalidate();
10434 }
10435
10436 /**
10437 * Cancels any animations for this view.
10438 */
10439 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -080010440 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -080010441 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -080010442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010443 mCurrentAnimation = null;
10444 }
10445
10446 /**
10447 * Sets the next animation to play for this view.
10448 * If you want the animation to play immediately, use
10449 * startAnimation. This method provides allows fine-grained
10450 * control over the start time and invalidation, but you
10451 * must make sure that 1) the animation has a start time set, and
10452 * 2) the view will be invalidated when the animation is supposed to
10453 * start.
10454 *
10455 * @param animation The next animation, or null.
10456 */
10457 public void setAnimation(Animation animation) {
10458 mCurrentAnimation = animation;
10459 if (animation != null) {
10460 animation.reset();
10461 }
10462 }
10463
10464 /**
10465 * Invoked by a parent ViewGroup to notify the start of the animation
10466 * currently associated with this view. If you override this method,
10467 * always call super.onAnimationStart();
10468 *
10469 * @see #setAnimation(android.view.animation.Animation)
10470 * @see #getAnimation()
10471 */
10472 protected void onAnimationStart() {
10473 mPrivateFlags |= ANIMATION_STARTED;
10474 }
10475
10476 /**
10477 * Invoked by a parent ViewGroup to notify the end of the animation
10478 * currently associated with this view. If you override this method,
10479 * always call super.onAnimationEnd();
10480 *
10481 * @see #setAnimation(android.view.animation.Animation)
10482 * @see #getAnimation()
10483 */
10484 protected void onAnimationEnd() {
10485 mPrivateFlags &= ~ANIMATION_STARTED;
10486 }
10487
10488 /**
10489 * Invoked if there is a Transform that involves alpha. Subclass that can
10490 * draw themselves with the specified alpha should return true, and then
10491 * respect that alpha when their onDraw() is called. If this returns false
10492 * then the view may be redirected to draw into an offscreen buffer to
10493 * fulfill the request, which will look fine, but may be slower than if the
10494 * subclass handles it internally. The default implementation returns false.
10495 *
10496 * @param alpha The alpha (0..255) to apply to the view's drawing
10497 * @return true if the view can draw with the specified alpha.
10498 */
10499 protected boolean onSetAlpha(int alpha) {
10500 return false;
10501 }
10502
10503 /**
10504 * This is used by the RootView to perform an optimization when
10505 * the view hierarchy contains one or several SurfaceView.
10506 * SurfaceView is always considered transparent, but its children are not,
10507 * therefore all View objects remove themselves from the global transparent
10508 * region (passed as a parameter to this function).
10509 *
10510 * @param region The transparent region for this ViewRoot (window).
10511 *
10512 * @return Returns true if the effective visibility of the view at this
10513 * point is opaque, regardless of the transparent region; returns false
10514 * if it is possible for underlying windows to be seen behind the view.
10515 *
10516 * {@hide}
10517 */
10518 public boolean gatherTransparentRegion(Region region) {
10519 final AttachInfo attachInfo = mAttachInfo;
10520 if (region != null && attachInfo != null) {
10521 final int pflags = mPrivateFlags;
10522 if ((pflags & SKIP_DRAW) == 0) {
10523 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10524 // remove it from the transparent region.
10525 final int[] location = attachInfo.mTransparentLocation;
10526 getLocationInWindow(location);
10527 region.op(location[0], location[1], location[0] + mRight - mLeft,
10528 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10529 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10530 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10531 // exists, so we remove the background drawable's non-transparent
10532 // parts from this transparent region.
10533 applyDrawableToTransparentRegion(mBGDrawable, region);
10534 }
10535 }
10536 return true;
10537 }
10538
10539 /**
10540 * Play a sound effect for this view.
10541 *
10542 * <p>The framework will play sound effects for some built in actions, such as
10543 * clicking, but you may wish to play these effects in your widget,
10544 * for instance, for internal navigation.
10545 *
10546 * <p>The sound effect will only be played if sound effects are enabled by the user, and
10547 * {@link #isSoundEffectsEnabled()} is true.
10548 *
10549 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10550 */
10551 public void playSoundEffect(int soundConstant) {
10552 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10553 return;
10554 }
10555 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10556 }
10557
10558 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010559 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010560 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010561 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010562 *
10563 * <p>The framework will provide haptic feedback for some built in actions,
10564 * such as long presses, but you may wish to provide feedback for your
10565 * own widget.
10566 *
10567 * <p>The feedback will only be performed if
10568 * {@link #isHapticFeedbackEnabled()} is true.
10569 *
10570 * @param feedbackConstant One of the constants defined in
10571 * {@link HapticFeedbackConstants}
10572 */
10573 public boolean performHapticFeedback(int feedbackConstant) {
10574 return performHapticFeedback(feedbackConstant, 0);
10575 }
10576
10577 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010578 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010579 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010580 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010581 *
10582 * @param feedbackConstant One of the constants defined in
10583 * {@link HapticFeedbackConstants}
10584 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10585 */
10586 public boolean performHapticFeedback(int feedbackConstant, int flags) {
10587 if (mAttachInfo == null) {
10588 return false;
10589 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010590 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010591 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010592 && !isHapticFeedbackEnabled()) {
10593 return false;
10594 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010595 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10596 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010597 }
10598
10599 /**
Christopher Tate2c095f32010-10-04 14:13:40 -070010600 * !!! TODO: real docs
10601 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010602 * The base class implementation makes the shadow the same size and appearance
Christopher Tate2c095f32010-10-04 14:13:40 -070010603 * as the view itself, and positions it with its center at the touch point.
10604 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010605 public static class DragShadowBuilder {
Christopher Tatea0374192010-10-05 13:06:41 -070010606 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010607
10608 /**
Christopher Tate17ed60c2011-01-18 12:50:26 -080010609 * Construct a shadow builder object for use with the given View object. The
10610 * default implementation will construct a drag shadow the same size and
10611 * appearance as the supplied View.
10612 *
10613 * @param view A view within the application's layout whose appearance
10614 * should be replicated as the drag shadow.
Christopher Tate2c095f32010-10-04 14:13:40 -070010615 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010616 public DragShadowBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010617 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010618 }
10619
Christopher Tate17ed60c2011-01-18 12:50:26 -080010620 /**
10621 * Construct a shadow builder object with no associated View. This
10622 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
10623 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
10624 * to supply the drag shadow's dimensions and appearance without
10625 * reference to any View object.
10626 */
10627 public DragShadowBuilder() {
10628 mView = new WeakReference<View>(null);
10629 }
10630
10631 /**
10632 * Returns the View object that had been passed to the
10633 * {@link #View.DragShadowBuilder(View)}
10634 * constructor. If that View parameter was {@code null} or if the
10635 * {@link #View.DragShadowBuilder()}
10636 * constructor was used to instantiate the builder object, this method will return
10637 * null.
10638 *
10639 * @return The View object associate with this builder object.
10640 */
Chris Tate6b391282010-10-14 15:48:59 -070010641 final public View getView() {
10642 return mView.get();
10643 }
10644
Christopher Tate2c095f32010-10-04 14:13:40 -070010645 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010646 * Provide the draggable-shadow metrics for the operation: the dimensions of
10647 * the shadow image itself, and the point within that shadow that should
Christopher Tate2c095f32010-10-04 14:13:40 -070010648 * be centered under the touch location while dragging.
10649 * <p>
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010650 * The default implementation sets the dimensions of the shadow to be the
Christopher Tate17ed60c2011-01-18 12:50:26 -080010651 * same as the dimensions of the View object that had been supplied to the
10652 * {@link #View.DragShadowBuilder(View)} constructor
10653 * when the builder object was instantiated, and centers the shadow under the touch
10654 * point.
Christopher Tate2c095f32010-10-04 14:13:40 -070010655 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010656 * @param shadowSize The application should set the {@code x} member of this
10657 * parameter to the desired shadow width, and the {@code y} member to
Christopher Tate2c095f32010-10-04 14:13:40 -070010658 * the desired height.
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010659 * @param shadowTouchPoint The application should set this point to be the
10660 * location within the shadow that should track directly underneath
Christopher Tate2c095f32010-10-04 14:13:40 -070010661 * the touch point on the screen during a drag.
10662 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010663 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070010664 final View view = mView.get();
10665 if (view != null) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010666 shadowSize.set(view.getWidth(), view.getHeight());
10667 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
Christopher Tatea0374192010-10-05 13:06:41 -070010668 } else {
10669 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10670 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010671 }
10672
10673 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010674 * Draw the shadow image for the upcoming drag. The shadow canvas was
10675 * created with the dimensions supplied by the
10676 * {@link #onProvideShadowMetrics(Point, Point)} callback.
Christopher Tate17ed60c2011-01-18 12:50:26 -080010677 * <p>
10678 * The default implementation replicates the appearance of the View object
10679 * that had been supplied to the
10680 * {@link #View.DragShadowBuilder(View)}
10681 * constructor when the builder object was instantiated.
Christopher Tate2c095f32010-10-04 14:13:40 -070010682 *
10683 * @param canvas
10684 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010685 public void onDrawShadow(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070010686 final View view = mView.get();
10687 if (view != null) {
10688 view.draw(canvas);
10689 } else {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010690 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
Christopher Tatea0374192010-10-05 13:06:41 -070010691 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010692 }
10693 }
10694
10695 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010696 * Drag and drop. App calls startDrag(), then callbacks to the shadow builder's
10697 * {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} and
10698 * {@link DragShadowBuilder#onDrawShadow(Canvas)} methods happen, then the drag
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010699 * operation is handed over to the OS.
Christopher Tatea53146c2010-09-07 11:57:52 -070010700 * !!! TODO: real docs
Christopher Tate407b4e92010-11-30 17:14:08 -080010701 *
10702 * @param data !!! TODO
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010703 * @param shadowBuilder !!! TODO
Christopher Tate407b4e92010-11-30 17:14:08 -080010704 * @param myLocalState An arbitrary object that will be passed as part of every DragEvent
10705 * delivered to the calling application during the course of the current drag operation.
10706 * This object is private to the application that called startDrag(), and is not
10707 * visible to other applications. It provides a lightweight way for the application to
10708 * propagate information from the initiator to the recipient of a drag within its own
10709 * application; for example, to help disambiguate between 'copy' and 'move' semantics.
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010710 * @param flags Flags affecting the drag operation. At present no flags are defined;
10711 * pass 0 for this parameter.
Christopher Tate407b4e92010-11-30 17:14:08 -080010712 * @return {@code true} if the drag operation was initiated successfully; {@code false} if
10713 * an error prevented the drag from taking place.
Christopher Tatea53146c2010-09-07 11:57:52 -070010714 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010715 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010716 Object myLocalState, int flags) {
Christopher Tate2c095f32010-10-04 14:13:40 -070010717 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010718 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
Christopher Tatea53146c2010-09-07 11:57:52 -070010719 }
10720 boolean okay = false;
10721
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010722 Point shadowSize = new Point();
10723 Point shadowTouchPoint = new Point();
10724 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
Christopher Tate2c095f32010-10-04 14:13:40 -070010725
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010726 if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
10727 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
10728 throw new IllegalStateException("Drag shadow dimensions must not be negative");
Christopher Tate2c095f32010-10-04 14:13:40 -070010729 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010730
Chris Tatea32dcf72010-10-14 12:13:50 -070010731 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010732 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
10733 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
Chris Tatea32dcf72010-10-14 12:13:50 -070010734 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010735 Surface surface = new Surface();
10736 try {
10737 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010738 flags, shadowSize.x, shadowSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070010739 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070010740 + " surface=" + surface);
10741 if (token != null) {
10742 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070010743 try {
Chris Tate6b391282010-10-14 15:48:59 -070010744 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010745 shadowBuilder.onDrawShadow(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070010746 } finally {
10747 surface.unlockCanvasAndPost(canvas);
10748 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010749
Christopher Tate407b4e92010-11-30 17:14:08 -080010750 final ViewRoot root = getViewRoot();
10751
10752 // Cache the local state object for delivery with DragEvents
10753 root.setLocalDragState(myLocalState);
10754
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010755 // repurpose 'shadowSize' for the last touch point
10756 root.getLastTouchPoint(shadowSize);
Christopher Tate2c095f32010-10-04 14:13:40 -070010757
Christopher Tatea53146c2010-09-07 11:57:52 -070010758 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010759 shadowSize.x, shadowSize.y,
10760 shadowTouchPoint.x, shadowTouchPoint.y, data);
Christopher Tate2c095f32010-10-04 14:13:40 -070010761 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070010762 }
10763 } catch (Exception e) {
10764 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
10765 surface.destroy();
10766 }
10767
10768 return okay;
10769 }
10770
Christopher Tatea53146c2010-09-07 11:57:52 -070010771 /**
10772 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
10773 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
10774 *
10775 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
10776 * being dragged. onDragEvent() should return 'true' if the view can handle
10777 * a drop of that content. A view that returns 'false' here will receive no
10778 * further calls to onDragEvent() about the drag/drop operation.
10779 *
10780 * For DRAG_ENTERED, event.getClipDescription() describes the content being
10781 * dragged. This will be the same content description passed in the
10782 * DRAG_STARTED_EVENT invocation.
10783 *
10784 * For DRAG_EXITED, event.getClipDescription() describes the content being
10785 * dragged. This will be the same content description passed in the
10786 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
10787 * drag-acceptance visual state.
10788 *
10789 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10790 * coordinates of the current drag point. The view must return 'true' if it
10791 * can accept a drop of the current drag content, false otherwise.
10792 *
10793 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10794 * within the view; also, event.getClipData() returns the full data payload
10795 * being dropped. The view should return 'true' if it consumed the dropped
10796 * content, 'false' if it did not.
10797 *
10798 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
10799 * to its normal visual state.
10800 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010801 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070010802 return false;
10803 }
10804
10805 /**
10806 * Views typically don't need to override dispatchDragEvent(); it just calls
Chris Tate32affef2010-10-18 15:29:21 -070010807 * onDragEvent(event) and passes the result up appropriately.
Christopher Tatea53146c2010-09-07 11:57:52 -070010808 */
10809 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070010810 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10811 && mOnDragListener.onDrag(this, event)) {
10812 return true;
10813 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010814 return onDragEvent(event);
10815 }
10816
10817 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070010818 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
10819 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070010820 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070010821 */
10822 public void onCloseSystemDialogs(String reason) {
10823 }
10824
10825 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010826 * Given a Drawable whose bounds have been set to draw into this view,
10827 * update a Region being computed for {@link #gatherTransparentRegion} so
10828 * that any non-transparent parts of the Drawable are removed from the
10829 * given transparent region.
10830 *
10831 * @param dr The Drawable whose transparency is to be applied to the region.
10832 * @param region A Region holding the current transparency information,
10833 * where any parts of the region that are set are considered to be
10834 * transparent. On return, this region will be modified to have the
10835 * transparency information reduced by the corresponding parts of the
10836 * Drawable that are not transparent.
10837 * {@hide}
10838 */
10839 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
10840 if (DBG) {
10841 Log.i("View", "Getting transparent region for: " + this);
10842 }
10843 final Region r = dr.getTransparentRegion();
10844 final Rect db = dr.getBounds();
10845 final AttachInfo attachInfo = mAttachInfo;
10846 if (r != null && attachInfo != null) {
10847 final int w = getRight()-getLeft();
10848 final int h = getBottom()-getTop();
10849 if (db.left > 0) {
10850 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
10851 r.op(0, 0, db.left, h, Region.Op.UNION);
10852 }
10853 if (db.right < w) {
10854 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
10855 r.op(db.right, 0, w, h, Region.Op.UNION);
10856 }
10857 if (db.top > 0) {
10858 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
10859 r.op(0, 0, w, db.top, Region.Op.UNION);
10860 }
10861 if (db.bottom < h) {
10862 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
10863 r.op(0, db.bottom, w, h, Region.Op.UNION);
10864 }
10865 final int[] location = attachInfo.mTransparentLocation;
10866 getLocationInWindow(location);
10867 r.translate(location[0], location[1]);
10868 region.op(r, Region.Op.INTERSECT);
10869 } else {
10870 region.op(db, Region.Op.DIFFERENCE);
10871 }
10872 }
10873
Adam Powelle14579b2009-12-16 18:39:52 -080010874 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010875 mHasPerformedLongPress = false;
10876
10877 if (mPendingCheckForLongPress == null) {
10878 mPendingCheckForLongPress = new CheckForLongPress();
10879 }
10880 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080010881 postDelayed(mPendingCheckForLongPress,
10882 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010883 }
10884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010885 /**
10886 * Inflate a view from an XML resource. This convenience method wraps the {@link
10887 * LayoutInflater} class, which provides a full range of options for view inflation.
10888 *
10889 * @param context The Context object for your activity or application.
10890 * @param resource The resource ID to inflate
10891 * @param root A view group that will be the parent. Used to properly inflate the
10892 * layout_* parameters.
10893 * @see LayoutInflater
10894 */
10895 public static View inflate(Context context, int resource, ViewGroup root) {
10896 LayoutInflater factory = LayoutInflater.from(context);
10897 return factory.inflate(resource, root);
10898 }
Romain Guy33e72ae2010-07-17 12:40:29 -070010899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010900 /**
Adam Powell637d3372010-08-25 14:37:03 -070010901 * Scroll the view with standard behavior for scrolling beyond the normal
10902 * content boundaries. Views that call this method should override
10903 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
10904 * results of an over-scroll operation.
10905 *
10906 * Views can use this method to handle any touch or fling-based scrolling.
10907 *
10908 * @param deltaX Change in X in pixels
10909 * @param deltaY Change in Y in pixels
10910 * @param scrollX Current X scroll value in pixels before applying deltaX
10911 * @param scrollY Current Y scroll value in pixels before applying deltaY
10912 * @param scrollRangeX Maximum content scroll range along the X axis
10913 * @param scrollRangeY Maximum content scroll range along the Y axis
10914 * @param maxOverScrollX Number of pixels to overscroll by in either direction
10915 * along the X axis.
10916 * @param maxOverScrollY Number of pixels to overscroll by in either direction
10917 * along the Y axis.
10918 * @param isTouchEvent true if this scroll operation is the result of a touch event.
10919 * @return true if scrolling was clamped to an over-scroll boundary along either
10920 * axis, false otherwise.
10921 */
10922 protected boolean overScrollBy(int deltaX, int deltaY,
10923 int scrollX, int scrollY,
10924 int scrollRangeX, int scrollRangeY,
10925 int maxOverScrollX, int maxOverScrollY,
10926 boolean isTouchEvent) {
10927 final int overScrollMode = mOverScrollMode;
10928 final boolean canScrollHorizontal =
10929 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
10930 final boolean canScrollVertical =
10931 computeVerticalScrollRange() > computeVerticalScrollExtent();
10932 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
10933 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
10934 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
10935 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
10936
10937 int newScrollX = scrollX + deltaX;
10938 if (!overScrollHorizontal) {
10939 maxOverScrollX = 0;
10940 }
10941
10942 int newScrollY = scrollY + deltaY;
10943 if (!overScrollVertical) {
10944 maxOverScrollY = 0;
10945 }
10946
10947 // Clamp values if at the limits and record
10948 final int left = -maxOverScrollX;
10949 final int right = maxOverScrollX + scrollRangeX;
10950 final int top = -maxOverScrollY;
10951 final int bottom = maxOverScrollY + scrollRangeY;
10952
10953 boolean clampedX = false;
10954 if (newScrollX > right) {
10955 newScrollX = right;
10956 clampedX = true;
10957 } else if (newScrollX < left) {
10958 newScrollX = left;
10959 clampedX = true;
10960 }
10961
10962 boolean clampedY = false;
10963 if (newScrollY > bottom) {
10964 newScrollY = bottom;
10965 clampedY = true;
10966 } else if (newScrollY < top) {
10967 newScrollY = top;
10968 clampedY = true;
10969 }
10970
10971 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
10972
10973 return clampedX || clampedY;
10974 }
10975
10976 /**
10977 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
10978 * respond to the results of an over-scroll operation.
10979 *
10980 * @param scrollX New X scroll value in pixels
10981 * @param scrollY New Y scroll value in pixels
10982 * @param clampedX True if scrollX was clamped to an over-scroll boundary
10983 * @param clampedY True if scrollY was clamped to an over-scroll boundary
10984 */
10985 protected void onOverScrolled(int scrollX, int scrollY,
10986 boolean clampedX, boolean clampedY) {
10987 // Intentionally empty.
10988 }
10989
10990 /**
10991 * Returns the over-scroll mode for this view. The result will be
10992 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10993 * (allow over-scrolling only if the view content is larger than the container),
10994 * or {@link #OVER_SCROLL_NEVER}.
10995 *
10996 * @return This view's over-scroll mode.
10997 */
10998 public int getOverScrollMode() {
10999 return mOverScrollMode;
11000 }
11001
11002 /**
11003 * Set the over-scroll mode for this view. Valid over-scroll modes are
11004 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11005 * (allow over-scrolling only if the view content is larger than the container),
11006 * or {@link #OVER_SCROLL_NEVER}.
11007 *
11008 * Setting the over-scroll mode of a view will have an effect only if the
11009 * view is capable of scrolling.
11010 *
11011 * @param overScrollMode The new over-scroll mode for this view.
11012 */
11013 public void setOverScrollMode(int overScrollMode) {
11014 if (overScrollMode != OVER_SCROLL_ALWAYS &&
11015 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
11016 overScrollMode != OVER_SCROLL_NEVER) {
11017 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
11018 }
11019 mOverScrollMode = overScrollMode;
11020 }
11021
11022 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
11024 * Each MeasureSpec represents a requirement for either the width or the height.
11025 * A MeasureSpec is comprised of a size and a mode. There are three possible
11026 * modes:
11027 * <dl>
11028 * <dt>UNSPECIFIED</dt>
11029 * <dd>
11030 * The parent has not imposed any constraint on the child. It can be whatever size
11031 * it wants.
11032 * </dd>
11033 *
11034 * <dt>EXACTLY</dt>
11035 * <dd>
11036 * The parent has determined an exact size for the child. The child is going to be
11037 * given those bounds regardless of how big it wants to be.
11038 * </dd>
11039 *
11040 * <dt>AT_MOST</dt>
11041 * <dd>
11042 * The child can be as large as it wants up to the specified size.
11043 * </dd>
11044 * </dl>
11045 *
11046 * MeasureSpecs are implemented as ints to reduce object allocation. This class
11047 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
11048 */
11049 public static class MeasureSpec {
11050 private static final int MODE_SHIFT = 30;
11051 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
11052
11053 /**
11054 * Measure specification mode: The parent has not imposed any constraint
11055 * on the child. It can be whatever size it wants.
11056 */
11057 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
11058
11059 /**
11060 * Measure specification mode: The parent has determined an exact size
11061 * for the child. The child is going to be given those bounds regardless
11062 * of how big it wants to be.
11063 */
11064 public static final int EXACTLY = 1 << MODE_SHIFT;
11065
11066 /**
11067 * Measure specification mode: The child can be as large as it wants up
11068 * to the specified size.
11069 */
11070 public static final int AT_MOST = 2 << MODE_SHIFT;
11071
11072 /**
11073 * Creates a measure specification based on the supplied size and mode.
11074 *
11075 * The mode must always be one of the following:
11076 * <ul>
11077 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
11078 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
11079 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
11080 * </ul>
11081 *
11082 * @param size the size of the measure specification
11083 * @param mode the mode of the measure specification
11084 * @return the measure specification based on size and mode
11085 */
11086 public static int makeMeasureSpec(int size, int mode) {
11087 return size + mode;
11088 }
11089
11090 /**
11091 * Extracts the mode from the supplied measure specification.
11092 *
11093 * @param measureSpec the measure specification to extract the mode from
11094 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
11095 * {@link android.view.View.MeasureSpec#AT_MOST} or
11096 * {@link android.view.View.MeasureSpec#EXACTLY}
11097 */
11098 public static int getMode(int measureSpec) {
11099 return (measureSpec & MODE_MASK);
11100 }
11101
11102 /**
11103 * Extracts the size from the supplied measure specification.
11104 *
11105 * @param measureSpec the measure specification to extract the size from
11106 * @return the size in pixels defined in the supplied measure specification
11107 */
11108 public static int getSize(int measureSpec) {
11109 return (measureSpec & ~MODE_MASK);
11110 }
11111
11112 /**
11113 * Returns a String representation of the specified measure
11114 * specification.
11115 *
11116 * @param measureSpec the measure specification to convert to a String
11117 * @return a String with the following format: "MeasureSpec: MODE SIZE"
11118 */
11119 public static String toString(int measureSpec) {
11120 int mode = getMode(measureSpec);
11121 int size = getSize(measureSpec);
11122
11123 StringBuilder sb = new StringBuilder("MeasureSpec: ");
11124
11125 if (mode == UNSPECIFIED)
11126 sb.append("UNSPECIFIED ");
11127 else if (mode == EXACTLY)
11128 sb.append("EXACTLY ");
11129 else if (mode == AT_MOST)
11130 sb.append("AT_MOST ");
11131 else
11132 sb.append(mode).append(" ");
11133
11134 sb.append(size);
11135 return sb.toString();
11136 }
11137 }
11138
11139 class CheckForLongPress implements Runnable {
11140
11141 private int mOriginalWindowAttachCount;
11142
11143 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011144 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011145 && mOriginalWindowAttachCount == mWindowAttachCount) {
11146 if (performLongClick()) {
11147 mHasPerformedLongPress = true;
11148 }
11149 }
11150 }
11151
11152 public void rememberWindowAttachCount() {
11153 mOriginalWindowAttachCount = mWindowAttachCount;
11154 }
11155 }
Adam Powelle14579b2009-12-16 18:39:52 -080011156
11157 private final class CheckForTap implements Runnable {
11158 public void run() {
11159 mPrivateFlags &= ~PREPRESSED;
11160 mPrivateFlags |= PRESSED;
11161 refreshDrawableState();
11162 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
11163 postCheckForLongClick(ViewConfiguration.getTapTimeout());
11164 }
11165 }
11166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167
Adam Powella35d7682010-03-12 14:48:13 -080011168 private final class PerformClick implements Runnable {
11169 public void run() {
11170 performClick();
11171 }
11172 }
11173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011174 /**
11175 * Interface definition for a callback to be invoked when a key event is
11176 * dispatched to this view. The callback will be invoked before the key
11177 * event is given to the view.
11178 */
11179 public interface OnKeyListener {
11180 /**
11181 * Called when a key is dispatched to a view. This allows listeners to
11182 * get a chance to respond before the target view.
11183 *
11184 * @param v The view the key has been dispatched to.
11185 * @param keyCode The code for the physical key that was pressed
11186 * @param event The KeyEvent object containing full information about
11187 * the event.
11188 * @return True if the listener has consumed the event, false otherwise.
11189 */
11190 boolean onKey(View v, int keyCode, KeyEvent event);
11191 }
11192
11193 /**
11194 * Interface definition for a callback to be invoked when a touch event is
11195 * dispatched to this view. The callback will be invoked before the touch
11196 * event is given to the view.
11197 */
11198 public interface OnTouchListener {
11199 /**
11200 * Called when a touch event is dispatched to a view. This allows listeners to
11201 * get a chance to respond before the target view.
11202 *
11203 * @param v The view the touch event has been dispatched to.
11204 * @param event The MotionEvent object containing full information about
11205 * the event.
11206 * @return True if the listener has consumed the event, false otherwise.
11207 */
11208 boolean onTouch(View v, MotionEvent event);
11209 }
11210
11211 /**
11212 * Interface definition for a callback to be invoked when a view has been clicked and held.
11213 */
11214 public interface OnLongClickListener {
11215 /**
11216 * Called when a view has been clicked and held.
11217 *
11218 * @param v The view that was clicked and held.
11219 *
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -080011220 * @return true if the callback consumed the long click, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011221 */
11222 boolean onLongClick(View v);
11223 }
11224
11225 /**
Chris Tate32affef2010-10-18 15:29:21 -070011226 * Interface definition for a callback to be invoked when a drag is being dispatched
11227 * to this view. The callback will be invoked before the hosting view's own
11228 * onDrag(event) method. If the listener wants to fall back to the hosting view's
11229 * onDrag(event) behavior, it should return 'false' from this callback.
11230 */
11231 public interface OnDragListener {
11232 /**
11233 * Called when a drag event is dispatched to a view. This allows listeners
11234 * to get a chance to override base View behavior.
11235 *
11236 * @param v The view the drag has been dispatched to.
11237 * @param event The DragEvent object containing full information
11238 * about the event.
11239 * @return true if the listener consumed the DragEvent, false in order to fall
11240 * back to the view's default handling.
11241 */
11242 boolean onDrag(View v, DragEvent event);
11243 }
11244
11245 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011246 * Interface definition for a callback to be invoked when the focus state of
11247 * a view changed.
11248 */
11249 public interface OnFocusChangeListener {
11250 /**
11251 * Called when the focus state of a view has changed.
11252 *
11253 * @param v The view whose state has changed.
11254 * @param hasFocus The new focus state of v.
11255 */
11256 void onFocusChange(View v, boolean hasFocus);
11257 }
11258
11259 /**
11260 * Interface definition for a callback to be invoked when a view is clicked.
11261 */
11262 public interface OnClickListener {
11263 /**
11264 * Called when a view has been clicked.
11265 *
11266 * @param v The view that was clicked.
11267 */
11268 void onClick(View v);
11269 }
11270
11271 /**
11272 * Interface definition for a callback to be invoked when the context menu
11273 * for this view is being built.
11274 */
11275 public interface OnCreateContextMenuListener {
11276 /**
11277 * Called when the context menu for this view is being built. It is not
11278 * safe to hold onto the menu after this method returns.
11279 *
11280 * @param menu The context menu that is being built
11281 * @param v The view for which the context menu is being built
11282 * @param menuInfo Extra information about the item for which the
11283 * context menu should be shown. This information will vary
11284 * depending on the class of v.
11285 */
11286 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
11287 }
11288
11289 private final class UnsetPressedState implements Runnable {
11290 public void run() {
11291 setPressed(false);
11292 }
11293 }
11294
11295 /**
11296 * Base class for derived classes that want to save and restore their own
11297 * state in {@link android.view.View#onSaveInstanceState()}.
11298 */
11299 public static class BaseSavedState extends AbsSavedState {
11300 /**
11301 * Constructor used when reading from a parcel. Reads the state of the superclass.
11302 *
11303 * @param source
11304 */
11305 public BaseSavedState(Parcel source) {
11306 super(source);
11307 }
11308
11309 /**
11310 * Constructor called by derived classes when creating their SavedState objects
11311 *
11312 * @param superState The state of the superclass of this view
11313 */
11314 public BaseSavedState(Parcelable superState) {
11315 super(superState);
11316 }
11317
11318 public static final Parcelable.Creator<BaseSavedState> CREATOR =
11319 new Parcelable.Creator<BaseSavedState>() {
11320 public BaseSavedState createFromParcel(Parcel in) {
11321 return new BaseSavedState(in);
11322 }
11323
11324 public BaseSavedState[] newArray(int size) {
11325 return new BaseSavedState[size];
11326 }
11327 };
11328 }
11329
11330 /**
11331 * A set of information given to a view when it is attached to its parent
11332 * window.
11333 */
11334 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011335 interface Callbacks {
11336 void playSoundEffect(int effectId);
11337 boolean performHapticFeedback(int effectId, boolean always);
11338 }
11339
11340 /**
11341 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11342 * to a Handler. This class contains the target (View) to invalidate and
11343 * the coordinates of the dirty rectangle.
11344 *
11345 * For performance purposes, this class also implements a pool of up to
11346 * POOL_LIMIT objects that get reused. This reduces memory allocations
11347 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011348 */
Romain Guyd928d682009-03-31 17:52:16 -070011349 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011350 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070011351 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11352 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070011353 public InvalidateInfo newInstance() {
11354 return new InvalidateInfo();
11355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011356
Romain Guyd928d682009-03-31 17:52:16 -070011357 public void onAcquired(InvalidateInfo element) {
11358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011359
Romain Guyd928d682009-03-31 17:52:16 -070011360 public void onReleased(InvalidateInfo element) {
11361 }
11362 }, POOL_LIMIT)
11363 );
11364
11365 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011366
11367 View target;
11368
11369 int left;
11370 int top;
11371 int right;
11372 int bottom;
11373
Romain Guyd928d682009-03-31 17:52:16 -070011374 public void setNextPoolable(InvalidateInfo element) {
11375 mNext = element;
11376 }
11377
11378 public InvalidateInfo getNextPoolable() {
11379 return mNext;
11380 }
11381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011382 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070011383 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011384 }
11385
11386 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070011387 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011388 }
11389 }
11390
11391 final IWindowSession mSession;
11392
11393 final IWindow mWindow;
11394
11395 final IBinder mWindowToken;
11396
11397 final Callbacks mRootCallbacks;
11398
11399 /**
11400 * The top view of the hierarchy.
11401 */
11402 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070011403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011404 IBinder mPanelParentWindowToken;
11405 Surface mSurface;
11406
Romain Guyb051e892010-09-28 19:09:36 -070011407 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080011408 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070011409 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070011410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011411 /**
Romain Guy8506ab42009-06-11 17:35:47 -070011412 * Scale factor used by the compatibility mode
11413 */
11414 float mApplicationScale;
11415
11416 /**
11417 * Indicates whether the application is in compatibility mode
11418 */
11419 boolean mScalingRequired;
11420
11421 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011422 * Left position of this view's window
11423 */
11424 int mWindowLeft;
11425
11426 /**
11427 * Top position of this view's window
11428 */
11429 int mWindowTop;
11430
11431 /**
Adam Powell26153a32010-11-08 15:22:27 -080011432 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070011433 */
Adam Powell26153a32010-11-08 15:22:27 -080011434 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070011435
11436 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011437 * For windows that are full-screen but using insets to layout inside
11438 * of the screen decorations, these are the current insets for the
11439 * content of the window.
11440 */
11441 final Rect mContentInsets = new Rect();
11442
11443 /**
11444 * For windows that are full-screen but using insets to layout inside
11445 * of the screen decorations, these are the current insets for the
11446 * actual visible parts of the window.
11447 */
11448 final Rect mVisibleInsets = new Rect();
11449
11450 /**
11451 * The internal insets given by this window. This value is
11452 * supplied by the client (through
11453 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11454 * be given to the window manager when changed to be used in laying
11455 * out windows behind it.
11456 */
11457 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11458 = new ViewTreeObserver.InternalInsetsInfo();
11459
11460 /**
11461 * All views in the window's hierarchy that serve as scroll containers,
11462 * used to determine if the window can be resized or must be panned
11463 * to adjust for a soft input area.
11464 */
11465 final ArrayList<View> mScrollContainers = new ArrayList<View>();
11466
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070011467 final KeyEvent.DispatcherState mKeyDispatchState
11468 = new KeyEvent.DispatcherState();
11469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011470 /**
11471 * Indicates whether the view's window currently has the focus.
11472 */
11473 boolean mHasWindowFocus;
11474
11475 /**
11476 * The current visibility of the window.
11477 */
11478 int mWindowVisibility;
11479
11480 /**
11481 * Indicates the time at which drawing started to occur.
11482 */
11483 long mDrawingTime;
11484
11485 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070011486 * Indicates whether or not ignoring the DIRTY_MASK flags.
11487 */
11488 boolean mIgnoreDirtyState;
11489
11490 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011491 * Indicates whether the view's window is currently in touch mode.
11492 */
11493 boolean mInTouchMode;
11494
11495 /**
11496 * Indicates that ViewRoot should trigger a global layout change
11497 * the next time it performs a traversal
11498 */
11499 boolean mRecomputeGlobalAttributes;
11500
11501 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011502 * Set during a traveral if any views want to keep the screen on.
11503 */
11504 boolean mKeepScreenOn;
11505
11506 /**
11507 * Set if the visibility of any views has changed.
11508 */
11509 boolean mViewVisibilityChanged;
11510
11511 /**
11512 * Set to true if a view has been scrolled.
11513 */
11514 boolean mViewScrollChanged;
11515
11516 /**
11517 * Global to the view hierarchy used as a temporary for dealing with
11518 * x/y points in the transparent region computations.
11519 */
11520 final int[] mTransparentLocation = new int[2];
11521
11522 /**
11523 * Global to the view hierarchy used as a temporary for dealing with
11524 * x/y points in the ViewGroup.invalidateChild implementation.
11525 */
11526 final int[] mInvalidateChildLocation = new int[2];
11527
Chet Haasec3aa3612010-06-17 08:50:37 -070011528
11529 /**
11530 * Global to the view hierarchy used as a temporary for dealing with
11531 * x/y location when view is transformed.
11532 */
11533 final float[] mTmpTransformLocation = new float[2];
11534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011535 /**
11536 * The view tree observer used to dispatch global events like
11537 * layout, pre-draw, touch mode change, etc.
11538 */
11539 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11540
11541 /**
11542 * A Canvas used by the view hierarchy to perform bitmap caching.
11543 */
11544 Canvas mCanvas;
11545
11546 /**
11547 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11548 * handler can be used to pump events in the UI events queue.
11549 */
11550 final Handler mHandler;
11551
11552 /**
11553 * Identifier for messages requesting the view to be invalidated.
11554 * Such messages should be sent to {@link #mHandler}.
11555 */
11556 static final int INVALIDATE_MSG = 0x1;
11557
11558 /**
11559 * Identifier for messages requesting the view to invalidate a region.
11560 * Such messages should be sent to {@link #mHandler}.
11561 */
11562 static final int INVALIDATE_RECT_MSG = 0x2;
11563
11564 /**
11565 * Temporary for use in computing invalidate rectangles while
11566 * calling up the hierarchy.
11567 */
11568 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070011569
11570 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070011571 * Temporary for use in computing hit areas with transformed views
11572 */
11573 final RectF mTmpTransformRect = new RectF();
11574
11575 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070011576 * Temporary list for use in collecting focusable descendents of a view.
11577 */
11578 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011580 /**
11581 * Creates a new set of attachment information with the specified
11582 * events handler and thread.
11583 *
11584 * @param handler the events handler the view must use
11585 */
11586 AttachInfo(IWindowSession session, IWindow window,
11587 Handler handler, Callbacks effectPlayer) {
11588 mSession = session;
11589 mWindow = window;
11590 mWindowToken = window.asBinder();
11591 mHandler = handler;
11592 mRootCallbacks = effectPlayer;
11593 }
11594 }
11595
11596 /**
11597 * <p>ScrollabilityCache holds various fields used by a View when scrolling
11598 * is supported. This avoids keeping too many unused fields in most
11599 * instances of View.</p>
11600 */
Mike Cleronf116bf82009-09-27 19:14:12 -070011601 private static class ScrollabilityCache implements Runnable {
11602
11603 /**
11604 * Scrollbars are not visible
11605 */
11606 public static final int OFF = 0;
11607
11608 /**
11609 * Scrollbars are visible
11610 */
11611 public static final int ON = 1;
11612
11613 /**
11614 * Scrollbars are fading away
11615 */
11616 public static final int FADING = 2;
11617
11618 public boolean fadeScrollBars;
11619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011620 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070011621 public int scrollBarDefaultDelayBeforeFade;
11622 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011623
11624 public int scrollBarSize;
11625 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070011626 public float[] interpolatorValues;
11627 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011628
11629 public final Paint paint;
11630 public final Matrix matrix;
11631 public Shader shader;
11632
Mike Cleronf116bf82009-09-27 19:14:12 -070011633 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11634
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011635 private static final float[] OPAQUE = { 255 };
11636 private static final float[] TRANSPARENT = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070011637
11638 /**
11639 * When fading should start. This time moves into the future every time
11640 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11641 */
11642 public long fadeStartTime;
11643
11644
11645 /**
11646 * The current state of the scrollbars: ON, OFF, or FADING
11647 */
11648 public int state = OFF;
11649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011650 private int mLastColor;
11651
Mike Cleronf116bf82009-09-27 19:14:12 -070011652 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011653 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11654 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070011655 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11656 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011657
11658 paint = new Paint();
11659 matrix = new Matrix();
11660 // use use a height of 1, and then wack the matrix each time we
11661 // actually use it.
11662 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011664 paint.setShader(shader);
11665 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070011666 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011667 }
Romain Guy8506ab42009-06-11 17:35:47 -070011668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011669 public void setFadeColor(int color) {
11670 if (color != 0 && color != mLastColor) {
11671 mLastColor = color;
11672 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070011673
Romain Guye55e1a72009-08-27 10:42:26 -070011674 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11675 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011677 paint.setShader(shader);
11678 // Restore the default transfer mode (src_over)
11679 paint.setXfermode(null);
11680 }
11681 }
Mike Cleronf116bf82009-09-27 19:14:12 -070011682
11683 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070011684 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070011685 if (now >= fadeStartTime) {
11686
11687 // the animation fades the scrollbars out by changing
11688 // the opacity (alpha) from fully opaque to fully
11689 // transparent
11690 int nextFrame = (int) now;
11691 int framesCount = 0;
11692
11693 Interpolator interpolator = scrollBarInterpolator;
11694
11695 // Start opaque
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011696 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
Mike Cleronf116bf82009-09-27 19:14:12 -070011697
11698 // End transparent
11699 nextFrame += scrollBarFadeDuration;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011700 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
Mike Cleronf116bf82009-09-27 19:14:12 -070011701
11702 state = FADING;
11703
11704 // Kick off the fade animation
11705 host.invalidate();
11706 }
11707 }
11708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011709 }
11710}