blob: 211eba3c3b79dd58537c15e1877b565ef9174348 [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 Debunne3dbf55c2010-12-16 10:31:51 -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>
549 *
Jeff Brown85a31762010-09-01 17:01:00 -0700550 * <a name="Security"></a>
551 * <h3>Security</h3>
552 * <p>
553 * Sometimes it is essential that an application be able to verify that an action
554 * is being performed with the full knowledge and consent of the user, such as
555 * granting a permission request, making a purchase or clicking on an advertisement.
556 * Unfortunately, a malicious application could try to spoof the user into
557 * performing these actions, unaware, by concealing the intended purpose of the view.
558 * As a remedy, the framework offers a touch filtering mechanism that can be used to
559 * improve the security of views that provide access to sensitive functionality.
560 * </p><p>
561 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
Jeff Brown49ed71d2010-12-06 17:13:33 -0800562 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework
Jeff Brown85a31762010-09-01 17:01:00 -0700563 * will discard touches that are received whenever the view's window is obscured by
564 * another visible window. As a result, the view will not receive touches whenever a
565 * toast, dialog or other window appears above the view's window.
566 * </p><p>
567 * For more fine-grained control over security, consider overriding the
568 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
569 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
570 * </p>
571 *
Romain Guyd6a463a2009-05-21 23:10:10 -0700572 * @attr ref android.R.styleable#View_background
573 * @attr ref android.R.styleable#View_clickable
574 * @attr ref android.R.styleable#View_contentDescription
575 * @attr ref android.R.styleable#View_drawingCacheQuality
576 * @attr ref android.R.styleable#View_duplicateParentState
577 * @attr ref android.R.styleable#View_id
578 * @attr ref android.R.styleable#View_fadingEdge
579 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700580 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700582 * @attr ref android.R.styleable#View_isScrollContainer
583 * @attr ref android.R.styleable#View_focusable
584 * @attr ref android.R.styleable#View_focusableInTouchMode
585 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
586 * @attr ref android.R.styleable#View_keepScreenOn
587 * @attr ref android.R.styleable#View_longClickable
588 * @attr ref android.R.styleable#View_minHeight
589 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 * @attr ref android.R.styleable#View_nextFocusDown
591 * @attr ref android.R.styleable#View_nextFocusLeft
592 * @attr ref android.R.styleable#View_nextFocusRight
593 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700594 * @attr ref android.R.styleable#View_onClick
595 * @attr ref android.R.styleable#View_padding
596 * @attr ref android.R.styleable#View_paddingBottom
597 * @attr ref android.R.styleable#View_paddingLeft
598 * @attr ref android.R.styleable#View_paddingRight
599 * @attr ref android.R.styleable#View_paddingTop
600 * @attr ref android.R.styleable#View_saveEnabled
Chet Haase73066682010-11-29 15:55:32 -0800601 * @attr ref android.R.styleable#View_rotation
602 * @attr ref android.R.styleable#View_rotationX
603 * @attr ref android.R.styleable#View_rotationY
604 * @attr ref android.R.styleable#View_scaleX
605 * @attr ref android.R.styleable#View_scaleY
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 * @attr ref android.R.styleable#View_scrollX
607 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700608 * @attr ref android.R.styleable#View_scrollbarSize
609 * @attr ref android.R.styleable#View_scrollbarStyle
610 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700611 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
612 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
614 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 * @attr ref android.R.styleable#View_scrollbarThumbVertical
616 * @attr ref android.R.styleable#View_scrollbarTrackVertical
617 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
618 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700619 * @attr ref android.R.styleable#View_soundEffectsEnabled
620 * @attr ref android.R.styleable#View_tag
Chet Haase73066682010-11-29 15:55:32 -0800621 * @attr ref android.R.styleable#View_transformPivotX
622 * @attr ref android.R.styleable#View_transformPivotY
623 * @attr ref android.R.styleable#View_translationX
624 * @attr ref android.R.styleable#View_translationY
Romain Guyd6a463a2009-05-21 23:10:10 -0700625 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 *
627 * @see android.view.ViewGroup
628 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700629public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 private static final boolean DBG = false;
631
632 /**
633 * The logging tag used by this class with android.util.Log.
634 */
635 protected static final String VIEW_LOG_TAG = "View";
636
637 /**
638 * Used to mark a View that has no ID.
639 */
640 public static final int NO_ID = -1;
641
642 /**
643 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
644 * calling setFlags.
645 */
646 private static final int NOT_FOCUSABLE = 0x00000000;
647
648 /**
649 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
650 * setFlags.
651 */
652 private static final int FOCUSABLE = 0x00000001;
653
654 /**
655 * Mask for use with setFlags indicating bits used for focus.
656 */
657 private static final int FOCUSABLE_MASK = 0x00000001;
658
659 /**
660 * This view will adjust its padding to fit sytem windows (e.g. status bar)
661 */
662 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
663
664 /**
665 * This view is visible. Use with {@link #setVisibility}.
666 */
667 public static final int VISIBLE = 0x00000000;
668
669 /**
670 * This view is invisible, but it still takes up space for layout purposes.
671 * Use with {@link #setVisibility}.
672 */
673 public static final int INVISIBLE = 0x00000004;
674
675 /**
676 * This view is invisible, and it doesn't take any space for layout
677 * purposes. Use with {@link #setVisibility}.
678 */
679 public static final int GONE = 0x00000008;
680
681 /**
682 * Mask for use with setFlags indicating bits used for visibility.
683 * {@hide}
684 */
685 static final int VISIBILITY_MASK = 0x0000000C;
686
687 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
688
689 /**
690 * This view is enabled. Intrepretation varies by subclass.
691 * Use with ENABLED_MASK when calling setFlags.
692 * {@hide}
693 */
694 static final int ENABLED = 0x00000000;
695
696 /**
697 * This view is disabled. Intrepretation varies by subclass.
698 * Use with ENABLED_MASK when calling setFlags.
699 * {@hide}
700 */
701 static final int DISABLED = 0x00000020;
702
703 /**
704 * Mask for use with setFlags indicating bits used for indicating whether
705 * this view is enabled
706 * {@hide}
707 */
708 static final int ENABLED_MASK = 0x00000020;
709
710 /**
711 * This view won't draw. {@link #onDraw} won't be called and further
712 * optimizations
713 * will be performed. It is okay to have this flag set and a background.
714 * Use with DRAW_MASK when calling setFlags.
715 * {@hide}
716 */
717 static final int WILL_NOT_DRAW = 0x00000080;
718
719 /**
720 * Mask for use with setFlags indicating bits used for indicating whether
721 * this view is will draw
722 * {@hide}
723 */
724 static final int DRAW_MASK = 0x00000080;
725
726 /**
727 * <p>This view doesn't show scrollbars.</p>
728 * {@hide}
729 */
730 static final int SCROLLBARS_NONE = 0x00000000;
731
732 /**
733 * <p>This view shows horizontal scrollbars.</p>
734 * {@hide}
735 */
736 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
737
738 /**
739 * <p>This view shows vertical scrollbars.</p>
740 * {@hide}
741 */
742 static final int SCROLLBARS_VERTICAL = 0x00000200;
743
744 /**
745 * <p>Mask for use with setFlags indicating bits used for indicating which
746 * scrollbars are enabled.</p>
747 * {@hide}
748 */
749 static final int SCROLLBARS_MASK = 0x00000300;
750
Jeff Brown85a31762010-09-01 17:01:00 -0700751 /**
752 * Indicates that the view should filter touches when its window is obscured.
753 * Refer to the class comments for more information about this security feature.
754 * {@hide}
755 */
756 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
757
758 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759
760 /**
761 * <p>This view doesn't show fading edges.</p>
762 * {@hide}
763 */
764 static final int FADING_EDGE_NONE = 0x00000000;
765
766 /**
767 * <p>This view shows horizontal fading edges.</p>
768 * {@hide}
769 */
770 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
771
772 /**
773 * <p>This view shows vertical fading edges.</p>
774 * {@hide}
775 */
776 static final int FADING_EDGE_VERTICAL = 0x00002000;
777
778 /**
779 * <p>Mask for use with setFlags indicating bits used for indicating which
780 * fading edges are enabled.</p>
781 * {@hide}
782 */
783 static final int FADING_EDGE_MASK = 0x00003000;
784
785 /**
786 * <p>Indicates this view can be clicked. When clickable, a View reacts
787 * to clicks by notifying the OnClickListener.<p>
788 * {@hide}
789 */
790 static final int CLICKABLE = 0x00004000;
791
792 /**
793 * <p>Indicates this view is caching its drawing into a bitmap.</p>
794 * {@hide}
795 */
796 static final int DRAWING_CACHE_ENABLED = 0x00008000;
797
798 /**
799 * <p>Indicates that no icicle should be saved for this view.<p>
800 * {@hide}
801 */
802 static final int SAVE_DISABLED = 0x000010000;
803
804 /**
805 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
806 * property.</p>
807 * {@hide}
808 */
809 static final int SAVE_DISABLED_MASK = 0x000010000;
810
811 /**
812 * <p>Indicates that no drawing cache should ever be created for this view.<p>
813 * {@hide}
814 */
815 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
816
817 /**
818 * <p>Indicates this view can take / keep focus when int touch mode.</p>
819 * {@hide}
820 */
821 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
822
823 /**
824 * <p>Enables low quality mode for the drawing cache.</p>
825 */
826 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
827
828 /**
829 * <p>Enables high quality mode for the drawing cache.</p>
830 */
831 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
832
833 /**
834 * <p>Enables automatic quality mode for the drawing cache.</p>
835 */
836 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
837
838 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
839 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
840 };
841
842 /**
843 * <p>Mask for use with setFlags indicating bits used for the cache
844 * quality property.</p>
845 * {@hide}
846 */
847 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
848
849 /**
850 * <p>
851 * Indicates this view can be long clicked. When long clickable, a View
852 * reacts to long clicks by notifying the OnLongClickListener or showing a
853 * context menu.
854 * </p>
855 * {@hide}
856 */
857 static final int LONG_CLICKABLE = 0x00200000;
858
859 /**
860 * <p>Indicates that this view gets its drawable states from its direct parent
861 * and ignores its original internal states.</p>
862 *
863 * @hide
864 */
865 static final int DUPLICATE_PARENT_STATE = 0x00400000;
866
867 /**
868 * The scrollbar style to display the scrollbars inside the content area,
869 * without increasing the padding. The scrollbars will be overlaid with
870 * translucency on the view's content.
871 */
872 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
873
874 /**
875 * The scrollbar style to display the scrollbars inside the padded area,
876 * increasing the padding of the view. The scrollbars will not overlap the
877 * content area of the view.
878 */
879 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
880
881 /**
882 * The scrollbar style to display the scrollbars at the edge of the view,
883 * without increasing the padding. The scrollbars will be overlaid with
884 * translucency.
885 */
886 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
887
888 /**
889 * The scrollbar style to display the scrollbars at the edge of the view,
890 * increasing the padding of the view. The scrollbars will only overlap the
891 * background, if any.
892 */
893 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
894
895 /**
896 * Mask to check if the scrollbar style is overlay or inset.
897 * {@hide}
898 */
899 static final int SCROLLBARS_INSET_MASK = 0x01000000;
900
901 /**
902 * Mask to check if the scrollbar style is inside or outside.
903 * {@hide}
904 */
905 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
906
907 /**
908 * Mask for scrollbar style.
909 * {@hide}
910 */
911 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
912
913 /**
914 * View flag indicating that the screen should remain on while the
915 * window containing this view is visible to the user. This effectively
916 * takes care of automatically setting the WindowManager's
917 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
918 */
919 public static final int KEEP_SCREEN_ON = 0x04000000;
920
921 /**
922 * View flag indicating whether this view should have sound effects enabled
923 * for events such as clicking and touching.
924 */
925 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
926
927 /**
928 * View flag indicating whether this view should have haptic feedback
929 * enabled for events such as long presses.
930 */
931 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
932
933 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700934 * <p>Indicates that the view hierarchy should stop saving state when
935 * it reaches this view. If state saving is initiated immediately at
936 * the view, it will be allowed.
937 * {@hide}
938 */
939 static final int PARENT_SAVE_DISABLED = 0x20000000;
940
941 /**
942 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
943 * {@hide}
944 */
945 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
946
947 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700948 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
949 * should add all focusable Views regardless if they are focusable in touch mode.
950 */
951 public static final int FOCUSABLES_ALL = 0x00000000;
952
953 /**
954 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
955 * should add only Views focusable in touch mode.
956 */
957 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
958
959 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 * Use with {@link #focusSearch}. Move focus to the previous selectable
961 * item.
962 */
963 public static final int FOCUS_BACKWARD = 0x00000001;
964
965 /**
966 * Use with {@link #focusSearch}. Move focus to the next selectable
967 * item.
968 */
969 public static final int FOCUS_FORWARD = 0x00000002;
970
971 /**
972 * Use with {@link #focusSearch}. Move focus to the left.
973 */
974 public static final int FOCUS_LEFT = 0x00000011;
975
976 /**
977 * Use with {@link #focusSearch}. Move focus up.
978 */
979 public static final int FOCUS_UP = 0x00000021;
980
981 /**
982 * Use with {@link #focusSearch}. Move focus to the right.
983 */
984 public static final int FOCUS_RIGHT = 0x00000042;
985
986 /**
987 * Use with {@link #focusSearch}. Move focus down.
988 */
989 public static final int FOCUS_DOWN = 0x00000082;
990
991 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -0800992 * Bits of {@link #getMeasuredWidthAndState()} and
993 * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
994 */
995 public static final int MEASURED_SIZE_MASK = 0x00ffffff;
996
997 /**
998 * Bits of {@link #getMeasuredWidthAndState()} and
999 * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1000 */
1001 public static final int MEASURED_STATE_MASK = 0xff000000;
1002
1003 /**
1004 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1005 * for functions that combine both width and height into a single int,
1006 * such as {@link #getMeasuredState()} and the childState argument of
1007 * {@link #resolveSizeAndState(int, int, int)}.
1008 */
1009 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1010
1011 /**
1012 * Bit of {@link #getMeasuredWidthAndState()} and
1013 * {@link #getMeasuredWidthAndState()} that indicates the measured size
1014 * is smaller that the space the view would like to have.
1015 */
1016 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1017
1018 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 * Base View state sets
1020 */
1021 // Singles
1022 /**
1023 * Indicates the view has no states set. States are used with
1024 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1025 * view depending on its state.
1026 *
1027 * @see android.graphics.drawable.Drawable
1028 * @see #getDrawableState()
1029 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001030 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 /**
1032 * Indicates the view is enabled. States are used with
1033 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1034 * view depending on its state.
1035 *
1036 * @see android.graphics.drawable.Drawable
1037 * @see #getDrawableState()
1038 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001039 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 /**
1041 * Indicates the view is focused. States are used with
1042 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1043 * view depending on its state.
1044 *
1045 * @see android.graphics.drawable.Drawable
1046 * @see #getDrawableState()
1047 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001048 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 /**
1050 * Indicates the view is selected. States are used with
1051 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1052 * view depending on its state.
1053 *
1054 * @see android.graphics.drawable.Drawable
1055 * @see #getDrawableState()
1056 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001057 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 /**
1059 * Indicates the view is pressed. States are used with
1060 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1061 * view depending on its state.
1062 *
1063 * @see android.graphics.drawable.Drawable
1064 * @see #getDrawableState()
1065 * @hide
1066 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001067 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 /**
1069 * Indicates the view's window has focus. States are used with
1070 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1071 * view depending on its state.
1072 *
1073 * @see android.graphics.drawable.Drawable
1074 * @see #getDrawableState()
1075 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001076 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 // Doubles
1078 /**
1079 * Indicates the view is enabled and has the focus.
1080 *
1081 * @see #ENABLED_STATE_SET
1082 * @see #FOCUSED_STATE_SET
1083 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001084 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 /**
1086 * Indicates the view is enabled and selected.
1087 *
1088 * @see #ENABLED_STATE_SET
1089 * @see #SELECTED_STATE_SET
1090 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001091 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 /**
1093 * Indicates the view is enabled and that its window has focus.
1094 *
1095 * @see #ENABLED_STATE_SET
1096 * @see #WINDOW_FOCUSED_STATE_SET
1097 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001098 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 /**
1100 * Indicates the view is focused and selected.
1101 *
1102 * @see #FOCUSED_STATE_SET
1103 * @see #SELECTED_STATE_SET
1104 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001105 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 /**
1107 * Indicates the view has the focus and that its window has the focus.
1108 *
1109 * @see #FOCUSED_STATE_SET
1110 * @see #WINDOW_FOCUSED_STATE_SET
1111 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001112 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 /**
1114 * Indicates the view is selected and that its window has the focus.
1115 *
1116 * @see #SELECTED_STATE_SET
1117 * @see #WINDOW_FOCUSED_STATE_SET
1118 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001119 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 // Triples
1121 /**
1122 * Indicates the view is enabled, focused and selected.
1123 *
1124 * @see #ENABLED_STATE_SET
1125 * @see #FOCUSED_STATE_SET
1126 * @see #SELECTED_STATE_SET
1127 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001128 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 /**
1130 * Indicates the view is enabled, focused and its window has the focus.
1131 *
1132 * @see #ENABLED_STATE_SET
1133 * @see #FOCUSED_STATE_SET
1134 * @see #WINDOW_FOCUSED_STATE_SET
1135 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001136 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 /**
1138 * Indicates the view is enabled, selected and its window has the focus.
1139 *
1140 * @see #ENABLED_STATE_SET
1141 * @see #SELECTED_STATE_SET
1142 * @see #WINDOW_FOCUSED_STATE_SET
1143 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001144 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 /**
1146 * Indicates the view is focused, selected and its window has the focus.
1147 *
1148 * @see #FOCUSED_STATE_SET
1149 * @see #SELECTED_STATE_SET
1150 * @see #WINDOW_FOCUSED_STATE_SET
1151 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001152 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 /**
1154 * Indicates the view is enabled, focused, selected and its window
1155 * has the focus.
1156 *
1157 * @see #ENABLED_STATE_SET
1158 * @see #FOCUSED_STATE_SET
1159 * @see #SELECTED_STATE_SET
1160 * @see #WINDOW_FOCUSED_STATE_SET
1161 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001162 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 /**
1164 * Indicates the view is pressed and its window has the focus.
1165 *
1166 * @see #PRESSED_STATE_SET
1167 * @see #WINDOW_FOCUSED_STATE_SET
1168 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001169 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 /**
1171 * Indicates the view is pressed and selected.
1172 *
1173 * @see #PRESSED_STATE_SET
1174 * @see #SELECTED_STATE_SET
1175 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001176 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 /**
1178 * Indicates the view is pressed, selected and its window has the focus.
1179 *
1180 * @see #PRESSED_STATE_SET
1181 * @see #SELECTED_STATE_SET
1182 * @see #WINDOW_FOCUSED_STATE_SET
1183 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001184 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 /**
1186 * Indicates the view is pressed and focused.
1187 *
1188 * @see #PRESSED_STATE_SET
1189 * @see #FOCUSED_STATE_SET
1190 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001191 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 /**
1193 * Indicates the view is pressed, focused and its window has the focus.
1194 *
1195 * @see #PRESSED_STATE_SET
1196 * @see #FOCUSED_STATE_SET
1197 * @see #WINDOW_FOCUSED_STATE_SET
1198 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001199 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 /**
1201 * Indicates the view is pressed, focused and selected.
1202 *
1203 * @see #PRESSED_STATE_SET
1204 * @see #SELECTED_STATE_SET
1205 * @see #FOCUSED_STATE_SET
1206 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001207 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 /**
1209 * Indicates the view is pressed, focused, selected and its window has the focus.
1210 *
1211 * @see #PRESSED_STATE_SET
1212 * @see #FOCUSED_STATE_SET
1213 * @see #SELECTED_STATE_SET
1214 * @see #WINDOW_FOCUSED_STATE_SET
1215 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001216 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 /**
1218 * Indicates the view is pressed and enabled.
1219 *
1220 * @see #PRESSED_STATE_SET
1221 * @see #ENABLED_STATE_SET
1222 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001223 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 /**
1225 * Indicates the view is pressed, enabled and its window has the focus.
1226 *
1227 * @see #PRESSED_STATE_SET
1228 * @see #ENABLED_STATE_SET
1229 * @see #WINDOW_FOCUSED_STATE_SET
1230 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001231 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 /**
1233 * Indicates the view is pressed, enabled and selected.
1234 *
1235 * @see #PRESSED_STATE_SET
1236 * @see #ENABLED_STATE_SET
1237 * @see #SELECTED_STATE_SET
1238 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001239 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 /**
1241 * Indicates the view is pressed, enabled, selected and its window has the
1242 * focus.
1243 *
1244 * @see #PRESSED_STATE_SET
1245 * @see #ENABLED_STATE_SET
1246 * @see #SELECTED_STATE_SET
1247 * @see #WINDOW_FOCUSED_STATE_SET
1248 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001249 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 /**
1251 * Indicates the view is pressed, enabled and focused.
1252 *
1253 * @see #PRESSED_STATE_SET
1254 * @see #ENABLED_STATE_SET
1255 * @see #FOCUSED_STATE_SET
1256 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001257 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 /**
1259 * Indicates the view is pressed, enabled, focused and its window has the
1260 * focus.
1261 *
1262 * @see #PRESSED_STATE_SET
1263 * @see #ENABLED_STATE_SET
1264 * @see #FOCUSED_STATE_SET
1265 * @see #WINDOW_FOCUSED_STATE_SET
1266 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001267 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 /**
1269 * Indicates the view is pressed, enabled, focused and selected.
1270 *
1271 * @see #PRESSED_STATE_SET
1272 * @see #ENABLED_STATE_SET
1273 * @see #SELECTED_STATE_SET
1274 * @see #FOCUSED_STATE_SET
1275 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001276 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 /**
1278 * Indicates the view is pressed, enabled, focused, selected and its window
1279 * has the focus.
1280 *
1281 * @see #PRESSED_STATE_SET
1282 * @see #ENABLED_STATE_SET
1283 * @see #SELECTED_STATE_SET
1284 * @see #FOCUSED_STATE_SET
1285 * @see #WINDOW_FOCUSED_STATE_SET
1286 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001287 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288
1289 /**
1290 * The order here is very important to {@link #getDrawableState()}
1291 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001292 private static final int[][] VIEW_STATE_SETS;
1293
Romain Guyb051e892010-09-28 19:09:36 -07001294 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1295 static final int VIEW_STATE_SELECTED = 1 << 1;
1296 static final int VIEW_STATE_FOCUSED = 1 << 2;
1297 static final int VIEW_STATE_ENABLED = 1 << 3;
1298 static final int VIEW_STATE_PRESSED = 1 << 4;
1299 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001300 static final int VIEW_STATE_ACCELERATED = 1 << 6;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001301
1302 static final int[] VIEW_STATE_IDS = new int[] {
1303 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1304 R.attr.state_selected, VIEW_STATE_SELECTED,
1305 R.attr.state_focused, VIEW_STATE_FOCUSED,
1306 R.attr.state_enabled, VIEW_STATE_ENABLED,
1307 R.attr.state_pressed, VIEW_STATE_PRESSED,
1308 R.attr.state_activated, VIEW_STATE_ACTIVATED,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001309 R.attr.state_accelerated, VIEW_STATE_ACCELERATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 };
1311
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001312 static {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001313 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1314 throw new IllegalStateException(
1315 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1316 }
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001317 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001318 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001319 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001320 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001321 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001322 orderedIds[i * 2] = viewState;
1323 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001324 }
1325 }
1326 }
Romain Guyb051e892010-09-28 19:09:36 -07001327 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1328 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1329 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001330 int numBits = Integer.bitCount(i);
1331 int[] set = new int[numBits];
1332 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001333 for (int j = 0; j < orderedIds.length; j += 2) {
1334 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001335 set[pos++] = orderedIds[j];
1336 }
1337 }
1338 VIEW_STATE_SETS[i] = set;
1339 }
1340
1341 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1342 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1343 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1344 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1345 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1346 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1347 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1348 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1349 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1350 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1351 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1352 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1353 | VIEW_STATE_FOCUSED];
1354 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1355 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1356 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1357 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1358 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1359 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1360 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1361 | VIEW_STATE_ENABLED];
1362 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1363 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1364 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1365 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1366 | VIEW_STATE_ENABLED];
1367 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1368 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1369 | VIEW_STATE_ENABLED];
1370 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1371 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1372 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1373
1374 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1375 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1376 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1377 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1378 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1379 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1380 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1381 | VIEW_STATE_PRESSED];
1382 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1383 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1384 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1385 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1386 | VIEW_STATE_PRESSED];
1387 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1388 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1389 | VIEW_STATE_PRESSED];
1390 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1391 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1392 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1393 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1394 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1395 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1396 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1397 | VIEW_STATE_PRESSED];
1398 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1399 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1400 | VIEW_STATE_PRESSED];
1401 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1402 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1403 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1404 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1405 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1406 | VIEW_STATE_PRESSED];
1407 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1408 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1409 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1410 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1411 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1412 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1413 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1414 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1415 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1416 | VIEW_STATE_PRESSED];
1417 }
1418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 /**
1420 * Used by views that contain lists of items. This state indicates that
1421 * the view is showing the last item.
1422 * @hide
1423 */
1424 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1425 /**
1426 * Used by views that contain lists of items. This state indicates that
1427 * the view is showing the first item.
1428 * @hide
1429 */
1430 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1431 /**
1432 * Used by views that contain lists of items. This state indicates that
1433 * the view is showing the middle item.
1434 * @hide
1435 */
1436 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1437 /**
1438 * Used by views that contain lists of items. This state indicates that
1439 * the view is showing only one item.
1440 * @hide
1441 */
1442 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1443 /**
1444 * Used by views that contain lists of items. This state indicates that
1445 * the view is pressed and showing the last item.
1446 * @hide
1447 */
1448 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1449 /**
1450 * Used by views that contain lists of items. This state indicates that
1451 * the view is pressed and showing the first item.
1452 * @hide
1453 */
1454 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, 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 middle item.
1458 * @hide
1459 */
1460 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, 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 only one item.
1464 * @hide
1465 */
1466 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1467
1468 /**
1469 * Temporary Rect currently for use in setBackground(). This will probably
1470 * be extended in the future to hold our own class with more than just
1471 * a Rect. :)
1472 */
1473 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001474
1475 /**
1476 * Map used to store views' tags.
1477 */
1478 private static WeakHashMap<View, SparseArray<Object>> sTags;
1479
1480 /**
1481 * Lock used to access sTags.
1482 */
1483 private static final Object sTagsLock = new Object();
1484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 /**
1486 * The animation currently associated with this view.
1487 * @hide
1488 */
1489 protected Animation mCurrentAnimation = null;
1490
1491 /**
1492 * Width as measured during measure pass.
1493 * {@hide}
1494 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001495 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001496 /*package*/ int mMeasuredWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497
1498 /**
1499 * Height as measured during measure pass.
1500 * {@hide}
1501 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001502 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001503 /*package*/ int mMeasuredHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504
1505 /**
1506 * The view's identifier.
1507 * {@hide}
1508 *
1509 * @see #setId(int)
1510 * @see #getId()
1511 */
1512 @ViewDebug.ExportedProperty(resolveId = true)
1513 int mID = NO_ID;
1514
1515 /**
1516 * The view's tag.
1517 * {@hide}
1518 *
1519 * @see #setTag(Object)
1520 * @see #getTag()
1521 */
1522 protected Object mTag;
1523
1524 // for mPrivateFlags:
1525 /** {@hide} */
1526 static final int WANTS_FOCUS = 0x00000001;
1527 /** {@hide} */
1528 static final int FOCUSED = 0x00000002;
1529 /** {@hide} */
1530 static final int SELECTED = 0x00000004;
1531 /** {@hide} */
1532 static final int IS_ROOT_NAMESPACE = 0x00000008;
1533 /** {@hide} */
1534 static final int HAS_BOUNDS = 0x00000010;
1535 /** {@hide} */
1536 static final int DRAWN = 0x00000020;
1537 /**
1538 * When this flag is set, this view is running an animation on behalf of its
1539 * children and should therefore not cancel invalidate requests, even if they
1540 * lie outside of this view's bounds.
1541 *
1542 * {@hide}
1543 */
1544 static final int DRAW_ANIMATION = 0x00000040;
1545 /** {@hide} */
1546 static final int SKIP_DRAW = 0x00000080;
1547 /** {@hide} */
1548 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1549 /** {@hide} */
1550 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1551 /** {@hide} */
1552 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1553 /** {@hide} */
1554 static final int MEASURED_DIMENSION_SET = 0x00000800;
1555 /** {@hide} */
1556 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001557 /** {@hide} */
1558 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559
1560 private static final int PRESSED = 0x00004000;
1561
1562 /** {@hide} */
1563 static final int DRAWING_CACHE_VALID = 0x00008000;
1564 /**
1565 * Flag used to indicate that this view should be drawn once more (and only once
1566 * more) after its animation has completed.
1567 * {@hide}
1568 */
1569 static final int ANIMATION_STARTED = 0x00010000;
1570
1571 private static final int SAVE_STATE_CALLED = 0x00020000;
1572
1573 /**
1574 * Indicates that the View returned true when onSetAlpha() was called and that
1575 * the alpha must be restored.
1576 * {@hide}
1577 */
1578 static final int ALPHA_SET = 0x00040000;
1579
1580 /**
1581 * Set by {@link #setScrollContainer(boolean)}.
1582 */
1583 static final int SCROLL_CONTAINER = 0x00080000;
1584
1585 /**
1586 * Set by {@link #setScrollContainer(boolean)}.
1587 */
1588 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1589
1590 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001591 * View flag indicating whether this view was invalidated (fully or partially.)
1592 *
1593 * @hide
1594 */
1595 static final int DIRTY = 0x00200000;
1596
1597 /**
1598 * View flag indicating whether this view was invalidated by an opaque
1599 * invalidate request.
1600 *
1601 * @hide
1602 */
1603 static final int DIRTY_OPAQUE = 0x00400000;
1604
1605 /**
1606 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1607 *
1608 * @hide
1609 */
1610 static final int DIRTY_MASK = 0x00600000;
1611
1612 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001613 * Indicates whether the background is opaque.
1614 *
1615 * @hide
1616 */
1617 static final int OPAQUE_BACKGROUND = 0x00800000;
1618
1619 /**
1620 * Indicates whether the scrollbars are opaque.
1621 *
1622 * @hide
1623 */
1624 static final int OPAQUE_SCROLLBARS = 0x01000000;
1625
1626 /**
1627 * Indicates whether the view is opaque.
1628 *
1629 * @hide
1630 */
1631 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001632
1633 /**
1634 * Indicates a prepressed state;
1635 * the short time between ACTION_DOWN and recognizing
1636 * a 'real' press. Prepressed is used to recognize quick taps
1637 * even when they are shorter than ViewConfiguration.getTapTimeout().
1638 *
1639 * @hide
1640 */
1641 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001642
1643 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001644 * Indicates whether the view is temporarily detached.
1645 *
1646 * @hide
1647 */
1648 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001649
1650 /**
1651 * Indicates that we should awaken scroll bars once attached
1652 *
1653 * @hide
1654 */
1655 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001656
1657 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001658 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1659 * for transform operations
1660 *
1661 * @hide
1662 */
Adam Powellf37df072010-09-17 16:22:49 -07001663 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001664
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001665 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001666 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001667
Chet Haasefd2b0022010-08-06 13:08:56 -07001668 /**
Adam Powell637d3372010-08-25 14:37:03 -07001669 * Always allow a user to over-scroll this view, provided it is a
1670 * view that can scroll.
1671 *
1672 * @see #getOverScrollMode()
1673 * @see #setOverScrollMode(int)
1674 */
1675 public static final int OVER_SCROLL_ALWAYS = 0;
1676
1677 /**
1678 * Allow a user to over-scroll this view only if the content is large
1679 * enough to meaningfully scroll, provided it is a view that can scroll.
1680 *
1681 * @see #getOverScrollMode()
1682 * @see #setOverScrollMode(int)
1683 */
1684 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1685
1686 /**
1687 * Never allow a user to over-scroll this view.
1688 *
1689 * @see #getOverScrollMode()
1690 * @see #setOverScrollMode(int)
1691 */
1692 public static final int OVER_SCROLL_NEVER = 2;
1693
1694 /**
1695 * Controls the over-scroll mode for this view.
1696 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1697 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1698 * and {@link #OVER_SCROLL_NEVER}.
1699 */
1700 private int mOverScrollMode;
1701
1702 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 * The parent this view is attached to.
1704 * {@hide}
1705 *
1706 * @see #getParent()
1707 */
1708 protected ViewParent mParent;
1709
1710 /**
1711 * {@hide}
1712 */
1713 AttachInfo mAttachInfo;
1714
1715 /**
1716 * {@hide}
1717 */
Romain Guy809a7f62009-05-14 15:44:42 -07001718 @ViewDebug.ExportedProperty(flagMapping = {
1719 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1720 name = "FORCE_LAYOUT"),
1721 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1722 name = "LAYOUT_REQUIRED"),
1723 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001724 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001725 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1726 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1727 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1728 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1729 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 int mPrivateFlags;
1731
1732 /**
1733 * Count of how many windows this view has been attached to.
1734 */
1735 int mWindowAttachCount;
1736
1737 /**
1738 * The layout parameters associated with this view and used by the parent
1739 * {@link android.view.ViewGroup} to determine how this view should be
1740 * laid out.
1741 * {@hide}
1742 */
1743 protected ViewGroup.LayoutParams mLayoutParams;
1744
1745 /**
1746 * The view flags hold various views states.
1747 * {@hide}
1748 */
1749 @ViewDebug.ExportedProperty
1750 int mViewFlags;
1751
1752 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001753 * The transform matrix for the View. This transform is calculated internally
1754 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1755 * is used by default. Do *not* use this variable directly; instead call
1756 * getMatrix(), which will automatically recalculate the matrix if necessary
1757 * to get the correct matrix based on the latest rotation and scale properties.
1758 */
1759 private final Matrix mMatrix = new Matrix();
1760
1761 /**
1762 * The transform matrix for the View. This transform is calculated internally
1763 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1764 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001765 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001766 * to get the correct matrix based on the latest rotation and scale properties.
1767 */
1768 private Matrix mInverseMatrix;
1769
1770 /**
1771 * An internal variable that tracks whether we need to recalculate the
1772 * transform matrix, based on whether the rotation or scaleX/Y properties
1773 * have changed since the matrix was last calculated.
1774 */
1775 private boolean mMatrixDirty = false;
1776
1777 /**
1778 * An internal variable that tracks whether we need to recalculate the
1779 * transform matrix, based on whether the rotation or scaleX/Y properties
1780 * have changed since the matrix was last calculated.
1781 */
1782 private boolean mInverseMatrixDirty = true;
1783
1784 /**
1785 * A variable that tracks whether we need to recalculate the
1786 * transform matrix, based on whether the rotation or scaleX/Y properties
1787 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001788 * is only valid after a call to updateMatrix() or to a function that
1789 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001790 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001791 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001792
1793 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001794 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1795 */
1796 private Camera mCamera = null;
1797
1798 /**
1799 * This matrix is used when computing the matrix for 3D rotations.
1800 */
1801 private Matrix matrix3D = null;
1802
1803 /**
1804 * These prev values are used to recalculate a centered pivot point when necessary. The
1805 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1806 * set), so thes values are only used then as well.
1807 */
1808 private int mPrevWidth = -1;
1809 private int mPrevHeight = -1;
1810
1811 /**
1812 * Convenience value to check for float values that are close enough to zero to be considered
1813 * zero.
1814 */
Romain Guy2542d192010-08-18 11:47:12 -07001815 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001816
1817 /**
1818 * The degrees rotation around the vertical axis through the pivot point.
1819 */
1820 @ViewDebug.ExportedProperty
1821 private float mRotationY = 0f;
1822
1823 /**
1824 * The degrees rotation around the horizontal axis through the pivot point.
1825 */
1826 @ViewDebug.ExportedProperty
1827 private float mRotationX = 0f;
1828
1829 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001830 * The degrees rotation around the pivot point.
1831 */
1832 @ViewDebug.ExportedProperty
1833 private float mRotation = 0f;
1834
1835 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001836 * The amount of translation of the object away from its left property (post-layout).
1837 */
1838 @ViewDebug.ExportedProperty
1839 private float mTranslationX = 0f;
1840
1841 /**
1842 * The amount of translation of the object away from its top property (post-layout).
1843 */
1844 @ViewDebug.ExportedProperty
1845 private float mTranslationY = 0f;
1846
1847 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001848 * The amount of scale in the x direction around the pivot point. A
1849 * value of 1 means no scaling is applied.
1850 */
1851 @ViewDebug.ExportedProperty
1852 private float mScaleX = 1f;
1853
1854 /**
1855 * The amount of scale in the y direction around the pivot point. A
1856 * value of 1 means no scaling is applied.
1857 */
1858 @ViewDebug.ExportedProperty
1859 private float mScaleY = 1f;
1860
1861 /**
1862 * The amount of scale in the x direction around the pivot point. A
1863 * value of 1 means no scaling is applied.
1864 */
1865 @ViewDebug.ExportedProperty
1866 private float mPivotX = 0f;
1867
1868 /**
1869 * The amount of scale in the y direction around the pivot point. A
1870 * value of 1 means no scaling is applied.
1871 */
1872 @ViewDebug.ExportedProperty
1873 private float mPivotY = 0f;
1874
1875 /**
1876 * The opacity of the View. This is a value from 0 to 1, where 0 means
1877 * completely transparent and 1 means completely opaque.
1878 */
1879 @ViewDebug.ExportedProperty
1880 private float mAlpha = 1f;
1881
1882 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 * The distance in pixels from the left edge of this view's parent
1884 * to the left edge of this view.
1885 * {@hide}
1886 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001887 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 protected int mLeft;
1889 /**
1890 * The distance in pixels from the left edge of this view's parent
1891 * to the right edge of this view.
1892 * {@hide}
1893 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001894 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 protected int mRight;
1896 /**
1897 * The distance in pixels from the top edge of this view's parent
1898 * to the top edge of this view.
1899 * {@hide}
1900 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001901 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 protected int mTop;
1903 /**
1904 * The distance in pixels from the top edge of this view's parent
1905 * to the bottom edge of this view.
1906 * {@hide}
1907 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001908 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 protected int mBottom;
1910
1911 /**
1912 * The offset, in pixels, by which the content of this view is scrolled
1913 * horizontally.
1914 * {@hide}
1915 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001916 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 protected int mScrollX;
1918 /**
1919 * The offset, in pixels, by which the content of this view is scrolled
1920 * vertically.
1921 * {@hide}
1922 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001923 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 protected int mScrollY;
1925
1926 /**
1927 * The left padding in pixels, that is the distance in pixels between the
1928 * left edge of this view and the left edge of its content.
1929 * {@hide}
1930 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001931 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 protected int mPaddingLeft;
1933 /**
1934 * The right padding in pixels, that is the distance in pixels between the
1935 * right edge of this view and the right edge of its content.
1936 * {@hide}
1937 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001938 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 protected int mPaddingRight;
1940 /**
1941 * The top padding in pixels, that is the distance in pixels between the
1942 * top edge of this view and the top edge of its content.
1943 * {@hide}
1944 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001945 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 protected int mPaddingTop;
1947 /**
1948 * The bottom padding in pixels, that is the distance in pixels between the
1949 * bottom edge of this view and the bottom edge of its content.
1950 * {@hide}
1951 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001952 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 protected int mPaddingBottom;
1954
1955 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001956 * Briefly describes the view and is primarily used for accessibility support.
1957 */
1958 private CharSequence mContentDescription;
1959
1960 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 * Cache the paddingRight set by the user to append to the scrollbar's size.
1962 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001963 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 int mUserPaddingRight;
1965
1966 /**
1967 * Cache the paddingBottom 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 mUserPaddingBottom;
1971
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001972 /**
Adam Powell20232d02010-12-08 21:08:53 -08001973 * Cache the paddingLeft set by the user to append to the scrollbar's size.
1974 */
1975 @ViewDebug.ExportedProperty(category = "padding")
1976 int mUserPaddingLeft;
1977
1978 /**
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001979 * @hide
1980 */
1981 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1982 /**
1983 * @hide
1984 */
1985 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986
1987 private Resources mResources = null;
1988
1989 private Drawable mBGDrawable;
1990
1991 private int mBackgroundResource;
1992 private boolean mBackgroundSizeChanged;
1993
1994 /**
1995 * Listener used to dispatch focus change events.
1996 * This field should be made private, so it is hidden from the SDK.
1997 * {@hide}
1998 */
1999 protected OnFocusChangeListener mOnFocusChangeListener;
2000
2001 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002002 * Listeners for layout change events.
2003 */
2004 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2005
2006 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 * Listener used to dispatch click events.
2008 * This field should be made private, so it is hidden from the SDK.
2009 * {@hide}
2010 */
2011 protected OnClickListener mOnClickListener;
2012
2013 /**
2014 * Listener used to dispatch long click events.
2015 * This field should be made private, so it is hidden from the SDK.
2016 * {@hide}
2017 */
2018 protected OnLongClickListener mOnLongClickListener;
2019
2020 /**
2021 * Listener used to build the context menu.
2022 * This field should be made private, so it is hidden from the SDK.
2023 * {@hide}
2024 */
2025 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2026
2027 private OnKeyListener mOnKeyListener;
2028
2029 private OnTouchListener mOnTouchListener;
2030
Chris Tate32affef2010-10-18 15:29:21 -07002031 private OnDragListener mOnDragListener;
2032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 /**
2034 * The application environment this view lives in.
2035 * This field should be made private, so it is hidden from the SDK.
2036 * {@hide}
2037 */
2038 protected Context mContext;
2039
2040 private ScrollabilityCache mScrollCache;
2041
2042 private int[] mDrawableState = null;
2043
Romain Guy02890fd2010-08-06 17:58:44 -07002044 private Bitmap mDrawingCache;
2045 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07002046 private DisplayList mDisplayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047
2048 /**
2049 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2050 * the user may specify which view to go to next.
2051 */
2052 private int mNextFocusLeftId = View.NO_ID;
2053
2054 /**
2055 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2056 * the user may specify which view to go to next.
2057 */
2058 private int mNextFocusRightId = View.NO_ID;
2059
2060 /**
2061 * When this view has focus and the next focus is {@link #FOCUS_UP},
2062 * the user may specify which view to go to next.
2063 */
2064 private int mNextFocusUpId = View.NO_ID;
2065
2066 /**
2067 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2068 * the user may specify which view to go to next.
2069 */
2070 private int mNextFocusDownId = View.NO_ID;
2071
Jeff Brown4e6319b2010-12-13 10:36:51 -08002072 /**
2073 * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2074 * the user may specify which view to go to next.
2075 */
2076 int mNextFocusForwardId = View.NO_ID;
2077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08002079 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08002080 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08002081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 private UnsetPressedState mUnsetPressedState;
2083
2084 /**
2085 * Whether the long press's action has been invoked. The tap's action is invoked on the
2086 * up event while a long press is invoked as soon as the long press duration is reached, so
2087 * a long press could be performed before the tap is checked, in which case the tap's action
2088 * should not be invoked.
2089 */
2090 private boolean mHasPerformedLongPress;
2091
2092 /**
2093 * The minimum height of the view. We'll try our best to have the height
2094 * of this view to at least this amount.
2095 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002096 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 private int mMinHeight;
2098
2099 /**
2100 * The minimum width of the view. We'll try our best to have the width
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 mMinWidth;
2105
2106 /**
2107 * The delegate to handle touch events that are physically in this view
2108 * but should be handled by another view.
2109 */
2110 private TouchDelegate mTouchDelegate = null;
2111
2112 /**
2113 * Solid color to use as a background when creating the drawing cache. Enables
2114 * the cache to use 16 bit bitmaps instead of 32 bit.
2115 */
2116 private int mDrawingCacheBackgroundColor = 0;
2117
2118 /**
2119 * Special tree observer used when mAttachInfo is null.
2120 */
2121 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002122
2123 /**
2124 * Cache the touch slop from the context that created the view.
2125 */
2126 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002129 * Cache drag/drop state
2130 *
2131 */
2132 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002133
2134 /**
Adam Powell20232d02010-12-08 21:08:53 -08002135 * Position of the vertical scroll bar.
2136 */
2137 private int mVerticalScrollbarPosition;
2138
2139 /**
2140 * Position the scroll bar at the default position as determined by the system.
2141 */
2142 public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2143
2144 /**
2145 * Position the scroll bar along the left edge.
2146 */
2147 public static final int SCROLLBAR_POSITION_LEFT = 1;
2148
2149 /**
2150 * Position the scroll bar along the right edge.
2151 */
2152 public static final int SCROLLBAR_POSITION_RIGHT = 2;
2153
2154 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 * Simple constructor to use when creating a view from code.
2156 *
2157 * @param context The Context the view is running in, through which it can
2158 * access the current theme, resources, etc.
2159 */
2160 public View(Context context) {
2161 mContext = context;
2162 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002163 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002164 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Adam Powell637d3372010-08-25 14:37:03 -07002165 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 }
2167
2168 /**
2169 * Constructor that is called when inflating a view from XML. This is called
2170 * when a view is being constructed from an XML file, supplying attributes
2171 * that were specified in the XML file. This version uses a default style of
2172 * 0, so the only attribute values applied are those in the Context's Theme
2173 * and the given AttributeSet.
2174 *
2175 * <p>
2176 * The method onFinishInflate() will be called after all children have been
2177 * added.
2178 *
2179 * @param context The Context the view is running in, through which it can
2180 * access the current theme, resources, etc.
2181 * @param attrs The attributes of the XML tag that is inflating the view.
2182 * @see #View(Context, AttributeSet, int)
2183 */
2184 public View(Context context, AttributeSet attrs) {
2185 this(context, attrs, 0);
2186 }
2187
2188 /**
2189 * Perform inflation from XML and apply a class-specific base style. This
2190 * constructor of View allows subclasses to use their own base style when
2191 * they are inflating. For example, a Button class's constructor would call
2192 * this version of the super class constructor and supply
2193 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2194 * the theme's button style to modify all of the base view attributes (in
2195 * particular its background) as well as the Button class's attributes.
2196 *
2197 * @param context The Context the view is running in, through which it can
2198 * access the current theme, resources, etc.
2199 * @param attrs The attributes of the XML tag that is inflating the view.
2200 * @param defStyle The default style to apply to this view. If 0, no style
2201 * will be applied (beyond what is included in the theme). This may
2202 * either be an attribute resource, whose value will be retrieved
2203 * from the current theme, or an explicit style resource.
2204 * @see #View(Context, AttributeSet)
2205 */
2206 public View(Context context, AttributeSet attrs, int defStyle) {
2207 this(context);
2208
2209 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2210 defStyle, 0);
2211
2212 Drawable background = null;
2213
2214 int leftPadding = -1;
2215 int topPadding = -1;
2216 int rightPadding = -1;
2217 int bottomPadding = -1;
2218
2219 int padding = -1;
2220
2221 int viewFlagValues = 0;
2222 int viewFlagMasks = 0;
2223
2224 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 int x = 0;
2227 int y = 0;
2228
Chet Haase73066682010-11-29 15:55:32 -08002229 float tx = 0;
2230 float ty = 0;
2231 float rotation = 0;
2232 float rotationX = 0;
2233 float rotationY = 0;
2234 float sx = 1f;
2235 float sy = 1f;
2236 boolean transformSet = false;
2237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2239
Adam Powell637d3372010-08-25 14:37:03 -07002240 int overScrollMode = mOverScrollMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 final int N = a.getIndexCount();
2242 for (int i = 0; i < N; i++) {
2243 int attr = a.getIndex(i);
2244 switch (attr) {
2245 case com.android.internal.R.styleable.View_background:
2246 background = a.getDrawable(attr);
2247 break;
2248 case com.android.internal.R.styleable.View_padding:
2249 padding = a.getDimensionPixelSize(attr, -1);
2250 break;
2251 case com.android.internal.R.styleable.View_paddingLeft:
2252 leftPadding = a.getDimensionPixelSize(attr, -1);
2253 break;
2254 case com.android.internal.R.styleable.View_paddingTop:
2255 topPadding = a.getDimensionPixelSize(attr, -1);
2256 break;
2257 case com.android.internal.R.styleable.View_paddingRight:
2258 rightPadding = a.getDimensionPixelSize(attr, -1);
2259 break;
2260 case com.android.internal.R.styleable.View_paddingBottom:
2261 bottomPadding = a.getDimensionPixelSize(attr, -1);
2262 break;
2263 case com.android.internal.R.styleable.View_scrollX:
2264 x = a.getDimensionPixelOffset(attr, 0);
2265 break;
2266 case com.android.internal.R.styleable.View_scrollY:
2267 y = a.getDimensionPixelOffset(attr, 0);
2268 break;
Chet Haase73066682010-11-29 15:55:32 -08002269 case com.android.internal.R.styleable.View_alpha:
2270 setAlpha(a.getFloat(attr, 1f));
2271 break;
2272 case com.android.internal.R.styleable.View_transformPivotX:
2273 setPivotX(a.getDimensionPixelOffset(attr, 0));
2274 break;
2275 case com.android.internal.R.styleable.View_transformPivotY:
2276 setPivotY(a.getDimensionPixelOffset(attr, 0));
2277 break;
2278 case com.android.internal.R.styleable.View_translationX:
2279 tx = a.getDimensionPixelOffset(attr, 0);
2280 transformSet = true;
2281 break;
2282 case com.android.internal.R.styleable.View_translationY:
2283 ty = a.getDimensionPixelOffset(attr, 0);
2284 transformSet = true;
2285 break;
2286 case com.android.internal.R.styleable.View_rotation:
2287 rotation = a.getFloat(attr, 0);
2288 transformSet = true;
2289 break;
2290 case com.android.internal.R.styleable.View_rotationX:
2291 rotationX = a.getFloat(attr, 0);
2292 transformSet = true;
2293 break;
2294 case com.android.internal.R.styleable.View_rotationY:
2295 rotationY = a.getFloat(attr, 0);
2296 transformSet = true;
2297 break;
2298 case com.android.internal.R.styleable.View_scaleX:
2299 sx = a.getFloat(attr, 1f);
2300 transformSet = true;
2301 break;
2302 case com.android.internal.R.styleable.View_scaleY:
2303 sy = a.getFloat(attr, 1f);
2304 transformSet = true;
2305 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 case com.android.internal.R.styleable.View_id:
2307 mID = a.getResourceId(attr, NO_ID);
2308 break;
2309 case com.android.internal.R.styleable.View_tag:
2310 mTag = a.getText(attr);
2311 break;
2312 case com.android.internal.R.styleable.View_fitsSystemWindows:
2313 if (a.getBoolean(attr, false)) {
2314 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2315 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2316 }
2317 break;
2318 case com.android.internal.R.styleable.View_focusable:
2319 if (a.getBoolean(attr, false)) {
2320 viewFlagValues |= FOCUSABLE;
2321 viewFlagMasks |= FOCUSABLE_MASK;
2322 }
2323 break;
2324 case com.android.internal.R.styleable.View_focusableInTouchMode:
2325 if (a.getBoolean(attr, false)) {
2326 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2327 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2328 }
2329 break;
2330 case com.android.internal.R.styleable.View_clickable:
2331 if (a.getBoolean(attr, false)) {
2332 viewFlagValues |= CLICKABLE;
2333 viewFlagMasks |= CLICKABLE;
2334 }
2335 break;
2336 case com.android.internal.R.styleable.View_longClickable:
2337 if (a.getBoolean(attr, false)) {
2338 viewFlagValues |= LONG_CLICKABLE;
2339 viewFlagMasks |= LONG_CLICKABLE;
2340 }
2341 break;
2342 case com.android.internal.R.styleable.View_saveEnabled:
2343 if (!a.getBoolean(attr, true)) {
2344 viewFlagValues |= SAVE_DISABLED;
2345 viewFlagMasks |= SAVE_DISABLED_MASK;
2346 }
2347 break;
2348 case com.android.internal.R.styleable.View_duplicateParentState:
2349 if (a.getBoolean(attr, false)) {
2350 viewFlagValues |= DUPLICATE_PARENT_STATE;
2351 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2352 }
2353 break;
2354 case com.android.internal.R.styleable.View_visibility:
2355 final int visibility = a.getInt(attr, 0);
2356 if (visibility != 0) {
2357 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2358 viewFlagMasks |= VISIBILITY_MASK;
2359 }
2360 break;
2361 case com.android.internal.R.styleable.View_drawingCacheQuality:
2362 final int cacheQuality = a.getInt(attr, 0);
2363 if (cacheQuality != 0) {
2364 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2365 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2366 }
2367 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002368 case com.android.internal.R.styleable.View_contentDescription:
2369 mContentDescription = a.getString(attr);
2370 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2372 if (!a.getBoolean(attr, true)) {
2373 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2374 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2375 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002376 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2378 if (!a.getBoolean(attr, true)) {
2379 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2380 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2381 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002382 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 case R.styleable.View_scrollbars:
2384 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2385 if (scrollbars != SCROLLBARS_NONE) {
2386 viewFlagValues |= scrollbars;
2387 viewFlagMasks |= SCROLLBARS_MASK;
2388 initializeScrollbars(a);
2389 }
2390 break;
2391 case R.styleable.View_fadingEdge:
2392 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2393 if (fadingEdge != FADING_EDGE_NONE) {
2394 viewFlagValues |= fadingEdge;
2395 viewFlagMasks |= FADING_EDGE_MASK;
2396 initializeFadingEdge(a);
2397 }
2398 break;
2399 case R.styleable.View_scrollbarStyle:
2400 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2401 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2402 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2403 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2404 }
2405 break;
2406 case R.styleable.View_isScrollContainer:
2407 setScrollContainer = true;
2408 if (a.getBoolean(attr, false)) {
2409 setScrollContainer(true);
2410 }
2411 break;
2412 case com.android.internal.R.styleable.View_keepScreenOn:
2413 if (a.getBoolean(attr, false)) {
2414 viewFlagValues |= KEEP_SCREEN_ON;
2415 viewFlagMasks |= KEEP_SCREEN_ON;
2416 }
2417 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002418 case R.styleable.View_filterTouchesWhenObscured:
2419 if (a.getBoolean(attr, false)) {
2420 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2421 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2422 }
2423 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 case R.styleable.View_nextFocusLeft:
2425 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2426 break;
2427 case R.styleable.View_nextFocusRight:
2428 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2429 break;
2430 case R.styleable.View_nextFocusUp:
2431 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2432 break;
2433 case R.styleable.View_nextFocusDown:
2434 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2435 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002436 case R.styleable.View_nextFocusForward:
2437 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2438 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 case R.styleable.View_minWidth:
2440 mMinWidth = a.getDimensionPixelSize(attr, 0);
2441 break;
2442 case R.styleable.View_minHeight:
2443 mMinHeight = a.getDimensionPixelSize(attr, 0);
2444 break;
Romain Guy9a817362009-05-01 10:57:14 -07002445 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002446 if (context.isRestricted()) {
2447 throw new IllegalStateException("The android:onClick attribute cannot "
2448 + "be used within a restricted context");
2449 }
2450
Romain Guy9a817362009-05-01 10:57:14 -07002451 final String handlerName = a.getString(attr);
2452 if (handlerName != null) {
2453 setOnClickListener(new OnClickListener() {
2454 private Method mHandler;
2455
2456 public void onClick(View v) {
2457 if (mHandler == null) {
2458 try {
2459 mHandler = getContext().getClass().getMethod(handlerName,
2460 View.class);
2461 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002462 int id = getId();
2463 String idText = id == NO_ID ? "" : " with id '"
2464 + getContext().getResources().getResourceEntryName(
2465 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002466 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002467 handlerName + "(View) in the activity "
2468 + getContext().getClass() + " for onClick handler"
2469 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002470 }
2471 }
2472
2473 try {
2474 mHandler.invoke(getContext(), View.this);
2475 } catch (IllegalAccessException e) {
2476 throw new IllegalStateException("Could not execute non "
2477 + "public method of the activity", e);
2478 } catch (InvocationTargetException e) {
2479 throw new IllegalStateException("Could not execute "
2480 + "method of the activity", e);
2481 }
2482 }
2483 });
2484 }
2485 break;
Adam Powell637d3372010-08-25 14:37:03 -07002486 case R.styleable.View_overScrollMode:
2487 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2488 break;
Adam Powell20232d02010-12-08 21:08:53 -08002489 case R.styleable.View_verticalScrollbarPosition:
2490 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2491 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 }
2493 }
2494
Adam Powell637d3372010-08-25 14:37:03 -07002495 setOverScrollMode(overScrollMode);
2496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 if (background != null) {
2498 setBackgroundDrawable(background);
2499 }
2500
2501 if (padding >= 0) {
2502 leftPadding = padding;
2503 topPadding = padding;
2504 rightPadding = padding;
2505 bottomPadding = padding;
2506 }
2507
2508 // If the user specified the padding (either with android:padding or
2509 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2510 // use the default padding or the padding from the background drawable
2511 // (stored at this point in mPadding*)
2512 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2513 topPadding >= 0 ? topPadding : mPaddingTop,
2514 rightPadding >= 0 ? rightPadding : mPaddingRight,
2515 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2516
2517 if (viewFlagMasks != 0) {
2518 setFlags(viewFlagValues, viewFlagMasks);
2519 }
2520
2521 // Needs to be called after mViewFlags is set
2522 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2523 recomputePadding();
2524 }
2525
2526 if (x != 0 || y != 0) {
2527 scrollTo(x, y);
2528 }
2529
Chet Haase73066682010-11-29 15:55:32 -08002530 if (transformSet) {
2531 setTranslationX(tx);
2532 setTranslationY(ty);
2533 setRotation(rotation);
2534 setRotationX(rotationX);
2535 setRotationY(rotationY);
2536 setScaleX(sx);
2537 setScaleY(sy);
2538 }
2539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2541 setScrollContainer(true);
2542 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002543
2544 computeOpaqueFlags();
2545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 a.recycle();
2547 }
2548
2549 /**
2550 * Non-public constructor for use in testing
2551 */
2552 View() {
2553 }
2554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 /**
2556 * <p>
2557 * Initializes the fading edges from a given set of styled attributes. This
2558 * method should be called by subclasses that need fading edges and when an
2559 * instance of these subclasses is created programmatically rather than
2560 * being inflated from XML. This method is automatically called when the XML
2561 * is inflated.
2562 * </p>
2563 *
2564 * @param a the styled attributes set to initialize the fading edges from
2565 */
2566 protected void initializeFadingEdge(TypedArray a) {
2567 initScrollCache();
2568
2569 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2570 R.styleable.View_fadingEdgeLength,
2571 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2572 }
2573
2574 /**
2575 * Returns the size of the vertical faded edges used to indicate that more
2576 * content in this view is visible.
2577 *
2578 * @return The size in pixels of the vertical faded edge or 0 if vertical
2579 * faded edges are not enabled for this view.
2580 * @attr ref android.R.styleable#View_fadingEdgeLength
2581 */
2582 public int getVerticalFadingEdgeLength() {
2583 if (isVerticalFadingEdgeEnabled()) {
2584 ScrollabilityCache cache = mScrollCache;
2585 if (cache != null) {
2586 return cache.fadingEdgeLength;
2587 }
2588 }
2589 return 0;
2590 }
2591
2592 /**
2593 * Set the size of the faded edge used to indicate that more content in this
2594 * view is available. Will not change whether the fading edge is enabled; use
2595 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2596 * to enable the fading edge for the vertical or horizontal fading edges.
2597 *
2598 * @param length The size in pixels of the faded edge used to indicate that more
2599 * content in this view is visible.
2600 */
2601 public void setFadingEdgeLength(int length) {
2602 initScrollCache();
2603 mScrollCache.fadingEdgeLength = length;
2604 }
2605
2606 /**
2607 * Returns the size of the horizontal faded edges used to indicate that more
2608 * content in this view is visible.
2609 *
2610 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2611 * faded edges are not enabled for this view.
2612 * @attr ref android.R.styleable#View_fadingEdgeLength
2613 */
2614 public int getHorizontalFadingEdgeLength() {
2615 if (isHorizontalFadingEdgeEnabled()) {
2616 ScrollabilityCache cache = mScrollCache;
2617 if (cache != null) {
2618 return cache.fadingEdgeLength;
2619 }
2620 }
2621 return 0;
2622 }
2623
2624 /**
2625 * Returns the width of the vertical scrollbar.
2626 *
2627 * @return The width in pixels of the vertical scrollbar or 0 if there
2628 * is no vertical scrollbar.
2629 */
2630 public int getVerticalScrollbarWidth() {
2631 ScrollabilityCache cache = mScrollCache;
2632 if (cache != null) {
2633 ScrollBarDrawable scrollBar = cache.scrollBar;
2634 if (scrollBar != null) {
2635 int size = scrollBar.getSize(true);
2636 if (size <= 0) {
2637 size = cache.scrollBarSize;
2638 }
2639 return size;
2640 }
2641 return 0;
2642 }
2643 return 0;
2644 }
2645
2646 /**
2647 * Returns the height of the horizontal scrollbar.
2648 *
2649 * @return The height in pixels of the horizontal scrollbar or 0 if
2650 * there is no horizontal scrollbar.
2651 */
2652 protected int getHorizontalScrollbarHeight() {
2653 ScrollabilityCache cache = mScrollCache;
2654 if (cache != null) {
2655 ScrollBarDrawable scrollBar = cache.scrollBar;
2656 if (scrollBar != null) {
2657 int size = scrollBar.getSize(false);
2658 if (size <= 0) {
2659 size = cache.scrollBarSize;
2660 }
2661 return size;
2662 }
2663 return 0;
2664 }
2665 return 0;
2666 }
2667
2668 /**
2669 * <p>
2670 * Initializes the scrollbars from a given set of styled attributes. This
2671 * method should be called by subclasses that need scrollbars and when an
2672 * instance of these subclasses is created programmatically rather than
2673 * being inflated from XML. This method is automatically called when the XML
2674 * is inflated.
2675 * </p>
2676 *
2677 * @param a the styled attributes set to initialize the scrollbars from
2678 */
2679 protected void initializeScrollbars(TypedArray a) {
2680 initScrollCache();
2681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002683
2684 if (scrollabilityCache.scrollBar == null) {
2685 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2686 }
2687
Romain Guy8bda2482010-03-02 11:42:11 -08002688 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689
Mike Cleronf116bf82009-09-27 19:14:12 -07002690 if (!fadeScrollbars) {
2691 scrollabilityCache.state = ScrollabilityCache.ON;
2692 }
2693 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2694
2695
2696 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2697 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2698 .getScrollBarFadeDuration());
2699 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2700 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2701 ViewConfiguration.getScrollDefaultDelay());
2702
2703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2705 com.android.internal.R.styleable.View_scrollbarSize,
2706 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2707
2708 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2709 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2710
2711 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2712 if (thumb != null) {
2713 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2714 }
2715
2716 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2717 false);
2718 if (alwaysDraw) {
2719 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2720 }
2721
2722 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2723 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2724
2725 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2726 if (thumb != null) {
2727 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2728 }
2729
2730 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2731 false);
2732 if (alwaysDraw) {
2733 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2734 }
2735
2736 // Re-apply user/background padding so that scrollbar(s) get added
2737 recomputePadding();
2738 }
2739
2740 /**
2741 * <p>
2742 * Initalizes the scrollability cache if necessary.
2743 * </p>
2744 */
2745 private void initScrollCache() {
2746 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002747 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 }
2749 }
2750
2751 /**
Adam Powell20232d02010-12-08 21:08:53 -08002752 * Set the position of the vertical scroll bar. Should be one of
2753 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
2754 * {@link #SCROLLBAR_POSITION_RIGHT}.
2755 *
2756 * @param position Where the vertical scroll bar should be positioned.
2757 */
2758 public void setVerticalScrollbarPosition(int position) {
2759 if (mVerticalScrollbarPosition != position) {
2760 mVerticalScrollbarPosition = position;
2761 computeOpaqueFlags();
2762 recomputePadding();
2763 }
2764 }
2765
2766 /**
2767 * @return The position where the vertical scroll bar will show, if applicable.
2768 * @see #setVerticalScrollbarPosition(int)
2769 */
2770 public int getVerticalScrollbarPosition() {
2771 return mVerticalScrollbarPosition;
2772 }
2773
2774 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 * Register a callback to be invoked when focus of this view changed.
2776 *
2777 * @param l The callback that will run.
2778 */
2779 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2780 mOnFocusChangeListener = l;
2781 }
2782
2783 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002784 * Add a listener that will be called when the bounds of the view change due to
2785 * layout processing.
2786 *
2787 * @param listener The listener that will be called when layout bounds change.
2788 */
2789 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2790 if (mOnLayoutChangeListeners == null) {
2791 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2792 }
2793 mOnLayoutChangeListeners.add(listener);
2794 }
2795
2796 /**
2797 * Remove a listener for layout changes.
2798 *
2799 * @param listener The listener for layout bounds change.
2800 */
2801 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2802 if (mOnLayoutChangeListeners == null) {
2803 return;
2804 }
2805 mOnLayoutChangeListeners.remove(listener);
2806 }
2807
2808 /**
2809 * Gets the current list of listeners for layout changes.
Chet Haase21cd1382010-09-01 17:42:29 -07002810 */
2811 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2812 return mOnLayoutChangeListeners;
2813 }
2814
2815 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 * Returns the focus-change callback registered for this view.
2817 *
2818 * @return The callback, or null if one is not registered.
2819 */
2820 public OnFocusChangeListener getOnFocusChangeListener() {
2821 return mOnFocusChangeListener;
2822 }
2823
2824 /**
2825 * Register a callback to be invoked when this view is clicked. If this view is not
2826 * clickable, it becomes clickable.
2827 *
2828 * @param l The callback that will run
2829 *
2830 * @see #setClickable(boolean)
2831 */
2832 public void setOnClickListener(OnClickListener l) {
2833 if (!isClickable()) {
2834 setClickable(true);
2835 }
2836 mOnClickListener = l;
2837 }
2838
2839 /**
2840 * Register a callback to be invoked when this view is clicked and held. If this view is not
2841 * long clickable, it becomes long clickable.
2842 *
2843 * @param l The callback that will run
2844 *
2845 * @see #setLongClickable(boolean)
2846 */
2847 public void setOnLongClickListener(OnLongClickListener l) {
2848 if (!isLongClickable()) {
2849 setLongClickable(true);
2850 }
2851 mOnLongClickListener = l;
2852 }
2853
2854 /**
2855 * Register a callback to be invoked when the context menu for this view is
2856 * being built. If this view is not long clickable, it becomes long clickable.
2857 *
2858 * @param l The callback that will run
2859 *
2860 */
2861 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2862 if (!isLongClickable()) {
2863 setLongClickable(true);
2864 }
2865 mOnCreateContextMenuListener = l;
2866 }
2867
2868 /**
2869 * Call this view's OnClickListener, if it is defined.
2870 *
2871 * @return True there was an assigned OnClickListener that was called, false
2872 * otherwise is returned.
2873 */
2874 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002875 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 if (mOnClickListener != null) {
2878 playSoundEffect(SoundEffectConstants.CLICK);
2879 mOnClickListener.onClick(this);
2880 return true;
2881 }
2882
2883 return false;
2884 }
2885
2886 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002887 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2888 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002890 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 */
2892 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002893 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 boolean handled = false;
2896 if (mOnLongClickListener != null) {
2897 handled = mOnLongClickListener.onLongClick(View.this);
2898 }
2899 if (!handled) {
2900 handled = showContextMenu();
2901 }
2902 if (handled) {
2903 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2904 }
2905 return handled;
2906 }
2907
2908 /**
2909 * Bring up the context menu for this view.
2910 *
2911 * @return Whether a context menu was displayed.
2912 */
2913 public boolean showContextMenu() {
2914 return getParent().showContextMenuForChild(this);
2915 }
2916
2917 /**
Adam Powell6e346362010-07-23 10:18:23 -07002918 * Start an action mode.
2919 *
2920 * @param callback Callback that will control the lifecycle of the action mode
2921 * @return The new action mode if it is started, null otherwise
2922 *
2923 * @see ActionMode
2924 */
2925 public ActionMode startActionMode(ActionMode.Callback callback) {
2926 return getParent().startActionModeForChild(this, callback);
2927 }
2928
2929 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 * Register a callback to be invoked when a key is pressed in this view.
2931 * @param l the key listener to attach to this view
2932 */
2933 public void setOnKeyListener(OnKeyListener l) {
2934 mOnKeyListener = l;
2935 }
2936
2937 /**
2938 * Register a callback to be invoked when a touch event is sent to this view.
2939 * @param l the touch listener to attach to this view
2940 */
2941 public void setOnTouchListener(OnTouchListener l) {
2942 mOnTouchListener = l;
2943 }
2944
2945 /**
Chris Tate32affef2010-10-18 15:29:21 -07002946 * Register a callback to be invoked when a drag event is sent to this view.
2947 * @param l The drag listener to attach to this view
2948 */
2949 public void setOnDragListener(OnDragListener l) {
2950 mOnDragListener = l;
2951 }
2952
2953 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2955 *
2956 * Note: this does not check whether this {@link View} should get focus, it just
2957 * gives it focus no matter what. It should only be called internally by framework
2958 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2959 *
2960 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2961 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2962 * focus moved when requestFocus() is called. It may not always
2963 * apply, in which case use the default View.FOCUS_DOWN.
2964 * @param previouslyFocusedRect The rectangle of the view that had focus
2965 * prior in this View's coordinate system.
2966 */
2967 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2968 if (DBG) {
2969 System.out.println(this + " requestFocus()");
2970 }
2971
2972 if ((mPrivateFlags & FOCUSED) == 0) {
2973 mPrivateFlags |= FOCUSED;
2974
2975 if (mParent != null) {
2976 mParent.requestChildFocus(this, this);
2977 }
2978
2979 onFocusChanged(true, direction, previouslyFocusedRect);
2980 refreshDrawableState();
2981 }
2982 }
2983
2984 /**
2985 * Request that a rectangle of this view be visible on the screen,
2986 * scrolling if necessary just enough.
2987 *
2988 * <p>A View should call this if it maintains some notion of which part
2989 * of its content is interesting. For example, a text editing view
2990 * should call this when its cursor moves.
2991 *
2992 * @param rectangle The rectangle.
2993 * @return Whether any parent scrolled.
2994 */
2995 public boolean requestRectangleOnScreen(Rect rectangle) {
2996 return requestRectangleOnScreen(rectangle, false);
2997 }
2998
2999 /**
3000 * Request that a rectangle of this view be visible on the screen,
3001 * scrolling if necessary just enough.
3002 *
3003 * <p>A View should call this if it maintains some notion of which part
3004 * of its content is interesting. For example, a text editing view
3005 * should call this when its cursor moves.
3006 *
3007 * <p>When <code>immediate</code> is set to true, scrolling will not be
3008 * animated.
3009 *
3010 * @param rectangle The rectangle.
3011 * @param immediate True to forbid animated scrolling, false otherwise
3012 * @return Whether any parent scrolled.
3013 */
3014 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3015 View child = this;
3016 ViewParent parent = mParent;
3017 boolean scrolled = false;
3018 while (parent != null) {
3019 scrolled |= parent.requestChildRectangleOnScreen(child,
3020 rectangle, immediate);
3021
3022 // offset rect so next call has the rectangle in the
3023 // coordinate system of its direct child.
3024 rectangle.offset(child.getLeft(), child.getTop());
3025 rectangle.offset(-child.getScrollX(), -child.getScrollY());
3026
3027 if (!(parent instanceof View)) {
3028 break;
3029 }
Romain Guy8506ab42009-06-11 17:35:47 -07003030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 child = (View) parent;
3032 parent = child.getParent();
3033 }
3034 return scrolled;
3035 }
3036
3037 /**
3038 * Called when this view wants to give up focus. This will cause
3039 * {@link #onFocusChanged} to be called.
3040 */
3041 public void clearFocus() {
3042 if (DBG) {
3043 System.out.println(this + " clearFocus()");
3044 }
3045
3046 if ((mPrivateFlags & FOCUSED) != 0) {
3047 mPrivateFlags &= ~FOCUSED;
3048
3049 if (mParent != null) {
3050 mParent.clearChildFocus(this);
3051 }
3052
3053 onFocusChanged(false, 0, null);
3054 refreshDrawableState();
3055 }
3056 }
3057
3058 /**
3059 * Called to clear the focus of a view that is about to be removed.
3060 * Doesn't call clearChildFocus, which prevents this view from taking
3061 * focus again before it has been removed from the parent
3062 */
3063 void clearFocusForRemoval() {
3064 if ((mPrivateFlags & FOCUSED) != 0) {
3065 mPrivateFlags &= ~FOCUSED;
3066
3067 onFocusChanged(false, 0, null);
3068 refreshDrawableState();
3069 }
3070 }
3071
3072 /**
3073 * Called internally by the view system when a new view is getting focus.
3074 * This is what clears the old focus.
3075 */
3076 void unFocus() {
3077 if (DBG) {
3078 System.out.println(this + " unFocus()");
3079 }
3080
3081 if ((mPrivateFlags & FOCUSED) != 0) {
3082 mPrivateFlags &= ~FOCUSED;
3083
3084 onFocusChanged(false, 0, null);
3085 refreshDrawableState();
3086 }
3087 }
3088
3089 /**
3090 * Returns true if this view has focus iteself, or is the ancestor of the
3091 * view that has focus.
3092 *
3093 * @return True if this view has or contains focus, false otherwise.
3094 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003095 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 public boolean hasFocus() {
3097 return (mPrivateFlags & FOCUSED) != 0;
3098 }
3099
3100 /**
3101 * Returns true if this view is focusable or if it contains a reachable View
3102 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3103 * is a View whose parents do not block descendants focus.
3104 *
3105 * Only {@link #VISIBLE} views are considered focusable.
3106 *
3107 * @return True if the view is focusable or if the view contains a focusable
3108 * View, false otherwise.
3109 *
3110 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3111 */
3112 public boolean hasFocusable() {
3113 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3114 }
3115
3116 /**
3117 * Called by the view system when the focus state of this view changes.
3118 * When the focus change event is caused by directional navigation, direction
3119 * and previouslyFocusedRect provide insight into where the focus is coming from.
3120 * When overriding, be sure to call up through to the super class so that
3121 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07003122 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 * @param gainFocus True if the View has focus; false otherwise.
3124 * @param direction The direction focus has moved when requestFocus()
3125 * is called to give this view focus. Values are
Jeff Brown4e6319b2010-12-13 10:36:51 -08003126 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3127 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3128 * It may not always apply, in which case use the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 * @param previouslyFocusedRect The rectangle, in this view's coordinate
3130 * system, of the previously focused view. If applicable, this will be
3131 * passed in as finer grained information about where the focus is coming
3132 * from (in addition to direction). Will be <code>null</code> otherwise.
3133 */
3134 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003135 if (gainFocus) {
3136 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3137 }
3138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 InputMethodManager imm = InputMethodManager.peekInstance();
3140 if (!gainFocus) {
3141 if (isPressed()) {
3142 setPressed(false);
3143 }
3144 if (imm != null && mAttachInfo != null
3145 && mAttachInfo.mHasWindowFocus) {
3146 imm.focusOut(this);
3147 }
Romain Guya2431d02009-04-30 16:30:00 -07003148 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 } else if (imm != null && mAttachInfo != null
3150 && mAttachInfo.mHasWindowFocus) {
3151 imm.focusIn(this);
3152 }
Romain Guy8506ab42009-06-11 17:35:47 -07003153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 invalidate();
3155 if (mOnFocusChangeListener != null) {
3156 mOnFocusChangeListener.onFocusChange(this, gainFocus);
3157 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003158
3159 if (mAttachInfo != null) {
3160 mAttachInfo.mKeyDispatchState.reset(this);
3161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 }
3163
3164 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07003165 * {@inheritDoc}
3166 */
3167 public void sendAccessibilityEvent(int eventType) {
3168 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3169 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3170 }
3171 }
3172
3173 /**
3174 * {@inheritDoc}
3175 */
3176 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3177 event.setClassName(getClass().getName());
3178 event.setPackageName(getContext().getPackageName());
3179 event.setEnabled(isEnabled());
3180 event.setContentDescription(mContentDescription);
3181
3182 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3183 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3184 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3185 event.setItemCount(focusablesTempList.size());
3186 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3187 focusablesTempList.clear();
3188 }
3189
3190 dispatchPopulateAccessibilityEvent(event);
3191
3192 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3193 }
3194
3195 /**
3196 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3197 * to be populated.
3198 *
3199 * @param event The event.
3200 *
3201 * @return True if the event population was completed.
3202 */
3203 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3204 return false;
3205 }
3206
3207 /**
3208 * Gets the {@link View} description. It briefly describes the view and is
3209 * primarily used for accessibility support. Set this property to enable
3210 * better accessibility support for your application. This is especially
3211 * true for views that do not have textual representation (For example,
3212 * ImageButton).
3213 *
3214 * @return The content descriptiopn.
3215 *
3216 * @attr ref android.R.styleable#View_contentDescription
3217 */
3218 public CharSequence getContentDescription() {
3219 return mContentDescription;
3220 }
3221
3222 /**
3223 * Sets the {@link View} description. It briefly describes the view and is
3224 * primarily used for accessibility support. Set this property to enable
3225 * better accessibility support for your application. This is especially
3226 * true for views that do not have textual representation (For example,
3227 * ImageButton).
3228 *
3229 * @param contentDescription The content description.
3230 *
3231 * @attr ref android.R.styleable#View_contentDescription
3232 */
3233 public void setContentDescription(CharSequence contentDescription) {
3234 mContentDescription = contentDescription;
3235 }
3236
3237 /**
Romain Guya2431d02009-04-30 16:30:00 -07003238 * Invoked whenever this view loses focus, either by losing window focus or by losing
3239 * focus within its window. This method can be used to clear any state tied to the
3240 * focus. For instance, if a button is held pressed with the trackball and the window
3241 * loses focus, this method can be used to cancel the press.
3242 *
3243 * Subclasses of View overriding this method should always call super.onFocusLost().
3244 *
3245 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003246 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003247 *
3248 * @hide pending API council approval
3249 */
3250 protected void onFocusLost() {
3251 resetPressedState();
3252 }
3253
3254 private void resetPressedState() {
3255 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3256 return;
3257 }
3258
3259 if (isPressed()) {
3260 setPressed(false);
3261
3262 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003263 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003264 }
3265 }
3266 }
3267
3268 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 * Returns true if this view has focus
3270 *
3271 * @return True if this view has focus, false otherwise.
3272 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003273 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 public boolean isFocused() {
3275 return (mPrivateFlags & FOCUSED) != 0;
3276 }
3277
3278 /**
3279 * Find the view in the hierarchy rooted at this view that currently has
3280 * focus.
3281 *
3282 * @return The view that currently has focus, or null if no focused view can
3283 * be found.
3284 */
3285 public View findFocus() {
3286 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3287 }
3288
3289 /**
3290 * Change whether this view is one of the set of scrollable containers in
3291 * its window. This will be used to determine whether the window can
3292 * resize or must pan when a soft input area is open -- scrollable
3293 * containers allow the window to use resize mode since the container
3294 * will appropriately shrink.
3295 */
3296 public void setScrollContainer(boolean isScrollContainer) {
3297 if (isScrollContainer) {
3298 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3299 mAttachInfo.mScrollContainers.add(this);
3300 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3301 }
3302 mPrivateFlags |= SCROLL_CONTAINER;
3303 } else {
3304 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3305 mAttachInfo.mScrollContainers.remove(this);
3306 }
3307 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3308 }
3309 }
3310
3311 /**
3312 * Returns the quality of the drawing cache.
3313 *
3314 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3315 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3316 *
3317 * @see #setDrawingCacheQuality(int)
3318 * @see #setDrawingCacheEnabled(boolean)
3319 * @see #isDrawingCacheEnabled()
3320 *
3321 * @attr ref android.R.styleable#View_drawingCacheQuality
3322 */
3323 public int getDrawingCacheQuality() {
3324 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3325 }
3326
3327 /**
3328 * Set the drawing cache quality of this view. This value is used only when the
3329 * drawing cache is enabled
3330 *
3331 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3332 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3333 *
3334 * @see #getDrawingCacheQuality()
3335 * @see #setDrawingCacheEnabled(boolean)
3336 * @see #isDrawingCacheEnabled()
3337 *
3338 * @attr ref android.R.styleable#View_drawingCacheQuality
3339 */
3340 public void setDrawingCacheQuality(int quality) {
3341 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3342 }
3343
3344 /**
3345 * Returns whether the screen should remain on, corresponding to the current
3346 * value of {@link #KEEP_SCREEN_ON}.
3347 *
3348 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3349 *
3350 * @see #setKeepScreenOn(boolean)
3351 *
3352 * @attr ref android.R.styleable#View_keepScreenOn
3353 */
3354 public boolean getKeepScreenOn() {
3355 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3356 }
3357
3358 /**
3359 * Controls whether the screen should remain on, modifying the
3360 * value of {@link #KEEP_SCREEN_ON}.
3361 *
3362 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3363 *
3364 * @see #getKeepScreenOn()
3365 *
3366 * @attr ref android.R.styleable#View_keepScreenOn
3367 */
3368 public void setKeepScreenOn(boolean keepScreenOn) {
3369 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3370 }
3371
3372 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003373 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3374 * @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 -08003375 *
3376 * @attr ref android.R.styleable#View_nextFocusLeft
3377 */
3378 public int getNextFocusLeftId() {
3379 return mNextFocusLeftId;
3380 }
3381
3382 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003383 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3384 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
3385 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 *
3387 * @attr ref android.R.styleable#View_nextFocusLeft
3388 */
3389 public void setNextFocusLeftId(int nextFocusLeftId) {
3390 mNextFocusLeftId = nextFocusLeftId;
3391 }
3392
3393 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003394 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3395 * @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 -08003396 *
3397 * @attr ref android.R.styleable#View_nextFocusRight
3398 */
3399 public int getNextFocusRightId() {
3400 return mNextFocusRightId;
3401 }
3402
3403 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003404 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3405 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
3406 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 *
3408 * @attr ref android.R.styleable#View_nextFocusRight
3409 */
3410 public void setNextFocusRightId(int nextFocusRightId) {
3411 mNextFocusRightId = nextFocusRightId;
3412 }
3413
3414 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003415 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3416 * @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 -08003417 *
3418 * @attr ref android.R.styleable#View_nextFocusUp
3419 */
3420 public int getNextFocusUpId() {
3421 return mNextFocusUpId;
3422 }
3423
3424 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003425 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3426 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
3427 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 *
3429 * @attr ref android.R.styleable#View_nextFocusUp
3430 */
3431 public void setNextFocusUpId(int nextFocusUpId) {
3432 mNextFocusUpId = nextFocusUpId;
3433 }
3434
3435 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003436 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3437 * @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 -08003438 *
3439 * @attr ref android.R.styleable#View_nextFocusDown
3440 */
3441 public int getNextFocusDownId() {
3442 return mNextFocusDownId;
3443 }
3444
3445 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003446 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3447 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
3448 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 *
3450 * @attr ref android.R.styleable#View_nextFocusDown
3451 */
3452 public void setNextFocusDownId(int nextFocusDownId) {
3453 mNextFocusDownId = nextFocusDownId;
3454 }
3455
3456 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003457 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3458 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3459 *
3460 * @attr ref android.R.styleable#View_nextFocusForward
3461 */
3462 public int getNextFocusForwardId() {
3463 return mNextFocusForwardId;
3464 }
3465
3466 /**
3467 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3468 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
3469 * decide automatically.
3470 *
3471 * @attr ref android.R.styleable#View_nextFocusForward
3472 */
3473 public void setNextFocusForwardId(int nextFocusForwardId) {
3474 mNextFocusForwardId = nextFocusForwardId;
3475 }
3476
3477 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 * Returns the visibility of this view and all of its ancestors
3479 *
3480 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3481 */
3482 public boolean isShown() {
3483 View current = this;
3484 //noinspection ConstantConditions
3485 do {
3486 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3487 return false;
3488 }
3489 ViewParent parent = current.mParent;
3490 if (parent == null) {
3491 return false; // We are not attached to the view root
3492 }
3493 if (!(parent instanceof View)) {
3494 return true;
3495 }
3496 current = (View) parent;
3497 } while (current != null);
3498
3499 return false;
3500 }
3501
3502 /**
3503 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3504 * is set
3505 *
3506 * @param insets Insets for system windows
3507 *
3508 * @return True if this view applied the insets, false otherwise
3509 */
3510 protected boolean fitSystemWindows(Rect insets) {
3511 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3512 mPaddingLeft = insets.left;
3513 mPaddingTop = insets.top;
3514 mPaddingRight = insets.right;
3515 mPaddingBottom = insets.bottom;
3516 requestLayout();
3517 return true;
3518 }
3519 return false;
3520 }
3521
3522 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003523 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3524 * @return True if window has FITS_SYSTEM_WINDOWS set
3525 *
3526 * @hide
3527 */
3528 public boolean isFitsSystemWindowsFlagSet() {
3529 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3530 }
3531
3532 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 * Returns the visibility status for this view.
3534 *
3535 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3536 * @attr ref android.R.styleable#View_visibility
3537 */
3538 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003539 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3540 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3541 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 })
3543 public int getVisibility() {
3544 return mViewFlags & VISIBILITY_MASK;
3545 }
3546
3547 /**
3548 * Set the enabled state of this view.
3549 *
3550 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3551 * @attr ref android.R.styleable#View_visibility
3552 */
3553 @RemotableViewMethod
3554 public void setVisibility(int visibility) {
3555 setFlags(visibility, VISIBILITY_MASK);
3556 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3557 }
3558
3559 /**
3560 * Returns the enabled status for this view. The interpretation of the
3561 * enabled state varies by subclass.
3562 *
3563 * @return True if this view is enabled, false otherwise.
3564 */
3565 @ViewDebug.ExportedProperty
3566 public boolean isEnabled() {
3567 return (mViewFlags & ENABLED_MASK) == ENABLED;
3568 }
3569
3570 /**
3571 * Set the enabled state of this view. The interpretation of the enabled
3572 * state varies by subclass.
3573 *
3574 * @param enabled True if this view is enabled, false otherwise.
3575 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003576 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003578 if (enabled == isEnabled()) return;
3579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3581
3582 /*
3583 * The View most likely has to change its appearance, so refresh
3584 * the drawable state.
3585 */
3586 refreshDrawableState();
3587
3588 // Invalidate too, since the default behavior for views is to be
3589 // be drawn at 50% alpha rather than to change the drawable.
3590 invalidate();
3591 }
3592
3593 /**
3594 * Set whether this view can receive the focus.
3595 *
3596 * Setting this to false will also ensure that this view is not focusable
3597 * in touch mode.
3598 *
3599 * @param focusable If true, this view can receive the focus.
3600 *
3601 * @see #setFocusableInTouchMode(boolean)
3602 * @attr ref android.R.styleable#View_focusable
3603 */
3604 public void setFocusable(boolean focusable) {
3605 if (!focusable) {
3606 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3607 }
3608 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3609 }
3610
3611 /**
3612 * Set whether this view can receive focus while in touch mode.
3613 *
3614 * Setting this to true will also ensure that this view is focusable.
3615 *
3616 * @param focusableInTouchMode If true, this view can receive the focus while
3617 * in touch mode.
3618 *
3619 * @see #setFocusable(boolean)
3620 * @attr ref android.R.styleable#View_focusableInTouchMode
3621 */
3622 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3623 // Focusable in touch mode should always be set before the focusable flag
3624 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3625 // which, in touch mode, will not successfully request focus on this view
3626 // because the focusable in touch mode flag is not set
3627 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3628 if (focusableInTouchMode) {
3629 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3630 }
3631 }
3632
3633 /**
3634 * Set whether this view should have sound effects enabled for events such as
3635 * clicking and touching.
3636 *
3637 * <p>You may wish to disable sound effects for a view if you already play sounds,
3638 * for instance, a dial key that plays dtmf tones.
3639 *
3640 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3641 * @see #isSoundEffectsEnabled()
3642 * @see #playSoundEffect(int)
3643 * @attr ref android.R.styleable#View_soundEffectsEnabled
3644 */
3645 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3646 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3647 }
3648
3649 /**
3650 * @return whether this view should have sound effects enabled for events such as
3651 * clicking and touching.
3652 *
3653 * @see #setSoundEffectsEnabled(boolean)
3654 * @see #playSoundEffect(int)
3655 * @attr ref android.R.styleable#View_soundEffectsEnabled
3656 */
3657 @ViewDebug.ExportedProperty
3658 public boolean isSoundEffectsEnabled() {
3659 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3660 }
3661
3662 /**
3663 * Set whether this view should have haptic feedback for events such as
3664 * long presses.
3665 *
3666 * <p>You may wish to disable haptic feedback if your view already controls
3667 * its own haptic feedback.
3668 *
3669 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3670 * @see #isHapticFeedbackEnabled()
3671 * @see #performHapticFeedback(int)
3672 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3673 */
3674 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3675 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3676 }
3677
3678 /**
3679 * @return whether this view should have haptic feedback enabled for events
3680 * long presses.
3681 *
3682 * @see #setHapticFeedbackEnabled(boolean)
3683 * @see #performHapticFeedback(int)
3684 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3685 */
3686 @ViewDebug.ExportedProperty
3687 public boolean isHapticFeedbackEnabled() {
3688 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3689 }
3690
3691 /**
3692 * If this view doesn't do any drawing on its own, set this flag to
3693 * allow further optimizations. By default, this flag is not set on
3694 * View, but could be set on some View subclasses such as ViewGroup.
3695 *
3696 * Typically, if you override {@link #onDraw} you should clear this flag.
3697 *
3698 * @param willNotDraw whether or not this View draw on its own
3699 */
3700 public void setWillNotDraw(boolean willNotDraw) {
3701 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3702 }
3703
3704 /**
3705 * Returns whether or not this View draws on its own.
3706 *
3707 * @return true if this view has nothing to draw, false otherwise
3708 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003709 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 public boolean willNotDraw() {
3711 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3712 }
3713
3714 /**
3715 * When a View's drawing cache is enabled, drawing is redirected to an
3716 * offscreen bitmap. Some views, like an ImageView, must be able to
3717 * bypass this mechanism if they already draw a single bitmap, to avoid
3718 * unnecessary usage of the memory.
3719 *
3720 * @param willNotCacheDrawing true if this view does not cache its
3721 * drawing, false otherwise
3722 */
3723 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3724 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3725 }
3726
3727 /**
3728 * Returns whether or not this View can cache its drawing or not.
3729 *
3730 * @return true if this view does not cache its drawing, false otherwise
3731 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003732 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 public boolean willNotCacheDrawing() {
3734 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3735 }
3736
3737 /**
3738 * Indicates whether this view reacts to click events or not.
3739 *
3740 * @return true if the view is clickable, false otherwise
3741 *
3742 * @see #setClickable(boolean)
3743 * @attr ref android.R.styleable#View_clickable
3744 */
3745 @ViewDebug.ExportedProperty
3746 public boolean isClickable() {
3747 return (mViewFlags & CLICKABLE) == CLICKABLE;
3748 }
3749
3750 /**
3751 * Enables or disables click events for this view. When a view
3752 * is clickable it will change its state to "pressed" on every click.
3753 * Subclasses should set the view clickable to visually react to
3754 * user's clicks.
3755 *
3756 * @param clickable true to make the view clickable, false otherwise
3757 *
3758 * @see #isClickable()
3759 * @attr ref android.R.styleable#View_clickable
3760 */
3761 public void setClickable(boolean clickable) {
3762 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3763 }
3764
3765 /**
3766 * Indicates whether this view reacts to long click events or not.
3767 *
3768 * @return true if the view is long clickable, false otherwise
3769 *
3770 * @see #setLongClickable(boolean)
3771 * @attr ref android.R.styleable#View_longClickable
3772 */
3773 public boolean isLongClickable() {
3774 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3775 }
3776
3777 /**
3778 * Enables or disables long click events for this view. When a view is long
3779 * clickable it reacts to the user holding down the button for a longer
3780 * duration than a tap. This event can either launch the listener or a
3781 * context menu.
3782 *
3783 * @param longClickable true to make the view long clickable, false otherwise
3784 * @see #isLongClickable()
3785 * @attr ref android.R.styleable#View_longClickable
3786 */
3787 public void setLongClickable(boolean longClickable) {
3788 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3789 }
3790
3791 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003792 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 *
3794 * @see #isClickable()
3795 * @see #setClickable(boolean)
3796 *
3797 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3798 * the View's internal state from a previously set "pressed" state.
3799 */
3800 public void setPressed(boolean pressed) {
3801 if (pressed) {
3802 mPrivateFlags |= PRESSED;
3803 } else {
3804 mPrivateFlags &= ~PRESSED;
3805 }
3806 refreshDrawableState();
3807 dispatchSetPressed(pressed);
3808 }
3809
3810 /**
3811 * Dispatch setPressed to all of this View's children.
3812 *
3813 * @see #setPressed(boolean)
3814 *
3815 * @param pressed The new pressed state
3816 */
3817 protected void dispatchSetPressed(boolean pressed) {
3818 }
3819
3820 /**
3821 * Indicates whether the view is currently in pressed state. Unless
3822 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3823 * the pressed state.
3824 *
3825 * @see #setPressed
3826 * @see #isClickable()
3827 * @see #setClickable(boolean)
3828 *
3829 * @return true if the view is currently pressed, false otherwise
3830 */
3831 public boolean isPressed() {
3832 return (mPrivateFlags & PRESSED) == PRESSED;
3833 }
3834
3835 /**
3836 * Indicates whether this view will save its state (that is,
3837 * whether its {@link #onSaveInstanceState} method will be called).
3838 *
3839 * @return Returns true if the view state saving is enabled, else false.
3840 *
3841 * @see #setSaveEnabled(boolean)
3842 * @attr ref android.R.styleable#View_saveEnabled
3843 */
3844 public boolean isSaveEnabled() {
3845 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3846 }
3847
3848 /**
3849 * Controls whether the saving of this view's state is
3850 * enabled (that is, whether its {@link #onSaveInstanceState} method
3851 * will be called). Note that even if freezing is enabled, the
3852 * view still must have an id assigned to it (via {@link #setId setId()})
3853 * for its state to be saved. This flag can only disable the
3854 * saving of this view; any child views may still have their state saved.
3855 *
3856 * @param enabled Set to false to <em>disable</em> state saving, or true
3857 * (the default) to allow it.
3858 *
3859 * @see #isSaveEnabled()
3860 * @see #setId(int)
3861 * @see #onSaveInstanceState()
3862 * @attr ref android.R.styleable#View_saveEnabled
3863 */
3864 public void setSaveEnabled(boolean enabled) {
3865 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3866 }
3867
Jeff Brown85a31762010-09-01 17:01:00 -07003868 /**
3869 * Gets whether the framework should discard touches when the view's
3870 * window is obscured by another visible window.
3871 * Refer to the {@link View} security documentation for more details.
3872 *
3873 * @return True if touch filtering is enabled.
3874 *
3875 * @see #setFilterTouchesWhenObscured(boolean)
3876 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3877 */
3878 @ViewDebug.ExportedProperty
3879 public boolean getFilterTouchesWhenObscured() {
3880 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3881 }
3882
3883 /**
3884 * Sets whether the framework should discard touches when the view's
3885 * window is obscured by another visible window.
3886 * Refer to the {@link View} security documentation for more details.
3887 *
3888 * @param enabled True if touch filtering should be enabled.
3889 *
3890 * @see #getFilterTouchesWhenObscured
3891 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3892 */
3893 public void setFilterTouchesWhenObscured(boolean enabled) {
3894 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3895 FILTER_TOUCHES_WHEN_OBSCURED);
3896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897
3898 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003899 * Indicates whether the entire hierarchy under this view will save its
3900 * state when a state saving traversal occurs from its parent. The default
3901 * is true; if false, these views will not be saved unless
3902 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3903 *
3904 * @return Returns true if the view state saving from parent is enabled, else false.
3905 *
3906 * @see #setSaveFromParentEnabled(boolean)
3907 */
3908 public boolean isSaveFromParentEnabled() {
3909 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3910 }
3911
3912 /**
3913 * Controls whether the entire hierarchy under this view will save its
3914 * state when a state saving traversal occurs from its parent. The default
3915 * is true; if false, these views will not be saved unless
3916 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3917 *
3918 * @param enabled Set to false to <em>disable</em> state saving, or true
3919 * (the default) to allow it.
3920 *
3921 * @see #isSaveFromParentEnabled()
3922 * @see #setId(int)
3923 * @see #onSaveInstanceState()
3924 */
3925 public void setSaveFromParentEnabled(boolean enabled) {
3926 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
3927 }
3928
3929
3930 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 * Returns whether this View is able to take focus.
3932 *
3933 * @return True if this view can take focus, or false otherwise.
3934 * @attr ref android.R.styleable#View_focusable
3935 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003936 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 public final boolean isFocusable() {
3938 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3939 }
3940
3941 /**
3942 * When a view is focusable, it may not want to take focus when in touch mode.
3943 * For example, a button would like focus when the user is navigating via a D-pad
3944 * so that the user can click on it, but once the user starts touching the screen,
3945 * the button shouldn't take focus
3946 * @return Whether the view is focusable in touch mode.
3947 * @attr ref android.R.styleable#View_focusableInTouchMode
3948 */
3949 @ViewDebug.ExportedProperty
3950 public final boolean isFocusableInTouchMode() {
3951 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3952 }
3953
3954 /**
3955 * Find the nearest view in the specified direction that can take focus.
3956 * This does not actually give focus to that view.
3957 *
3958 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3959 *
3960 * @return The nearest focusable in the specified direction, or null if none
3961 * can be found.
3962 */
3963 public View focusSearch(int direction) {
3964 if (mParent != null) {
3965 return mParent.focusSearch(this, direction);
3966 } else {
3967 return null;
3968 }
3969 }
3970
3971 /**
3972 * This method is the last chance for the focused view and its ancestors to
3973 * respond to an arrow key. This is called when the focused view did not
3974 * consume the key internally, nor could the view system find a new view in
3975 * the requested direction to give focus to.
3976 *
3977 * @param focused The currently focused view.
3978 * @param direction The direction focus wants to move. One of FOCUS_UP,
3979 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3980 * @return True if the this view consumed this unhandled move.
3981 */
3982 public boolean dispatchUnhandledMove(View focused, int direction) {
3983 return false;
3984 }
3985
3986 /**
3987 * If a user manually specified the next view id for a particular direction,
Jeff Brown4e6319b2010-12-13 10:36:51 -08003988 * use the root to look up the view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 * @param root The root view of the hierarchy containing this view.
Jeff Brown4e6319b2010-12-13 10:36:51 -08003990 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
3991 * or FOCUS_BACKWARD.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 * @return The user specified next view, or null if there is none.
3993 */
3994 View findUserSetNextFocus(View root, int direction) {
3995 switch (direction) {
3996 case FOCUS_LEFT:
3997 if (mNextFocusLeftId == View.NO_ID) return null;
3998 return findViewShouldExist(root, mNextFocusLeftId);
3999 case FOCUS_RIGHT:
4000 if (mNextFocusRightId == View.NO_ID) return null;
4001 return findViewShouldExist(root, mNextFocusRightId);
4002 case FOCUS_UP:
4003 if (mNextFocusUpId == View.NO_ID) return null;
4004 return findViewShouldExist(root, mNextFocusUpId);
4005 case FOCUS_DOWN:
4006 if (mNextFocusDownId == View.NO_ID) return null;
4007 return findViewShouldExist(root, mNextFocusDownId);
Jeff Brown4e6319b2010-12-13 10:36:51 -08004008 case FOCUS_FORWARD:
4009 if (mNextFocusForwardId == View.NO_ID) return null;
4010 return findViewShouldExist(root, mNextFocusForwardId);
4011 case FOCUS_BACKWARD: {
4012 final int id = mID;
4013 return root.findViewByPredicate(new Predicate<View>() {
4014 @Override
4015 public boolean apply(View t) {
4016 return t.mNextFocusForwardId == id;
4017 }
4018 });
4019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 }
4021 return null;
4022 }
4023
4024 private static View findViewShouldExist(View root, int childViewId) {
4025 View result = root.findViewById(childViewId);
4026 if (result == null) {
4027 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4028 + "by user for id " + childViewId);
4029 }
4030 return result;
4031 }
4032
4033 /**
4034 * Find and return all focusable views that are descendants of this view,
4035 * possibly including this view if it is focusable itself.
4036 *
4037 * @param direction The direction of the focus
4038 * @return A list of focusable views
4039 */
4040 public ArrayList<View> getFocusables(int direction) {
4041 ArrayList<View> result = new ArrayList<View>(24);
4042 addFocusables(result, direction);
4043 return result;
4044 }
4045
4046 /**
4047 * Add any focusable views that are descendants of this view (possibly
4048 * including this view if it is focusable itself) to views. If we are in touch mode,
4049 * only add views that are also focusable in touch mode.
4050 *
4051 * @param views Focusable views found so far
4052 * @param direction The direction of the focus
4053 */
4054 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07004055 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057
svetoslavganov75986cf2009-05-14 22:28:01 -07004058 /**
4059 * Adds any focusable views that are descendants of this view (possibly
4060 * including this view if it is focusable itself) to views. This method
4061 * adds all focusable views regardless if we are in touch mode or
4062 * only views focusable in touch mode if we are in touch mode depending on
4063 * the focusable mode paramater.
4064 *
4065 * @param views Focusable views found so far or null if all we are interested is
4066 * the number of focusables.
4067 * @param direction The direction of the focus.
4068 * @param focusableMode The type of focusables to be added.
4069 *
4070 * @see #FOCUSABLES_ALL
4071 * @see #FOCUSABLES_TOUCH_MODE
4072 */
4073 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4074 if (!isFocusable()) {
4075 return;
4076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077
svetoslavganov75986cf2009-05-14 22:28:01 -07004078 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4079 isInTouchMode() && !isFocusableInTouchMode()) {
4080 return;
4081 }
4082
4083 if (views != null) {
4084 views.add(this);
4085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 }
4087
4088 /**
4089 * Find and return all touchable views that are descendants of this view,
4090 * possibly including this view if it is touchable itself.
4091 *
4092 * @return A list of touchable views
4093 */
4094 public ArrayList<View> getTouchables() {
4095 ArrayList<View> result = new ArrayList<View>();
4096 addTouchables(result);
4097 return result;
4098 }
4099
4100 /**
4101 * Add any touchable views that are descendants of this view (possibly
4102 * including this view if it is touchable itself) to views.
4103 *
4104 * @param views Touchable views found so far
4105 */
4106 public void addTouchables(ArrayList<View> views) {
4107 final int viewFlags = mViewFlags;
4108
4109 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4110 && (viewFlags & ENABLED_MASK) == ENABLED) {
4111 views.add(this);
4112 }
4113 }
4114
4115 /**
4116 * Call this to try to give focus to a specific view or to one of its
4117 * descendants.
4118 *
4119 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4120 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4121 * while the device is in touch mode.
4122 *
4123 * See also {@link #focusSearch}, which is what you call to say that you
4124 * have focus, and you want your parent to look for the next one.
4125 *
4126 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4127 * {@link #FOCUS_DOWN} and <code>null</code>.
4128 *
4129 * @return Whether this view or one of its descendants actually took focus.
4130 */
4131 public final boolean requestFocus() {
4132 return requestFocus(View.FOCUS_DOWN);
4133 }
4134
4135
4136 /**
4137 * Call this to try to give focus to a specific view or to one of its
4138 * descendants and give it a hint about what direction focus is heading.
4139 *
4140 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4141 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4142 * while the device is in touch mode.
4143 *
4144 * See also {@link #focusSearch}, which is what you call to say that you
4145 * have focus, and you want your parent to look for the next one.
4146 *
4147 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4148 * <code>null</code> set for the previously focused rectangle.
4149 *
4150 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4151 * @return Whether this view or one of its descendants actually took focus.
4152 */
4153 public final boolean requestFocus(int direction) {
4154 return requestFocus(direction, null);
4155 }
4156
4157 /**
4158 * Call this to try to give focus to a specific view or to one of its descendants
4159 * and give it hints about the direction and a specific rectangle that the focus
4160 * is coming from. The rectangle can help give larger views a finer grained hint
4161 * about where focus is coming from, and therefore, where to show selection, or
4162 * forward focus change internally.
4163 *
4164 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4165 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4166 * while the device is in touch mode.
4167 *
4168 * A View will not take focus if it is not visible.
4169 *
4170 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4171 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4172 *
4173 * See also {@link #focusSearch}, which is what you call to say that you
4174 * have focus, and you want your parent to look for the next one.
4175 *
4176 * You may wish to override this method if your custom {@link View} has an internal
4177 * {@link View} that it wishes to forward the request to.
4178 *
4179 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4180 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4181 * to give a finer grained hint about where focus is coming from. May be null
4182 * if there is no hint.
4183 * @return Whether this view or one of its descendants actually took focus.
4184 */
4185 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4186 // need to be focusable
4187 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4188 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4189 return false;
4190 }
4191
4192 // need to be focusable in touch mode if in touch mode
4193 if (isInTouchMode() &&
4194 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4195 return false;
4196 }
4197
4198 // need to not have any parents blocking us
4199 if (hasAncestorThatBlocksDescendantFocus()) {
4200 return false;
4201 }
4202
4203 handleFocusGainInternal(direction, previouslyFocusedRect);
4204 return true;
4205 }
4206
Christopher Tate2c095f32010-10-04 14:13:40 -07004207 /** Gets the ViewRoot, or null if not attached. */
4208 /*package*/ ViewRoot getViewRoot() {
4209 View root = getRootView();
4210 return root != null ? (ViewRoot)root.getParent() : null;
4211 }
4212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 /**
4214 * Call this to try to give focus to a specific view or to one of its descendants. This is a
4215 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4216 * touch mode to request focus when they are touched.
4217 *
4218 * @return Whether this view or one of its descendants actually took focus.
4219 *
4220 * @see #isInTouchMode()
4221 *
4222 */
4223 public final boolean requestFocusFromTouch() {
4224 // Leave touch mode if we need to
4225 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07004226 ViewRoot viewRoot = getViewRoot();
4227 if (viewRoot != null) {
4228 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229 }
4230 }
4231 return requestFocus(View.FOCUS_DOWN);
4232 }
4233
4234 /**
4235 * @return Whether any ancestor of this view blocks descendant focus.
4236 */
4237 private boolean hasAncestorThatBlocksDescendantFocus() {
4238 ViewParent ancestor = mParent;
4239 while (ancestor instanceof ViewGroup) {
4240 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4241 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4242 return true;
4243 } else {
4244 ancestor = vgAncestor.getParent();
4245 }
4246 }
4247 return false;
4248 }
4249
4250 /**
Romain Guya440b002010-02-24 15:57:54 -08004251 * @hide
4252 */
4253 public void dispatchStartTemporaryDetach() {
4254 onStartTemporaryDetach();
4255 }
4256
4257 /**
4258 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4260 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004261 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 */
4263 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004264 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004265 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004266 }
4267
4268 /**
4269 * @hide
4270 */
4271 public void dispatchFinishTemporaryDetach() {
4272 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 }
Romain Guy8506ab42009-06-11 17:35:47 -07004274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004275 /**
4276 * Called after {@link #onStartTemporaryDetach} when the container is done
4277 * changing the view.
4278 */
4279 public void onFinishTemporaryDetach() {
4280 }
Romain Guy8506ab42009-06-11 17:35:47 -07004281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282 /**
4283 * capture information of this view for later analysis: developement only
4284 * check dynamic switch to make sure we only dump view
4285 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4286 */
4287 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004288 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 return;
4290 }
4291 ViewDebug.dumpCapturedView(subTag, v);
4292 }
4293
4294 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004295 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4296 * for this view's window. Returns null if the view is not currently attached
4297 * to the window. Normally you will not need to use this directly, but
4298 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4299 */
4300 public KeyEvent.DispatcherState getKeyDispatcherState() {
4301 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4302 }
4303
4304 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 * Dispatch a key event before it is processed by any input method
4306 * associated with the view hierarchy. This can be used to intercept
4307 * key events in special situations before the IME consumes them; a
4308 * typical example would be handling the BACK key to update the application's
4309 * UI instead of allowing the IME to see it and close itself.
4310 *
4311 * @param event The key event to be dispatched.
4312 * @return True if the event was handled, false otherwise.
4313 */
4314 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4315 return onKeyPreIme(event.getKeyCode(), event);
4316 }
4317
4318 /**
4319 * Dispatch a key event to the next view on the focus path. This path runs
4320 * from the top of the view tree down to the currently focused view. If this
4321 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4322 * the next node down the focus path. This method also fires any key
4323 * listeners.
4324 *
4325 * @param event The key event to be dispatched.
4326 * @return True if the event was handled, false otherwise.
4327 */
4328 public boolean dispatchKeyEvent(KeyEvent event) {
4329 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330
Romain Guyf607bdc2010-09-10 19:20:06 -07004331 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 if (android.util.Config.LOGV) {
4333 captureViewInfo("captureViewKeyEvent", this);
4334 }
4335
Romain Guyf607bdc2010-09-10 19:20:06 -07004336 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4338 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4339 return true;
4340 }
4341
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004342 return event.dispatch(this, mAttachInfo != null
4343 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 }
4345
4346 /**
4347 * Dispatches a key shortcut event.
4348 *
4349 * @param event The key event to be dispatched.
4350 * @return True if the event was handled by the view, false otherwise.
4351 */
4352 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4353 return onKeyShortcut(event.getKeyCode(), event);
4354 }
4355
4356 /**
4357 * Pass the touch screen motion event down to the target view, or this
4358 * view if it is the target.
4359 *
4360 * @param event The motion event to be dispatched.
4361 * @return True if the event was handled by the view, false otherwise.
4362 */
4363 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004364 if (!onFilterTouchEventForSecurity(event)) {
4365 return false;
4366 }
4367
Romain Guyf607bdc2010-09-10 19:20:06 -07004368 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4370 mOnTouchListener.onTouch(this, event)) {
4371 return true;
4372 }
4373 return onTouchEvent(event);
4374 }
4375
4376 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004377 * Filter the touch event to apply security policies.
4378 *
4379 * @param event The motion event to be filtered.
4380 * @return True if the event should be dispatched, false if the event should be dropped.
4381 *
4382 * @see #getFilterTouchesWhenObscured
4383 */
4384 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004385 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004386 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4387 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4388 // Window is obscured, drop this touch.
4389 return false;
4390 }
4391 return true;
4392 }
4393
4394 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004395 * Pass a trackball motion event down to the focused view.
4396 *
4397 * @param event The motion event to be dispatched.
4398 * @return True if the event was handled by the view, false otherwise.
4399 */
4400 public boolean dispatchTrackballEvent(MotionEvent event) {
4401 //Log.i("view", "view=" + this + ", " + event.toString());
4402 return onTrackballEvent(event);
4403 }
4404
4405 /**
4406 * Called when the window containing this view gains or loses window focus.
4407 * ViewGroups should override to route to their children.
4408 *
4409 * @param hasFocus True if the window containing this view now has focus,
4410 * false otherwise.
4411 */
4412 public void dispatchWindowFocusChanged(boolean hasFocus) {
4413 onWindowFocusChanged(hasFocus);
4414 }
4415
4416 /**
4417 * Called when the window containing this view gains or loses focus. Note
4418 * that this is separate from view focus: to receive key events, both
4419 * your view and its window must have focus. If a window is displayed
4420 * on top of yours that takes input focus, then your own window will lose
4421 * focus but the view focus will remain unchanged.
4422 *
4423 * @param hasWindowFocus True if the window containing this view now has
4424 * focus, false otherwise.
4425 */
4426 public void onWindowFocusChanged(boolean hasWindowFocus) {
4427 InputMethodManager imm = InputMethodManager.peekInstance();
4428 if (!hasWindowFocus) {
4429 if (isPressed()) {
4430 setPressed(false);
4431 }
4432 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4433 imm.focusOut(this);
4434 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004435 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004436 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004437 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004438 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4439 imm.focusIn(this);
4440 }
4441 refreshDrawableState();
4442 }
4443
4444 /**
4445 * Returns true if this view is in a window that currently has window focus.
4446 * Note that this is not the same as the view itself having focus.
4447 *
4448 * @return True if this view is in a window that currently has window focus.
4449 */
4450 public boolean hasWindowFocus() {
4451 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4452 }
4453
4454 /**
Adam Powell326d8082009-12-09 15:10:07 -08004455 * Dispatch a view visibility change down the view hierarchy.
4456 * ViewGroups should override to route to their children.
4457 * @param changedView The view whose visibility changed. Could be 'this' or
4458 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004459 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4460 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004461 */
4462 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4463 onVisibilityChanged(changedView, visibility);
4464 }
4465
4466 /**
4467 * Called when the visibility of the view or an ancestor of the view is changed.
4468 * @param changedView The view whose visibility changed. Could be 'this' or
4469 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004470 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4471 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004472 */
4473 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004474 if (visibility == VISIBLE) {
4475 if (mAttachInfo != null) {
4476 initialAwakenScrollBars();
4477 } else {
4478 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4479 }
4480 }
Adam Powell326d8082009-12-09 15:10:07 -08004481 }
4482
4483 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004484 * Dispatch a hint about whether this view is displayed. For instance, when
4485 * a View moves out of the screen, it might receives a display hint indicating
4486 * the view is not displayed. Applications should not <em>rely</em> on this hint
4487 * as there is no guarantee that they will receive one.
4488 *
4489 * @param hint A hint about whether or not this view is displayed:
4490 * {@link #VISIBLE} or {@link #INVISIBLE}.
4491 */
4492 public void dispatchDisplayHint(int hint) {
4493 onDisplayHint(hint);
4494 }
4495
4496 /**
4497 * Gives this view a hint about whether is displayed or not. For instance, when
4498 * a View moves out of the screen, it might receives a display hint indicating
4499 * the view is not displayed. Applications should not <em>rely</em> on this hint
4500 * as there is no guarantee that they will receive one.
4501 *
4502 * @param hint A hint about whether or not this view is displayed:
4503 * {@link #VISIBLE} or {@link #INVISIBLE}.
4504 */
4505 protected void onDisplayHint(int hint) {
4506 }
4507
4508 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509 * Dispatch a window visibility change down the view hierarchy.
4510 * ViewGroups should override to route to their children.
4511 *
4512 * @param visibility The new visibility of the window.
4513 *
4514 * @see #onWindowVisibilityChanged
4515 */
4516 public void dispatchWindowVisibilityChanged(int visibility) {
4517 onWindowVisibilityChanged(visibility);
4518 }
4519
4520 /**
4521 * Called when the window containing has change its visibility
4522 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4523 * that this tells you whether or not your window is being made visible
4524 * to the window manager; this does <em>not</em> tell you whether or not
4525 * your window is obscured by other windows on the screen, even if it
4526 * is itself visible.
4527 *
4528 * @param visibility The new visibility of the window.
4529 */
4530 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004531 if (visibility == VISIBLE) {
4532 initialAwakenScrollBars();
4533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 }
4535
4536 /**
4537 * Returns the current visibility of the window this view is attached to
4538 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4539 *
4540 * @return Returns the current visibility of the view's window.
4541 */
4542 public int getWindowVisibility() {
4543 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4544 }
4545
4546 /**
4547 * Retrieve the overall visible display size in which the window this view is
4548 * attached to has been positioned in. This takes into account screen
4549 * decorations above the window, for both cases where the window itself
4550 * is being position inside of them or the window is being placed under
4551 * then and covered insets are used for the window to position its content
4552 * inside. In effect, this tells you the available area where content can
4553 * be placed and remain visible to users.
4554 *
4555 * <p>This function requires an IPC back to the window manager to retrieve
4556 * the requested information, so should not be used in performance critical
4557 * code like drawing.
4558 *
4559 * @param outRect Filled in with the visible display frame. If the view
4560 * is not attached to a window, this is simply the raw display size.
4561 */
4562 public void getWindowVisibleDisplayFrame(Rect outRect) {
4563 if (mAttachInfo != null) {
4564 try {
4565 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4566 } catch (RemoteException e) {
4567 return;
4568 }
4569 // XXX This is really broken, and probably all needs to be done
4570 // in the window manager, and we need to know more about whether
4571 // we want the area behind or in front of the IME.
4572 final Rect insets = mAttachInfo.mVisibleInsets;
4573 outRect.left += insets.left;
4574 outRect.top += insets.top;
4575 outRect.right -= insets.right;
4576 outRect.bottom -= insets.bottom;
4577 return;
4578 }
4579 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4580 outRect.set(0, 0, d.getWidth(), d.getHeight());
4581 }
4582
4583 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004584 * Dispatch a notification about a resource configuration change down
4585 * the view hierarchy.
4586 * ViewGroups should override to route to their children.
4587 *
4588 * @param newConfig The new resource configuration.
4589 *
4590 * @see #onConfigurationChanged
4591 */
4592 public void dispatchConfigurationChanged(Configuration newConfig) {
4593 onConfigurationChanged(newConfig);
4594 }
4595
4596 /**
4597 * Called when the current configuration of the resources being used
4598 * by the application have changed. You can use this to decide when
4599 * to reload resources that can changed based on orientation and other
4600 * configuration characterstics. You only need to use this if you are
4601 * not relying on the normal {@link android.app.Activity} mechanism of
4602 * recreating the activity instance upon a configuration change.
4603 *
4604 * @param newConfig The new resource configuration.
4605 */
4606 protected void onConfigurationChanged(Configuration newConfig) {
4607 }
4608
4609 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004610 * Private function to aggregate all per-view attributes in to the view
4611 * root.
4612 */
4613 void dispatchCollectViewAttributes(int visibility) {
4614 performCollectViewAttributes(visibility);
4615 }
4616
4617 void performCollectViewAttributes(int visibility) {
4618 //noinspection PointlessBitwiseExpression
4619 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4620 == (VISIBLE | KEEP_SCREEN_ON)) {
4621 mAttachInfo.mKeepScreenOn = true;
4622 }
4623 }
4624
4625 void needGlobalAttributesUpdate(boolean force) {
4626 AttachInfo ai = mAttachInfo;
4627 if (ai != null) {
4628 if (ai.mKeepScreenOn || force) {
4629 ai.mRecomputeGlobalAttributes = true;
4630 }
4631 }
4632 }
4633
4634 /**
4635 * Returns whether the device is currently in touch mode. Touch mode is entered
4636 * once the user begins interacting with the device by touch, and affects various
4637 * things like whether focus is always visible to the user.
4638 *
4639 * @return Whether the device is in touch mode.
4640 */
4641 @ViewDebug.ExportedProperty
4642 public boolean isInTouchMode() {
4643 if (mAttachInfo != null) {
4644 return mAttachInfo.mInTouchMode;
4645 } else {
4646 return ViewRoot.isInTouchMode();
4647 }
4648 }
4649
4650 /**
4651 * Returns the context the view is running in, through which it can
4652 * access the current theme, resources, etc.
4653 *
4654 * @return The view's Context.
4655 */
4656 @ViewDebug.CapturedViewProperty
4657 public final Context getContext() {
4658 return mContext;
4659 }
4660
4661 /**
4662 * Handle a key event before it is processed by any input method
4663 * associated with the view hierarchy. This can be used to intercept
4664 * key events in special situations before the IME consumes them; a
4665 * typical example would be handling the BACK key to update the application's
4666 * UI instead of allowing the IME to see it and close itself.
4667 *
4668 * @param keyCode The value in event.getKeyCode().
4669 * @param event Description of the key event.
4670 * @return If you handled the event, return true. If you want to allow the
4671 * event to be handled by the next receiver, return false.
4672 */
4673 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4674 return false;
4675 }
4676
4677 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004678 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
4679 * KeyEvent.Callback.onKeyDown()}: perform press of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004680 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4681 * is released, if the view is enabled and clickable.
4682 *
4683 * @param keyCode A key code that represents the button pressed, from
4684 * {@link android.view.KeyEvent}.
4685 * @param event The KeyEvent object that defines the button action.
4686 */
4687 public boolean onKeyDown(int keyCode, KeyEvent event) {
4688 boolean result = false;
4689
4690 switch (keyCode) {
4691 case KeyEvent.KEYCODE_DPAD_CENTER:
4692 case KeyEvent.KEYCODE_ENTER: {
4693 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4694 return true;
4695 }
4696 // Long clickable items don't necessarily have to be clickable
4697 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4698 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4699 (event.getRepeatCount() == 0)) {
4700 setPressed(true);
4701 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004702 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004703 }
4704 return true;
4705 }
4706 break;
4707 }
4708 }
4709 return result;
4710 }
4711
4712 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004713 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4714 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4715 * the event).
4716 */
4717 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4718 return false;
4719 }
4720
4721 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004722 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
4723 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004724 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4725 * {@link KeyEvent#KEYCODE_ENTER} is released.
4726 *
4727 * @param keyCode A key code that represents the button pressed, from
4728 * {@link android.view.KeyEvent}.
4729 * @param event The KeyEvent object that defines the button action.
4730 */
4731 public boolean onKeyUp(int keyCode, KeyEvent event) {
4732 boolean result = false;
4733
4734 switch (keyCode) {
4735 case KeyEvent.KEYCODE_DPAD_CENTER:
4736 case KeyEvent.KEYCODE_ENTER: {
4737 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4738 return true;
4739 }
4740 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4741 setPressed(false);
4742
4743 if (!mHasPerformedLongPress) {
4744 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004745 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004746
4747 result = performClick();
4748 }
4749 }
4750 break;
4751 }
4752 }
4753 return result;
4754 }
4755
4756 /**
4757 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4758 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4759 * the event).
4760 *
4761 * @param keyCode A key code that represents the button pressed, from
4762 * {@link android.view.KeyEvent}.
4763 * @param repeatCount The number of times the action was made.
4764 * @param event The KeyEvent object that defines the button action.
4765 */
4766 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4767 return false;
4768 }
4769
4770 /**
4771 * Called when an unhandled key shortcut event occurs.
4772 *
4773 * @param keyCode The value in event.getKeyCode().
4774 * @param event Description of the key event.
4775 * @return If you handled the event, return true. If you want to allow the
4776 * event to be handled by the next receiver, return false.
4777 */
4778 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4779 return false;
4780 }
4781
4782 /**
4783 * Check whether the called view is a text editor, in which case it
4784 * would make sense to automatically display a soft input window for
4785 * it. Subclasses should override this if they implement
4786 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004787 * a call on that method would return a non-null InputConnection, and
4788 * they are really a first-class editor that the user would normally
4789 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004790 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004791 * <p>The default implementation always returns false. This does
4792 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4793 * will not be called or the user can not otherwise perform edits on your
4794 * view; it is just a hint to the system that this is not the primary
4795 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004796 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004797 * @return Returns true if this view is a text editor, else false.
4798 */
4799 public boolean onCheckIsTextEditor() {
4800 return false;
4801 }
Romain Guy8506ab42009-06-11 17:35:47 -07004802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004803 /**
4804 * Create a new InputConnection for an InputMethod to interact
4805 * with the view. The default implementation returns null, since it doesn't
4806 * support input methods. You can override this to implement such support.
4807 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004808 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004809 * <p>When implementing this, you probably also want to implement
4810 * {@link #onCheckIsTextEditor()} to indicate you will return a
4811 * non-null InputConnection.
4812 *
4813 * @param outAttrs Fill in with attribute information about the connection.
4814 */
4815 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4816 return null;
4817 }
4818
4819 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004820 * Called by the {@link android.view.inputmethod.InputMethodManager}
4821 * when a view who is not the current
4822 * input connection target is trying to make a call on the manager. The
4823 * default implementation returns false; you can override this to return
4824 * true for certain views if you are performing InputConnection proxying
4825 * to them.
4826 * @param view The View that is making the InputMethodManager call.
4827 * @return Return true to allow the call, false to reject.
4828 */
4829 public boolean checkInputConnectionProxy(View view) {
4830 return false;
4831 }
Romain Guy8506ab42009-06-11 17:35:47 -07004832
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004833 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004834 * Show the context menu for this view. It is not safe to hold on to the
4835 * menu after returning from this method.
4836 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004837 * You should normally not overload this method. Overload
4838 * {@link #onCreateContextMenu(ContextMenu)} or define an
4839 * {@link OnCreateContextMenuListener} to add items to the context menu.
4840 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004841 * @param menu The context menu to populate
4842 */
4843 public void createContextMenu(ContextMenu menu) {
4844 ContextMenuInfo menuInfo = getContextMenuInfo();
4845
4846 // Sets the current menu info so all items added to menu will have
4847 // my extra info set.
4848 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4849
4850 onCreateContextMenu(menu);
4851 if (mOnCreateContextMenuListener != null) {
4852 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4853 }
4854
4855 // Clear the extra information so subsequent items that aren't mine don't
4856 // have my extra info.
4857 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4858
4859 if (mParent != null) {
4860 mParent.createContextMenu(menu);
4861 }
4862 }
4863
4864 /**
4865 * Views should implement this if they have extra information to associate
4866 * with the context menu. The return result is supplied as a parameter to
4867 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4868 * callback.
4869 *
4870 * @return Extra information about the item for which the context menu
4871 * should be shown. This information will vary across different
4872 * subclasses of View.
4873 */
4874 protected ContextMenuInfo getContextMenuInfo() {
4875 return null;
4876 }
4877
4878 /**
4879 * Views should implement this if the view itself is going to add items to
4880 * the context menu.
4881 *
4882 * @param menu the context menu to populate
4883 */
4884 protected void onCreateContextMenu(ContextMenu menu) {
4885 }
4886
4887 /**
4888 * Implement this method to handle trackball motion events. The
4889 * <em>relative</em> movement of the trackball since the last event
4890 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4891 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4892 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4893 * they will often be fractional values, representing the more fine-grained
4894 * movement information available from a trackball).
4895 *
4896 * @param event The motion event.
4897 * @return True if the event was handled, false otherwise.
4898 */
4899 public boolean onTrackballEvent(MotionEvent event) {
4900 return false;
4901 }
4902
4903 /**
4904 * Implement this method to handle touch screen motion events.
4905 *
4906 * @param event The motion event.
4907 * @return True if the event was handled, false otherwise.
4908 */
4909 public boolean onTouchEvent(MotionEvent event) {
4910 final int viewFlags = mViewFlags;
4911
4912 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4913 // A disabled view that is clickable still consumes the touch
4914 // events, it just doesn't respond to them.
4915 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4916 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4917 }
4918
4919 if (mTouchDelegate != null) {
4920 if (mTouchDelegate.onTouchEvent(event)) {
4921 return true;
4922 }
4923 }
4924
4925 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4926 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4927 switch (event.getAction()) {
4928 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004929 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4930 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 // take focus if we don't have it already and we should in
4932 // touch mode.
4933 boolean focusTaken = false;
4934 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4935 focusTaken = requestFocus();
4936 }
4937
4938 if (!mHasPerformedLongPress) {
4939 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004940 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941
4942 // Only perform take click actions if we were in the pressed state
4943 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004944 // Use a Runnable and post this rather than calling
4945 // performClick directly. This lets other visual state
4946 // of the view update before click actions start.
4947 if (mPerformClick == null) {
4948 mPerformClick = new PerformClick();
4949 }
4950 if (!post(mPerformClick)) {
4951 performClick();
4952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004953 }
4954 }
4955
4956 if (mUnsetPressedState == null) {
4957 mUnsetPressedState = new UnsetPressedState();
4958 }
4959
Adam Powelle14579b2009-12-16 18:39:52 -08004960 if (prepressed) {
4961 mPrivateFlags |= PRESSED;
4962 refreshDrawableState();
4963 postDelayed(mUnsetPressedState,
4964 ViewConfiguration.getPressedStateDuration());
4965 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004966 // If the post failed, unpress right now
4967 mUnsetPressedState.run();
4968 }
Adam Powelle14579b2009-12-16 18:39:52 -08004969 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004970 }
4971 break;
4972
4973 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004974 if (mPendingCheckForTap == null) {
4975 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 }
Adam Powelle14579b2009-12-16 18:39:52 -08004977 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004978 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004979 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004980 break;
4981
4982 case MotionEvent.ACTION_CANCEL:
4983 mPrivateFlags &= ~PRESSED;
4984 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004985 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004986 break;
4987
4988 case MotionEvent.ACTION_MOVE:
4989 final int x = (int) event.getX();
4990 final int y = (int) event.getY();
4991
4992 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004993 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004994 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004995 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004996 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004997 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004998 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004999
5000 // Need to switch from pressed to not pressed
5001 mPrivateFlags &= ~PRESSED;
5002 refreshDrawableState();
5003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005004 }
5005 break;
5006 }
5007 return true;
5008 }
5009
5010 return false;
5011 }
5012
5013 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05005014 * Remove the longpress detection timer.
5015 */
5016 private void removeLongPressCallback() {
5017 if (mPendingCheckForLongPress != null) {
5018 removeCallbacks(mPendingCheckForLongPress);
5019 }
5020 }
Adam Powelle14579b2009-12-16 18:39:52 -08005021
5022 /**
Romain Guya440b002010-02-24 15:57:54 -08005023 * Remove the prepress detection timer.
5024 */
5025 private void removeUnsetPressCallback() {
5026 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
5027 setPressed(false);
5028 removeCallbacks(mUnsetPressedState);
5029 }
5030 }
5031
5032 /**
Adam Powelle14579b2009-12-16 18:39:52 -08005033 * Remove the tap detection timer.
5034 */
5035 private void removeTapCallback() {
5036 if (mPendingCheckForTap != null) {
5037 mPrivateFlags &= ~PREPRESSED;
5038 removeCallbacks(mPendingCheckForTap);
5039 }
5040 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05005041
5042 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005043 * Cancels a pending long press. Your subclass can use this if you
5044 * want the context menu to come up if the user presses and holds
5045 * at the same place, but you don't want it to come up if they press
5046 * and then move around enough to cause scrolling.
5047 */
5048 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05005049 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08005050
5051 /*
5052 * The prepressed state handled by the tap callback is a display
5053 * construct, but the tap callback will post a long press callback
5054 * less its own timeout. Remove it here.
5055 */
5056 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057 }
5058
5059 /**
5060 * Sets the TouchDelegate for this View.
5061 */
5062 public void setTouchDelegate(TouchDelegate delegate) {
5063 mTouchDelegate = delegate;
5064 }
5065
5066 /**
5067 * Gets the TouchDelegate for this View.
5068 */
5069 public TouchDelegate getTouchDelegate() {
5070 return mTouchDelegate;
5071 }
5072
5073 /**
5074 * Set flags controlling behavior of this view.
5075 *
5076 * @param flags Constant indicating the value which should be set
5077 * @param mask Constant indicating the bit range that should be changed
5078 */
5079 void setFlags(int flags, int mask) {
5080 int old = mViewFlags;
5081 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
5082
5083 int changed = mViewFlags ^ old;
5084 if (changed == 0) {
5085 return;
5086 }
5087 int privateFlags = mPrivateFlags;
5088
5089 /* Check if the FOCUSABLE bit has changed */
5090 if (((changed & FOCUSABLE_MASK) != 0) &&
5091 ((privateFlags & HAS_BOUNDS) !=0)) {
5092 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
5093 && ((privateFlags & FOCUSED) != 0)) {
5094 /* Give up focus if we are no longer focusable */
5095 clearFocus();
5096 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
5097 && ((privateFlags & FOCUSED) == 0)) {
5098 /*
5099 * Tell the view system that we are now available to take focus
5100 * if no one else already has it.
5101 */
5102 if (mParent != null) mParent.focusableViewAvailable(this);
5103 }
5104 }
5105
5106 if ((flags & VISIBILITY_MASK) == VISIBLE) {
5107 if ((changed & VISIBILITY_MASK) != 0) {
5108 /*
5109 * If this view is becoming visible, set the DRAWN flag so that
5110 * the next invalidate() will not be skipped.
5111 */
5112 mPrivateFlags |= DRAWN;
5113
5114 needGlobalAttributesUpdate(true);
5115
5116 // a view becoming visible is worth notifying the parent
5117 // about in case nothing has focus. even if this specific view
5118 // isn't focusable, it may contain something that is, so let
5119 // the root view try to give this focus if nothing else does.
5120 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
5121 mParent.focusableViewAvailable(this);
5122 }
5123 }
5124 }
5125
5126 /* Check if the GONE bit has changed */
5127 if ((changed & GONE) != 0) {
5128 needGlobalAttributesUpdate(false);
5129 requestLayout();
5130 invalidate();
5131
Romain Guyecd80ee2009-12-03 17:13:02 -08005132 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5133 if (hasFocus()) clearFocus();
5134 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005135 }
5136 if (mAttachInfo != null) {
5137 mAttachInfo.mViewVisibilityChanged = true;
5138 }
5139 }
5140
5141 /* Check if the VISIBLE bit has changed */
5142 if ((changed & INVISIBLE) != 0) {
5143 needGlobalAttributesUpdate(false);
5144 invalidate();
5145
5146 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5147 // root view becoming invisible shouldn't clear focus
5148 if (getRootView() != this) {
5149 clearFocus();
5150 }
5151 }
5152 if (mAttachInfo != null) {
5153 mAttachInfo.mViewVisibilityChanged = true;
5154 }
5155 }
5156
Adam Powell326d8082009-12-09 15:10:07 -08005157 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07005158 if (mParent instanceof ViewGroup) {
5159 ((ViewGroup)mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
5160 }
Adam Powell326d8082009-12-09 15:10:07 -08005161 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5162 }
5163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005164 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5165 destroyDrawingCache();
5166 }
5167
5168 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5169 destroyDrawingCache();
5170 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5171 }
5172
5173 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5174 destroyDrawingCache();
5175 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5176 }
5177
5178 if ((changed & DRAW_MASK) != 0) {
5179 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5180 if (mBGDrawable != null) {
5181 mPrivateFlags &= ~SKIP_DRAW;
5182 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5183 } else {
5184 mPrivateFlags |= SKIP_DRAW;
5185 }
5186 } else {
5187 mPrivateFlags &= ~SKIP_DRAW;
5188 }
5189 requestLayout();
5190 invalidate();
5191 }
5192
5193 if ((changed & KEEP_SCREEN_ON) != 0) {
5194 if (mParent != null) {
5195 mParent.recomputeViewAttributes(this);
5196 }
5197 }
5198 }
5199
5200 /**
5201 * Change the view's z order in the tree, so it's on top of other sibling
5202 * views
5203 */
5204 public void bringToFront() {
5205 if (mParent != null) {
5206 mParent.bringChildToFront(this);
5207 }
5208 }
5209
5210 /**
5211 * This is called in response to an internal scroll in this view (i.e., the
5212 * view scrolled its own contents). This is typically as a result of
5213 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5214 * called.
5215 *
5216 * @param l Current horizontal scroll origin.
5217 * @param t Current vertical scroll origin.
5218 * @param oldl Previous horizontal scroll origin.
5219 * @param oldt Previous vertical scroll origin.
5220 */
5221 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5222 mBackgroundSizeChanged = true;
5223
5224 final AttachInfo ai = mAttachInfo;
5225 if (ai != null) {
5226 ai.mViewScrollChanged = true;
5227 }
5228 }
5229
5230 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005231 * Interface definition for a callback to be invoked when the layout bounds of a view
5232 * changes due to layout processing.
5233 */
5234 public interface OnLayoutChangeListener {
5235 /**
5236 * Called when the focus state of a view has changed.
5237 *
5238 * @param v The view whose state has changed.
5239 * @param left The new value of the view's left property.
5240 * @param top The new value of the view's top property.
5241 * @param right The new value of the view's right property.
5242 * @param bottom The new value of the view's bottom property.
5243 * @param oldLeft The previous value of the view's left property.
5244 * @param oldTop The previous value of the view's top property.
5245 * @param oldRight The previous value of the view's right property.
5246 * @param oldBottom The previous value of the view's bottom property.
5247 */
5248 void onLayoutChange(View v, int left, int top, int right, int bottom,
5249 int oldLeft, int oldTop, int oldRight, int oldBottom);
5250 }
5251
5252 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005253 * This is called during layout when the size of this view has changed. If
5254 * you were just added to the view hierarchy, you're called with the old
5255 * values of 0.
5256 *
5257 * @param w Current width of this view.
5258 * @param h Current height of this view.
5259 * @param oldw Old width of this view.
5260 * @param oldh Old height of this view.
5261 */
5262 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5263 }
5264
5265 /**
5266 * Called by draw to draw the child views. This may be overridden
5267 * by derived classes to gain control just before its children are drawn
5268 * (but after its own view has been drawn).
5269 * @param canvas the canvas on which to draw the view
5270 */
5271 protected void dispatchDraw(Canvas canvas) {
5272 }
5273
5274 /**
5275 * Gets the parent of this view. Note that the parent is a
5276 * ViewParent and not necessarily a View.
5277 *
5278 * @return Parent of this view.
5279 */
5280 public final ViewParent getParent() {
5281 return mParent;
5282 }
5283
5284 /**
5285 * Return the scrolled left position of this view. This is the left edge of
5286 * the displayed part of your view. You do not need to draw any pixels
5287 * farther left, since those are outside of the frame of your view on
5288 * screen.
5289 *
5290 * @return The left edge of the displayed part of your view, in pixels.
5291 */
5292 public final int getScrollX() {
5293 return mScrollX;
5294 }
5295
5296 /**
5297 * Return the scrolled top position of this view. This is the top edge of
5298 * the displayed part of your view. You do not need to draw any pixels above
5299 * it, since those are outside of the frame of your view on screen.
5300 *
5301 * @return The top edge of the displayed part of your view, in pixels.
5302 */
5303 public final int getScrollY() {
5304 return mScrollY;
5305 }
5306
5307 /**
5308 * Return the width of the your view.
5309 *
5310 * @return The width of your view, in pixels.
5311 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005312 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005313 public final int getWidth() {
5314 return mRight - mLeft;
5315 }
5316
5317 /**
5318 * Return the height of your view.
5319 *
5320 * @return The height of your view, in pixels.
5321 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005322 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005323 public final int getHeight() {
5324 return mBottom - mTop;
5325 }
5326
5327 /**
5328 * Return the visible drawing bounds of your view. Fills in the output
5329 * rectangle with the values from getScrollX(), getScrollY(),
5330 * getWidth(), and getHeight().
5331 *
5332 * @param outRect The (scrolled) drawing bounds of the view.
5333 */
5334 public void getDrawingRect(Rect outRect) {
5335 outRect.left = mScrollX;
5336 outRect.top = mScrollY;
5337 outRect.right = mScrollX + (mRight - mLeft);
5338 outRect.bottom = mScrollY + (mBottom - mTop);
5339 }
5340
5341 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005342 * Like {@link #getMeasuredWidthAndState()}, but only returns the
5343 * raw width component (that is the result is masked by
5344 * {@link #MEASURED_SIZE_MASK}).
5345 *
5346 * @return The raw measured width of this view.
5347 */
5348 public final int getMeasuredWidth() {
5349 return mMeasuredWidth & MEASURED_SIZE_MASK;
5350 }
5351
5352 /**
5353 * Return the full width measurement information for this view as computed
5354 * by the most recent call to {@link #measure}. This result is a bit mask
5355 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005356 * This should be used during measurement and layout calculations only. Use
5357 * {@link #getWidth()} to see how wide a view is after layout.
5358 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005359 * @return The measured width of this view as a bit mask.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005360 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08005361 public final int getMeasuredWidthAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 return mMeasuredWidth;
5363 }
5364
5365 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005366 * Like {@link #getMeasuredHeightAndState()}, but only returns the
5367 * raw width component (that is the result is masked by
5368 * {@link #MEASURED_SIZE_MASK}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005369 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005370 * @return The raw measured height of this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005371 */
5372 public final int getMeasuredHeight() {
Dianne Hackborn189ee182010-12-02 21:48:53 -08005373 return mMeasuredHeight & MEASURED_SIZE_MASK;
5374 }
5375
5376 /**
5377 * Return the full height measurement information for this view as computed
5378 * by the most recent call to {@link #measure}. This result is a bit mask
5379 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5380 * This should be used during measurement and layout calculations only. Use
5381 * {@link #getHeight()} to see how wide a view is after layout.
5382 *
5383 * @return The measured width of this view as a bit mask.
5384 */
5385 public final int getMeasuredHeightAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 return mMeasuredHeight;
5387 }
5388
5389 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005390 * Return only the state bits of {@link #getMeasuredWidthAndState()}
5391 * and {@link #getMeasuredHeightAndState()}, combined into one integer.
5392 * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
5393 * and the height component is at the shifted bits
5394 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
5395 */
5396 public final int getMeasuredState() {
5397 return (mMeasuredWidth&MEASURED_STATE_MASK)
5398 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
5399 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
5400 }
5401
5402 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005403 * The transform matrix of this view, which is calculated based on the current
5404 * roation, scale, and pivot properties.
5405 *
5406 * @see #getRotation()
5407 * @see #getScaleX()
5408 * @see #getScaleY()
5409 * @see #getPivotX()
5410 * @see #getPivotY()
5411 * @return The current transform matrix for the view
5412 */
5413 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005414 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005415 return mMatrix;
5416 }
5417
5418 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005419 * Utility function to determine if the value is far enough away from zero to be
5420 * considered non-zero.
5421 * @param value A floating point value to check for zero-ness
5422 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5423 */
5424 private static boolean nonzero(float value) {
5425 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5426 }
5427
5428 /**
Jeff Brown86671742010-09-30 20:00:15 -07005429 * Returns true if the transform matrix is the identity matrix.
5430 * Recomputes the matrix if necessary.
Romain Guy33e72ae2010-07-17 12:40:29 -07005431 *
5432 * @return True if the transform matrix is the identity matrix, false otherwise.
5433 */
Jeff Brown86671742010-09-30 20:00:15 -07005434 final boolean hasIdentityMatrix() {
5435 updateMatrix();
5436 return mMatrixIsIdentity;
5437 }
5438
5439 /**
5440 * Recomputes the transform matrix if necessary.
5441 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005442 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005443 if (mMatrixDirty) {
5444 // transform-related properties have changed since the last time someone
5445 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005446
5447 // Figure out if we need to update the pivot point
5448 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005449 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005450 mPrevWidth = mRight - mLeft;
5451 mPrevHeight = mBottom - mTop;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -08005452 mPivotX = mPrevWidth / 2f;
5453 mPivotY = mPrevHeight / 2f;
Chet Haasefd2b0022010-08-06 13:08:56 -07005454 }
5455 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005456 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005457 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5458 mMatrix.setTranslate(mTranslationX, mTranslationY);
5459 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5460 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5461 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005462 if (mCamera == null) {
5463 mCamera = new Camera();
5464 matrix3D = new Matrix();
5465 }
5466 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005467 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005468 mCamera.rotateX(mRotationX);
5469 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005470 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005471 mCamera.getMatrix(matrix3D);
5472 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005473 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005474 mMatrix.postConcat(matrix3D);
5475 mCamera.restore();
5476 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005477 mMatrixDirty = false;
5478 mMatrixIsIdentity = mMatrix.isIdentity();
5479 mInverseMatrixDirty = true;
5480 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005481 }
5482
5483 /**
5484 * Utility method to retrieve the inverse of the current mMatrix property.
5485 * We cache the matrix to avoid recalculating it when transform properties
5486 * have not changed.
5487 *
5488 * @return The inverse of the current matrix of this view.
5489 */
Jeff Brown86671742010-09-30 20:00:15 -07005490 final Matrix getInverseMatrix() {
5491 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005492 if (mInverseMatrixDirty) {
5493 if (mInverseMatrix == null) {
5494 mInverseMatrix = new Matrix();
5495 }
5496 mMatrix.invert(mInverseMatrix);
5497 mInverseMatrixDirty = false;
5498 }
5499 return mInverseMatrix;
5500 }
5501
5502 /**
5503 * The degrees that the view is rotated around the pivot point.
5504 *
5505 * @see #getPivotX()
5506 * @see #getPivotY()
5507 * @return The degrees of rotation.
5508 */
5509 public float getRotation() {
5510 return mRotation;
5511 }
5512
5513 /**
Chet Haase897247b2010-09-09 14:54:47 -07005514 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5515 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005516 *
5517 * @param rotation The degrees of rotation.
5518 * @see #getPivotX()
5519 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005520 *
5521 * @attr ref android.R.styleable#View_rotation
Chet Haasec3aa3612010-06-17 08:50:37 -07005522 */
5523 public void setRotation(float rotation) {
5524 if (mRotation != rotation) {
5525 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005526 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005527 mRotation = rotation;
5528 mMatrixDirty = true;
5529 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005530 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005531 }
5532 }
5533
5534 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005535 * The degrees that the view is rotated around the vertical axis through the pivot point.
5536 *
5537 * @see #getPivotX()
5538 * @see #getPivotY()
5539 * @return The degrees of Y rotation.
5540 */
5541 public float getRotationY() {
5542 return mRotationY;
5543 }
5544
5545 /**
Chet Haase897247b2010-09-09 14:54:47 -07005546 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5547 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5548 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005549 *
5550 * @param rotationY The degrees of Y rotation.
5551 * @see #getPivotX()
5552 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005553 *
5554 * @attr ref android.R.styleable#View_rotationY
Chet Haasefd2b0022010-08-06 13:08:56 -07005555 */
5556 public void setRotationY(float rotationY) {
5557 if (mRotationY != rotationY) {
5558 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005559 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005560 mRotationY = rotationY;
5561 mMatrixDirty = true;
5562 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005563 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005564 }
5565 }
5566
5567 /**
5568 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5569 *
5570 * @see #getPivotX()
5571 * @see #getPivotY()
5572 * @return The degrees of X rotation.
5573 */
5574 public float getRotationX() {
5575 return mRotationX;
5576 }
5577
5578 /**
Chet Haase897247b2010-09-09 14:54:47 -07005579 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5580 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5581 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005582 *
5583 * @param rotationX The degrees of X rotation.
5584 * @see #getPivotX()
5585 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005586 *
5587 * @attr ref android.R.styleable#View_rotationX
Chet Haasefd2b0022010-08-06 13:08:56 -07005588 */
5589 public void setRotationX(float rotationX) {
5590 if (mRotationX != rotationX) {
5591 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005592 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005593 mRotationX = rotationX;
5594 mMatrixDirty = true;
5595 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005596 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005597 }
5598 }
5599
5600 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005601 * The amount that the view is scaled in x around the pivot point, as a proportion of
5602 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5603 *
Joe Onorato93162322010-09-16 15:42:01 -04005604 * <p>By default, this is 1.0f.
5605 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005606 * @see #getPivotX()
5607 * @see #getPivotY()
5608 * @return The scaling factor.
5609 */
5610 public float getScaleX() {
5611 return mScaleX;
5612 }
5613
5614 /**
5615 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5616 * the view's unscaled width. A value of 1 means that no scaling is applied.
5617 *
5618 * @param scaleX The scaling factor.
5619 * @see #getPivotX()
5620 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005621 *
5622 * @attr ref android.R.styleable#View_scaleX
Chet Haasec3aa3612010-06-17 08:50:37 -07005623 */
5624 public void setScaleX(float scaleX) {
5625 if (mScaleX != scaleX) {
5626 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005627 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005628 mScaleX = scaleX;
5629 mMatrixDirty = true;
5630 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005631 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005632 }
5633 }
5634
5635 /**
5636 * The amount that the view is scaled in y around the pivot point, as a proportion of
5637 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5638 *
Joe Onorato93162322010-09-16 15:42:01 -04005639 * <p>By default, this is 1.0f.
5640 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005641 * @see #getPivotX()
5642 * @see #getPivotY()
5643 * @return The scaling factor.
5644 */
5645 public float getScaleY() {
5646 return mScaleY;
5647 }
5648
5649 /**
5650 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5651 * the view's unscaled width. A value of 1 means that no scaling is applied.
5652 *
5653 * @param scaleY The scaling factor.
5654 * @see #getPivotX()
5655 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005656 *
5657 * @attr ref android.R.styleable#View_scaleY
Chet Haasec3aa3612010-06-17 08:50:37 -07005658 */
5659 public void setScaleY(float scaleY) {
5660 if (mScaleY != scaleY) {
5661 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005662 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005663 mScaleY = scaleY;
5664 mMatrixDirty = true;
5665 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005666 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005667 }
5668 }
5669
5670 /**
5671 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5672 * and {@link #setScaleX(float) scaled}.
5673 *
5674 * @see #getRotation()
5675 * @see #getScaleX()
5676 * @see #getScaleY()
5677 * @see #getPivotY()
5678 * @return The x location of the pivot point.
5679 */
5680 public float getPivotX() {
5681 return mPivotX;
5682 }
5683
5684 /**
5685 * Sets the x location of the point around which the view is
5686 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005687 * By default, the pivot point is centered on the object.
5688 * Setting this property disables this behavior and causes the view to use only the
5689 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005690 *
5691 * @param pivotX The x location of the pivot point.
5692 * @see #getRotation()
5693 * @see #getScaleX()
5694 * @see #getScaleY()
5695 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005696 *
5697 * @attr ref android.R.styleable#View_transformPivotX
Chet Haasec3aa3612010-06-17 08:50:37 -07005698 */
5699 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005700 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005701 if (mPivotX != pivotX) {
5702 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005703 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005704 mPivotX = pivotX;
5705 mMatrixDirty = true;
5706 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005707 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005708 }
5709 }
5710
5711 /**
5712 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5713 * and {@link #setScaleY(float) scaled}.
5714 *
5715 * @see #getRotation()
5716 * @see #getScaleX()
5717 * @see #getScaleY()
5718 * @see #getPivotY()
5719 * @return The y location of the pivot point.
5720 */
5721 public float getPivotY() {
5722 return mPivotY;
5723 }
5724
5725 /**
5726 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005727 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5728 * Setting this property disables this behavior and causes the view to use only the
5729 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005730 *
5731 * @param pivotY The y location of the pivot point.
5732 * @see #getRotation()
5733 * @see #getScaleX()
5734 * @see #getScaleY()
5735 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005736 *
5737 * @attr ref android.R.styleable#View_transformPivotY
Chet Haasec3aa3612010-06-17 08:50:37 -07005738 */
5739 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005740 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005741 if (mPivotY != pivotY) {
5742 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005743 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005744 mPivotY = pivotY;
5745 mMatrixDirty = true;
5746 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005747 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005748 }
5749 }
5750
5751 /**
5752 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5753 * completely transparent and 1 means the view is completely opaque.
5754 *
Joe Onorato93162322010-09-16 15:42:01 -04005755 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005756 * @return The opacity of the view.
5757 */
5758 public float getAlpha() {
5759 return mAlpha;
5760 }
5761
5762 /**
5763 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5764 * completely transparent and 1 means the view is completely opaque.
5765 *
5766 * @param alpha The opacity of the view.
Chet Haase73066682010-11-29 15:55:32 -08005767 *
5768 * @attr ref android.R.styleable#View_alpha
Chet Haasec3aa3612010-06-17 08:50:37 -07005769 */
5770 public void setAlpha(float alpha) {
5771 mAlpha = alpha;
Chet Haaseed032702010-10-01 14:05:54 -07005772 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07005773 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005774 // subclass is handling alpha - don't optimize rendering cache invalidation
5775 invalidate();
5776 } else {
Romain Guya3496a92010-10-12 11:53:24 -07005777 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005778 invalidate(false);
5779 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005780 }
5781
5782 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 * Top position of this view relative to its parent.
5784 *
5785 * @return The top of this view, in pixels.
5786 */
5787 @ViewDebug.CapturedViewProperty
5788 public final int getTop() {
5789 return mTop;
5790 }
5791
5792 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005793 * Sets the top position of this view relative to its parent. This method is meant to be called
5794 * by the layout system and should not generally be called otherwise, because the property
5795 * may be changed at any time by the layout.
5796 *
5797 * @param top The top of this view, in pixels.
5798 */
5799 public final void setTop(int top) {
5800 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07005801 updateMatrix();
5802 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005803 final ViewParent p = mParent;
5804 if (p != null && mAttachInfo != null) {
5805 final Rect r = mAttachInfo.mTmpInvalRect;
5806 int minTop;
5807 int yLoc;
5808 if (top < mTop) {
5809 minTop = top;
5810 yLoc = top - mTop;
5811 } else {
5812 minTop = mTop;
5813 yLoc = 0;
5814 }
5815 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5816 p.invalidateChild(this, r);
5817 }
5818 } else {
5819 // Double-invalidation is necessary to capture view's old and new areas
5820 invalidate();
5821 }
5822
Chet Haaseed032702010-10-01 14:05:54 -07005823 int width = mRight - mLeft;
5824 int oldHeight = mBottom - mTop;
5825
Chet Haase21cd1382010-09-01 17:42:29 -07005826 mTop = top;
5827
Chet Haaseed032702010-10-01 14:05:54 -07005828 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5829
Chet Haase21cd1382010-09-01 17:42:29 -07005830 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005831 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5832 // A change in dimension means an auto-centered pivot point changes, too
5833 mMatrixDirty = true;
5834 }
Chet Haase21cd1382010-09-01 17:42:29 -07005835 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5836 invalidate();
5837 }
Chet Haase55dbb652010-12-21 20:15:08 -08005838 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07005839 }
5840 }
5841
5842 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 * Bottom position of this view relative to its parent.
5844 *
5845 * @return The bottom of this view, in pixels.
5846 */
5847 @ViewDebug.CapturedViewProperty
5848 public final int getBottom() {
5849 return mBottom;
5850 }
5851
5852 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005853 * Sets the bottom position of this view relative to its parent. This method is meant to be
5854 * called by the layout system and should not generally be called otherwise, because the
5855 * property may be changed at any time by the layout.
5856 *
5857 * @param bottom The bottom of this view, in pixels.
5858 */
5859 public final void setBottom(int bottom) {
5860 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07005861 updateMatrix();
5862 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005863 final ViewParent p = mParent;
5864 if (p != null && mAttachInfo != null) {
5865 final Rect r = mAttachInfo.mTmpInvalRect;
5866 int maxBottom;
5867 if (bottom < mBottom) {
5868 maxBottom = mBottom;
5869 } else {
5870 maxBottom = bottom;
5871 }
5872 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5873 p.invalidateChild(this, r);
5874 }
5875 } else {
5876 // Double-invalidation is necessary to capture view's old and new areas
5877 invalidate();
5878 }
5879
Chet Haaseed032702010-10-01 14:05:54 -07005880 int width = mRight - mLeft;
5881 int oldHeight = mBottom - mTop;
5882
Chet Haase21cd1382010-09-01 17:42:29 -07005883 mBottom = bottom;
5884
Chet Haaseed032702010-10-01 14:05:54 -07005885 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5886
Chet Haase21cd1382010-09-01 17:42:29 -07005887 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005888 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5889 // A change in dimension means an auto-centered pivot point changes, too
5890 mMatrixDirty = true;
5891 }
Chet Haase21cd1382010-09-01 17:42:29 -07005892 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5893 invalidate();
5894 }
Chet Haase55dbb652010-12-21 20:15:08 -08005895 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07005896 }
5897 }
5898
5899 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 * Left position of this view relative to its parent.
5901 *
5902 * @return The left edge of this view, in pixels.
5903 */
5904 @ViewDebug.CapturedViewProperty
5905 public final int getLeft() {
5906 return mLeft;
5907 }
5908
5909 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005910 * Sets the left position of this view relative to its parent. This method is meant to be called
5911 * by the layout system and should not generally be called otherwise, because the property
5912 * may be changed at any time by the layout.
5913 *
5914 * @param left The bottom of this view, in pixels.
5915 */
5916 public final void setLeft(int left) {
5917 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07005918 updateMatrix();
5919 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005920 final ViewParent p = mParent;
5921 if (p != null && mAttachInfo != null) {
5922 final Rect r = mAttachInfo.mTmpInvalRect;
5923 int minLeft;
5924 int xLoc;
5925 if (left < mLeft) {
5926 minLeft = left;
5927 xLoc = left - mLeft;
5928 } else {
5929 minLeft = mLeft;
5930 xLoc = 0;
5931 }
5932 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
5933 p.invalidateChild(this, r);
5934 }
5935 } else {
5936 // Double-invalidation is necessary to capture view's old and new areas
5937 invalidate();
5938 }
5939
Chet Haaseed032702010-10-01 14:05:54 -07005940 int oldWidth = mRight - mLeft;
5941 int height = mBottom - mTop;
5942
Chet Haase21cd1382010-09-01 17:42:29 -07005943 mLeft = left;
5944
Chet Haaseed032702010-10-01 14:05:54 -07005945 onSizeChanged(mRight - mLeft, height, oldWidth, height);
5946
Chet Haase21cd1382010-09-01 17:42:29 -07005947 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005948 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5949 // A change in dimension means an auto-centered pivot point changes, too
5950 mMatrixDirty = true;
5951 }
Chet Haase21cd1382010-09-01 17:42:29 -07005952 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5953 invalidate();
5954 }
Chet Haase55dbb652010-12-21 20:15:08 -08005955 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07005956 }
5957 }
5958
5959 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960 * Right position of this view relative to its parent.
5961 *
5962 * @return The right edge of this view, in pixels.
5963 */
5964 @ViewDebug.CapturedViewProperty
5965 public final int getRight() {
5966 return mRight;
5967 }
5968
5969 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005970 * Sets the right position of this view relative to its parent. This method is meant to be called
5971 * by the layout system and should not generally be called otherwise, because the property
5972 * may be changed at any time by the layout.
5973 *
5974 * @param right The bottom of this view, in pixels.
5975 */
5976 public final void setRight(int right) {
5977 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07005978 updateMatrix();
5979 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005980 final ViewParent p = mParent;
5981 if (p != null && mAttachInfo != null) {
5982 final Rect r = mAttachInfo.mTmpInvalRect;
5983 int maxRight;
5984 if (right < mRight) {
5985 maxRight = mRight;
5986 } else {
5987 maxRight = right;
5988 }
5989 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
5990 p.invalidateChild(this, r);
5991 }
5992 } else {
5993 // Double-invalidation is necessary to capture view's old and new areas
5994 invalidate();
5995 }
5996
Chet Haaseed032702010-10-01 14:05:54 -07005997 int oldWidth = mRight - mLeft;
5998 int height = mBottom - mTop;
5999
Chet Haase21cd1382010-09-01 17:42:29 -07006000 mRight = right;
6001
Chet Haaseed032702010-10-01 14:05:54 -07006002 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6003
Chet Haase21cd1382010-09-01 17:42:29 -07006004 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006005 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6006 // A change in dimension means an auto-centered pivot point changes, too
6007 mMatrixDirty = true;
6008 }
Chet Haase21cd1382010-09-01 17:42:29 -07006009 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6010 invalidate();
6011 }
Chet Haase55dbb652010-12-21 20:15:08 -08006012 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006013 }
6014 }
6015
6016 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006017 * The visual x position of this view, in pixels. This is equivalent to the
6018 * {@link #setTranslationX(float) translationX} property plus the current
6019 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07006020 *
Chet Haasedf030d22010-07-30 17:22:38 -07006021 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006022 */
Chet Haasedf030d22010-07-30 17:22:38 -07006023 public float getX() {
6024 return mLeft + mTranslationX;
6025 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006026
Chet Haasedf030d22010-07-30 17:22:38 -07006027 /**
6028 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
6029 * {@link #setTranslationX(float) translationX} property to be the difference between
6030 * the x value passed in and the current {@link #getLeft() left} property.
6031 *
6032 * @param x The visual x position of this view, in pixels.
6033 */
6034 public void setX(float x) {
6035 setTranslationX(x - mLeft);
6036 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006037
Chet Haasedf030d22010-07-30 17:22:38 -07006038 /**
6039 * The visual y position of this view, in pixels. This is equivalent to the
6040 * {@link #setTranslationY(float) translationY} property plus the current
6041 * {@link #getTop() top} property.
6042 *
6043 * @return The visual y position of this view, in pixels.
6044 */
6045 public float getY() {
6046 return mTop + mTranslationY;
6047 }
6048
6049 /**
6050 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
6051 * {@link #setTranslationY(float) translationY} property to be the difference between
6052 * the y value passed in and the current {@link #getTop() top} property.
6053 *
6054 * @param y The visual y position of this view, in pixels.
6055 */
6056 public void setY(float y) {
6057 setTranslationY(y - mTop);
6058 }
6059
6060
6061 /**
6062 * The horizontal location of this view relative to its {@link #getLeft() left} position.
6063 * This position is post-layout, in addition to wherever the object's
6064 * layout placed it.
6065 *
6066 * @return The horizontal position of this view relative to its left position, in pixels.
6067 */
6068 public float getTranslationX() {
6069 return mTranslationX;
6070 }
6071
6072 /**
6073 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
6074 * This effectively positions the object post-layout, in addition to wherever the object's
6075 * layout placed it.
6076 *
6077 * @param translationX The horizontal position of this view relative to its left position,
6078 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006079 *
6080 * @attr ref android.R.styleable#View_translationX
Chet Haasedf030d22010-07-30 17:22:38 -07006081 */
6082 public void setTranslationX(float translationX) {
6083 if (mTranslationX != translationX) {
6084 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006085 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006086 mTranslationX = translationX;
6087 mMatrixDirty = true;
6088 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006089 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006090 }
6091 }
6092
6093 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006094 * The horizontal location of this view relative to its {@link #getTop() top} position.
6095 * This position is post-layout, in addition to wherever the object's
6096 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006097 *
Chet Haasedf030d22010-07-30 17:22:38 -07006098 * @return The vertical position of this view relative to its top position,
6099 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006100 */
Chet Haasedf030d22010-07-30 17:22:38 -07006101 public float getTranslationY() {
6102 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07006103 }
6104
6105 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006106 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
6107 * This effectively positions the object post-layout, in addition to wherever the object's
6108 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006109 *
Chet Haasedf030d22010-07-30 17:22:38 -07006110 * @param translationY The vertical position of this view relative to its top position,
6111 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006112 *
6113 * @attr ref android.R.styleable#View_translationY
Chet Haasec3aa3612010-06-17 08:50:37 -07006114 */
Chet Haasedf030d22010-07-30 17:22:38 -07006115 public void setTranslationY(float translationY) {
6116 if (mTranslationY != translationY) {
6117 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006118 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006119 mTranslationY = translationY;
6120 mMatrixDirty = true;
6121 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006122 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006123 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006124 }
6125
6126 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 * Hit rectangle in parent's coordinates
6128 *
6129 * @param outRect The hit rectangle of the view.
6130 */
6131 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07006132 updateMatrix();
6133 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006134 outRect.set(mLeft, mTop, mRight, mBottom);
6135 } else {
6136 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07006137 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07006138 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07006139 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
6140 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07006141 }
6142 }
6143
6144 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07006145 * Determines whether the given point, in local coordinates is inside the view.
6146 */
6147 /*package*/ final boolean pointInView(float localX, float localY) {
6148 return localX >= 0 && localX < (mRight - mLeft)
6149 && localY >= 0 && localY < (mBottom - mTop);
6150 }
6151
6152 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07006153 * Utility method to determine whether the given point, in local coordinates,
6154 * is inside the view, where the area of the view is expanded by the slop factor.
6155 * This method is called while processing touch-move events to determine if the event
6156 * is still within the view.
6157 */
6158 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07006159 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07006160 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 }
6162
6163 /**
6164 * When a view has focus and the user navigates away from it, the next view is searched for
6165 * starting from the rectangle filled in by this method.
6166 *
6167 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
6168 * view maintains some idea of internal selection, such as a cursor, or a selected row
6169 * or column, you should override this method and fill in a more specific rectangle.
6170 *
6171 * @param r The rectangle to fill in, in this view's coordinates.
6172 */
6173 public void getFocusedRect(Rect r) {
6174 getDrawingRect(r);
6175 }
6176
6177 /**
6178 * If some part of this view is not clipped by any of its parents, then
6179 * return that area in r in global (root) coordinates. To convert r to local
6180 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
6181 * -globalOffset.y)) If the view is completely clipped or translated out,
6182 * return false.
6183 *
6184 * @param r If true is returned, r holds the global coordinates of the
6185 * visible portion of this view.
6186 * @param globalOffset If true is returned, globalOffset holds the dx,dy
6187 * between this view and its root. globalOffet may be null.
6188 * @return true if r is non-empty (i.e. part of the view is visible at the
6189 * root level.
6190 */
6191 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6192 int width = mRight - mLeft;
6193 int height = mBottom - mTop;
6194 if (width > 0 && height > 0) {
6195 r.set(0, 0, width, height);
6196 if (globalOffset != null) {
6197 globalOffset.set(-mScrollX, -mScrollY);
6198 }
6199 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6200 }
6201 return false;
6202 }
6203
6204 public final boolean getGlobalVisibleRect(Rect r) {
6205 return getGlobalVisibleRect(r, null);
6206 }
6207
6208 public final boolean getLocalVisibleRect(Rect r) {
6209 Point offset = new Point();
6210 if (getGlobalVisibleRect(r, offset)) {
6211 r.offset(-offset.x, -offset.y); // make r local
6212 return true;
6213 }
6214 return false;
6215 }
6216
6217 /**
6218 * Offset this view's vertical location by the specified number of pixels.
6219 *
6220 * @param offset the number of pixels to offset the view by
6221 */
6222 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006223 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006224 updateMatrix();
6225 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006226 final ViewParent p = mParent;
6227 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006228 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006229 int minTop;
6230 int maxBottom;
6231 int yLoc;
6232 if (offset < 0) {
6233 minTop = mTop + offset;
6234 maxBottom = mBottom;
6235 yLoc = offset;
6236 } else {
6237 minTop = mTop;
6238 maxBottom = mBottom + offset;
6239 yLoc = 0;
6240 }
6241 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6242 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006243 }
6244 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006245 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006246 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006247
Chet Haasec3aa3612010-06-17 08:50:37 -07006248 mTop += offset;
6249 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006250
Chet Haasec3aa3612010-06-17 08:50:37 -07006251 if (!mMatrixIsIdentity) {
6252 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006253 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006254 }
6255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 }
6257
6258 /**
6259 * Offset this view's horizontal location by the specified amount of pixels.
6260 *
6261 * @param offset the numer of pixels to offset the view by
6262 */
6263 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006264 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006265 updateMatrix();
6266 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006267 final ViewParent p = mParent;
6268 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006269 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006270 int minLeft;
6271 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006272 if (offset < 0) {
6273 minLeft = mLeft + offset;
6274 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006275 } else {
6276 minLeft = mLeft;
6277 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006278 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006279 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07006280 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006281 }
6282 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006283 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006284 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006285
Chet Haasec3aa3612010-06-17 08:50:37 -07006286 mLeft += offset;
6287 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006288
Chet Haasec3aa3612010-06-17 08:50:37 -07006289 if (!mMatrixIsIdentity) {
6290 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006291 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006292 }
6293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 }
6295
6296 /**
6297 * Get the LayoutParams associated with this view. All views should have
6298 * layout parameters. These supply parameters to the <i>parent</i> of this
6299 * view specifying how it should be arranged. There are many subclasses of
6300 * ViewGroup.LayoutParams, and these correspond to the different subclasses
6301 * of ViewGroup that are responsible for arranging their children.
6302 * @return The LayoutParams associated with this view
6303 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07006304 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 public ViewGroup.LayoutParams getLayoutParams() {
6306 return mLayoutParams;
6307 }
6308
6309 /**
6310 * Set the layout parameters associated with this view. These supply
6311 * parameters to the <i>parent</i> of this view specifying how it should be
6312 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6313 * correspond to the different subclasses of ViewGroup that are responsible
6314 * for arranging their children.
6315 *
6316 * @param params the layout parameters for this view
6317 */
6318 public void setLayoutParams(ViewGroup.LayoutParams params) {
6319 if (params == null) {
6320 throw new NullPointerException("params == null");
6321 }
6322 mLayoutParams = params;
6323 requestLayout();
6324 }
6325
6326 /**
6327 * Set the scrolled position of your view. This will cause a call to
6328 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6329 * invalidated.
6330 * @param x the x position to scroll to
6331 * @param y the y position to scroll to
6332 */
6333 public void scrollTo(int x, int y) {
6334 if (mScrollX != x || mScrollY != y) {
6335 int oldX = mScrollX;
6336 int oldY = mScrollY;
6337 mScrollX = x;
6338 mScrollY = y;
6339 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006340 if (!awakenScrollBars()) {
6341 invalidate();
6342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343 }
6344 }
6345
6346 /**
6347 * Move the scrolled position of your view. This will cause a call to
6348 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6349 * invalidated.
6350 * @param x the amount of pixels to scroll by horizontally
6351 * @param y the amount of pixels to scroll by vertically
6352 */
6353 public void scrollBy(int x, int y) {
6354 scrollTo(mScrollX + x, mScrollY + y);
6355 }
6356
6357 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006358 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6359 * animation to fade the scrollbars out after a default delay. If a subclass
6360 * provides animated scrolling, the start delay should equal the duration
6361 * of the scrolling animation.</p>
6362 *
6363 * <p>The animation starts only if at least one of the scrollbars is
6364 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6365 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6366 * this method returns true, and false otherwise. If the animation is
6367 * started, this method calls {@link #invalidate()}; in that case the
6368 * caller should not call {@link #invalidate()}.</p>
6369 *
6370 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006371 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006372 *
6373 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6374 * and {@link #scrollTo(int, int)}.</p>
6375 *
6376 * @return true if the animation is played, false otherwise
6377 *
6378 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006379 * @see #scrollBy(int, int)
6380 * @see #scrollTo(int, int)
6381 * @see #isHorizontalScrollBarEnabled()
6382 * @see #isVerticalScrollBarEnabled()
6383 * @see #setHorizontalScrollBarEnabled(boolean)
6384 * @see #setVerticalScrollBarEnabled(boolean)
6385 */
6386 protected boolean awakenScrollBars() {
6387 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006388 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006389 }
6390
6391 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006392 * Trigger the scrollbars to draw.
6393 * This method differs from awakenScrollBars() only in its default duration.
6394 * initialAwakenScrollBars() will show the scroll bars for longer than
6395 * usual to give the user more of a chance to notice them.
6396 *
6397 * @return true if the animation is played, false otherwise.
6398 */
6399 private boolean initialAwakenScrollBars() {
6400 return mScrollCache != null &&
6401 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6402 }
6403
6404 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006405 * <p>
6406 * Trigger the scrollbars to draw. When invoked this method starts an
6407 * animation to fade the scrollbars out after a fixed delay. If a subclass
6408 * provides animated scrolling, the start delay should equal the duration of
6409 * the scrolling animation.
6410 * </p>
6411 *
6412 * <p>
6413 * The animation starts only if at least one of the scrollbars is enabled,
6414 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6415 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6416 * this method returns true, and false otherwise. If the animation is
6417 * started, this method calls {@link #invalidate()}; in that case the caller
6418 * should not call {@link #invalidate()}.
6419 * </p>
6420 *
6421 * <p>
6422 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006423 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006424 * </p>
6425 *
6426 * @param startDelay the delay, in milliseconds, after which the animation
6427 * should start; when the delay is 0, the animation starts
6428 * immediately
6429 * @return true if the animation is played, false otherwise
6430 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006431 * @see #scrollBy(int, int)
6432 * @see #scrollTo(int, int)
6433 * @see #isHorizontalScrollBarEnabled()
6434 * @see #isVerticalScrollBarEnabled()
6435 * @see #setHorizontalScrollBarEnabled(boolean)
6436 * @see #setVerticalScrollBarEnabled(boolean)
6437 */
6438 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006439 return awakenScrollBars(startDelay, true);
6440 }
6441
6442 /**
6443 * <p>
6444 * Trigger the scrollbars to draw. When invoked this method starts an
6445 * animation to fade the scrollbars out after a fixed delay. If a subclass
6446 * provides animated scrolling, the start delay should equal the duration of
6447 * the scrolling animation.
6448 * </p>
6449 *
6450 * <p>
6451 * The animation starts only if at least one of the scrollbars is enabled,
6452 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6453 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6454 * this method returns true, and false otherwise. If the animation is
6455 * started, this method calls {@link #invalidate()} if the invalidate parameter
6456 * is set to true; in that case the caller
6457 * should not call {@link #invalidate()}.
6458 * </p>
6459 *
6460 * <p>
6461 * This method should be invoked everytime a subclass directly updates the
6462 * scroll parameters.
6463 * </p>
6464 *
6465 * @param startDelay the delay, in milliseconds, after which the animation
6466 * should start; when the delay is 0, the animation starts
6467 * immediately
6468 *
6469 * @param invalidate Wheter this method should call invalidate
6470 *
6471 * @return true if the animation is played, false otherwise
6472 *
6473 * @see #scrollBy(int, int)
6474 * @see #scrollTo(int, int)
6475 * @see #isHorizontalScrollBarEnabled()
6476 * @see #isVerticalScrollBarEnabled()
6477 * @see #setHorizontalScrollBarEnabled(boolean)
6478 * @see #setVerticalScrollBarEnabled(boolean)
6479 */
6480 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006481 final ScrollabilityCache scrollCache = mScrollCache;
6482
6483 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6484 return false;
6485 }
6486
6487 if (scrollCache.scrollBar == null) {
6488 scrollCache.scrollBar = new ScrollBarDrawable();
6489 }
6490
6491 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6492
Mike Cleron290947b2009-09-29 18:34:32 -07006493 if (invalidate) {
6494 // Invalidate to show the scrollbars
6495 invalidate();
6496 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006497
6498 if (scrollCache.state == ScrollabilityCache.OFF) {
6499 // FIXME: this is copied from WindowManagerService.
6500 // We should get this value from the system when it
6501 // is possible to do so.
6502 final int KEY_REPEAT_FIRST_DELAY = 750;
6503 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6504 }
6505
6506 // Tell mScrollCache when we should start fading. This may
6507 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006508 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006509 scrollCache.fadeStartTime = fadeStartTime;
6510 scrollCache.state = ScrollabilityCache.ON;
6511
6512 // Schedule our fader to run, unscheduling any old ones first
6513 if (mAttachInfo != null) {
6514 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6515 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6516 }
6517
6518 return true;
6519 }
6520
6521 return false;
6522 }
6523
6524 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 * Mark the the area defined by dirty as needing to be drawn. If the view is
6526 * visible, {@link #onDraw} will be called at some point in the future.
6527 * This must be called from a UI thread. To call from a non-UI thread, call
6528 * {@link #postInvalidate()}.
6529 *
6530 * WARNING: This method is destructive to dirty.
6531 * @param dirty the rectangle representing the bounds of the dirty region
6532 */
6533 public void invalidate(Rect dirty) {
6534 if (ViewDebug.TRACE_HIERARCHY) {
6535 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6536 }
6537
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006538 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6539 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6541 final ViewParent p = mParent;
6542 final AttachInfo ai = mAttachInfo;
Romain Guyaf636eb2010-12-09 17:47:21 -08006543 if (p != null && ai != null && ai.mHardwareAccelerated) {
6544 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6545 // with a null dirty rect, which tells the ViewRoot to redraw everything
6546 p.invalidateChild(this, null);
6547 return;
6548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 if (p != null && ai != null) {
6550 final int scrollX = mScrollX;
6551 final int scrollY = mScrollY;
6552 final Rect r = ai.mTmpInvalRect;
6553 r.set(dirty.left - scrollX, dirty.top - scrollY,
6554 dirty.right - scrollX, dirty.bottom - scrollY);
6555 mParent.invalidateChild(this, r);
6556 }
6557 }
6558 }
6559
6560 /**
6561 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6562 * The coordinates of the dirty rect are relative to the view.
6563 * If the view is visible, {@link #onDraw} will be called at some point
6564 * in the future. This must be called from a UI thread. To call
6565 * from a non-UI thread, call {@link #postInvalidate()}.
6566 * @param l the left position of the dirty region
6567 * @param t the top position of the dirty region
6568 * @param r the right position of the dirty region
6569 * @param b the bottom position of the dirty region
6570 */
6571 public void invalidate(int l, int t, int r, int b) {
6572 if (ViewDebug.TRACE_HIERARCHY) {
6573 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6574 }
6575
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006576 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6577 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6579 final ViewParent p = mParent;
6580 final AttachInfo ai = mAttachInfo;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006581 if (p != null && ai != null && ai.mHardwareAccelerated) {
6582 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6583 // with a null dirty rect, which tells the ViewRoot to redraw everything
6584 p.invalidateChild(this, null);
6585 return;
6586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006587 if (p != null && ai != null && l < r && t < b) {
6588 final int scrollX = mScrollX;
6589 final int scrollY = mScrollY;
6590 final Rect tmpr = ai.mTmpInvalRect;
6591 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6592 p.invalidateChild(this, tmpr);
6593 }
6594 }
6595 }
6596
6597 /**
6598 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6599 * be called at some point in the future. This must be called from a
6600 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6601 */
6602 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006603 invalidate(true);
6604 }
6605
6606 /**
6607 * This is where the invalidate() work actually happens. A full invalidate()
6608 * causes the drawing cache to be invalidated, but this function can be called with
6609 * invalidateCache set to false to skip that invalidation step for cases that do not
6610 * need it (for example, a component that remains at the same dimensions with the same
6611 * content).
6612 *
6613 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6614 * well. This is usually true for a full invalidate, but may be set to false if the
6615 * View's contents or dimensions have not changed.
6616 */
6617 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 if (ViewDebug.TRACE_HIERARCHY) {
6619 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6620 }
6621
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006622 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6623 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID)) {
Chet Haaseed032702010-10-01 14:05:54 -07006624 mPrivateFlags &= ~DRAWN;
6625 if (invalidateCache) {
6626 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006629 final ViewParent p = mParent;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006630 if (p != null && ai != null && ai.mHardwareAccelerated) {
6631 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6632 // with a null dirty rect, which tells the ViewRoot to redraw everything
6633 p.invalidateChild(this, null);
6634 return;
6635 }
Michael Jurkaebefea42010-11-15 16:04:01 -08006636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 if (p != null && ai != null) {
6638 final Rect r = ai.mTmpInvalRect;
6639 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6640 // Don't call invalidate -- we don't want to internally scroll
6641 // our own bounds
6642 p.invalidateChild(this, r);
6643 }
6644 }
6645 }
6646
6647 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006648 * Indicates whether this View is opaque. An opaque View guarantees that it will
6649 * draw all the pixels overlapping its bounds using a fully opaque color.
6650 *
6651 * Subclasses of View should override this method whenever possible to indicate
6652 * whether an instance is opaque. Opaque Views are treated in a special way by
6653 * the View hierarchy, possibly allowing it to perform optimizations during
6654 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006655 *
Romain Guy24443ea2009-05-11 11:56:30 -07006656 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006657 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006658 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006659 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006660 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6661 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006662 }
6663
Adam Powell20232d02010-12-08 21:08:53 -08006664 /**
6665 * @hide
6666 */
6667 protected void computeOpaqueFlags() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006668 // Opaque if:
6669 // - Has a background
6670 // - Background is opaque
6671 // - Doesn't have scrollbars or scrollbars are inside overlay
6672
6673 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6674 mPrivateFlags |= OPAQUE_BACKGROUND;
6675 } else {
6676 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6677 }
6678
6679 final int flags = mViewFlags;
6680 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6681 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6682 mPrivateFlags |= OPAQUE_SCROLLBARS;
6683 } else {
6684 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6685 }
6686 }
6687
6688 /**
6689 * @hide
6690 */
6691 protected boolean hasOpaqueScrollbars() {
6692 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006693 }
6694
6695 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 * @return A handler associated with the thread running the View. This
6697 * handler can be used to pump events in the UI events queue.
6698 */
6699 public Handler getHandler() {
6700 if (mAttachInfo != null) {
6701 return mAttachInfo.mHandler;
6702 }
6703 return null;
6704 }
6705
6706 /**
6707 * Causes the Runnable to be added to the message queue.
6708 * The runnable will be run on the user interface thread.
6709 *
6710 * @param action The Runnable that will be executed.
6711 *
6712 * @return Returns true if the Runnable was successfully placed in to the
6713 * message queue. Returns false on failure, usually because the
6714 * looper processing the message queue is exiting.
6715 */
6716 public boolean post(Runnable action) {
6717 Handler handler;
6718 if (mAttachInfo != null) {
6719 handler = mAttachInfo.mHandler;
6720 } else {
6721 // Assume that post will succeed later
6722 ViewRoot.getRunQueue().post(action);
6723 return true;
6724 }
6725
6726 return handler.post(action);
6727 }
6728
6729 /**
6730 * Causes the Runnable to be added to the message queue, to be run
6731 * after the specified amount of time elapses.
6732 * The runnable will be run on the user interface thread.
6733 *
6734 * @param action The Runnable that will be executed.
6735 * @param delayMillis The delay (in milliseconds) until the Runnable
6736 * will be executed.
6737 *
6738 * @return true if the Runnable was successfully placed in to the
6739 * message queue. Returns false on failure, usually because the
6740 * looper processing the message queue is exiting. Note that a
6741 * result of true does not mean the Runnable will be processed --
6742 * if the looper is quit before the delivery time of the message
6743 * occurs then the message will be dropped.
6744 */
6745 public boolean postDelayed(Runnable action, long delayMillis) {
6746 Handler handler;
6747 if (mAttachInfo != null) {
6748 handler = mAttachInfo.mHandler;
6749 } else {
6750 // Assume that post will succeed later
6751 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6752 return true;
6753 }
6754
6755 return handler.postDelayed(action, delayMillis);
6756 }
6757
6758 /**
6759 * Removes the specified Runnable from the message queue.
6760 *
6761 * @param action The Runnable to remove from the message handling queue
6762 *
6763 * @return true if this view could ask the Handler to remove the Runnable,
6764 * false otherwise. When the returned value is true, the Runnable
6765 * may or may not have been actually removed from the message queue
6766 * (for instance, if the Runnable was not in the queue already.)
6767 */
6768 public boolean removeCallbacks(Runnable action) {
6769 Handler handler;
6770 if (mAttachInfo != null) {
6771 handler = mAttachInfo.mHandler;
6772 } else {
6773 // Assume that post will succeed later
6774 ViewRoot.getRunQueue().removeCallbacks(action);
6775 return true;
6776 }
6777
6778 handler.removeCallbacks(action);
6779 return true;
6780 }
6781
6782 /**
6783 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6784 * Use this to invalidate the View from a non-UI thread.
6785 *
6786 * @see #invalidate()
6787 */
6788 public void postInvalidate() {
6789 postInvalidateDelayed(0);
6790 }
6791
6792 /**
6793 * Cause an invalidate of the specified area to happen on a subsequent cycle
6794 * through the event loop. Use this to invalidate the View from a non-UI thread.
6795 *
6796 * @param left The left coordinate of the rectangle to invalidate.
6797 * @param top The top coordinate of the rectangle to invalidate.
6798 * @param right The right coordinate of the rectangle to invalidate.
6799 * @param bottom The bottom coordinate of the rectangle to invalidate.
6800 *
6801 * @see #invalidate(int, int, int, int)
6802 * @see #invalidate(Rect)
6803 */
6804 public void postInvalidate(int left, int top, int right, int bottom) {
6805 postInvalidateDelayed(0, left, top, right, bottom);
6806 }
6807
6808 /**
6809 * Cause an invalidate to happen on a subsequent cycle through the event
6810 * loop. Waits for the specified amount of time.
6811 *
6812 * @param delayMilliseconds the duration in milliseconds to delay the
6813 * invalidation by
6814 */
6815 public void postInvalidateDelayed(long delayMilliseconds) {
6816 // We try only with the AttachInfo because there's no point in invalidating
6817 // if we are not attached to our window
6818 if (mAttachInfo != null) {
6819 Message msg = Message.obtain();
6820 msg.what = AttachInfo.INVALIDATE_MSG;
6821 msg.obj = this;
6822 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6823 }
6824 }
6825
6826 /**
6827 * Cause an invalidate of the specified area to happen on a subsequent cycle
6828 * through the event loop. Waits for the specified amount of time.
6829 *
6830 * @param delayMilliseconds the duration in milliseconds to delay the
6831 * invalidation by
6832 * @param left The left coordinate of the rectangle to invalidate.
6833 * @param top The top coordinate of the rectangle to invalidate.
6834 * @param right The right coordinate of the rectangle to invalidate.
6835 * @param bottom The bottom coordinate of the rectangle to invalidate.
6836 */
6837 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6838 int right, int bottom) {
6839
6840 // We try only with the AttachInfo because there's no point in invalidating
6841 // if we are not attached to our window
6842 if (mAttachInfo != null) {
6843 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6844 info.target = this;
6845 info.left = left;
6846 info.top = top;
6847 info.right = right;
6848 info.bottom = bottom;
6849
6850 final Message msg = Message.obtain();
6851 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6852 msg.obj = info;
6853 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6854 }
6855 }
6856
6857 /**
6858 * Called by a parent to request that a child update its values for mScrollX
6859 * and mScrollY if necessary. This will typically be done if the child is
6860 * animating a scroll using a {@link android.widget.Scroller Scroller}
6861 * object.
6862 */
6863 public void computeScroll() {
6864 }
6865
6866 /**
6867 * <p>Indicate whether the horizontal edges are faded when the view is
6868 * scrolled horizontally.</p>
6869 *
6870 * @return true if the horizontal edges should are faded on scroll, false
6871 * otherwise
6872 *
6873 * @see #setHorizontalFadingEdgeEnabled(boolean)
6874 * @attr ref android.R.styleable#View_fadingEdge
6875 */
6876 public boolean isHorizontalFadingEdgeEnabled() {
6877 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6878 }
6879
6880 /**
6881 * <p>Define whether the horizontal edges should be faded when this view
6882 * is scrolled horizontally.</p>
6883 *
6884 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6885 * be faded when the view is scrolled
6886 * horizontally
6887 *
6888 * @see #isHorizontalFadingEdgeEnabled()
6889 * @attr ref android.R.styleable#View_fadingEdge
6890 */
6891 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6892 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6893 if (horizontalFadingEdgeEnabled) {
6894 initScrollCache();
6895 }
6896
6897 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6898 }
6899 }
6900
6901 /**
6902 * <p>Indicate whether the vertical edges are faded when the view is
6903 * scrolled horizontally.</p>
6904 *
6905 * @return true if the vertical edges should are faded on scroll, false
6906 * otherwise
6907 *
6908 * @see #setVerticalFadingEdgeEnabled(boolean)
6909 * @attr ref android.R.styleable#View_fadingEdge
6910 */
6911 public boolean isVerticalFadingEdgeEnabled() {
6912 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6913 }
6914
6915 /**
6916 * <p>Define whether the vertical edges should be faded when this view
6917 * is scrolled vertically.</p>
6918 *
6919 * @param verticalFadingEdgeEnabled true if the vertical edges should
6920 * be faded when the view is scrolled
6921 * vertically
6922 *
6923 * @see #isVerticalFadingEdgeEnabled()
6924 * @attr ref android.R.styleable#View_fadingEdge
6925 */
6926 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6927 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6928 if (verticalFadingEdgeEnabled) {
6929 initScrollCache();
6930 }
6931
6932 mViewFlags ^= FADING_EDGE_VERTICAL;
6933 }
6934 }
6935
6936 /**
6937 * Returns the strength, or intensity, of the top faded edge. The strength is
6938 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6939 * returns 0.0 or 1.0 but no value in between.
6940 *
6941 * Subclasses should override this method to provide a smoother fade transition
6942 * when scrolling occurs.
6943 *
6944 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6945 */
6946 protected float getTopFadingEdgeStrength() {
6947 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6948 }
6949
6950 /**
6951 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6952 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6953 * returns 0.0 or 1.0 but no value in between.
6954 *
6955 * Subclasses should override this method to provide a smoother fade transition
6956 * when scrolling occurs.
6957 *
6958 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6959 */
6960 protected float getBottomFadingEdgeStrength() {
6961 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6962 computeVerticalScrollRange() ? 1.0f : 0.0f;
6963 }
6964
6965 /**
6966 * Returns the strength, or intensity, of the left faded edge. The strength is
6967 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6968 * returns 0.0 or 1.0 but no value in between.
6969 *
6970 * Subclasses should override this method to provide a smoother fade transition
6971 * when scrolling occurs.
6972 *
6973 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6974 */
6975 protected float getLeftFadingEdgeStrength() {
6976 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6977 }
6978
6979 /**
6980 * Returns the strength, or intensity, of the right faded edge. The strength is
6981 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6982 * returns 0.0 or 1.0 but no value in between.
6983 *
6984 * Subclasses should override this method to provide a smoother fade transition
6985 * when scrolling occurs.
6986 *
6987 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6988 */
6989 protected float getRightFadingEdgeStrength() {
6990 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6991 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6992 }
6993
6994 /**
6995 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6996 * scrollbar is not drawn by default.</p>
6997 *
6998 * @return true if the horizontal scrollbar should be painted, false
6999 * otherwise
7000 *
7001 * @see #setHorizontalScrollBarEnabled(boolean)
7002 */
7003 public boolean isHorizontalScrollBarEnabled() {
7004 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7005 }
7006
7007 /**
7008 * <p>Define whether the horizontal scrollbar should be drawn or not. The
7009 * scrollbar is not drawn by default.</p>
7010 *
7011 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
7012 * be painted
7013 *
7014 * @see #isHorizontalScrollBarEnabled()
7015 */
7016 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
7017 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
7018 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007019 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007020 recomputePadding();
7021 }
7022 }
7023
7024 /**
7025 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
7026 * scrollbar is not drawn by default.</p>
7027 *
7028 * @return true if the vertical scrollbar should be painted, false
7029 * otherwise
7030 *
7031 * @see #setVerticalScrollBarEnabled(boolean)
7032 */
7033 public boolean isVerticalScrollBarEnabled() {
7034 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
7035 }
7036
7037 /**
7038 * <p>Define whether the vertical scrollbar should be drawn or not. The
7039 * scrollbar is not drawn by default.</p>
7040 *
7041 * @param verticalScrollBarEnabled true if the vertical scrollbar should
7042 * be painted
7043 *
7044 * @see #isVerticalScrollBarEnabled()
7045 */
7046 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
7047 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
7048 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007049 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 recomputePadding();
7051 }
7052 }
7053
Adam Powell20232d02010-12-08 21:08:53 -08007054 /**
7055 * @hide
7056 */
7057 protected void recomputePadding() {
7058 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007059 }
Mike Cleronfe81d382009-09-28 14:22:16 -07007060
7061 /**
7062 * Define whether scrollbars will fade when the view is not scrolling.
7063 *
7064 * @param fadeScrollbars wheter to enable fading
7065 *
7066 */
7067 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
7068 initScrollCache();
7069 final ScrollabilityCache scrollabilityCache = mScrollCache;
7070 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07007071 if (fadeScrollbars) {
7072 scrollabilityCache.state = ScrollabilityCache.OFF;
7073 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07007074 scrollabilityCache.state = ScrollabilityCache.ON;
7075 }
7076 }
7077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007078 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07007079 *
7080 * Returns true if scrollbars will fade when this view is not scrolling
7081 *
7082 * @return true if scrollbar fading is enabled
7083 */
7084 public boolean isScrollbarFadingEnabled() {
7085 return mScrollCache != null && mScrollCache.fadeScrollBars;
7086 }
7087
7088 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007089 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
7090 * inset. When inset, they add to the padding of the view. And the scrollbars
7091 * can be drawn inside the padding area or on the edge of the view. For example,
7092 * if a view has a background drawable and you want to draw the scrollbars
7093 * inside the padding specified by the drawable, you can use
7094 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
7095 * appear at the edge of the view, ignoring the padding, then you can use
7096 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
7097 * @param style the style of the scrollbars. Should be one of
7098 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
7099 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
7100 * @see #SCROLLBARS_INSIDE_OVERLAY
7101 * @see #SCROLLBARS_INSIDE_INSET
7102 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7103 * @see #SCROLLBARS_OUTSIDE_INSET
7104 */
7105 public void setScrollBarStyle(int style) {
7106 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
7107 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07007108 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007109 recomputePadding();
7110 }
7111 }
7112
7113 /**
7114 * <p>Returns the current scrollbar style.</p>
7115 * @return the current scrollbar style
7116 * @see #SCROLLBARS_INSIDE_OVERLAY
7117 * @see #SCROLLBARS_INSIDE_INSET
7118 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7119 * @see #SCROLLBARS_OUTSIDE_INSET
7120 */
7121 public int getScrollBarStyle() {
7122 return mViewFlags & SCROLLBARS_STYLE_MASK;
7123 }
7124
7125 /**
7126 * <p>Compute the horizontal range that the horizontal scrollbar
7127 * represents.</p>
7128 *
7129 * <p>The range is expressed in arbitrary units that must be the same as the
7130 * units used by {@link #computeHorizontalScrollExtent()} and
7131 * {@link #computeHorizontalScrollOffset()}.</p>
7132 *
7133 * <p>The default range is the drawing width of this view.</p>
7134 *
7135 * @return the total horizontal range represented by the horizontal
7136 * scrollbar
7137 *
7138 * @see #computeHorizontalScrollExtent()
7139 * @see #computeHorizontalScrollOffset()
7140 * @see android.widget.ScrollBarDrawable
7141 */
7142 protected int computeHorizontalScrollRange() {
7143 return getWidth();
7144 }
7145
7146 /**
7147 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7148 * within the horizontal range. This value is used to compute the position
7149 * of the thumb within the scrollbar's track.</p>
7150 *
7151 * <p>The range is expressed in arbitrary units that must be the same as the
7152 * units used by {@link #computeHorizontalScrollRange()} and
7153 * {@link #computeHorizontalScrollExtent()}.</p>
7154 *
7155 * <p>The default offset is the scroll offset of this view.</p>
7156 *
7157 * @return the horizontal offset of the scrollbar's thumb
7158 *
7159 * @see #computeHorizontalScrollRange()
7160 * @see #computeHorizontalScrollExtent()
7161 * @see android.widget.ScrollBarDrawable
7162 */
7163 protected int computeHorizontalScrollOffset() {
7164 return mScrollX;
7165 }
7166
7167 /**
7168 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7169 * within the horizontal range. This value is used to compute the length
7170 * of the thumb within the scrollbar's track.</p>
7171 *
7172 * <p>The range is expressed in arbitrary units that must be the same as the
7173 * units used by {@link #computeHorizontalScrollRange()} and
7174 * {@link #computeHorizontalScrollOffset()}.</p>
7175 *
7176 * <p>The default extent is the drawing width of this view.</p>
7177 *
7178 * @return the horizontal extent of the scrollbar's thumb
7179 *
7180 * @see #computeHorizontalScrollRange()
7181 * @see #computeHorizontalScrollOffset()
7182 * @see android.widget.ScrollBarDrawable
7183 */
7184 protected int computeHorizontalScrollExtent() {
7185 return getWidth();
7186 }
7187
7188 /**
7189 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7190 *
7191 * <p>The range is expressed in arbitrary units that must be the same as the
7192 * units used by {@link #computeVerticalScrollExtent()} and
7193 * {@link #computeVerticalScrollOffset()}.</p>
7194 *
7195 * @return the total vertical range represented by the vertical scrollbar
7196 *
7197 * <p>The default range is the drawing height of this view.</p>
7198 *
7199 * @see #computeVerticalScrollExtent()
7200 * @see #computeVerticalScrollOffset()
7201 * @see android.widget.ScrollBarDrawable
7202 */
7203 protected int computeVerticalScrollRange() {
7204 return getHeight();
7205 }
7206
7207 /**
7208 * <p>Compute the vertical offset of the vertical scrollbar's thumb
7209 * within the horizontal range. This value is used to compute the position
7210 * of the thumb within the scrollbar's track.</p>
7211 *
7212 * <p>The range is expressed in arbitrary units that must be the same as the
7213 * units used by {@link #computeVerticalScrollRange()} and
7214 * {@link #computeVerticalScrollExtent()}.</p>
7215 *
7216 * <p>The default offset is the scroll offset of this view.</p>
7217 *
7218 * @return the vertical offset of the scrollbar's thumb
7219 *
7220 * @see #computeVerticalScrollRange()
7221 * @see #computeVerticalScrollExtent()
7222 * @see android.widget.ScrollBarDrawable
7223 */
7224 protected int computeVerticalScrollOffset() {
7225 return mScrollY;
7226 }
7227
7228 /**
7229 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7230 * within the vertical range. This value is used to compute the length
7231 * of the thumb within the scrollbar's track.</p>
7232 *
7233 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08007234 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007235 * {@link #computeVerticalScrollOffset()}.</p>
7236 *
7237 * <p>The default extent is the drawing height of this view.</p>
7238 *
7239 * @return the vertical extent of the scrollbar's thumb
7240 *
7241 * @see #computeVerticalScrollRange()
7242 * @see #computeVerticalScrollOffset()
7243 * @see android.widget.ScrollBarDrawable
7244 */
7245 protected int computeVerticalScrollExtent() {
7246 return getHeight();
7247 }
7248
7249 /**
7250 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7251 * scrollbars are painted only if they have been awakened first.</p>
7252 *
7253 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07007254 *
7255 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007256 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08007257 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007258 // scrollbars are drawn only when the animation is running
7259 final ScrollabilityCache cache = mScrollCache;
7260 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007261
7262 int state = cache.state;
7263
7264 if (state == ScrollabilityCache.OFF) {
7265 return;
7266 }
7267
7268 boolean invalidate = false;
7269
7270 if (state == ScrollabilityCache.FADING) {
7271 // We're fading -- get our fade interpolation
7272 if (cache.interpolatorValues == null) {
7273 cache.interpolatorValues = new float[1];
7274 }
7275
7276 float[] values = cache.interpolatorValues;
7277
7278 // Stops the animation if we're done
7279 if (cache.scrollBarInterpolator.timeToValues(values) ==
7280 Interpolator.Result.FREEZE_END) {
7281 cache.state = ScrollabilityCache.OFF;
7282 } else {
7283 cache.scrollBar.setAlpha(Math.round(values[0]));
7284 }
7285
7286 // This will make the scroll bars inval themselves after
7287 // drawing. We only want this when we're fading so that
7288 // we prevent excessive redraws
7289 invalidate = true;
7290 } else {
7291 // We're just on -- but we may have been fading before so
7292 // reset alpha
7293 cache.scrollBar.setAlpha(255);
7294 }
7295
7296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007297 final int viewFlags = mViewFlags;
7298
7299 final boolean drawHorizontalScrollBar =
7300 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7301 final boolean drawVerticalScrollBar =
7302 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7303 && !isVerticalScrollBarHidden();
7304
7305 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7306 final int width = mRight - mLeft;
7307 final int height = mBottom - mTop;
7308
7309 final ScrollBarDrawable scrollBar = cache.scrollBar;
7310 int size = scrollBar.getSize(false);
7311 if (size <= 0) {
7312 size = cache.scrollBarSize;
7313 }
7314
Mike Reede8853fc2009-09-04 14:01:48 -04007315 final int scrollX = mScrollX;
7316 final int scrollY = mScrollY;
7317 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7318
Mike Cleronf116bf82009-09-27 19:14:12 -07007319 int left, top, right, bottom;
7320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007321 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007322 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04007323 computeHorizontalScrollOffset(),
7324 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04007325 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07007326 getVerticalScrollbarWidth() : 0;
7327 top = scrollY + height - size - (mUserPaddingBottom & inside);
7328 left = scrollX + (mPaddingLeft & inside);
7329 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7330 bottom = top + size;
7331 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7332 if (invalidate) {
7333 invalidate(left, top, right, bottom);
7334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007335 }
7336
7337 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04007338 scrollBar.setParameters(computeVerticalScrollRange(),
7339 computeVerticalScrollOffset(),
7340 computeVerticalScrollExtent(), true);
Adam Powell20232d02010-12-08 21:08:53 -08007341 switch (mVerticalScrollbarPosition) {
7342 default:
7343 case SCROLLBAR_POSITION_DEFAULT:
7344 case SCROLLBAR_POSITION_RIGHT:
7345 left = scrollX + width - size - (mUserPaddingRight & inside);
7346 break;
7347 case SCROLLBAR_POSITION_LEFT:
7348 left = scrollX + (mUserPaddingLeft & inside);
7349 break;
7350 }
Mike Cleronf116bf82009-09-27 19:14:12 -07007351 top = scrollY + (mPaddingTop & inside);
7352 right = left + size;
7353 bottom = scrollY + height - (mUserPaddingBottom & inside);
7354 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7355 if (invalidate) {
7356 invalidate(left, top, right, bottom);
7357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007358 }
7359 }
7360 }
7361 }
Romain Guy8506ab42009-06-11 17:35:47 -07007362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007363 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007364 * 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 -08007365 * FastScroller is visible.
7366 * @return whether to temporarily hide the vertical scrollbar
7367 * @hide
7368 */
7369 protected boolean isVerticalScrollBarHidden() {
7370 return false;
7371 }
7372
7373 /**
7374 * <p>Draw the horizontal scrollbar if
7375 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7376 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007377 * @param canvas the canvas on which to draw the scrollbar
7378 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007379 *
7380 * @see #isHorizontalScrollBarEnabled()
7381 * @see #computeHorizontalScrollRange()
7382 * @see #computeHorizontalScrollExtent()
7383 * @see #computeHorizontalScrollOffset()
7384 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007385 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007386 */
Romain Guy8fb95422010-08-17 18:38:51 -07007387 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7388 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007389 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007390 scrollBar.draw(canvas);
7391 }
Mike Reede8853fc2009-09-04 14:01:48 -04007392
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007393 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007394 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7395 * returns true.</p>
7396 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 * @param canvas the canvas on which to draw the scrollbar
7398 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007399 *
7400 * @see #isVerticalScrollBarEnabled()
7401 * @see #computeVerticalScrollRange()
7402 * @see #computeVerticalScrollExtent()
7403 * @see #computeVerticalScrollOffset()
7404 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007405 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406 */
Romain Guy8fb95422010-08-17 18:38:51 -07007407 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7408 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007409 scrollBar.setBounds(l, t, r, b);
7410 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007411 }
7412
7413 /**
7414 * Implement this to do your drawing.
7415 *
7416 * @param canvas the canvas on which the background will be drawn
7417 */
7418 protected void onDraw(Canvas canvas) {
7419 }
7420
7421 /*
7422 * Caller is responsible for calling requestLayout if necessary.
7423 * (This allows addViewInLayout to not request a new layout.)
7424 */
7425 void assignParent(ViewParent parent) {
7426 if (mParent == null) {
7427 mParent = parent;
7428 } else if (parent == null) {
7429 mParent = null;
7430 } else {
7431 throw new RuntimeException("view " + this + " being added, but"
7432 + " it already has a parent");
7433 }
7434 }
7435
7436 /**
7437 * This is called when the view is attached to a window. At this point it
7438 * has a Surface and will start drawing. Note that this function is
7439 * guaranteed to be called before {@link #onDraw}, however it may be called
7440 * any time before the first onDraw -- including before or after
7441 * {@link #onMeasure}.
7442 *
7443 * @see #onDetachedFromWindow()
7444 */
7445 protected void onAttachedToWindow() {
7446 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7447 mParent.requestTransparentRegion(this);
7448 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007449 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7450 initialAwakenScrollBars();
7451 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7452 }
Chet Haasea9b61ac2010-12-20 07:40:25 -08007453 jumpDrawablesToCurrentState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007454 }
7455
7456 /**
7457 * This is called when the view is detached from a window. At this point it
7458 * no longer has a surface for drawing.
7459 *
7460 * @see #onAttachedToWindow()
7461 */
7462 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007463 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08007464 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007465 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007466 destroyDrawingCache();
7467 }
7468
7469 /**
7470 * @return The number of times this view has been attached to a window
7471 */
7472 protected int getWindowAttachCount() {
7473 return mWindowAttachCount;
7474 }
7475
7476 /**
7477 * Retrieve a unique token identifying the window this view is attached to.
7478 * @return Return the window's token for use in
7479 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7480 */
7481 public IBinder getWindowToken() {
7482 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7483 }
7484
7485 /**
7486 * Retrieve a unique token identifying the top-level "real" window of
7487 * the window that this view is attached to. That is, this is like
7488 * {@link #getWindowToken}, except if the window this view in is a panel
7489 * window (attached to another containing window), then the token of
7490 * the containing window is returned instead.
7491 *
7492 * @return Returns the associated window token, either
7493 * {@link #getWindowToken()} or the containing window's token.
7494 */
7495 public IBinder getApplicationWindowToken() {
7496 AttachInfo ai = mAttachInfo;
7497 if (ai != null) {
7498 IBinder appWindowToken = ai.mPanelParentWindowToken;
7499 if (appWindowToken == null) {
7500 appWindowToken = ai.mWindowToken;
7501 }
7502 return appWindowToken;
7503 }
7504 return null;
7505 }
7506
7507 /**
7508 * Retrieve private session object this view hierarchy is using to
7509 * communicate with the window manager.
7510 * @return the session object to communicate with the window manager
7511 */
7512 /*package*/ IWindowSession getWindowSession() {
7513 return mAttachInfo != null ? mAttachInfo.mSession : null;
7514 }
7515
7516 /**
7517 * @param info the {@link android.view.View.AttachInfo} to associated with
7518 * this view
7519 */
7520 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7521 //System.out.println("Attached! " + this);
7522 mAttachInfo = info;
7523 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007524 // We will need to evaluate the drawable state at least once.
7525 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007526 if (mFloatingTreeObserver != null) {
7527 info.mTreeObserver.merge(mFloatingTreeObserver);
7528 mFloatingTreeObserver = null;
7529 }
7530 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7531 mAttachInfo.mScrollContainers.add(this);
7532 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7533 }
7534 performCollectViewAttributes(visibility);
7535 onAttachedToWindow();
7536 int vis = info.mWindowVisibility;
7537 if (vis != GONE) {
7538 onWindowVisibilityChanged(vis);
7539 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007540 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7541 // If nobody has evaluated the drawable state yet, then do it now.
7542 refreshDrawableState();
7543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007544 }
7545
7546 void dispatchDetachedFromWindow() {
7547 //System.out.println("Detached! " + this);
7548 AttachInfo info = mAttachInfo;
7549 if (info != null) {
7550 int vis = info.mWindowVisibility;
7551 if (vis != GONE) {
7552 onWindowVisibilityChanged(GONE);
7553 }
7554 }
7555
7556 onDetachedFromWindow();
7557 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7558 mAttachInfo.mScrollContainers.remove(this);
7559 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7560 }
7561 mAttachInfo = null;
7562 }
7563
7564 /**
7565 * Store this view hierarchy's frozen state into the given container.
7566 *
7567 * @param container The SparseArray in which to save the view's state.
7568 *
7569 * @see #restoreHierarchyState
7570 * @see #dispatchSaveInstanceState
7571 * @see #onSaveInstanceState
7572 */
7573 public void saveHierarchyState(SparseArray<Parcelable> container) {
7574 dispatchSaveInstanceState(container);
7575 }
7576
7577 /**
7578 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7579 * May be overridden to modify how freezing happens to a view's children; for example, some
7580 * views may want to not store state for their children.
7581 *
7582 * @param container The SparseArray in which to save the view's state.
7583 *
7584 * @see #dispatchRestoreInstanceState
7585 * @see #saveHierarchyState
7586 * @see #onSaveInstanceState
7587 */
7588 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7589 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7590 mPrivateFlags &= ~SAVE_STATE_CALLED;
7591 Parcelable state = onSaveInstanceState();
7592 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7593 throw new IllegalStateException(
7594 "Derived class did not call super.onSaveInstanceState()");
7595 }
7596 if (state != null) {
7597 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7598 // + ": " + state);
7599 container.put(mID, state);
7600 }
7601 }
7602 }
7603
7604 /**
7605 * Hook allowing a view to generate a representation of its internal state
7606 * that can later be used to create a new instance with that same state.
7607 * This state should only contain information that is not persistent or can
7608 * not be reconstructed later. For example, you will never store your
7609 * current position on screen because that will be computed again when a
7610 * new instance of the view is placed in its view hierarchy.
7611 * <p>
7612 * Some examples of things you may store here: the current cursor position
7613 * in a text view (but usually not the text itself since that is stored in a
7614 * content provider or other persistent storage), the currently selected
7615 * item in a list view.
7616 *
7617 * @return Returns a Parcelable object containing the view's current dynamic
7618 * state, or null if there is nothing interesting to save. The
7619 * default implementation returns null.
7620 * @see #onRestoreInstanceState
7621 * @see #saveHierarchyState
7622 * @see #dispatchSaveInstanceState
7623 * @see #setSaveEnabled(boolean)
7624 */
7625 protected Parcelable onSaveInstanceState() {
7626 mPrivateFlags |= SAVE_STATE_CALLED;
7627 return BaseSavedState.EMPTY_STATE;
7628 }
7629
7630 /**
7631 * Restore this view hierarchy's frozen state from the given container.
7632 *
7633 * @param container The SparseArray which holds previously frozen states.
7634 *
7635 * @see #saveHierarchyState
7636 * @see #dispatchRestoreInstanceState
7637 * @see #onRestoreInstanceState
7638 */
7639 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7640 dispatchRestoreInstanceState(container);
7641 }
7642
7643 /**
7644 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7645 * children. May be overridden to modify how restoreing happens to a view's children; for
7646 * example, some views may want to not store state for their children.
7647 *
7648 * @param container The SparseArray which holds previously saved state.
7649 *
7650 * @see #dispatchSaveInstanceState
7651 * @see #restoreHierarchyState
7652 * @see #onRestoreInstanceState
7653 */
7654 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7655 if (mID != NO_ID) {
7656 Parcelable state = container.get(mID);
7657 if (state != null) {
7658 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7659 // + ": " + state);
7660 mPrivateFlags &= ~SAVE_STATE_CALLED;
7661 onRestoreInstanceState(state);
7662 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7663 throw new IllegalStateException(
7664 "Derived class did not call super.onRestoreInstanceState()");
7665 }
7666 }
7667 }
7668 }
7669
7670 /**
7671 * Hook allowing a view to re-apply a representation of its internal state that had previously
7672 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7673 * null state.
7674 *
7675 * @param state The frozen state that had previously been returned by
7676 * {@link #onSaveInstanceState}.
7677 *
7678 * @see #onSaveInstanceState
7679 * @see #restoreHierarchyState
7680 * @see #dispatchRestoreInstanceState
7681 */
7682 protected void onRestoreInstanceState(Parcelable state) {
7683 mPrivateFlags |= SAVE_STATE_CALLED;
7684 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007685 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7686 + "received " + state.getClass().toString() + " instead. This usually happens "
7687 + "when two views of different type have the same id in the same hierarchy. "
7688 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7689 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 }
7691 }
7692
7693 /**
7694 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7695 *
7696 * @return the drawing start time in milliseconds
7697 */
7698 public long getDrawingTime() {
7699 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7700 }
7701
7702 /**
7703 * <p>Enables or disables the duplication of the parent's state into this view. When
7704 * duplication is enabled, this view gets its drawable state from its parent rather
7705 * than from its own internal properties.</p>
7706 *
7707 * <p>Note: in the current implementation, setting this property to true after the
7708 * view was added to a ViewGroup might have no effect at all. This property should
7709 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7710 *
7711 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7712 * property is enabled, an exception will be thrown.</p>
7713 *
7714 * @param enabled True to enable duplication of the parent's drawable state, false
7715 * to disable it.
7716 *
7717 * @see #getDrawableState()
7718 * @see #isDuplicateParentStateEnabled()
7719 */
7720 public void setDuplicateParentStateEnabled(boolean enabled) {
7721 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7722 }
7723
7724 /**
7725 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7726 *
7727 * @return True if this view's drawable state is duplicated from the parent,
7728 * false otherwise
7729 *
7730 * @see #getDrawableState()
7731 * @see #setDuplicateParentStateEnabled(boolean)
7732 */
7733 public boolean isDuplicateParentStateEnabled() {
7734 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7735 }
7736
7737 /**
7738 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
7739 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
7740 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
7741 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
7742 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
7743 * null.</p>
7744 *
7745 * @param enabled true to enable the drawing cache, false otherwise
7746 *
7747 * @see #isDrawingCacheEnabled()
7748 * @see #getDrawingCache()
7749 * @see #buildDrawingCache()
7750 */
7751 public void setDrawingCacheEnabled(boolean enabled) {
7752 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
7753 }
7754
7755 /**
7756 * <p>Indicates whether the drawing cache is enabled for this view.</p>
7757 *
7758 * @return true if the drawing cache is enabled
7759 *
7760 * @see #setDrawingCacheEnabled(boolean)
7761 * @see #getDrawingCache()
7762 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07007763 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 public boolean isDrawingCacheEnabled() {
7765 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
7766 }
7767
7768 /**
Romain Guyb051e892010-09-28 19:09:36 -07007769 * <p>Returns a display list that can be used to draw this view again
7770 * without executing its draw method.</p>
7771 *
7772 * @return A DisplayList ready to replay, or null if caching is not enabled.
7773 */
7774 DisplayList getDisplayList() {
7775 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7776 return null;
7777 }
Romain Guyb051e892010-09-28 19:09:36 -07007778 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
7779 return null;
7780 }
7781
7782 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
7783 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mDisplayList == null)) {
7784
Romain Guyb051e892010-09-28 19:09:36 -07007785 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
7786
7787 final HardwareCanvas canvas = mDisplayList.start();
7788 try {
7789 int width = mRight - mLeft;
7790 int height = mBottom - mTop;
7791
7792 canvas.setViewport(width, height);
7793 canvas.onPreDraw();
7794
7795 final int restoreCount = canvas.save();
7796
Romain Guy2fe9a8f2010-10-04 20:17:01 -07007797 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07007798
7799 // Fast path for layouts with no backgrounds
7800 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7801 mPrivateFlags &= ~DIRTY_MASK;
7802 dispatchDraw(canvas);
7803 } else {
7804 draw(canvas);
7805 }
7806
7807 canvas.restoreToCount(restoreCount);
7808 } finally {
7809 canvas.onPostDraw();
7810
7811 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07007812 }
7813 }
7814
7815 return mDisplayList;
7816 }
7817
7818 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007819 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
7820 *
7821 * @return A non-scaled bitmap representing this view or null if cache is disabled.
7822 *
7823 * @see #getDrawingCache(boolean)
7824 */
7825 public Bitmap getDrawingCache() {
7826 return getDrawingCache(false);
7827 }
7828
7829 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007830 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
7831 * is null when caching is disabled. If caching is enabled and the cache is not ready,
7832 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
7833 * draw from the cache when the cache is enabled. To benefit from the cache, you must
7834 * request the drawing cache by calling this method and draw it on screen if the
7835 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007836 *
7837 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7838 * this method will create a bitmap of the same size as this view. Because this bitmap
7839 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7840 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7841 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7842 * size than the view. This implies that your application must be able to handle this
7843 * size.</p>
7844 *
7845 * @param autoScale Indicates whether the generated bitmap should be scaled based on
7846 * the current density of the screen when the application is in compatibility
7847 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 *
Romain Guyfbd8f692009-06-26 14:51:58 -07007849 * @return A bitmap representing this view or null if cache is disabled.
7850 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 * @see #setDrawingCacheEnabled(boolean)
7852 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07007853 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 * @see #destroyDrawingCache()
7855 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007856 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7858 return null;
7859 }
7860 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007861 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 }
Romain Guy02890fd2010-08-06 17:58:44 -07007863 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 }
7865
7866 /**
7867 * <p>Frees the resources used by the drawing cache. If you call
7868 * {@link #buildDrawingCache()} manually without calling
7869 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7870 * should cleanup the cache with this method afterwards.</p>
7871 *
7872 * @see #setDrawingCacheEnabled(boolean)
7873 * @see #buildDrawingCache()
7874 * @see #getDrawingCache()
7875 */
7876 public void destroyDrawingCache() {
7877 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007878 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 mDrawingCache = null;
7880 }
Romain Guyfbd8f692009-06-26 14:51:58 -07007881 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007882 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07007883 mUnscaledDrawingCache = null;
7884 }
Romain Guyb051e892010-09-28 19:09:36 -07007885 if (mDisplayList != null) {
Romain Guyb051e892010-09-28 19:09:36 -07007886 mDisplayList = null;
7887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007888 }
7889
7890 /**
7891 * Setting a solid background color for the drawing cache's bitmaps will improve
7892 * perfromance and memory usage. Note, though that this should only be used if this
7893 * view will always be drawn on top of a solid color.
7894 *
7895 * @param color The background color to use for the drawing cache's bitmap
7896 *
7897 * @see #setDrawingCacheEnabled(boolean)
7898 * @see #buildDrawingCache()
7899 * @see #getDrawingCache()
7900 */
7901 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08007902 if (color != mDrawingCacheBackgroundColor) {
7903 mDrawingCacheBackgroundColor = color;
7904 mPrivateFlags &= ~DRAWING_CACHE_VALID;
7905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 }
7907
7908 /**
7909 * @see #setDrawingCacheBackgroundColor(int)
7910 *
7911 * @return The background color to used for the drawing cache's bitmap
7912 */
7913 public int getDrawingCacheBackgroundColor() {
7914 return mDrawingCacheBackgroundColor;
7915 }
7916
7917 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007918 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
7919 *
7920 * @see #buildDrawingCache(boolean)
7921 */
7922 public void buildDrawingCache() {
7923 buildDrawingCache(false);
7924 }
7925
7926 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
7928 *
7929 * <p>If you call {@link #buildDrawingCache()} manually without calling
7930 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7931 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007932 *
7933 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7934 * this method will create a bitmap of the same size as this view. Because this bitmap
7935 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7936 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7937 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7938 * size than the view. This implies that your application must be able to handle this
7939 * size.</p>
Romain Guy0d9275e2010-10-26 14:22:30 -07007940 *
7941 * <p>You should avoid calling this method when hardware acceleration is enabled. If
7942 * you do not need the drawing cache bitmap, calling this method will increase memory
7943 * usage and cause the view to be rendered in software once, thus negatively impacting
7944 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007945 *
7946 * @see #getDrawingCache()
7947 * @see #destroyDrawingCache()
7948 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007949 public void buildDrawingCache(boolean autoScale) {
7950 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07007951 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007952
7953 if (ViewDebug.TRACE_HIERARCHY) {
7954 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007956
Romain Guy8506ab42009-06-11 17:35:47 -07007957 int width = mRight - mLeft;
7958 int height = mBottom - mTop;
7959
7960 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007961 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007962
Romain Guye1123222009-06-29 14:24:56 -07007963 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007964 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7965 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007967
7968 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007969 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08007970 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971
7972 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007973 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08007974 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007975 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7976 destroyDrawingCache();
7977 return;
7978 }
7979
7980 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07007981 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982
7983 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 Bitmap.Config quality;
7985 if (!opaque) {
7986 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7987 case DRAWING_CACHE_QUALITY_AUTO:
7988 quality = Bitmap.Config.ARGB_8888;
7989 break;
7990 case DRAWING_CACHE_QUALITY_LOW:
7991 quality = Bitmap.Config.ARGB_4444;
7992 break;
7993 case DRAWING_CACHE_QUALITY_HIGH:
7994 quality = Bitmap.Config.ARGB_8888;
7995 break;
7996 default:
7997 quality = Bitmap.Config.ARGB_8888;
7998 break;
7999 }
8000 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07008001 // Optimization for translucent windows
8002 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08008003 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008004 }
8005
8006 // Try to cleanup memory
8007 if (bitmap != null) bitmap.recycle();
8008
8009 try {
8010 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07008011 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07008012 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07008013 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008014 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07008015 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008016 }
Adam Powell26153a32010-11-08 15:22:27 -08008017 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008018 } catch (OutOfMemoryError e) {
8019 // If there is not enough memory to create the bitmap cache, just
8020 // ignore the issue as bitmap caches are not required to draw the
8021 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07008022 if (autoScale) {
8023 mDrawingCache = null;
8024 } else {
8025 mUnscaledDrawingCache = null;
8026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 return;
8028 }
8029
8030 clear = drawingCacheBackgroundColor != 0;
8031 }
8032
8033 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 if (attachInfo != null) {
8035 canvas = attachInfo.mCanvas;
8036 if (canvas == null) {
8037 canvas = new Canvas();
8038 }
8039 canvas.setBitmap(bitmap);
8040 // Temporarily clobber the cached Canvas in case one of our children
8041 // is also using a drawing cache. Without this, the children would
8042 // steal the canvas by attaching their own bitmap to it and bad, bad
8043 // thing would happen (invisible views, corrupted drawings, etc.)
8044 attachInfo.mCanvas = null;
8045 } else {
8046 // This case should hopefully never or seldom happen
8047 canvas = new Canvas(bitmap);
8048 }
8049
8050 if (clear) {
8051 bitmap.eraseColor(drawingCacheBackgroundColor);
8052 }
8053
8054 computeScroll();
8055 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07008056
Romain Guye1123222009-06-29 14:24:56 -07008057 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008058 final float scale = attachInfo.mApplicationScale;
8059 canvas.scale(scale, scale);
8060 }
8061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008062 canvas.translate(-mScrollX, -mScrollY);
8063
Romain Guy5bcdff42009-05-14 21:27:18 -07008064 mPrivateFlags |= DRAWN;
Romain Guy0d9275e2010-10-26 14:22:30 -07008065 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated) {
8066 mPrivateFlags |= DRAWING_CACHE_VALID;
8067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008068
8069 // Fast path for layouts with no backgrounds
8070 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8071 if (ViewDebug.TRACE_HIERARCHY) {
8072 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8073 }
Romain Guy5bcdff42009-05-14 21:27:18 -07008074 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 dispatchDraw(canvas);
8076 } else {
8077 draw(canvas);
8078 }
8079
8080 canvas.restoreToCount(restoreCount);
8081
8082 if (attachInfo != null) {
8083 // Restore the cached Canvas for our siblings
8084 attachInfo.mCanvas = canvas;
8085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008086 }
8087 }
8088
8089 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008090 * Create a snapshot of the view into a bitmap. We should probably make
8091 * some form of this public, but should think about the API.
8092 */
Romain Guy223ff5c2010-03-02 17:07:47 -08008093 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008094 int width = mRight - mLeft;
8095 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008096
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008097 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07008098 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008099 width = (int) ((width * scale) + 0.5f);
8100 height = (int) ((height * scale) + 0.5f);
8101
Romain Guy8c11e312009-09-14 15:15:30 -07008102 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008103 if (bitmap == null) {
8104 throw new OutOfMemoryError();
8105 }
8106
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008107 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8108
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008109 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008110 if (attachInfo != null) {
8111 canvas = attachInfo.mCanvas;
8112 if (canvas == null) {
8113 canvas = new Canvas();
8114 }
8115 canvas.setBitmap(bitmap);
8116 // Temporarily clobber the cached Canvas in case one of our children
8117 // is also using a drawing cache. Without this, the children would
8118 // steal the canvas by attaching their own bitmap to it and bad, bad
8119 // things would happen (invisible views, corrupted drawings, etc.)
8120 attachInfo.mCanvas = null;
8121 } else {
8122 // This case should hopefully never or seldom happen
8123 canvas = new Canvas(bitmap);
8124 }
8125
Romain Guy5bcdff42009-05-14 21:27:18 -07008126 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008127 bitmap.eraseColor(backgroundColor);
8128 }
8129
8130 computeScroll();
8131 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008132 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008133 canvas.translate(-mScrollX, -mScrollY);
8134
Romain Guy5bcdff42009-05-14 21:27:18 -07008135 // Temporarily remove the dirty mask
8136 int flags = mPrivateFlags;
8137 mPrivateFlags &= ~DIRTY_MASK;
8138
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008139 // Fast path for layouts with no backgrounds
8140 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8141 dispatchDraw(canvas);
8142 } else {
8143 draw(canvas);
8144 }
8145
Romain Guy5bcdff42009-05-14 21:27:18 -07008146 mPrivateFlags = flags;
8147
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008148 canvas.restoreToCount(restoreCount);
8149
8150 if (attachInfo != null) {
8151 // Restore the cached Canvas for our siblings
8152 attachInfo.mCanvas = canvas;
8153 }
Romain Guy8506ab42009-06-11 17:35:47 -07008154
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008155 return bitmap;
8156 }
8157
8158 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 * Indicates whether this View is currently in edit mode. A View is usually
8160 * in edit mode when displayed within a developer tool. For instance, if
8161 * this View is being drawn by a visual user interface builder, this method
8162 * should return true.
8163 *
8164 * Subclasses should check the return value of this method to provide
8165 * different behaviors if their normal behavior might interfere with the
8166 * host environment. For instance: the class spawns a thread in its
8167 * constructor, the drawing code relies on device-specific features, etc.
8168 *
8169 * This method is usually checked in the drawing code of custom widgets.
8170 *
8171 * @return True if this View is in edit mode, false otherwise.
8172 */
8173 public boolean isInEditMode() {
8174 return false;
8175 }
8176
8177 /**
8178 * If the View draws content inside its padding and enables fading edges,
8179 * it needs to support padding offsets. Padding offsets are added to the
8180 * fading edges to extend the length of the fade so that it covers pixels
8181 * drawn inside the padding.
8182 *
8183 * Subclasses of this class should override this method if they need
8184 * to draw content inside the padding.
8185 *
8186 * @return True if padding offset must be applied, false otherwise.
8187 *
8188 * @see #getLeftPaddingOffset()
8189 * @see #getRightPaddingOffset()
8190 * @see #getTopPaddingOffset()
8191 * @see #getBottomPaddingOffset()
8192 *
8193 * @since CURRENT
8194 */
8195 protected boolean isPaddingOffsetRequired() {
8196 return false;
8197 }
8198
8199 /**
8200 * Amount by which to extend the left fading region. Called only when
8201 * {@link #isPaddingOffsetRequired()} returns true.
8202 *
8203 * @return The left padding offset in pixels.
8204 *
8205 * @see #isPaddingOffsetRequired()
8206 *
8207 * @since CURRENT
8208 */
8209 protected int getLeftPaddingOffset() {
8210 return 0;
8211 }
8212
8213 /**
8214 * Amount by which to extend the right fading region. Called only when
8215 * {@link #isPaddingOffsetRequired()} returns true.
8216 *
8217 * @return The right padding offset in pixels.
8218 *
8219 * @see #isPaddingOffsetRequired()
8220 *
8221 * @since CURRENT
8222 */
8223 protected int getRightPaddingOffset() {
8224 return 0;
8225 }
8226
8227 /**
8228 * Amount by which to extend the top fading region. Called only when
8229 * {@link #isPaddingOffsetRequired()} returns true.
8230 *
8231 * @return The top padding offset in pixels.
8232 *
8233 * @see #isPaddingOffsetRequired()
8234 *
8235 * @since CURRENT
8236 */
8237 protected int getTopPaddingOffset() {
8238 return 0;
8239 }
8240
8241 /**
8242 * Amount by which to extend the bottom fading region. Called only when
8243 * {@link #isPaddingOffsetRequired()} returns true.
8244 *
8245 * @return The bottom padding offset in pixels.
8246 *
8247 * @see #isPaddingOffsetRequired()
8248 *
8249 * @since CURRENT
8250 */
8251 protected int getBottomPaddingOffset() {
8252 return 0;
8253 }
8254
8255 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008256 * <p>Indicates whether this view is attached to an hardware accelerated
8257 * window or not.</p>
8258 *
8259 * <p>Even if this method returns true, it does not mean that every call
8260 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8261 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8262 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8263 * window is hardware accelerated,
8264 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8265 * return false, and this method will return true.</p>
8266 *
8267 * @return True if the view is attached to a window and the window is
8268 * hardware accelerated; false in any other case.
8269 */
8270 public boolean isHardwareAccelerated() {
8271 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8272 }
8273
8274 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008275 * Manually render this view (and all of its children) to the given Canvas.
8276 * The view must have already done a full layout before this function is
Chet Haasec75ec332010-12-17 07:44:30 -08008277 * called. When implementing a view, implement {@link #onDraw} instead of
8278 * overriding this method. If you do need to override this method, call
8279 * the superclass version.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280 *
8281 * @param canvas The Canvas to which the View is rendered.
8282 */
8283 public void draw(Canvas canvas) {
8284 if (ViewDebug.TRACE_HIERARCHY) {
8285 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8286 }
8287
Romain Guy5bcdff42009-05-14 21:27:18 -07008288 final int privateFlags = mPrivateFlags;
8289 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8290 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8291 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008293 /*
8294 * Draw traversal performs several drawing steps which must be executed
8295 * in the appropriate order:
8296 *
8297 * 1. Draw the background
8298 * 2. If necessary, save the canvas' layers to prepare for fading
8299 * 3. Draw view's content
8300 * 4. Draw children
8301 * 5. If necessary, draw the fading edges and restore layers
8302 * 6. Draw decorations (scrollbars for instance)
8303 */
8304
8305 // Step 1, draw the background, if needed
8306 int saveCount;
8307
Romain Guy24443ea2009-05-11 11:56:30 -07008308 if (!dirtyOpaque) {
8309 final Drawable background = mBGDrawable;
8310 if (background != null) {
8311 final int scrollX = mScrollX;
8312 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008313
Romain Guy24443ea2009-05-11 11:56:30 -07008314 if (mBackgroundSizeChanged) {
8315 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8316 mBackgroundSizeChanged = false;
8317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008318
Romain Guy24443ea2009-05-11 11:56:30 -07008319 if ((scrollX | scrollY) == 0) {
8320 background.draw(canvas);
8321 } else {
8322 canvas.translate(scrollX, scrollY);
8323 background.draw(canvas);
8324 canvas.translate(-scrollX, -scrollY);
8325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008326 }
8327 }
8328
8329 // skip step 2 & 5 if possible (common case)
8330 final int viewFlags = mViewFlags;
8331 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8332 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8333 if (!verticalEdges && !horizontalEdges) {
8334 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008335 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336
8337 // Step 4, draw the children
8338 dispatchDraw(canvas);
8339
8340 // Step 6, draw decorations (scrollbars)
8341 onDrawScrollBars(canvas);
8342
8343 // we're done...
8344 return;
8345 }
8346
8347 /*
8348 * Here we do the full fledged routine...
8349 * (this is an uncommon case where speed matters less,
8350 * this is why we repeat some of the tests that have been
8351 * done above)
8352 */
8353
8354 boolean drawTop = false;
8355 boolean drawBottom = false;
8356 boolean drawLeft = false;
8357 boolean drawRight = false;
8358
8359 float topFadeStrength = 0.0f;
8360 float bottomFadeStrength = 0.0f;
8361 float leftFadeStrength = 0.0f;
8362 float rightFadeStrength = 0.0f;
8363
8364 // Step 2, save the canvas' layers
8365 int paddingLeft = mPaddingLeft;
8366 int paddingTop = mPaddingTop;
8367
8368 final boolean offsetRequired = isPaddingOffsetRequired();
8369 if (offsetRequired) {
8370 paddingLeft += getLeftPaddingOffset();
8371 paddingTop += getTopPaddingOffset();
8372 }
8373
8374 int left = mScrollX + paddingLeft;
8375 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8376 int top = mScrollY + paddingTop;
8377 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8378
8379 if (offsetRequired) {
8380 right += getRightPaddingOffset();
8381 bottom += getBottomPaddingOffset();
8382 }
8383
8384 final ScrollabilityCache scrollabilityCache = mScrollCache;
8385 int length = scrollabilityCache.fadingEdgeLength;
8386
8387 // clip the fade length if top and bottom fades overlap
8388 // overlapping fades produce odd-looking artifacts
8389 if (verticalEdges && (top + length > bottom - length)) {
8390 length = (bottom - top) / 2;
8391 }
8392
8393 // also clip horizontal fades if necessary
8394 if (horizontalEdges && (left + length > right - length)) {
8395 length = (right - left) / 2;
8396 }
8397
8398 if (verticalEdges) {
8399 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008400 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008401 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008402 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008403 }
8404
8405 if (horizontalEdges) {
8406 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008407 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008408 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008409 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008410 }
8411
8412 saveCount = canvas.getSaveCount();
8413
8414 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008415 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008416 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8417
8418 if (drawTop) {
8419 canvas.saveLayer(left, top, right, top + length, null, flags);
8420 }
8421
8422 if (drawBottom) {
8423 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8424 }
8425
8426 if (drawLeft) {
8427 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8428 }
8429
8430 if (drawRight) {
8431 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8432 }
8433 } else {
8434 scrollabilityCache.setFadeColor(solidColor);
8435 }
8436
8437 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008438 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008439
8440 // Step 4, draw the children
8441 dispatchDraw(canvas);
8442
8443 // Step 5, draw the fade effect and restore layers
8444 final Paint p = scrollabilityCache.paint;
8445 final Matrix matrix = scrollabilityCache.matrix;
8446 final Shader fade = scrollabilityCache.shader;
8447 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8448
8449 if (drawTop) {
8450 matrix.setScale(1, fadeHeight * topFadeStrength);
8451 matrix.postTranslate(left, top);
8452 fade.setLocalMatrix(matrix);
8453 canvas.drawRect(left, top, right, top + length, p);
8454 }
8455
8456 if (drawBottom) {
8457 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8458 matrix.postRotate(180);
8459 matrix.postTranslate(left, bottom);
8460 fade.setLocalMatrix(matrix);
8461 canvas.drawRect(left, bottom - length, right, bottom, p);
8462 }
8463
8464 if (drawLeft) {
8465 matrix.setScale(1, fadeHeight * leftFadeStrength);
8466 matrix.postRotate(-90);
8467 matrix.postTranslate(left, top);
8468 fade.setLocalMatrix(matrix);
8469 canvas.drawRect(left, top, left + length, bottom, p);
8470 }
8471
8472 if (drawRight) {
8473 matrix.setScale(1, fadeHeight * rightFadeStrength);
8474 matrix.postRotate(90);
8475 matrix.postTranslate(right, top);
8476 fade.setLocalMatrix(matrix);
8477 canvas.drawRect(right - length, top, right, bottom, p);
8478 }
8479
8480 canvas.restoreToCount(saveCount);
8481
8482 // Step 6, draw decorations (scrollbars)
8483 onDrawScrollBars(canvas);
8484 }
8485
8486 /**
8487 * Override this if your view is known to always be drawn on top of a solid color background,
8488 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8489 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8490 * should be set to 0xFF.
8491 *
8492 * @see #setVerticalFadingEdgeEnabled
8493 * @see #setHorizontalFadingEdgeEnabled
8494 *
8495 * @return The known solid color background for this view, or 0 if the color may vary
8496 */
8497 public int getSolidColor() {
8498 return 0;
8499 }
8500
8501 /**
8502 * Build a human readable string representation of the specified view flags.
8503 *
8504 * @param flags the view flags to convert to a string
8505 * @return a String representing the supplied flags
8506 */
8507 private static String printFlags(int flags) {
8508 String output = "";
8509 int numFlags = 0;
8510 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8511 output += "TAKES_FOCUS";
8512 numFlags++;
8513 }
8514
8515 switch (flags & VISIBILITY_MASK) {
8516 case INVISIBLE:
8517 if (numFlags > 0) {
8518 output += " ";
8519 }
8520 output += "INVISIBLE";
8521 // USELESS HERE numFlags++;
8522 break;
8523 case GONE:
8524 if (numFlags > 0) {
8525 output += " ";
8526 }
8527 output += "GONE";
8528 // USELESS HERE numFlags++;
8529 break;
8530 default:
8531 break;
8532 }
8533 return output;
8534 }
8535
8536 /**
8537 * Build a human readable string representation of the specified private
8538 * view flags.
8539 *
8540 * @param privateFlags the private view flags to convert to a string
8541 * @return a String representing the supplied flags
8542 */
8543 private static String printPrivateFlags(int privateFlags) {
8544 String output = "";
8545 int numFlags = 0;
8546
8547 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8548 output += "WANTS_FOCUS";
8549 numFlags++;
8550 }
8551
8552 if ((privateFlags & FOCUSED) == FOCUSED) {
8553 if (numFlags > 0) {
8554 output += " ";
8555 }
8556 output += "FOCUSED";
8557 numFlags++;
8558 }
8559
8560 if ((privateFlags & SELECTED) == SELECTED) {
8561 if (numFlags > 0) {
8562 output += " ";
8563 }
8564 output += "SELECTED";
8565 numFlags++;
8566 }
8567
8568 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8569 if (numFlags > 0) {
8570 output += " ";
8571 }
8572 output += "IS_ROOT_NAMESPACE";
8573 numFlags++;
8574 }
8575
8576 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8577 if (numFlags > 0) {
8578 output += " ";
8579 }
8580 output += "HAS_BOUNDS";
8581 numFlags++;
8582 }
8583
8584 if ((privateFlags & DRAWN) == DRAWN) {
8585 if (numFlags > 0) {
8586 output += " ";
8587 }
8588 output += "DRAWN";
8589 // USELESS HERE numFlags++;
8590 }
8591 return output;
8592 }
8593
8594 /**
8595 * <p>Indicates whether or not this view's layout will be requested during
8596 * the next hierarchy layout pass.</p>
8597 *
8598 * @return true if the layout will be forced during next layout pass
8599 */
8600 public boolean isLayoutRequested() {
8601 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8602 }
8603
8604 /**
8605 * Assign a size and position to a view and all of its
8606 * descendants
8607 *
8608 * <p>This is the second phase of the layout mechanism.
8609 * (The first is measuring). In this phase, each parent calls
8610 * layout on all of its children to position them.
8611 * This is typically done using the child measurements
8612 * that were stored in the measure pass().
8613 *
8614 * Derived classes with children should override
8615 * onLayout. In that method, they should
Chet Haase21cd1382010-09-01 17:42:29 -07008616 * call layout on each of their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008617 *
8618 * @param l Left position, relative to parent
8619 * @param t Top position, relative to parent
8620 * @param r Right position, relative to parent
8621 * @param b Bottom position, relative to parent
8622 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008623 @SuppressWarnings({"unchecked"})
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008624 public final void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008625 int oldL = mLeft;
8626 int oldT = mTop;
8627 int oldB = mBottom;
8628 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 boolean changed = setFrame(l, t, r, b);
8630 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8631 if (ViewDebug.TRACE_HIERARCHY) {
8632 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8633 }
8634
8635 onLayout(changed, l, t, r, b);
8636 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008637
8638 if (mOnLayoutChangeListeners != null) {
8639 ArrayList<OnLayoutChangeListener> listenersCopy =
8640 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8641 int numListeners = listenersCopy.size();
8642 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07008643 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07008644 }
8645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 }
8647 mPrivateFlags &= ~FORCE_LAYOUT;
8648 }
8649
8650 /**
8651 * Called from layout when this view should
8652 * assign a size and position to each of its children.
8653 *
8654 * Derived classes with children should override
8655 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008656 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008657 * @param changed This is a new size or position for this view
8658 * @param left Left position, relative to parent
8659 * @param top Top position, relative to parent
8660 * @param right Right position, relative to parent
8661 * @param bottom Bottom position, relative to parent
8662 */
8663 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8664 }
8665
8666 /**
8667 * Assign a size and position to this view.
8668 *
8669 * This is called from layout.
8670 *
8671 * @param left Left position, relative to parent
8672 * @param top Top position, relative to parent
8673 * @param right Right position, relative to parent
8674 * @param bottom Bottom position, relative to parent
8675 * @return true if the new size and position are different than the
8676 * previous ones
8677 * {@hide}
8678 */
8679 protected boolean setFrame(int left, int top, int right, int bottom) {
8680 boolean changed = false;
8681
8682 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008683 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 + right + "," + bottom + ")");
8685 }
8686
8687 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8688 changed = true;
8689
8690 // Remember our drawn bit
8691 int drawn = mPrivateFlags & DRAWN;
8692
8693 // Invalidate our old position
8694 invalidate();
8695
8696
8697 int oldWidth = mRight - mLeft;
8698 int oldHeight = mBottom - mTop;
8699
8700 mLeft = left;
8701 mTop = top;
8702 mRight = right;
8703 mBottom = bottom;
8704
8705 mPrivateFlags |= HAS_BOUNDS;
8706
8707 int newWidth = right - left;
8708 int newHeight = bottom - top;
8709
8710 if (newWidth != oldWidth || newHeight != oldHeight) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08008711 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8712 // A change in dimension means an auto-centered pivot point changes, too
8713 mMatrixDirty = true;
8714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008715 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8716 }
8717
8718 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8719 // If we are visible, force the DRAWN bit to on so that
8720 // this invalidate will go through (at least to our parent).
8721 // This is because someone may have invalidated this view
Chet Haase6c7ad5d2010-12-28 08:40:00 -08008722 // before this call to setFrame came in, thereby clearing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 // the DRAWN bit.
8724 mPrivateFlags |= DRAWN;
8725 invalidate();
8726 }
8727
8728 // Reset drawn bit to original value (invalidate turns it off)
8729 mPrivateFlags |= drawn;
8730
8731 mBackgroundSizeChanged = true;
8732 }
8733 return changed;
8734 }
8735
8736 /**
8737 * Finalize inflating a view from XML. This is called as the last phase
8738 * of inflation, after all child views have been added.
8739 *
8740 * <p>Even if the subclass overrides onFinishInflate, they should always be
8741 * sure to call the super method, so that we get called.
8742 */
8743 protected void onFinishInflate() {
8744 }
8745
8746 /**
8747 * Returns the resources associated with this view.
8748 *
8749 * @return Resources object.
8750 */
8751 public Resources getResources() {
8752 return mResources;
8753 }
8754
8755 /**
8756 * Invalidates the specified Drawable.
8757 *
8758 * @param drawable the drawable to invalidate
8759 */
8760 public void invalidateDrawable(Drawable drawable) {
8761 if (verifyDrawable(drawable)) {
8762 final Rect dirty = drawable.getBounds();
8763 final int scrollX = mScrollX;
8764 final int scrollY = mScrollY;
8765
8766 invalidate(dirty.left + scrollX, dirty.top + scrollY,
8767 dirty.right + scrollX, dirty.bottom + scrollY);
8768 }
8769 }
8770
8771 /**
8772 * Schedules an action on a drawable to occur at a specified time.
8773 *
8774 * @param who the recipient of the action
8775 * @param what the action to run on the drawable
8776 * @param when the time at which the action must occur. Uses the
8777 * {@link SystemClock#uptimeMillis} timebase.
8778 */
8779 public void scheduleDrawable(Drawable who, Runnable what, long when) {
8780 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8781 mAttachInfo.mHandler.postAtTime(what, who, when);
8782 }
8783 }
8784
8785 /**
8786 * Cancels a scheduled action on a drawable.
8787 *
8788 * @param who the recipient of the action
8789 * @param what the action to cancel
8790 */
8791 public void unscheduleDrawable(Drawable who, Runnable what) {
8792 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8793 mAttachInfo.mHandler.removeCallbacks(what, who);
8794 }
8795 }
8796
8797 /**
8798 * Unschedule any events associated with the given Drawable. This can be
8799 * used when selecting a new Drawable into a view, so that the previous
8800 * one is completely unscheduled.
8801 *
8802 * @param who The Drawable to unschedule.
8803 *
8804 * @see #drawableStateChanged
8805 */
8806 public void unscheduleDrawable(Drawable who) {
8807 if (mAttachInfo != null) {
8808 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
8809 }
8810 }
8811
8812 /**
8813 * If your view subclass is displaying its own Drawable objects, it should
8814 * override this function and return true for any Drawable it is
8815 * displaying. This allows animations for those drawables to be
8816 * scheduled.
8817 *
8818 * <p>Be sure to call through to the super class when overriding this
8819 * function.
8820 *
8821 * @param who The Drawable to verify. Return true if it is one you are
8822 * displaying, else return the result of calling through to the
8823 * super class.
8824 *
8825 * @return boolean If true than the Drawable is being displayed in the
8826 * view; else false and it is not allowed to animate.
8827 *
8828 * @see #unscheduleDrawable
8829 * @see #drawableStateChanged
8830 */
8831 protected boolean verifyDrawable(Drawable who) {
8832 return who == mBGDrawable;
8833 }
8834
8835 /**
8836 * This function is called whenever the state of the view changes in such
8837 * a way that it impacts the state of drawables being shown.
8838 *
8839 * <p>Be sure to call through to the superclass when overriding this
8840 * function.
8841 *
8842 * @see Drawable#setState
8843 */
8844 protected void drawableStateChanged() {
8845 Drawable d = mBGDrawable;
8846 if (d != null && d.isStateful()) {
8847 d.setState(getDrawableState());
8848 }
8849 }
8850
8851 /**
8852 * Call this to force a view to update its drawable state. This will cause
8853 * drawableStateChanged to be called on this view. Views that are interested
8854 * in the new state should call getDrawableState.
8855 *
8856 * @see #drawableStateChanged
8857 * @see #getDrawableState
8858 */
8859 public void refreshDrawableState() {
8860 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
8861 drawableStateChanged();
8862
8863 ViewParent parent = mParent;
8864 if (parent != null) {
8865 parent.childDrawableStateChanged(this);
8866 }
8867 }
8868
8869 /**
8870 * Return an array of resource IDs of the drawable states representing the
8871 * current state of the view.
8872 *
8873 * @return The current drawable state
8874 *
8875 * @see Drawable#setState
8876 * @see #drawableStateChanged
8877 * @see #onCreateDrawableState
8878 */
8879 public final int[] getDrawableState() {
8880 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
8881 return mDrawableState;
8882 } else {
8883 mDrawableState = onCreateDrawableState(0);
8884 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
8885 return mDrawableState;
8886 }
8887 }
8888
8889 /**
8890 * Generate the new {@link android.graphics.drawable.Drawable} state for
8891 * this view. This is called by the view
8892 * system when the cached Drawable state is determined to be invalid. To
8893 * retrieve the current state, you should use {@link #getDrawableState}.
8894 *
8895 * @param extraSpace if non-zero, this is the number of extra entries you
8896 * would like in the returned array in which you can place your own
8897 * states.
8898 *
8899 * @return Returns an array holding the current {@link Drawable} state of
8900 * the view.
8901 *
8902 * @see #mergeDrawableStates
8903 */
8904 protected int[] onCreateDrawableState(int extraSpace) {
8905 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
8906 mParent instanceof View) {
8907 return ((View) mParent).onCreateDrawableState(extraSpace);
8908 }
8909
8910 int[] drawableState;
8911
8912 int privateFlags = mPrivateFlags;
8913
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008914 int viewStateIndex = 0;
8915 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
8916 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
8917 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07008918 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008919 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
8920 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08008921 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
8922 // This is set if HW acceleration is requested, even if the current
8923 // process doesn't allow it. This is just to allow app preview
8924 // windows to better match their app.
8925 viewStateIndex |= VIEW_STATE_ACCELERATED;
8926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927
8928 drawableState = VIEW_STATE_SETS[viewStateIndex];
8929
8930 //noinspection ConstantIfStatement
8931 if (false) {
8932 Log.i("View", "drawableStateIndex=" + viewStateIndex);
8933 Log.i("View", toString()
8934 + " pressed=" + ((privateFlags & PRESSED) != 0)
8935 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
8936 + " fo=" + hasFocus()
8937 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008938 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939 + ": " + Arrays.toString(drawableState));
8940 }
8941
8942 if (extraSpace == 0) {
8943 return drawableState;
8944 }
8945
8946 final int[] fullState;
8947 if (drawableState != null) {
8948 fullState = new int[drawableState.length + extraSpace];
8949 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
8950 } else {
8951 fullState = new int[extraSpace];
8952 }
8953
8954 return fullState;
8955 }
8956
8957 /**
8958 * Merge your own state values in <var>additionalState</var> into the base
8959 * state values <var>baseState</var> that were returned by
8960 * {@link #onCreateDrawableState}.
8961 *
8962 * @param baseState The base state values returned by
8963 * {@link #onCreateDrawableState}, which will be modified to also hold your
8964 * own additional state values.
8965 *
8966 * @param additionalState The additional state values you would like
8967 * added to <var>baseState</var>; this array is not modified.
8968 *
8969 * @return As a convenience, the <var>baseState</var> array you originally
8970 * passed into the function is returned.
8971 *
8972 * @see #onCreateDrawableState
8973 */
8974 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
8975 final int N = baseState.length;
8976 int i = N - 1;
8977 while (i >= 0 && baseState[i] == 0) {
8978 i--;
8979 }
8980 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
8981 return baseState;
8982 }
8983
8984 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07008985 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
8986 * on all Drawable objects associated with this view.
8987 */
8988 public void jumpDrawablesToCurrentState() {
8989 if (mBGDrawable != null) {
8990 mBGDrawable.jumpToCurrentState();
8991 }
8992 }
8993
8994 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008995 * Sets the background color for this view.
8996 * @param color the color of the background
8997 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008998 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008999 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07009000 if (mBGDrawable instanceof ColorDrawable) {
9001 ((ColorDrawable) mBGDrawable).setColor(color);
9002 } else {
9003 setBackgroundDrawable(new ColorDrawable(color));
9004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009005 }
9006
9007 /**
9008 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07009009 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009010 * @param resid The identifier of the resource.
9011 * @attr ref android.R.styleable#View_background
9012 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009013 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009014 public void setBackgroundResource(int resid) {
9015 if (resid != 0 && resid == mBackgroundResource) {
9016 return;
9017 }
9018
9019 Drawable d= null;
9020 if (resid != 0) {
9021 d = mResources.getDrawable(resid);
9022 }
9023 setBackgroundDrawable(d);
9024
9025 mBackgroundResource = resid;
9026 }
9027
9028 /**
9029 * Set the background to a given Drawable, or remove the background. If the
9030 * background has padding, this View's padding is set to the background's
9031 * padding. However, when a background is removed, this View's padding isn't
9032 * touched. If setting the padding is desired, please use
9033 * {@link #setPadding(int, int, int, int)}.
9034 *
9035 * @param d The Drawable to use as the background, or null to remove the
9036 * background
9037 */
9038 public void setBackgroundDrawable(Drawable d) {
9039 boolean requestLayout = false;
9040
9041 mBackgroundResource = 0;
9042
9043 /*
9044 * Regardless of whether we're setting a new background or not, we want
9045 * to clear the previous drawable.
9046 */
9047 if (mBGDrawable != null) {
9048 mBGDrawable.setCallback(null);
9049 unscheduleDrawable(mBGDrawable);
9050 }
9051
9052 if (d != null) {
9053 Rect padding = sThreadLocal.get();
9054 if (padding == null) {
9055 padding = new Rect();
9056 sThreadLocal.set(padding);
9057 }
9058 if (d.getPadding(padding)) {
9059 setPadding(padding.left, padding.top, padding.right, padding.bottom);
9060 }
9061
9062 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
9063 // if it has a different minimum size, we should layout again
9064 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9065 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9066 requestLayout = true;
9067 }
9068
9069 d.setCallback(this);
9070 if (d.isStateful()) {
9071 d.setState(getDrawableState());
9072 }
9073 d.setVisible(getVisibility() == VISIBLE, false);
9074 mBGDrawable = d;
9075
9076 if ((mPrivateFlags & SKIP_DRAW) != 0) {
9077 mPrivateFlags &= ~SKIP_DRAW;
9078 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9079 requestLayout = true;
9080 }
9081 } else {
9082 /* Remove the background */
9083 mBGDrawable = null;
9084
9085 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9086 /*
9087 * This view ONLY drew the background before and we're removing
9088 * the background, so now it won't draw anything
9089 * (hence we SKIP_DRAW)
9090 */
9091 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9092 mPrivateFlags |= SKIP_DRAW;
9093 }
9094
9095 /*
9096 * When the background is set, we try to apply its padding to this
9097 * View. When the background is removed, we don't touch this View's
9098 * padding. This is noted in the Javadocs. Hence, we don't need to
9099 * requestLayout(), the invalidate() below is sufficient.
9100 */
9101
9102 // The old background's minimum size could have affected this
9103 // View's layout, so let's requestLayout
9104 requestLayout = true;
9105 }
9106
Romain Guy8f1344f52009-05-15 16:03:59 -07009107 computeOpaqueFlags();
9108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 if (requestLayout) {
9110 requestLayout();
9111 }
9112
9113 mBackgroundSizeChanged = true;
9114 invalidate();
9115 }
9116
9117 /**
9118 * Gets the background drawable
9119 * @return The drawable used as the background for this view, if any.
9120 */
9121 public Drawable getBackground() {
9122 return mBGDrawable;
9123 }
9124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009125 /**
9126 * Sets the padding. The view may add on the space required to display
9127 * the scrollbars, depending on the style and visibility of the scrollbars.
9128 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9129 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9130 * from the values set in this call.
9131 *
9132 * @attr ref android.R.styleable#View_padding
9133 * @attr ref android.R.styleable#View_paddingBottom
9134 * @attr ref android.R.styleable#View_paddingLeft
9135 * @attr ref android.R.styleable#View_paddingRight
9136 * @attr ref android.R.styleable#View_paddingTop
9137 * @param left the left padding in pixels
9138 * @param top the top padding in pixels
9139 * @param right the right padding in pixels
9140 * @param bottom the bottom padding in pixels
9141 */
9142 public void setPadding(int left, int top, int right, int bottom) {
9143 boolean changed = false;
9144
Adam Powell20232d02010-12-08 21:08:53 -08009145 mUserPaddingLeft = left;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009146 mUserPaddingRight = right;
9147 mUserPaddingBottom = bottom;
9148
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009149 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07009150
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009151 // Common case is there are no scroll bars.
9152 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009153 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
Adam Powell20232d02010-12-08 21:08:53 -08009154 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9155 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009156 ? 0 : getVerticalScrollbarWidth();
Adam Powell20232d02010-12-08 21:08:53 -08009157 switch (mVerticalScrollbarPosition) {
9158 case SCROLLBAR_POSITION_DEFAULT:
9159 case SCROLLBAR_POSITION_RIGHT:
9160 right += offset;
9161 break;
9162 case SCROLLBAR_POSITION_LEFT:
9163 left += offset;
9164 break;
9165 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009166 }
Adam Powell20232d02010-12-08 21:08:53 -08009167 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009168 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9169 ? 0 : getHorizontalScrollbarHeight();
9170 }
9171 }
Romain Guy8506ab42009-06-11 17:35:47 -07009172
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009173 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009174 changed = true;
9175 mPaddingLeft = left;
9176 }
9177 if (mPaddingTop != top) {
9178 changed = true;
9179 mPaddingTop = top;
9180 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009181 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009182 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009183 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009184 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009185 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009186 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009187 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009188 }
9189
9190 if (changed) {
9191 requestLayout();
9192 }
9193 }
9194
9195 /**
9196 * Returns the top padding of this view.
9197 *
9198 * @return the top padding in pixels
9199 */
9200 public int getPaddingTop() {
9201 return mPaddingTop;
9202 }
9203
9204 /**
9205 * Returns the bottom padding of this view. If there are inset and enabled
9206 * scrollbars, this value may include the space required to display the
9207 * scrollbars as well.
9208 *
9209 * @return the bottom padding in pixels
9210 */
9211 public int getPaddingBottom() {
9212 return mPaddingBottom;
9213 }
9214
9215 /**
9216 * Returns the left padding of this view. If there are inset and enabled
9217 * scrollbars, this value may include the space required to display the
9218 * scrollbars as well.
9219 *
9220 * @return the left padding in pixels
9221 */
9222 public int getPaddingLeft() {
9223 return mPaddingLeft;
9224 }
9225
9226 /**
9227 * Returns the right padding of this view. If there are inset and enabled
9228 * scrollbars, this value may include the space required to display the
9229 * scrollbars as well.
9230 *
9231 * @return the right padding in pixels
9232 */
9233 public int getPaddingRight() {
9234 return mPaddingRight;
9235 }
9236
9237 /**
9238 * Changes the selection state of this view. A view can be selected or not.
9239 * Note that selection is not the same as focus. Views are typically
9240 * selected in the context of an AdapterView like ListView or GridView;
9241 * the selected view is the view that is highlighted.
9242 *
9243 * @param selected true if the view must be selected, false otherwise
9244 */
9245 public void setSelected(boolean selected) {
9246 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9247 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009248 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009249 invalidate();
9250 refreshDrawableState();
9251 dispatchSetSelected(selected);
9252 }
9253 }
9254
9255 /**
9256 * Dispatch setSelected to all of this View's children.
9257 *
9258 * @see #setSelected(boolean)
9259 *
9260 * @param selected The new selected state
9261 */
9262 protected void dispatchSetSelected(boolean selected) {
9263 }
9264
9265 /**
9266 * Indicates the selection state of this view.
9267 *
9268 * @return true if the view is selected, false otherwise
9269 */
9270 @ViewDebug.ExportedProperty
9271 public boolean isSelected() {
9272 return (mPrivateFlags & SELECTED) != 0;
9273 }
9274
9275 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009276 * Changes the activated state of this view. A view can be activated or not.
9277 * Note that activation is not the same as selection. Selection is
9278 * a transient property, representing the view (hierarchy) the user is
9279 * currently interacting with. Activation is a longer-term state that the
9280 * user can move views in and out of. For example, in a list view with
9281 * single or multiple selection enabled, the views in the current selection
9282 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9283 * here.) The activated state is propagated down to children of the view it
9284 * is set on.
9285 *
9286 * @param activated true if the view must be activated, false otherwise
9287 */
9288 public void setActivated(boolean activated) {
9289 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9290 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
9291 invalidate();
9292 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009293 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009294 }
9295 }
9296
9297 /**
9298 * Dispatch setActivated to all of this View's children.
9299 *
9300 * @see #setActivated(boolean)
9301 *
9302 * @param activated The new activated state
9303 */
9304 protected void dispatchSetActivated(boolean activated) {
9305 }
9306
9307 /**
9308 * Indicates the activation state of this view.
9309 *
9310 * @return true if the view is activated, false otherwise
9311 */
9312 @ViewDebug.ExportedProperty
9313 public boolean isActivated() {
9314 return (mPrivateFlags & ACTIVATED) != 0;
9315 }
9316
9317 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009318 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9319 * observer can be used to get notifications when global events, like
9320 * layout, happen.
9321 *
9322 * The returned ViewTreeObserver observer is not guaranteed to remain
9323 * valid for the lifetime of this View. If the caller of this method keeps
9324 * a long-lived reference to ViewTreeObserver, it should always check for
9325 * the return value of {@link ViewTreeObserver#isAlive()}.
9326 *
9327 * @return The ViewTreeObserver for this view's hierarchy.
9328 */
9329 public ViewTreeObserver getViewTreeObserver() {
9330 if (mAttachInfo != null) {
9331 return mAttachInfo.mTreeObserver;
9332 }
9333 if (mFloatingTreeObserver == null) {
9334 mFloatingTreeObserver = new ViewTreeObserver();
9335 }
9336 return mFloatingTreeObserver;
9337 }
9338
9339 /**
9340 * <p>Finds the topmost view in the current view hierarchy.</p>
9341 *
9342 * @return the topmost view containing this view
9343 */
9344 public View getRootView() {
9345 if (mAttachInfo != null) {
9346 final View v = mAttachInfo.mRootView;
9347 if (v != null) {
9348 return v;
9349 }
9350 }
Romain Guy8506ab42009-06-11 17:35:47 -07009351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 View parent = this;
9353
9354 while (parent.mParent != null && parent.mParent instanceof View) {
9355 parent = (View) parent.mParent;
9356 }
9357
9358 return parent;
9359 }
9360
9361 /**
9362 * <p>Computes the coordinates of this view on the screen. The argument
9363 * must be an array of two integers. After the method returns, the array
9364 * contains the x and y location in that order.</p>
9365 *
9366 * @param location an array of two integers in which to hold the coordinates
9367 */
9368 public void getLocationOnScreen(int[] location) {
9369 getLocationInWindow(location);
9370
9371 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009372 if (info != null) {
9373 location[0] += info.mWindowLeft;
9374 location[1] += info.mWindowTop;
9375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009376 }
9377
9378 /**
9379 * <p>Computes the coordinates of this view in its window. The argument
9380 * must be an array of two integers. After the method returns, the array
9381 * contains the x and y location in that order.</p>
9382 *
9383 * @param location an array of two integers in which to hold the coordinates
9384 */
9385 public void getLocationInWindow(int[] location) {
9386 if (location == null || location.length < 2) {
9387 throw new IllegalArgumentException("location must be an array of "
9388 + "two integers");
9389 }
9390
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009391 location[0] = mLeft + (int) (mTranslationX + 0.5f);
9392 location[1] = mTop + (int) (mTranslationY + 0.5f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009393
9394 ViewParent viewParent = mParent;
9395 while (viewParent instanceof View) {
9396 final View view = (View)viewParent;
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009397 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
9398 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009399 viewParent = view.mParent;
9400 }
Romain Guy8506ab42009-06-11 17:35:47 -07009401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009402 if (viewParent instanceof ViewRoot) {
9403 // *cough*
9404 final ViewRoot vr = (ViewRoot)viewParent;
9405 location[1] -= vr.mCurScrollY;
9406 }
9407 }
9408
9409 /**
9410 * {@hide}
9411 * @param id the id of the view to be found
9412 * @return the view of the specified id, null if cannot be found
9413 */
9414 protected View findViewTraversal(int id) {
9415 if (id == mID) {
9416 return this;
9417 }
9418 return null;
9419 }
9420
9421 /**
9422 * {@hide}
9423 * @param tag the tag of the view to be found
9424 * @return the view of specified tag, null if cannot be found
9425 */
9426 protected View findViewWithTagTraversal(Object tag) {
9427 if (tag != null && tag.equals(mTag)) {
9428 return this;
9429 }
9430 return null;
9431 }
9432
9433 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009434 * {@hide}
9435 * @param predicate The predicate to evaluate.
9436 * @return The first view that matches the predicate or null.
9437 */
9438 protected View findViewByPredicateTraversal(Predicate<View> predicate) {
9439 if (predicate.apply(this)) {
9440 return this;
9441 }
9442 return null;
9443 }
9444
9445 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009446 * Look for a child view with the given id. If this view has the given
9447 * id, return this view.
9448 *
9449 * @param id The id to search for.
9450 * @return The view that has the given id in the hierarchy or null
9451 */
9452 public final View findViewById(int id) {
9453 if (id < 0) {
9454 return null;
9455 }
9456 return findViewTraversal(id);
9457 }
9458
9459 /**
9460 * Look for a child view with the given tag. If this view has the given
9461 * tag, return this view.
9462 *
9463 * @param tag The tag to search for, using "tag.equals(getTag())".
9464 * @return The View that has the given tag in the hierarchy or null
9465 */
9466 public final View findViewWithTag(Object tag) {
9467 if (tag == null) {
9468 return null;
9469 }
9470 return findViewWithTagTraversal(tag);
9471 }
9472
9473 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009474 * {@hide}
9475 * Look for a child view that matches the specified predicate.
9476 * If this view matches the predicate, return this view.
9477 *
9478 * @param predicate The predicate to evaluate.
9479 * @return The first view that matches the predicate or null.
9480 */
9481 public final View findViewByPredicate(Predicate<View> predicate) {
9482 return findViewByPredicateTraversal(predicate);
9483 }
9484
9485 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486 * Sets the identifier for this view. The identifier does not have to be
9487 * unique in this view's hierarchy. The identifier should be a positive
9488 * number.
9489 *
9490 * @see #NO_ID
9491 * @see #getId
9492 * @see #findViewById
9493 *
9494 * @param id a number used to identify the view
9495 *
9496 * @attr ref android.R.styleable#View_id
9497 */
9498 public void setId(int id) {
9499 mID = id;
9500 }
9501
9502 /**
9503 * {@hide}
9504 *
9505 * @param isRoot true if the view belongs to the root namespace, false
9506 * otherwise
9507 */
9508 public void setIsRootNamespace(boolean isRoot) {
9509 if (isRoot) {
9510 mPrivateFlags |= IS_ROOT_NAMESPACE;
9511 } else {
9512 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9513 }
9514 }
9515
9516 /**
9517 * {@hide}
9518 *
9519 * @return true if the view belongs to the root namespace, false otherwise
9520 */
9521 public boolean isRootNamespace() {
9522 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9523 }
9524
9525 /**
9526 * Returns this view's identifier.
9527 *
9528 * @return a positive integer used to identify the view or {@link #NO_ID}
9529 * if the view has no ID
9530 *
9531 * @see #setId
9532 * @see #findViewById
9533 * @attr ref android.R.styleable#View_id
9534 */
9535 @ViewDebug.CapturedViewProperty
9536 public int getId() {
9537 return mID;
9538 }
9539
9540 /**
9541 * Returns this view's tag.
9542 *
9543 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07009544 *
9545 * @see #setTag(Object)
9546 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009547 */
9548 @ViewDebug.ExportedProperty
9549 public Object getTag() {
9550 return mTag;
9551 }
9552
9553 /**
9554 * Sets the tag associated with this view. A tag can be used to mark
9555 * a view in its hierarchy and does not have to be unique within the
9556 * hierarchy. Tags can also be used to store data within a view without
9557 * resorting to another data structure.
9558 *
9559 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07009560 *
9561 * @see #getTag()
9562 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009563 */
9564 public void setTag(final Object tag) {
9565 mTag = tag;
9566 }
9567
9568 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009569 * Returns the tag associated with this view and the specified key.
9570 *
9571 * @param key The key identifying the tag
9572 *
9573 * @return the Object stored in this view as a tag
9574 *
9575 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009576 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009577 */
9578 public Object getTag(int key) {
9579 SparseArray<Object> tags = null;
9580 synchronized (sTagsLock) {
9581 if (sTags != null) {
9582 tags = sTags.get(this);
9583 }
9584 }
9585
9586 if (tags != null) return tags.get(key);
9587 return null;
9588 }
9589
9590 /**
9591 * Sets a tag associated with this view and a key. A tag can be used
9592 * to mark a view in its hierarchy and does not have to be unique within
9593 * the hierarchy. Tags can also be used to store data within a view
9594 * without resorting to another data structure.
9595 *
9596 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009597 * application to ensure it is unique (see the <a
9598 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9599 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009600 * the Android framework or not associated with any package will cause
9601 * an {@link IllegalArgumentException} to be thrown.
9602 *
9603 * @param key The key identifying the tag
9604 * @param tag An Object to tag the view with
9605 *
9606 * @throws IllegalArgumentException If they specified key is not valid
9607 *
9608 * @see #setTag(Object)
9609 * @see #getTag(int)
9610 */
9611 public void setTag(int key, final Object tag) {
9612 // If the package id is 0x00 or 0x01, it's either an undefined package
9613 // or a framework id
9614 if ((key >>> 24) < 2) {
9615 throw new IllegalArgumentException("The key must be an application-specific "
9616 + "resource id.");
9617 }
9618
9619 setTagInternal(this, key, tag);
9620 }
9621
9622 /**
9623 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9624 * framework id.
9625 *
9626 * @hide
9627 */
9628 public void setTagInternal(int key, Object tag) {
9629 if ((key >>> 24) != 0x1) {
9630 throw new IllegalArgumentException("The key must be a framework-specific "
9631 + "resource id.");
9632 }
9633
Romain Guy8506ab42009-06-11 17:35:47 -07009634 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009635 }
9636
9637 private static void setTagInternal(View view, int key, Object tag) {
9638 SparseArray<Object> tags = null;
9639 synchronized (sTagsLock) {
9640 if (sTags == null) {
9641 sTags = new WeakHashMap<View, SparseArray<Object>>();
9642 } else {
9643 tags = sTags.get(view);
9644 }
9645 }
9646
9647 if (tags == null) {
9648 tags = new SparseArray<Object>(2);
9649 synchronized (sTagsLock) {
9650 sTags.put(view, tags);
9651 }
9652 }
9653
9654 tags.put(key, tag);
9655 }
9656
9657 /**
Romain Guy13922e02009-05-12 17:56:14 -07009658 * @param consistency The type of consistency. See ViewDebug for more information.
9659 *
9660 * @hide
9661 */
9662 protected boolean dispatchConsistencyCheck(int consistency) {
9663 return onConsistencyCheck(consistency);
9664 }
9665
9666 /**
9667 * Method that subclasses should implement to check their consistency. The type of
9668 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009669 *
Romain Guy13922e02009-05-12 17:56:14 -07009670 * @param consistency The type of consistency. See ViewDebug for more information.
9671 *
9672 * @throws IllegalStateException if the view is in an inconsistent state.
9673 *
9674 * @hide
9675 */
9676 protected boolean onConsistencyCheck(int consistency) {
9677 boolean result = true;
9678
9679 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9680 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9681
9682 if (checkLayout) {
9683 if (getParent() == null) {
9684 result = false;
9685 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9686 "View " + this + " does not have a parent.");
9687 }
9688
9689 if (mAttachInfo == null) {
9690 result = false;
9691 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9692 "View " + this + " is not attached to a window.");
9693 }
9694 }
9695
9696 if (checkDrawing) {
9697 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9698 // from their draw() method
9699
9700 if ((mPrivateFlags & DRAWN) != DRAWN &&
9701 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9702 result = false;
9703 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9704 "View " + this + " was invalidated but its drawing cache is valid.");
9705 }
9706 }
9707
9708 return result;
9709 }
9710
9711 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009712 * Prints information about this view in the log output, with the tag
9713 * {@link #VIEW_LOG_TAG}.
9714 *
9715 * @hide
9716 */
9717 public void debug() {
9718 debug(0);
9719 }
9720
9721 /**
9722 * Prints information about this view in the log output, with the tag
9723 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
9724 * indentation defined by the <code>depth</code>.
9725 *
9726 * @param depth the indentation level
9727 *
9728 * @hide
9729 */
9730 protected void debug(int depth) {
9731 String output = debugIndent(depth - 1);
9732
9733 output += "+ " + this;
9734 int id = getId();
9735 if (id != -1) {
9736 output += " (id=" + id + ")";
9737 }
9738 Object tag = getTag();
9739 if (tag != null) {
9740 output += " (tag=" + tag + ")";
9741 }
9742 Log.d(VIEW_LOG_TAG, output);
9743
9744 if ((mPrivateFlags & FOCUSED) != 0) {
9745 output = debugIndent(depth) + " FOCUSED";
9746 Log.d(VIEW_LOG_TAG, output);
9747 }
9748
9749 output = debugIndent(depth);
9750 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
9751 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
9752 + "} ";
9753 Log.d(VIEW_LOG_TAG, output);
9754
9755 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
9756 || mPaddingBottom != 0) {
9757 output = debugIndent(depth);
9758 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
9759 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
9760 Log.d(VIEW_LOG_TAG, output);
9761 }
9762
9763 output = debugIndent(depth);
9764 output += "mMeasureWidth=" + mMeasuredWidth +
9765 " mMeasureHeight=" + mMeasuredHeight;
9766 Log.d(VIEW_LOG_TAG, output);
9767
9768 output = debugIndent(depth);
9769 if (mLayoutParams == null) {
9770 output += "BAD! no layout params";
9771 } else {
9772 output = mLayoutParams.debug(output);
9773 }
9774 Log.d(VIEW_LOG_TAG, output);
9775
9776 output = debugIndent(depth);
9777 output += "flags={";
9778 output += View.printFlags(mViewFlags);
9779 output += "}";
9780 Log.d(VIEW_LOG_TAG, output);
9781
9782 output = debugIndent(depth);
9783 output += "privateFlags={";
9784 output += View.printPrivateFlags(mPrivateFlags);
9785 output += "}";
9786 Log.d(VIEW_LOG_TAG, output);
9787 }
9788
9789 /**
9790 * Creates an string of whitespaces used for indentation.
9791 *
9792 * @param depth the indentation level
9793 * @return a String containing (depth * 2 + 3) * 2 white spaces
9794 *
9795 * @hide
9796 */
9797 protected static String debugIndent(int depth) {
9798 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
9799 for (int i = 0; i < (depth * 2) + 3; i++) {
9800 spaces.append(' ').append(' ');
9801 }
9802 return spaces.toString();
9803 }
9804
9805 /**
9806 * <p>Return the offset of the widget's text baseline from the widget's top
9807 * boundary. If this widget does not support baseline alignment, this
9808 * method returns -1. </p>
9809 *
9810 * @return the offset of the baseline within the widget's bounds or -1
9811 * if baseline alignment is not supported
9812 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07009813 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009814 public int getBaseline() {
9815 return -1;
9816 }
9817
9818 /**
9819 * Call this when something has changed which has invalidated the
9820 * layout of this view. This will schedule a layout pass of the view
9821 * tree.
9822 */
9823 public void requestLayout() {
9824 if (ViewDebug.TRACE_HIERARCHY) {
9825 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
9826 }
9827
9828 mPrivateFlags |= FORCE_LAYOUT;
9829
9830 if (mParent != null && !mParent.isLayoutRequested()) {
9831 mParent.requestLayout();
9832 }
9833 }
9834
9835 /**
9836 * Forces this view to be laid out during the next layout pass.
9837 * This method does not call requestLayout() or forceLayout()
9838 * on the parent.
9839 */
9840 public void forceLayout() {
9841 mPrivateFlags |= FORCE_LAYOUT;
9842 }
9843
9844 /**
9845 * <p>
9846 * This is called to find out how big a view should be. The parent
9847 * supplies constraint information in the width and height parameters.
9848 * </p>
9849 *
9850 * <p>
9851 * The actual mesurement work of a view is performed in
9852 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
9853 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
9854 * </p>
9855 *
9856 *
9857 * @param widthMeasureSpec Horizontal space requirements as imposed by the
9858 * parent
9859 * @param heightMeasureSpec Vertical space requirements as imposed by the
9860 * parent
9861 *
9862 * @see #onMeasure(int, int)
9863 */
9864 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
9865 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
9866 widthMeasureSpec != mOldWidthMeasureSpec ||
9867 heightMeasureSpec != mOldHeightMeasureSpec) {
9868
9869 // first clears the measured dimension flag
9870 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9871
9872 if (ViewDebug.TRACE_HIERARCHY) {
9873 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
9874 }
9875
9876 // measure ourselves, this should set the measured dimension flag back
9877 onMeasure(widthMeasureSpec, heightMeasureSpec);
9878
9879 // flag not set, setMeasuredDimension() was not invoked, we raise
9880 // an exception to warn the developer
9881 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9882 throw new IllegalStateException("onMeasure() did not set the"
9883 + " measured dimension by calling"
9884 + " setMeasuredDimension()");
9885 }
9886
9887 mPrivateFlags |= LAYOUT_REQUIRED;
9888 }
9889
9890 mOldWidthMeasureSpec = widthMeasureSpec;
9891 mOldHeightMeasureSpec = heightMeasureSpec;
9892 }
9893
9894 /**
9895 * <p>
9896 * Measure the view and its content to determine the measured width and the
9897 * measured height. This method is invoked by {@link #measure(int, int)} and
9898 * should be overriden by subclasses to provide accurate and efficient
9899 * measurement of their contents.
9900 * </p>
9901 *
9902 * <p>
9903 * <strong>CONTRACT:</strong> When overriding this method, you
9904 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
9905 * measured width and height of this view. Failure to do so will trigger an
9906 * <code>IllegalStateException</code>, thrown by
9907 * {@link #measure(int, int)}. Calling the superclass'
9908 * {@link #onMeasure(int, int)} is a valid use.
9909 * </p>
9910 *
9911 * <p>
9912 * The base class implementation of measure defaults to the background size,
9913 * unless a larger size is allowed by the MeasureSpec. Subclasses should
9914 * override {@link #onMeasure(int, int)} to provide better measurements of
9915 * their content.
9916 * </p>
9917 *
9918 * <p>
9919 * If this method is overridden, it is the subclass's responsibility to make
9920 * sure the measured height and width are at least the view's minimum height
9921 * and width ({@link #getSuggestedMinimumHeight()} and
9922 * {@link #getSuggestedMinimumWidth()}).
9923 * </p>
9924 *
9925 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
9926 * The requirements are encoded with
9927 * {@link android.view.View.MeasureSpec}.
9928 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
9929 * The requirements are encoded with
9930 * {@link android.view.View.MeasureSpec}.
9931 *
9932 * @see #getMeasuredWidth()
9933 * @see #getMeasuredHeight()
9934 * @see #setMeasuredDimension(int, int)
9935 * @see #getSuggestedMinimumHeight()
9936 * @see #getSuggestedMinimumWidth()
9937 * @see android.view.View.MeasureSpec#getMode(int)
9938 * @see android.view.View.MeasureSpec#getSize(int)
9939 */
9940 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9941 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
9942 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
9943 }
9944
9945 /**
9946 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
9947 * measured width and measured height. Failing to do so will trigger an
9948 * exception at measurement time.</p>
9949 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08009950 * @param measuredWidth The measured width of this view. May be a complex
9951 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
9952 * {@link #MEASURED_STATE_TOO_SMALL}.
9953 * @param measuredHeight The measured height of this view. May be a complex
9954 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
9955 * {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009956 */
9957 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
9958 mMeasuredWidth = measuredWidth;
9959 mMeasuredHeight = measuredHeight;
9960
9961 mPrivateFlags |= MEASURED_DIMENSION_SET;
9962 }
9963
9964 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08009965 * Merge two states as returned by {@link #getMeasuredState()}.
9966 * @param curState The current state as returned from a view or the result
9967 * of combining multiple views.
9968 * @param newState The new view state to combine.
9969 * @return Returns a new integer reflecting the combination of the two
9970 * states.
9971 */
9972 public static int combineMeasuredStates(int curState, int newState) {
9973 return curState | newState;
9974 }
9975
9976 /**
9977 * Version of {@link #resolveSizeAndState(int, int, int)}
9978 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
9979 */
9980 public static int resolveSize(int size, int measureSpec) {
9981 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
9982 }
9983
9984 /**
9985 * Utility to reconcile a desired size and state, with constraints imposed
9986 * by a MeasureSpec. Will take the desired size, unless a different size
9987 * is imposed by the constraints. The returned value is a compound integer,
9988 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
9989 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
9990 * size is smaller than the size the view wants to be.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009991 *
9992 * @param size How big the view wants to be
9993 * @param measureSpec Constraints imposed by the parent
Dianne Hackborn189ee182010-12-02 21:48:53 -08009994 * @return Size information bit mask as defined by
9995 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009996 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08009997 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009998 int result = size;
9999 int specMode = MeasureSpec.getMode(measureSpec);
10000 int specSize = MeasureSpec.getSize(measureSpec);
10001 switch (specMode) {
10002 case MeasureSpec.UNSPECIFIED:
10003 result = size;
10004 break;
10005 case MeasureSpec.AT_MOST:
Dianne Hackborn189ee182010-12-02 21:48:53 -080010006 if (specSize < size) {
10007 result = specSize | MEASURED_STATE_TOO_SMALL;
10008 } else {
10009 result = size;
10010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010011 break;
10012 case MeasureSpec.EXACTLY:
10013 result = specSize;
10014 break;
10015 }
Dianne Hackborn189ee182010-12-02 21:48:53 -080010016 return result | (childMeasuredState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010017 }
10018
10019 /**
10020 * Utility to return a default size. Uses the supplied size if the
10021 * MeasureSpec imposed no contraints. Will get larger if allowed
10022 * by the MeasureSpec.
10023 *
10024 * @param size Default size for this view
10025 * @param measureSpec Constraints imposed by the parent
10026 * @return The size this view should be.
10027 */
10028 public static int getDefaultSize(int size, int measureSpec) {
10029 int result = size;
10030 int specMode = MeasureSpec.getMode(measureSpec);
10031 int specSize = MeasureSpec.getSize(measureSpec);
10032
10033 switch (specMode) {
10034 case MeasureSpec.UNSPECIFIED:
10035 result = size;
10036 break;
10037 case MeasureSpec.AT_MOST:
10038 case MeasureSpec.EXACTLY:
10039 result = specSize;
10040 break;
10041 }
10042 return result;
10043 }
10044
10045 /**
10046 * Returns the suggested minimum height that the view should use. This
10047 * returns the maximum of the view's minimum height
10048 * and the background's minimum height
10049 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10050 * <p>
10051 * When being used in {@link #onMeasure(int, int)}, the caller should still
10052 * ensure the returned height is within the requirements of the parent.
10053 *
10054 * @return The suggested minimum height of the view.
10055 */
10056 protected int getSuggestedMinimumHeight() {
10057 int suggestedMinHeight = mMinHeight;
10058
10059 if (mBGDrawable != null) {
10060 final int bgMinHeight = mBGDrawable.getMinimumHeight();
10061 if (suggestedMinHeight < bgMinHeight) {
10062 suggestedMinHeight = bgMinHeight;
10063 }
10064 }
10065
10066 return suggestedMinHeight;
10067 }
10068
10069 /**
10070 * Returns the suggested minimum width that the view should use. This
10071 * returns the maximum of the view's minimum width)
10072 * and the background's minimum width
10073 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10074 * <p>
10075 * When being used in {@link #onMeasure(int, int)}, the caller should still
10076 * ensure the returned width is within the requirements of the parent.
10077 *
10078 * @return The suggested minimum width of the view.
10079 */
10080 protected int getSuggestedMinimumWidth() {
10081 int suggestedMinWidth = mMinWidth;
10082
10083 if (mBGDrawable != null) {
10084 final int bgMinWidth = mBGDrawable.getMinimumWidth();
10085 if (suggestedMinWidth < bgMinWidth) {
10086 suggestedMinWidth = bgMinWidth;
10087 }
10088 }
10089
10090 return suggestedMinWidth;
10091 }
10092
10093 /**
10094 * Sets the minimum height of the view. It is not guaranteed the view will
10095 * be able to achieve this minimum height (for example, if its parent layout
10096 * constrains it with less available height).
10097 *
10098 * @param minHeight The minimum height the view will try to be.
10099 */
10100 public void setMinimumHeight(int minHeight) {
10101 mMinHeight = minHeight;
10102 }
10103
10104 /**
10105 * Sets the minimum width of the view. It is not guaranteed the view will
10106 * be able to achieve this minimum width (for example, if its parent layout
10107 * constrains it with less available width).
10108 *
10109 * @param minWidth The minimum width the view will try to be.
10110 */
10111 public void setMinimumWidth(int minWidth) {
10112 mMinWidth = minWidth;
10113 }
10114
10115 /**
10116 * Get the animation currently associated with this view.
10117 *
10118 * @return The animation that is currently playing or
10119 * scheduled to play for this view.
10120 */
10121 public Animation getAnimation() {
10122 return mCurrentAnimation;
10123 }
10124
10125 /**
10126 * Start the specified animation now.
10127 *
10128 * @param animation the animation to start now
10129 */
10130 public void startAnimation(Animation animation) {
10131 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10132 setAnimation(animation);
10133 invalidate();
10134 }
10135
10136 /**
10137 * Cancels any animations for this view.
10138 */
10139 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -080010140 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -080010141 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -080010142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010143 mCurrentAnimation = null;
10144 }
10145
10146 /**
10147 * Sets the next animation to play for this view.
10148 * If you want the animation to play immediately, use
10149 * startAnimation. This method provides allows fine-grained
10150 * control over the start time and invalidation, but you
10151 * must make sure that 1) the animation has a start time set, and
10152 * 2) the view will be invalidated when the animation is supposed to
10153 * start.
10154 *
10155 * @param animation The next animation, or null.
10156 */
10157 public void setAnimation(Animation animation) {
10158 mCurrentAnimation = animation;
10159 if (animation != null) {
10160 animation.reset();
10161 }
10162 }
10163
10164 /**
10165 * Invoked by a parent ViewGroup to notify the start of the animation
10166 * currently associated with this view. If you override this method,
10167 * always call super.onAnimationStart();
10168 *
10169 * @see #setAnimation(android.view.animation.Animation)
10170 * @see #getAnimation()
10171 */
10172 protected void onAnimationStart() {
10173 mPrivateFlags |= ANIMATION_STARTED;
10174 }
10175
10176 /**
10177 * Invoked by a parent ViewGroup to notify the end of the animation
10178 * currently associated with this view. If you override this method,
10179 * always call super.onAnimationEnd();
10180 *
10181 * @see #setAnimation(android.view.animation.Animation)
10182 * @see #getAnimation()
10183 */
10184 protected void onAnimationEnd() {
10185 mPrivateFlags &= ~ANIMATION_STARTED;
10186 }
10187
10188 /**
10189 * Invoked if there is a Transform that involves alpha. Subclass that can
10190 * draw themselves with the specified alpha should return true, and then
10191 * respect that alpha when their onDraw() is called. If this returns false
10192 * then the view may be redirected to draw into an offscreen buffer to
10193 * fulfill the request, which will look fine, but may be slower than if the
10194 * subclass handles it internally. The default implementation returns false.
10195 *
10196 * @param alpha The alpha (0..255) to apply to the view's drawing
10197 * @return true if the view can draw with the specified alpha.
10198 */
10199 protected boolean onSetAlpha(int alpha) {
10200 return false;
10201 }
10202
10203 /**
10204 * This is used by the RootView to perform an optimization when
10205 * the view hierarchy contains one or several SurfaceView.
10206 * SurfaceView is always considered transparent, but its children are not,
10207 * therefore all View objects remove themselves from the global transparent
10208 * region (passed as a parameter to this function).
10209 *
10210 * @param region The transparent region for this ViewRoot (window).
10211 *
10212 * @return Returns true if the effective visibility of the view at this
10213 * point is opaque, regardless of the transparent region; returns false
10214 * if it is possible for underlying windows to be seen behind the view.
10215 *
10216 * {@hide}
10217 */
10218 public boolean gatherTransparentRegion(Region region) {
10219 final AttachInfo attachInfo = mAttachInfo;
10220 if (region != null && attachInfo != null) {
10221 final int pflags = mPrivateFlags;
10222 if ((pflags & SKIP_DRAW) == 0) {
10223 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10224 // remove it from the transparent region.
10225 final int[] location = attachInfo.mTransparentLocation;
10226 getLocationInWindow(location);
10227 region.op(location[0], location[1], location[0] + mRight - mLeft,
10228 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10229 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10230 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10231 // exists, so we remove the background drawable's non-transparent
10232 // parts from this transparent region.
10233 applyDrawableToTransparentRegion(mBGDrawable, region);
10234 }
10235 }
10236 return true;
10237 }
10238
10239 /**
10240 * Play a sound effect for this view.
10241 *
10242 * <p>The framework will play sound effects for some built in actions, such as
10243 * clicking, but you may wish to play these effects in your widget,
10244 * for instance, for internal navigation.
10245 *
10246 * <p>The sound effect will only be played if sound effects are enabled by the user, and
10247 * {@link #isSoundEffectsEnabled()} is true.
10248 *
10249 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10250 */
10251 public void playSoundEffect(int soundConstant) {
10252 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10253 return;
10254 }
10255 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10256 }
10257
10258 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010259 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010260 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010261 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010262 *
10263 * <p>The framework will provide haptic feedback for some built in actions,
10264 * such as long presses, but you may wish to provide feedback for your
10265 * own widget.
10266 *
10267 * <p>The feedback will only be performed if
10268 * {@link #isHapticFeedbackEnabled()} is true.
10269 *
10270 * @param feedbackConstant One of the constants defined in
10271 * {@link HapticFeedbackConstants}
10272 */
10273 public boolean performHapticFeedback(int feedbackConstant) {
10274 return performHapticFeedback(feedbackConstant, 0);
10275 }
10276
10277 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010278 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010279 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010280 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010281 *
10282 * @param feedbackConstant One of the constants defined in
10283 * {@link HapticFeedbackConstants}
10284 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10285 */
10286 public boolean performHapticFeedback(int feedbackConstant, int flags) {
10287 if (mAttachInfo == null) {
10288 return false;
10289 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010290 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010291 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010292 && !isHapticFeedbackEnabled()) {
10293 return false;
10294 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010295 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10296 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010297 }
10298
10299 /**
Christopher Tate2c095f32010-10-04 14:13:40 -070010300 * !!! TODO: real docs
10301 *
10302 * The base class implementation makes the thumbnail the same size and appearance
10303 * as the view itself, and positions it with its center at the touch point.
10304 */
Christopher Tatea0374192010-10-05 13:06:41 -070010305 public static class DragThumbnailBuilder {
10306 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010307
10308 /**
10309 * Construct a thumbnail builder object for use with the given view.
10310 * @param view
10311 */
10312 public DragThumbnailBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010313 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010314 }
10315
Chris Tate6b391282010-10-14 15:48:59 -070010316 final public View getView() {
10317 return mView.get();
10318 }
10319
Christopher Tate2c095f32010-10-04 14:13:40 -070010320 /**
10321 * Provide the draggable-thumbnail metrics for the operation: the dimensions of
10322 * the thumbnail image itself, and the point within that thumbnail that should
10323 * be centered under the touch location while dragging.
10324 * <p>
10325 * The default implementation sets the dimensions of the thumbnail to be the
10326 * same as the dimensions of the View itself and centers the thumbnail under
10327 * the touch point.
10328 *
10329 * @param thumbnailSize The application should set the {@code x} member of this
10330 * parameter to the desired thumbnail width, and the {@code y} member to
10331 * the desired height.
10332 * @param thumbnailTouchPoint The application should set this point to be the
10333 * location within the thumbnail that should track directly underneath
10334 * the touch point on the screen during a drag.
10335 */
10336 public void onProvideThumbnailMetrics(Point thumbnailSize, Point thumbnailTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070010337 final View view = mView.get();
10338 if (view != null) {
10339 thumbnailSize.set(view.getWidth(), view.getHeight());
10340 thumbnailTouchPoint.set(thumbnailSize.x / 2, thumbnailSize.y / 2);
10341 } else {
10342 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10343 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010344 }
10345
10346 /**
10347 * Draw the thumbnail image for the upcoming drag. The thumbnail canvas was
10348 * created with the dimensions supplied by the onProvideThumbnailMetrics()
10349 * callback.
10350 *
10351 * @param canvas
10352 */
10353 public void onDrawThumbnail(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070010354 final View view = mView.get();
10355 if (view != null) {
10356 view.draw(canvas);
10357 } else {
10358 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag thumb but no view");
10359 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010360 }
10361 }
10362
10363 /**
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010364 * Drag and drop. App calls startDrag(), then callbacks to the thumbnail builder's
10365 * onProvideThumbnailMetrics() and onDrawThumbnail() methods happen, then the drag
10366 * operation is handed over to the OS.
Christopher Tatea53146c2010-09-07 11:57:52 -070010367 * !!! TODO: real docs
Christopher Tate407b4e92010-11-30 17:14:08 -080010368 *
10369 * @param data !!! TODO
10370 * @param thumbBuilder !!! TODO
10371 * @param myWindowOnly When {@code true}, indicates that the drag operation should be
10372 * restricted to the calling application. In this case only the calling application
10373 * will see any DragEvents related to this drag operation.
10374 * @param myLocalState An arbitrary object that will be passed as part of every DragEvent
10375 * delivered to the calling application during the course of the current drag operation.
10376 * This object is private to the application that called startDrag(), and is not
10377 * visible to other applications. It provides a lightweight way for the application to
10378 * propagate information from the initiator to the recipient of a drag within its own
10379 * application; for example, to help disambiguate between 'copy' and 'move' semantics.
10380 * @return {@code true} if the drag operation was initiated successfully; {@code false} if
10381 * an error prevented the drag from taking place.
Christopher Tatea53146c2010-09-07 11:57:52 -070010382 */
Christopher Tate2c095f32010-10-04 14:13:40 -070010383 public final boolean startDrag(ClipData data, DragThumbnailBuilder thumbBuilder,
Christopher Tate407b4e92010-11-30 17:14:08 -080010384 boolean myWindowOnly, Object myLocalState) {
Christopher Tate2c095f32010-10-04 14:13:40 -070010385 if (ViewDebug.DEBUG_DRAG) {
10386 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " local=" + myWindowOnly);
Christopher Tatea53146c2010-09-07 11:57:52 -070010387 }
10388 boolean okay = false;
10389
Christopher Tate2c095f32010-10-04 14:13:40 -070010390 Point thumbSize = new Point();
10391 Point thumbTouchPoint = new Point();
10392 thumbBuilder.onProvideThumbnailMetrics(thumbSize, thumbTouchPoint);
10393
10394 if ((thumbSize.x < 0) || (thumbSize.y < 0) ||
10395 (thumbTouchPoint.x < 0) || (thumbTouchPoint.y < 0)) {
10396 throw new IllegalStateException("Drag thumb dimensions must not be negative");
10397 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010398
Chris Tatea32dcf72010-10-14 12:13:50 -070010399 if (ViewDebug.DEBUG_DRAG) {
10400 Log.d(VIEW_LOG_TAG, "drag thumb: width=" + thumbSize.x + " height=" + thumbSize.y
10401 + " thumbX=" + thumbTouchPoint.x + " thumbY=" + thumbTouchPoint.y);
10402 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010403 Surface surface = new Surface();
10404 try {
10405 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Chris Tatea32dcf72010-10-14 12:13:50 -070010406 myWindowOnly, thumbSize.x, thumbSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070010407 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070010408 + " surface=" + surface);
10409 if (token != null) {
10410 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070010411 try {
Chris Tate6b391282010-10-14 15:48:59 -070010412 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate2c095f32010-10-04 14:13:40 -070010413 thumbBuilder.onDrawThumbnail(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070010414 } finally {
10415 surface.unlockCanvasAndPost(canvas);
10416 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010417
Christopher Tate407b4e92010-11-30 17:14:08 -080010418 final ViewRoot root = getViewRoot();
10419
10420 // Cache the local state object for delivery with DragEvents
10421 root.setLocalDragState(myLocalState);
10422
Christopher Tate2c095f32010-10-04 14:13:40 -070010423 // repurpose 'thumbSize' for the last touch point
Christopher Tate407b4e92010-11-30 17:14:08 -080010424 root.getLastTouchPoint(thumbSize);
Christopher Tate2c095f32010-10-04 14:13:40 -070010425
Christopher Tatea53146c2010-09-07 11:57:52 -070010426 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080010427 thumbSize.x, thumbSize.y,
10428 thumbTouchPoint.x, thumbTouchPoint.y, data);
Christopher Tate2c095f32010-10-04 14:13:40 -070010429 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070010430 }
10431 } catch (Exception e) {
10432 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
10433 surface.destroy();
10434 }
10435
10436 return okay;
10437 }
10438
Christopher Tatea53146c2010-09-07 11:57:52 -070010439 /**
10440 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
10441 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
10442 *
10443 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
10444 * being dragged. onDragEvent() should return 'true' if the view can handle
10445 * a drop of that content. A view that returns 'false' here will receive no
10446 * further calls to onDragEvent() about the drag/drop operation.
10447 *
10448 * For DRAG_ENTERED, event.getClipDescription() describes the content being
10449 * dragged. This will be the same content description passed in the
10450 * DRAG_STARTED_EVENT invocation.
10451 *
10452 * For DRAG_EXITED, event.getClipDescription() describes the content being
10453 * dragged. This will be the same content description passed in the
10454 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
10455 * drag-acceptance visual state.
10456 *
10457 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10458 * coordinates of the current drag point. The view must return 'true' if it
10459 * can accept a drop of the current drag content, false otherwise.
10460 *
10461 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10462 * within the view; also, event.getClipData() returns the full data payload
10463 * being dropped. The view should return 'true' if it consumed the dropped
10464 * content, 'false' if it did not.
10465 *
10466 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
10467 * to its normal visual state.
10468 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010469 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070010470 return false;
10471 }
10472
10473 /**
10474 * Views typically don't need to override dispatchDragEvent(); it just calls
Chris Tate32affef2010-10-18 15:29:21 -070010475 * onDragEvent(event) and passes the result up appropriately.
Christopher Tatea53146c2010-09-07 11:57:52 -070010476 */
10477 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070010478 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10479 && mOnDragListener.onDrag(this, event)) {
10480 return true;
10481 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010482 return onDragEvent(event);
10483 }
10484
10485 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070010486 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
10487 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070010488 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070010489 */
10490 public void onCloseSystemDialogs(String reason) {
10491 }
10492
10493 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010494 * Given a Drawable whose bounds have been set to draw into this view,
10495 * update a Region being computed for {@link #gatherTransparentRegion} so
10496 * that any non-transparent parts of the Drawable are removed from the
10497 * given transparent region.
10498 *
10499 * @param dr The Drawable whose transparency is to be applied to the region.
10500 * @param region A Region holding the current transparency information,
10501 * where any parts of the region that are set are considered to be
10502 * transparent. On return, this region will be modified to have the
10503 * transparency information reduced by the corresponding parts of the
10504 * Drawable that are not transparent.
10505 * {@hide}
10506 */
10507 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
10508 if (DBG) {
10509 Log.i("View", "Getting transparent region for: " + this);
10510 }
10511 final Region r = dr.getTransparentRegion();
10512 final Rect db = dr.getBounds();
10513 final AttachInfo attachInfo = mAttachInfo;
10514 if (r != null && attachInfo != null) {
10515 final int w = getRight()-getLeft();
10516 final int h = getBottom()-getTop();
10517 if (db.left > 0) {
10518 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
10519 r.op(0, 0, db.left, h, Region.Op.UNION);
10520 }
10521 if (db.right < w) {
10522 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
10523 r.op(db.right, 0, w, h, Region.Op.UNION);
10524 }
10525 if (db.top > 0) {
10526 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
10527 r.op(0, 0, w, db.top, Region.Op.UNION);
10528 }
10529 if (db.bottom < h) {
10530 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
10531 r.op(0, db.bottom, w, h, Region.Op.UNION);
10532 }
10533 final int[] location = attachInfo.mTransparentLocation;
10534 getLocationInWindow(location);
10535 r.translate(location[0], location[1]);
10536 region.op(r, Region.Op.INTERSECT);
10537 } else {
10538 region.op(db, Region.Op.DIFFERENCE);
10539 }
10540 }
10541
Adam Powelle14579b2009-12-16 18:39:52 -080010542 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010543 mHasPerformedLongPress = false;
10544
10545 if (mPendingCheckForLongPress == null) {
10546 mPendingCheckForLongPress = new CheckForLongPress();
10547 }
10548 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080010549 postDelayed(mPendingCheckForLongPress,
10550 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010551 }
10552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010553 /**
10554 * Inflate a view from an XML resource. This convenience method wraps the {@link
10555 * LayoutInflater} class, which provides a full range of options for view inflation.
10556 *
10557 * @param context The Context object for your activity or application.
10558 * @param resource The resource ID to inflate
10559 * @param root A view group that will be the parent. Used to properly inflate the
10560 * layout_* parameters.
10561 * @see LayoutInflater
10562 */
10563 public static View inflate(Context context, int resource, ViewGroup root) {
10564 LayoutInflater factory = LayoutInflater.from(context);
10565 return factory.inflate(resource, root);
10566 }
Romain Guy33e72ae2010-07-17 12:40:29 -070010567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010568 /**
Adam Powell637d3372010-08-25 14:37:03 -070010569 * Scroll the view with standard behavior for scrolling beyond the normal
10570 * content boundaries. Views that call this method should override
10571 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
10572 * results of an over-scroll operation.
10573 *
10574 * Views can use this method to handle any touch or fling-based scrolling.
10575 *
10576 * @param deltaX Change in X in pixels
10577 * @param deltaY Change in Y in pixels
10578 * @param scrollX Current X scroll value in pixels before applying deltaX
10579 * @param scrollY Current Y scroll value in pixels before applying deltaY
10580 * @param scrollRangeX Maximum content scroll range along the X axis
10581 * @param scrollRangeY Maximum content scroll range along the Y axis
10582 * @param maxOverScrollX Number of pixels to overscroll by in either direction
10583 * along the X axis.
10584 * @param maxOverScrollY Number of pixels to overscroll by in either direction
10585 * along the Y axis.
10586 * @param isTouchEvent true if this scroll operation is the result of a touch event.
10587 * @return true if scrolling was clamped to an over-scroll boundary along either
10588 * axis, false otherwise.
10589 */
10590 protected boolean overScrollBy(int deltaX, int deltaY,
10591 int scrollX, int scrollY,
10592 int scrollRangeX, int scrollRangeY,
10593 int maxOverScrollX, int maxOverScrollY,
10594 boolean isTouchEvent) {
10595 final int overScrollMode = mOverScrollMode;
10596 final boolean canScrollHorizontal =
10597 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
10598 final boolean canScrollVertical =
10599 computeVerticalScrollRange() > computeVerticalScrollExtent();
10600 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
10601 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
10602 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
10603 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
10604
10605 int newScrollX = scrollX + deltaX;
10606 if (!overScrollHorizontal) {
10607 maxOverScrollX = 0;
10608 }
10609
10610 int newScrollY = scrollY + deltaY;
10611 if (!overScrollVertical) {
10612 maxOverScrollY = 0;
10613 }
10614
10615 // Clamp values if at the limits and record
10616 final int left = -maxOverScrollX;
10617 final int right = maxOverScrollX + scrollRangeX;
10618 final int top = -maxOverScrollY;
10619 final int bottom = maxOverScrollY + scrollRangeY;
10620
10621 boolean clampedX = false;
10622 if (newScrollX > right) {
10623 newScrollX = right;
10624 clampedX = true;
10625 } else if (newScrollX < left) {
10626 newScrollX = left;
10627 clampedX = true;
10628 }
10629
10630 boolean clampedY = false;
10631 if (newScrollY > bottom) {
10632 newScrollY = bottom;
10633 clampedY = true;
10634 } else if (newScrollY < top) {
10635 newScrollY = top;
10636 clampedY = true;
10637 }
10638
10639 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
10640
10641 return clampedX || clampedY;
10642 }
10643
10644 /**
10645 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
10646 * respond to the results of an over-scroll operation.
10647 *
10648 * @param scrollX New X scroll value in pixels
10649 * @param scrollY New Y scroll value in pixels
10650 * @param clampedX True if scrollX was clamped to an over-scroll boundary
10651 * @param clampedY True if scrollY was clamped to an over-scroll boundary
10652 */
10653 protected void onOverScrolled(int scrollX, int scrollY,
10654 boolean clampedX, boolean clampedY) {
10655 // Intentionally empty.
10656 }
10657
10658 /**
10659 * Returns the over-scroll mode for this view. The result will be
10660 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10661 * (allow over-scrolling only if the view content is larger than the container),
10662 * or {@link #OVER_SCROLL_NEVER}.
10663 *
10664 * @return This view's over-scroll mode.
10665 */
10666 public int getOverScrollMode() {
10667 return mOverScrollMode;
10668 }
10669
10670 /**
10671 * Set the over-scroll mode for this view. Valid over-scroll modes are
10672 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10673 * (allow over-scrolling only if the view content is larger than the container),
10674 * or {@link #OVER_SCROLL_NEVER}.
10675 *
10676 * Setting the over-scroll mode of a view will have an effect only if the
10677 * view is capable of scrolling.
10678 *
10679 * @param overScrollMode The new over-scroll mode for this view.
10680 */
10681 public void setOverScrollMode(int overScrollMode) {
10682 if (overScrollMode != OVER_SCROLL_ALWAYS &&
10683 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
10684 overScrollMode != OVER_SCROLL_NEVER) {
10685 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
10686 }
10687 mOverScrollMode = overScrollMode;
10688 }
10689
10690 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010691 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
10692 * Each MeasureSpec represents a requirement for either the width or the height.
10693 * A MeasureSpec is comprised of a size and a mode. There are three possible
10694 * modes:
10695 * <dl>
10696 * <dt>UNSPECIFIED</dt>
10697 * <dd>
10698 * The parent has not imposed any constraint on the child. It can be whatever size
10699 * it wants.
10700 * </dd>
10701 *
10702 * <dt>EXACTLY</dt>
10703 * <dd>
10704 * The parent has determined an exact size for the child. The child is going to be
10705 * given those bounds regardless of how big it wants to be.
10706 * </dd>
10707 *
10708 * <dt>AT_MOST</dt>
10709 * <dd>
10710 * The child can be as large as it wants up to the specified size.
10711 * </dd>
10712 * </dl>
10713 *
10714 * MeasureSpecs are implemented as ints to reduce object allocation. This class
10715 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
10716 */
10717 public static class MeasureSpec {
10718 private static final int MODE_SHIFT = 30;
10719 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
10720
10721 /**
10722 * Measure specification mode: The parent has not imposed any constraint
10723 * on the child. It can be whatever size it wants.
10724 */
10725 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
10726
10727 /**
10728 * Measure specification mode: The parent has determined an exact size
10729 * for the child. The child is going to be given those bounds regardless
10730 * of how big it wants to be.
10731 */
10732 public static final int EXACTLY = 1 << MODE_SHIFT;
10733
10734 /**
10735 * Measure specification mode: The child can be as large as it wants up
10736 * to the specified size.
10737 */
10738 public static final int AT_MOST = 2 << MODE_SHIFT;
10739
10740 /**
10741 * Creates a measure specification based on the supplied size and mode.
10742 *
10743 * The mode must always be one of the following:
10744 * <ul>
10745 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
10746 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
10747 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
10748 * </ul>
10749 *
10750 * @param size the size of the measure specification
10751 * @param mode the mode of the measure specification
10752 * @return the measure specification based on size and mode
10753 */
10754 public static int makeMeasureSpec(int size, int mode) {
10755 return size + mode;
10756 }
10757
10758 /**
10759 * Extracts the mode from the supplied measure specification.
10760 *
10761 * @param measureSpec the measure specification to extract the mode from
10762 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
10763 * {@link android.view.View.MeasureSpec#AT_MOST} or
10764 * {@link android.view.View.MeasureSpec#EXACTLY}
10765 */
10766 public static int getMode(int measureSpec) {
10767 return (measureSpec & MODE_MASK);
10768 }
10769
10770 /**
10771 * Extracts the size from the supplied measure specification.
10772 *
10773 * @param measureSpec the measure specification to extract the size from
10774 * @return the size in pixels defined in the supplied measure specification
10775 */
10776 public static int getSize(int measureSpec) {
10777 return (measureSpec & ~MODE_MASK);
10778 }
10779
10780 /**
10781 * Returns a String representation of the specified measure
10782 * specification.
10783 *
10784 * @param measureSpec the measure specification to convert to a String
10785 * @return a String with the following format: "MeasureSpec: MODE SIZE"
10786 */
10787 public static String toString(int measureSpec) {
10788 int mode = getMode(measureSpec);
10789 int size = getSize(measureSpec);
10790
10791 StringBuilder sb = new StringBuilder("MeasureSpec: ");
10792
10793 if (mode == UNSPECIFIED)
10794 sb.append("UNSPECIFIED ");
10795 else if (mode == EXACTLY)
10796 sb.append("EXACTLY ");
10797 else if (mode == AT_MOST)
10798 sb.append("AT_MOST ");
10799 else
10800 sb.append(mode).append(" ");
10801
10802 sb.append(size);
10803 return sb.toString();
10804 }
10805 }
10806
10807 class CheckForLongPress implements Runnable {
10808
10809 private int mOriginalWindowAttachCount;
10810
10811 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070010812 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010813 && mOriginalWindowAttachCount == mWindowAttachCount) {
10814 if (performLongClick()) {
10815 mHasPerformedLongPress = true;
10816 }
10817 }
10818 }
10819
10820 public void rememberWindowAttachCount() {
10821 mOriginalWindowAttachCount = mWindowAttachCount;
10822 }
10823 }
Adam Powelle14579b2009-12-16 18:39:52 -080010824
10825 private final class CheckForTap implements Runnable {
10826 public void run() {
10827 mPrivateFlags &= ~PREPRESSED;
10828 mPrivateFlags |= PRESSED;
10829 refreshDrawableState();
10830 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
10831 postCheckForLongClick(ViewConfiguration.getTapTimeout());
10832 }
10833 }
10834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010835
Adam Powella35d7682010-03-12 14:48:13 -080010836 private final class PerformClick implements Runnable {
10837 public void run() {
10838 performClick();
10839 }
10840 }
10841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010842 /**
10843 * Interface definition for a callback to be invoked when a key event is
10844 * dispatched to this view. The callback will be invoked before the key
10845 * event is given to the view.
10846 */
10847 public interface OnKeyListener {
10848 /**
10849 * Called when a key is dispatched to a view. This allows listeners to
10850 * get a chance to respond before the target view.
10851 *
10852 * @param v The view the key has been dispatched to.
10853 * @param keyCode The code for the physical key that was pressed
10854 * @param event The KeyEvent object containing full information about
10855 * the event.
10856 * @return True if the listener has consumed the event, false otherwise.
10857 */
10858 boolean onKey(View v, int keyCode, KeyEvent event);
10859 }
10860
10861 /**
10862 * Interface definition for a callback to be invoked when a touch event is
10863 * dispatched to this view. The callback will be invoked before the touch
10864 * event is given to the view.
10865 */
10866 public interface OnTouchListener {
10867 /**
10868 * Called when a touch event is dispatched to a view. This allows listeners to
10869 * get a chance to respond before the target view.
10870 *
10871 * @param v The view the touch event has been dispatched to.
10872 * @param event The MotionEvent object containing full information about
10873 * the event.
10874 * @return True if the listener has consumed the event, false otherwise.
10875 */
10876 boolean onTouch(View v, MotionEvent event);
10877 }
10878
10879 /**
10880 * Interface definition for a callback to be invoked when a view has been clicked and held.
10881 */
10882 public interface OnLongClickListener {
10883 /**
10884 * Called when a view has been clicked and held.
10885 *
10886 * @param v The view that was clicked and held.
10887 *
10888 * return True if the callback consumed the long click, false otherwise
10889 */
10890 boolean onLongClick(View v);
10891 }
10892
10893 /**
Chris Tate32affef2010-10-18 15:29:21 -070010894 * Interface definition for a callback to be invoked when a drag is being dispatched
10895 * to this view. The callback will be invoked before the hosting view's own
10896 * onDrag(event) method. If the listener wants to fall back to the hosting view's
10897 * onDrag(event) behavior, it should return 'false' from this callback.
10898 */
10899 public interface OnDragListener {
10900 /**
10901 * Called when a drag event is dispatched to a view. This allows listeners
10902 * to get a chance to override base View behavior.
10903 *
10904 * @param v The view the drag has been dispatched to.
10905 * @param event The DragEvent object containing full information
10906 * about the event.
10907 * @return true if the listener consumed the DragEvent, false in order to fall
10908 * back to the view's default handling.
10909 */
10910 boolean onDrag(View v, DragEvent event);
10911 }
10912
10913 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010914 * Interface definition for a callback to be invoked when the focus state of
10915 * a view changed.
10916 */
10917 public interface OnFocusChangeListener {
10918 /**
10919 * Called when the focus state of a view has changed.
10920 *
10921 * @param v The view whose state has changed.
10922 * @param hasFocus The new focus state of v.
10923 */
10924 void onFocusChange(View v, boolean hasFocus);
10925 }
10926
10927 /**
10928 * Interface definition for a callback to be invoked when a view is clicked.
10929 */
10930 public interface OnClickListener {
10931 /**
10932 * Called when a view has been clicked.
10933 *
10934 * @param v The view that was clicked.
10935 */
10936 void onClick(View v);
10937 }
10938
10939 /**
10940 * Interface definition for a callback to be invoked when the context menu
10941 * for this view is being built.
10942 */
10943 public interface OnCreateContextMenuListener {
10944 /**
10945 * Called when the context menu for this view is being built. It is not
10946 * safe to hold onto the menu after this method returns.
10947 *
10948 * @param menu The context menu that is being built
10949 * @param v The view for which the context menu is being built
10950 * @param menuInfo Extra information about the item for which the
10951 * context menu should be shown. This information will vary
10952 * depending on the class of v.
10953 */
10954 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
10955 }
10956
10957 private final class UnsetPressedState implements Runnable {
10958 public void run() {
10959 setPressed(false);
10960 }
10961 }
10962
10963 /**
10964 * Base class for derived classes that want to save and restore their own
10965 * state in {@link android.view.View#onSaveInstanceState()}.
10966 */
10967 public static class BaseSavedState extends AbsSavedState {
10968 /**
10969 * Constructor used when reading from a parcel. Reads the state of the superclass.
10970 *
10971 * @param source
10972 */
10973 public BaseSavedState(Parcel source) {
10974 super(source);
10975 }
10976
10977 /**
10978 * Constructor called by derived classes when creating their SavedState objects
10979 *
10980 * @param superState The state of the superclass of this view
10981 */
10982 public BaseSavedState(Parcelable superState) {
10983 super(superState);
10984 }
10985
10986 public static final Parcelable.Creator<BaseSavedState> CREATOR =
10987 new Parcelable.Creator<BaseSavedState>() {
10988 public BaseSavedState createFromParcel(Parcel in) {
10989 return new BaseSavedState(in);
10990 }
10991
10992 public BaseSavedState[] newArray(int size) {
10993 return new BaseSavedState[size];
10994 }
10995 };
10996 }
10997
10998 /**
10999 * A set of information given to a view when it is attached to its parent
11000 * window.
11001 */
11002 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011003 interface Callbacks {
11004 void playSoundEffect(int effectId);
11005 boolean performHapticFeedback(int effectId, boolean always);
11006 }
11007
11008 /**
11009 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11010 * to a Handler. This class contains the target (View) to invalidate and
11011 * the coordinates of the dirty rectangle.
11012 *
11013 * For performance purposes, this class also implements a pool of up to
11014 * POOL_LIMIT objects that get reused. This reduces memory allocations
11015 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011016 */
Romain Guyd928d682009-03-31 17:52:16 -070011017 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011018 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070011019 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11020 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070011021 public InvalidateInfo newInstance() {
11022 return new InvalidateInfo();
11023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011024
Romain Guyd928d682009-03-31 17:52:16 -070011025 public void onAcquired(InvalidateInfo element) {
11026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011027
Romain Guyd928d682009-03-31 17:52:16 -070011028 public void onReleased(InvalidateInfo element) {
11029 }
11030 }, POOL_LIMIT)
11031 );
11032
11033 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011034
11035 View target;
11036
11037 int left;
11038 int top;
11039 int right;
11040 int bottom;
11041
Romain Guyd928d682009-03-31 17:52:16 -070011042 public void setNextPoolable(InvalidateInfo element) {
11043 mNext = element;
11044 }
11045
11046 public InvalidateInfo getNextPoolable() {
11047 return mNext;
11048 }
11049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011050 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070011051 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011052 }
11053
11054 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070011055 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011056 }
11057 }
11058
11059 final IWindowSession mSession;
11060
11061 final IWindow mWindow;
11062
11063 final IBinder mWindowToken;
11064
11065 final Callbacks mRootCallbacks;
11066
11067 /**
11068 * The top view of the hierarchy.
11069 */
11070 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070011071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011072 IBinder mPanelParentWindowToken;
11073 Surface mSurface;
11074
Romain Guyb051e892010-09-28 19:09:36 -070011075 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080011076 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070011077 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070011078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011079 /**
Romain Guy8506ab42009-06-11 17:35:47 -070011080 * Scale factor used by the compatibility mode
11081 */
11082 float mApplicationScale;
11083
11084 /**
11085 * Indicates whether the application is in compatibility mode
11086 */
11087 boolean mScalingRequired;
11088
11089 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011090 * Left position of this view's window
11091 */
11092 int mWindowLeft;
11093
11094 /**
11095 * Top position of this view's window
11096 */
11097 int mWindowTop;
11098
11099 /**
Adam Powell26153a32010-11-08 15:22:27 -080011100 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070011101 */
Adam Powell26153a32010-11-08 15:22:27 -080011102 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070011103
11104 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011105 * For windows that are full-screen but using insets to layout inside
11106 * of the screen decorations, these are the current insets for the
11107 * content of the window.
11108 */
11109 final Rect mContentInsets = new Rect();
11110
11111 /**
11112 * For windows that are full-screen but using insets to layout inside
11113 * of the screen decorations, these are the current insets for the
11114 * actual visible parts of the window.
11115 */
11116 final Rect mVisibleInsets = new Rect();
11117
11118 /**
11119 * The internal insets given by this window. This value is
11120 * supplied by the client (through
11121 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11122 * be given to the window manager when changed to be used in laying
11123 * out windows behind it.
11124 */
11125 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11126 = new ViewTreeObserver.InternalInsetsInfo();
11127
11128 /**
11129 * All views in the window's hierarchy that serve as scroll containers,
11130 * used to determine if the window can be resized or must be panned
11131 * to adjust for a soft input area.
11132 */
11133 final ArrayList<View> mScrollContainers = new ArrayList<View>();
11134
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070011135 final KeyEvent.DispatcherState mKeyDispatchState
11136 = new KeyEvent.DispatcherState();
11137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011138 /**
11139 * Indicates whether the view's window currently has the focus.
11140 */
11141 boolean mHasWindowFocus;
11142
11143 /**
11144 * The current visibility of the window.
11145 */
11146 int mWindowVisibility;
11147
11148 /**
11149 * Indicates the time at which drawing started to occur.
11150 */
11151 long mDrawingTime;
11152
11153 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070011154 * Indicates whether or not ignoring the DIRTY_MASK flags.
11155 */
11156 boolean mIgnoreDirtyState;
11157
11158 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011159 * Indicates whether the view's window is currently in touch mode.
11160 */
11161 boolean mInTouchMode;
11162
11163 /**
11164 * Indicates that ViewRoot should trigger a global layout change
11165 * the next time it performs a traversal
11166 */
11167 boolean mRecomputeGlobalAttributes;
11168
11169 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011170 * Set during a traveral if any views want to keep the screen on.
11171 */
11172 boolean mKeepScreenOn;
11173
11174 /**
11175 * Set if the visibility of any views has changed.
11176 */
11177 boolean mViewVisibilityChanged;
11178
11179 /**
11180 * Set to true if a view has been scrolled.
11181 */
11182 boolean mViewScrollChanged;
11183
11184 /**
11185 * Global to the view hierarchy used as a temporary for dealing with
11186 * x/y points in the transparent region computations.
11187 */
11188 final int[] mTransparentLocation = new int[2];
11189
11190 /**
11191 * Global to the view hierarchy used as a temporary for dealing with
11192 * x/y points in the ViewGroup.invalidateChild implementation.
11193 */
11194 final int[] mInvalidateChildLocation = new int[2];
11195
Chet Haasec3aa3612010-06-17 08:50:37 -070011196
11197 /**
11198 * Global to the view hierarchy used as a temporary for dealing with
11199 * x/y location when view is transformed.
11200 */
11201 final float[] mTmpTransformLocation = new float[2];
11202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011203 /**
11204 * The view tree observer used to dispatch global events like
11205 * layout, pre-draw, touch mode change, etc.
11206 */
11207 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11208
11209 /**
11210 * A Canvas used by the view hierarchy to perform bitmap caching.
11211 */
11212 Canvas mCanvas;
11213
11214 /**
11215 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11216 * handler can be used to pump events in the UI events queue.
11217 */
11218 final Handler mHandler;
11219
11220 /**
11221 * Identifier for messages requesting the view to be invalidated.
11222 * Such messages should be sent to {@link #mHandler}.
11223 */
11224 static final int INVALIDATE_MSG = 0x1;
11225
11226 /**
11227 * Identifier for messages requesting the view to invalidate a region.
11228 * Such messages should be sent to {@link #mHandler}.
11229 */
11230 static final int INVALIDATE_RECT_MSG = 0x2;
11231
11232 /**
11233 * Temporary for use in computing invalidate rectangles while
11234 * calling up the hierarchy.
11235 */
11236 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070011237
11238 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070011239 * Temporary for use in computing hit areas with transformed views
11240 */
11241 final RectF mTmpTransformRect = new RectF();
11242
11243 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070011244 * Temporary list for use in collecting focusable descendents of a view.
11245 */
11246 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011248 /**
11249 * Creates a new set of attachment information with the specified
11250 * events handler and thread.
11251 *
11252 * @param handler the events handler the view must use
11253 */
11254 AttachInfo(IWindowSession session, IWindow window,
11255 Handler handler, Callbacks effectPlayer) {
11256 mSession = session;
11257 mWindow = window;
11258 mWindowToken = window.asBinder();
11259 mHandler = handler;
11260 mRootCallbacks = effectPlayer;
11261 }
11262 }
11263
11264 /**
11265 * <p>ScrollabilityCache holds various fields used by a View when scrolling
11266 * is supported. This avoids keeping too many unused fields in most
11267 * instances of View.</p>
11268 */
Mike Cleronf116bf82009-09-27 19:14:12 -070011269 private static class ScrollabilityCache implements Runnable {
11270
11271 /**
11272 * Scrollbars are not visible
11273 */
11274 public static final int OFF = 0;
11275
11276 /**
11277 * Scrollbars are visible
11278 */
11279 public static final int ON = 1;
11280
11281 /**
11282 * Scrollbars are fading away
11283 */
11284 public static final int FADING = 2;
11285
11286 public boolean fadeScrollBars;
11287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011288 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070011289 public int scrollBarDefaultDelayBeforeFade;
11290 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011291
11292 public int scrollBarSize;
11293 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070011294 public float[] interpolatorValues;
11295 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011296
11297 public final Paint paint;
11298 public final Matrix matrix;
11299 public Shader shader;
11300
Mike Cleronf116bf82009-09-27 19:14:12 -070011301 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11302
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011303 private static final float[] OPAQUE = { 255 };
11304 private static final float[] TRANSPARENT = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070011305
11306 /**
11307 * When fading should start. This time moves into the future every time
11308 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11309 */
11310 public long fadeStartTime;
11311
11312
11313 /**
11314 * The current state of the scrollbars: ON, OFF, or FADING
11315 */
11316 public int state = OFF;
11317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011318 private int mLastColor;
11319
Mike Cleronf116bf82009-09-27 19:14:12 -070011320 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011321 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11322 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070011323 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11324 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011325
11326 paint = new Paint();
11327 matrix = new Matrix();
11328 // use use a height of 1, and then wack the matrix each time we
11329 // actually use it.
11330 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011332 paint.setShader(shader);
11333 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070011334 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011335 }
Romain Guy8506ab42009-06-11 17:35:47 -070011336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011337 public void setFadeColor(int color) {
11338 if (color != 0 && color != mLastColor) {
11339 mLastColor = color;
11340 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070011341
Romain Guye55e1a72009-08-27 10:42:26 -070011342 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11343 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011345 paint.setShader(shader);
11346 // Restore the default transfer mode (src_over)
11347 paint.setXfermode(null);
11348 }
11349 }
Mike Cleronf116bf82009-09-27 19:14:12 -070011350
11351 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070011352 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070011353 if (now >= fadeStartTime) {
11354
11355 // the animation fades the scrollbars out by changing
11356 // the opacity (alpha) from fully opaque to fully
11357 // transparent
11358 int nextFrame = (int) now;
11359 int framesCount = 0;
11360
11361 Interpolator interpolator = scrollBarInterpolator;
11362
11363 // Start opaque
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011364 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
Mike Cleronf116bf82009-09-27 19:14:12 -070011365
11366 // End transparent
11367 nextFrame += scrollBarFadeDuration;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011368 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
Mike Cleronf116bf82009-09-27 19:14:12 -070011369
11370 state = FADING;
11371
11372 // Kick off the fade animation
11373 host.invalidate();
11374 }
11375 }
11376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011377 }
11378}