blob: c319ad107257e3f2916c581e9c5be80e02425dde [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080019import com.android.internal.R;
20import com.android.internal.util.Predicate;
21import com.android.internal.view.menu.MenuBuilder;
22
Christopher Tatea53146c2010-09-07 11:57:52 -070023import android.content.ClipData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080025import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.res.Resources;
27import android.content.res.TypedArray;
28import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070029import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070031import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.graphics.LinearGradient;
33import android.graphics.Matrix;
34import android.graphics.Paint;
35import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070036import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.graphics.PorterDuff;
38import android.graphics.PorterDuffXfermode;
39import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070040import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.graphics.Region;
42import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.graphics.drawable.ColorDrawable;
44import android.graphics.drawable.Drawable;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Message;
48import android.os.Parcel;
49import android.os.Parcelable;
50import android.os.RemoteException;
51import android.os.SystemClock;
52import android.os.SystemProperties;
53import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070055import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070056import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070057import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070058import android.util.Pools;
59import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.ContextMenu.ContextMenuInfo;
Gilles Debunnefb817032011-01-13 13:52:49 -080061import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070062import android.view.accessibility.AccessibilityEvent;
63import android.view.accessibility.AccessibilityEventSource;
64import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070066import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070067import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.view.inputmethod.InputConnection;
69import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.widget.ScrollBarDrawable;
71
Christopher Tatea0374192010-10-05 13:06:41 -070072import java.lang.ref.WeakReference;
svetoslavganov75986cf2009-05-14 22:28:01 -070073import java.lang.reflect.InvocationTargetException;
74import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import java.util.ArrayList;
76import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070077import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070078import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
80/**
81 * <p>
82 * This class represents the basic building block for user interface components. A View
83 * occupies a rectangular area on the screen and is responsible for drawing and
84 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070085 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
87 * are invisible containers that hold other Views (or other ViewGroups) and define
88 * their layout properties.
89 * </p>
90 *
91 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070092 * <p>For an introduction to using this class to develop your
93 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070095 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
102 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
103 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
104 * </p>
105 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700106 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 * <a name="Using"></a>
108 * <h3>Using Views</h3>
109 * <p>
110 * All of the views in a window are arranged in a single tree. You can add views
111 * either from code or by specifying a tree of views in one or more XML layout
112 * files. There are many specialized subclasses of views that act as controls or
113 * are capable of displaying text, images, or other content.
114 * </p>
115 * <p>
116 * Once you have created a tree of views, there are typically a few types of
117 * common operations you may wish to perform:
118 * <ul>
119 * <li><strong>Set properties:</strong> for example setting the text of a
120 * {@link android.widget.TextView}. The available properties and the methods
121 * that set them will vary among the different subclasses of views. Note that
122 * properties that are known at build time can be set in the XML layout
123 * files.</li>
124 * <li><strong>Set focus:</strong> The framework will handled moving focus in
125 * response to user input. To force focus to a specific view, call
126 * {@link #requestFocus}.</li>
127 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
128 * that will be notified when something interesting happens to the view. For
129 * example, all views will let you set a listener to be notified when the view
130 * gains or loses focus. You can register such a listener using
131 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
132 * specialized listeners. For example, a Button exposes a listener to notify
133 * clients when the button is clicked.</li>
134 * <li><strong>Set visibility:</strong> You can hide or show views using
135 * {@link #setVisibility}.</li>
136 * </ul>
137 * </p>
138 * <p><em>
139 * Note: The Android framework is responsible for measuring, laying out and
140 * drawing views. You should not call methods that perform these actions on
141 * views yourself unless you are actually implementing a
142 * {@link android.view.ViewGroup}.
143 * </em></p>
144 *
145 * <a name="Lifecycle"></a>
146 * <h3>Implementing a Custom View</h3>
147 *
148 * <p>
149 * To implement a custom view, you will usually begin by providing overrides for
150 * some of the standard methods that the framework calls on all views. You do
151 * not need to override all of these methods. In fact, you can start by just
152 * overriding {@link #onDraw(android.graphics.Canvas)}.
153 * <table border="2" width="85%" align="center" cellpadding="5">
154 * <thead>
155 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
156 * </thead>
157 *
158 * <tbody>
159 * <tr>
160 * <td rowspan="2">Creation</td>
161 * <td>Constructors</td>
162 * <td>There is a form of the constructor that are called when the view
163 * is created from code and a form that is called when the view is
164 * inflated from a layout file. The second form should parse and apply
165 * any attributes defined in the layout file.
166 * </td>
167 * </tr>
168 * <tr>
169 * <td><code>{@link #onFinishInflate()}</code></td>
170 * <td>Called after a view and all of its children has been inflated
171 * from XML.</td>
172 * </tr>
173 *
174 * <tr>
175 * <td rowspan="3">Layout</td>
176 * <td><code>{@link #onMeasure}</code></td>
177 * <td>Called to determine the size requirements for this view and all
178 * of its children.
179 * </td>
180 * </tr>
181 * <tr>
182 * <td><code>{@link #onLayout}</code></td>
183 * <td>Called when this view should assign a size and position to all
184 * of its children.
185 * </td>
186 * </tr>
187 * <tr>
188 * <td><code>{@link #onSizeChanged}</code></td>
189 * <td>Called when the size of this view has changed.
190 * </td>
191 * </tr>
192 *
193 * <tr>
194 * <td>Drawing</td>
195 * <td><code>{@link #onDraw}</code></td>
196 * <td>Called when the view should render its content.
197 * </td>
198 * </tr>
199 *
200 * <tr>
201 * <td rowspan="4">Event processing</td>
202 * <td><code>{@link #onKeyDown}</code></td>
203 * <td>Called when a new key event occurs.
204 * </td>
205 * </tr>
206 * <tr>
207 * <td><code>{@link #onKeyUp}</code></td>
208 * <td>Called when a key up event occurs.
209 * </td>
210 * </tr>
211 * <tr>
212 * <td><code>{@link #onTrackballEvent}</code></td>
213 * <td>Called when a trackball motion event occurs.
214 * </td>
215 * </tr>
216 * <tr>
217 * <td><code>{@link #onTouchEvent}</code></td>
218 * <td>Called when a touch screen motion event occurs.
219 * </td>
220 * </tr>
221 *
222 * <tr>
223 * <td rowspan="2">Focus</td>
224 * <td><code>{@link #onFocusChanged}</code></td>
225 * <td>Called when the view gains or loses focus.
226 * </td>
227 * </tr>
228 *
229 * <tr>
230 * <td><code>{@link #onWindowFocusChanged}</code></td>
231 * <td>Called when the window containing the view gains or loses focus.
232 * </td>
233 * </tr>
234 *
235 * <tr>
236 * <td rowspan="3">Attaching</td>
237 * <td><code>{@link #onAttachedToWindow()}</code></td>
238 * <td>Called when the view is attached to a window.
239 * </td>
240 * </tr>
241 *
242 * <tr>
243 * <td><code>{@link #onDetachedFromWindow}</code></td>
244 * <td>Called when the view is detached from its window.
245 * </td>
246 * </tr>
247 *
248 * <tr>
249 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
250 * <td>Called when the visibility of the window containing the view
251 * has changed.
252 * </td>
253 * </tr>
254 * </tbody>
255 *
256 * </table>
257 * </p>
258 *
259 * <a name="IDs"></a>
260 * <h3>IDs</h3>
261 * Views may have an integer id associated with them. These ids are typically
262 * assigned in the layout XML files, and are used to find specific views within
263 * the view tree. A common pattern is to:
264 * <ul>
265 * <li>Define a Button in the layout file and assign it a unique ID.
266 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700267 * &lt;Button
268 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 * android:layout_width="wrap_content"
270 * android:layout_height="wrap_content"
271 * android:text="@string/my_button_text"/&gt;
272 * </pre></li>
273 * <li>From the onCreate method of an Activity, find the Button
274 * <pre class="prettyprint">
275 * Button myButton = (Button) findViewById(R.id.my_button);
276 * </pre></li>
277 * </ul>
278 * <p>
279 * View IDs need not be unique throughout the tree, but it is good practice to
280 * ensure that they are at least unique within the part of the tree you are
281 * searching.
282 * </p>
283 *
284 * <a name="Position"></a>
285 * <h3>Position</h3>
286 * <p>
287 * The geometry of a view is that of a rectangle. A view has a location,
288 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
289 * two dimensions, expressed as a width and a height. The unit for location
290 * and dimensions is the pixel.
291 * </p>
292 *
293 * <p>
294 * It is possible to retrieve the location of a view by invoking the methods
295 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
296 * coordinate of the rectangle representing the view. The latter returns the
297 * top, or Y, coordinate of the rectangle representing the view. These methods
298 * both return the location of the view relative to its parent. For instance,
299 * when getLeft() returns 20, that means the view is located 20 pixels to the
300 * right of the left edge of its direct parent.
301 * </p>
302 *
303 * <p>
304 * In addition, several convenience methods are offered to avoid unnecessary
305 * computations, namely {@link #getRight()} and {@link #getBottom()}.
306 * These methods return the coordinates of the right and bottom edges of the
307 * rectangle representing the view. For instance, calling {@link #getRight()}
308 * is similar to the following computation: <code>getLeft() + getWidth()</code>
309 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
310 * </p>
311 *
312 * <a name="SizePaddingMargins"></a>
313 * <h3>Size, padding and margins</h3>
314 * <p>
315 * The size of a view is expressed with a width and a height. A view actually
316 * possess two pairs of width and height values.
317 * </p>
318 *
319 * <p>
320 * The first pair is known as <em>measured width</em> and
321 * <em>measured height</em>. These dimensions define how big a view wants to be
322 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
323 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
324 * and {@link #getMeasuredHeight()}.
325 * </p>
326 *
327 * <p>
328 * The second pair is simply known as <em>width</em> and <em>height</em>, or
329 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
330 * dimensions define the actual size of the view on screen, at drawing time and
331 * after layout. These values may, but do not have to, be different from the
332 * measured width and height. The width and height can be obtained by calling
333 * {@link #getWidth()} and {@link #getHeight()}.
334 * </p>
335 *
336 * <p>
337 * To measure its dimensions, a view takes into account its padding. The padding
338 * is expressed in pixels for the left, top, right and bottom parts of the view.
339 * Padding can be used to offset the content of the view by a specific amount of
340 * pixels. For instance, a left padding of 2 will push the view's content by
341 * 2 pixels to the right of the left edge. Padding can be set using the
342 * {@link #setPadding(int, int, int, int)} method and queried by calling
343 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
344 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
345 * </p>
346 *
347 * <p>
348 * Even though a view can define a padding, it does not provide any support for
349 * margins. However, view groups provide such a support. Refer to
350 * {@link android.view.ViewGroup} and
351 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
352 * </p>
353 *
354 * <a name="Layout"></a>
355 * <h3>Layout</h3>
356 * <p>
357 * Layout is a two pass process: a measure pass and a layout pass. The measuring
358 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
359 * of the view tree. Each view pushes dimension specifications down the tree
360 * during the recursion. At the end of the measure pass, every view has stored
361 * its measurements. The second pass happens in
362 * {@link #layout(int,int,int,int)} and is also top-down. During
363 * this pass each parent is responsible for positioning all of its children
364 * using the sizes computed in the measure pass.
365 * </p>
366 *
367 * <p>
368 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
369 * {@link #getMeasuredHeight()} values must be set, along with those for all of
370 * that view's descendants. A view's measured width and measured height values
371 * must respect the constraints imposed by the view's parents. This guarantees
372 * that at the end of the measure pass, all parents accept all of their
373 * children's measurements. A parent view may call measure() more than once on
374 * its children. For example, the parent may measure each child once with
375 * unspecified dimensions to find out how big they want to be, then call
376 * measure() on them again with actual numbers if the sum of all the children's
377 * unconstrained sizes is too big or too small.
378 * </p>
379 *
380 * <p>
381 * The measure pass uses two classes to communicate dimensions. The
382 * {@link MeasureSpec} class is used by views to tell their parents how they
383 * want to be measured and positioned. The base LayoutParams class just
384 * describes how big the view wants to be for both width and height. For each
385 * dimension, it can specify one of:
386 * <ul>
387 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800388 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 * (minus padding)
390 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
391 * enclose its content (plus padding).
392 * </ul>
393 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
394 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
395 * an X and Y value.
396 * </p>
397 *
398 * <p>
399 * MeasureSpecs are used to push requirements down the tree from parent to
400 * child. A MeasureSpec can be in one of three modes:
401 * <ul>
402 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
403 * of a child view. For example, a LinearLayout may call measure() on its child
404 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
405 * tall the child view wants to be given a width of 240 pixels.
406 * <li>EXACTLY: This is used by the parent to impose an exact size on the
407 * child. The child must use this size, and guarantee that all of its
408 * descendants will fit within this size.
409 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
410 * child. The child must gurantee that it and all of its descendants will fit
411 * within this size.
412 * </ul>
413 * </p>
414 *
415 * <p>
416 * To intiate a layout, call {@link #requestLayout}. This method is typically
417 * called by a view on itself when it believes that is can no longer fit within
418 * its current bounds.
419 * </p>
420 *
421 * <a name="Drawing"></a>
422 * <h3>Drawing</h3>
423 * <p>
424 * Drawing is handled by walking the tree and rendering each view that
425 * intersects the the invalid region. Because the tree is traversed in-order,
426 * this means that parents will draw before (i.e., behind) their children, with
427 * siblings drawn in the order they appear in the tree.
428 * If you set a background drawable for a View, then the View will draw it for you
429 * before calling back to its <code>onDraw()</code> method.
430 * </p>
431 *
432 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700433 * Note that the framework will not draw views that are not in the invalid region.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 * </p>
435 *
436 * <p>
437 * To force a view to draw, call {@link #invalidate()}.
438 * </p>
439 *
440 * <a name="EventHandlingThreading"></a>
441 * <h3>Event Handling and Threading</h3>
442 * <p>
443 * The basic cycle of a view is as follows:
444 * <ol>
445 * <li>An event comes in and is dispatched to the appropriate view. The view
446 * handles the event and notifies any listeners.</li>
447 * <li>If in the course of processing the event, the view's bounds may need
448 * to be changed, the view will call {@link #requestLayout()}.</li>
449 * <li>Similarly, if in the course of processing the event the view's appearance
450 * may need to be changed, the view will call {@link #invalidate()}.</li>
451 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
452 * the framework will take care of measuring, laying out, and drawing the tree
453 * as appropriate.</li>
454 * </ol>
455 * </p>
456 *
457 * <p><em>Note: The entire view tree is single threaded. You must always be on
458 * the UI thread when calling any method on any view.</em>
459 * If you are doing work on other threads and want to update the state of a view
460 * from that thread, you should use a {@link Handler}.
461 * </p>
462 *
463 * <a name="FocusHandling"></a>
464 * <h3>Focus Handling</h3>
465 * <p>
466 * The framework will handle routine focus movement in response to user input.
467 * This includes changing the focus as views are removed or hidden, or as new
468 * views become available. Views indicate their willingness to take focus
469 * through the {@link #isFocusable} method. To change whether a view can take
470 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
471 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
472 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
473 * </p>
474 * <p>
475 * Focus movement is based on an algorithm which finds the nearest neighbor in a
476 * given direction. In rare cases, the default algorithm may not match the
477 * intended behavior of the developer. In these situations, you can provide
478 * explicit overrides by using these XML attributes in the layout file:
479 * <pre>
480 * nextFocusDown
481 * nextFocusLeft
482 * nextFocusRight
483 * nextFocusUp
484 * </pre>
485 * </p>
486 *
487 *
488 * <p>
489 * To get a particular view to take focus, call {@link #requestFocus()}.
490 * </p>
491 *
492 * <a name="TouchMode"></a>
493 * <h3>Touch Mode</h3>
494 * <p>
495 * When a user is navigating a user interface via directional keys such as a D-pad, it is
496 * necessary to give focus to actionable items such as buttons so the user can see
497 * what will take input. If the device has touch capabilities, however, and the user
498 * begins interacting with the interface by touching it, it is no longer necessary to
499 * always highlight, or give focus to, a particular view. This motivates a mode
500 * for interaction named 'touch mode'.
501 * </p>
502 * <p>
503 * For a touch capable device, once the user touches the screen, the device
504 * will enter touch mode. From this point onward, only views for which
505 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
506 * Other views that are touchable, like buttons, will not take focus when touched; they will
507 * only fire the on click listeners.
508 * </p>
509 * <p>
510 * Any time a user hits a directional key, such as a D-pad direction, the view device will
511 * exit touch mode, and find a view to take focus, so that the user may resume interacting
512 * with the user interface without touching the screen again.
513 * </p>
514 * <p>
515 * The touch mode state is maintained across {@link android.app.Activity}s. Call
516 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
517 * </p>
518 *
519 * <a name="Scrolling"></a>
520 * <h3>Scrolling</h3>
521 * <p>
522 * The framework provides basic support for views that wish to internally
523 * scroll their content. This includes keeping track of the X and Y scroll
524 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700525 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
526 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 * </p>
528 *
529 * <a name="Tags"></a>
530 * <h3>Tags</h3>
531 * <p>
532 * Unlike IDs, tags are not used to identify views. Tags are essentially an
533 * extra piece of information that can be associated with a view. They are most
534 * often used as a convenience to store data related to views in the views
535 * themselves rather than by putting them in a separate structure.
536 * </p>
537 *
538 * <a name="Animation"></a>
539 * <h3>Animation</h3>
540 * <p>
541 * You can attach an {@link Animation} object to a view using
542 * {@link #setAnimation(Animation)} or
543 * {@link #startAnimation(Animation)}. The animation can alter the scale,
544 * rotation, translation and alpha of a view over time. If the animation is
545 * attached to a view that has children, the animation will affect the entire
546 * subtree rooted by that node. When an animation is started, the framework will
547 * take care of redrawing the appropriate views until the animation completes.
548 * </p>
Romain Guy171c5922011-01-06 10:04:23 -0800549 * <p>
550 * Starting with Android 3.0, the preferred way of animating views is to use the
551 * {@link android.animation} package APIs.
552 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 *
Jeff Brown85a31762010-09-01 17:01:00 -0700554 * <a name="Security"></a>
555 * <h3>Security</h3>
556 * <p>
557 * Sometimes it is essential that an application be able to verify that an action
558 * is being performed with the full knowledge and consent of the user, such as
559 * granting a permission request, making a purchase or clicking on an advertisement.
560 * Unfortunately, a malicious application could try to spoof the user into
561 * performing these actions, unaware, by concealing the intended purpose of the view.
562 * As a remedy, the framework offers a touch filtering mechanism that can be used to
563 * improve the security of views that provide access to sensitive functionality.
564 * </p><p>
565 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
Jeff Brown49ed71d2010-12-06 17:13:33 -0800566 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework
Jeff Brown85a31762010-09-01 17:01:00 -0700567 * will discard touches that are received whenever the view's window is obscured by
568 * another visible window. As a result, the view will not receive touches whenever a
569 * toast, dialog or other window appears above the view's window.
570 * </p><p>
571 * For more fine-grained control over security, consider overriding the
572 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
573 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
574 * </p>
575 *
Romain Guy171c5922011-01-06 10:04:23 -0800576 * @attr ref android.R.styleable#View_alpha
Romain Guyd6a463a2009-05-21 23:10:10 -0700577 * @attr ref android.R.styleable#View_background
578 * @attr ref android.R.styleable#View_clickable
579 * @attr ref android.R.styleable#View_contentDescription
580 * @attr ref android.R.styleable#View_drawingCacheQuality
581 * @attr ref android.R.styleable#View_duplicateParentState
582 * @attr ref android.R.styleable#View_id
583 * @attr ref android.R.styleable#View_fadingEdge
584 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700585 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700587 * @attr ref android.R.styleable#View_isScrollContainer
588 * @attr ref android.R.styleable#View_focusable
589 * @attr ref android.R.styleable#View_focusableInTouchMode
590 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
591 * @attr ref android.R.styleable#View_keepScreenOn
Romain Guy171c5922011-01-06 10:04:23 -0800592 * @attr ref android.R.styleable#View_layerType
Romain Guyd6a463a2009-05-21 23:10:10 -0700593 * @attr ref android.R.styleable#View_longClickable
594 * @attr ref android.R.styleable#View_minHeight
595 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 * @attr ref android.R.styleable#View_nextFocusDown
597 * @attr ref android.R.styleable#View_nextFocusLeft
598 * @attr ref android.R.styleable#View_nextFocusRight
599 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700600 * @attr ref android.R.styleable#View_onClick
601 * @attr ref android.R.styleable#View_padding
602 * @attr ref android.R.styleable#View_paddingBottom
603 * @attr ref android.R.styleable#View_paddingLeft
604 * @attr ref android.R.styleable#View_paddingRight
605 * @attr ref android.R.styleable#View_paddingTop
606 * @attr ref android.R.styleable#View_saveEnabled
Chet Haase73066682010-11-29 15:55:32 -0800607 * @attr ref android.R.styleable#View_rotation
608 * @attr ref android.R.styleable#View_rotationX
609 * @attr ref android.R.styleable#View_rotationY
610 * @attr ref android.R.styleable#View_scaleX
611 * @attr ref android.R.styleable#View_scaleY
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 * @attr ref android.R.styleable#View_scrollX
613 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700614 * @attr ref android.R.styleable#View_scrollbarSize
615 * @attr ref android.R.styleable#View_scrollbarStyle
616 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700617 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
618 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
620 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 * @attr ref android.R.styleable#View_scrollbarThumbVertical
622 * @attr ref android.R.styleable#View_scrollbarTrackVertical
623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
624 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700625 * @attr ref android.R.styleable#View_soundEffectsEnabled
626 * @attr ref android.R.styleable#View_tag
Chet Haase73066682010-11-29 15:55:32 -0800627 * @attr ref android.R.styleable#View_transformPivotX
628 * @attr ref android.R.styleable#View_transformPivotY
629 * @attr ref android.R.styleable#View_translationX
630 * @attr ref android.R.styleable#View_translationY
Romain Guyd6a463a2009-05-21 23:10:10 -0700631 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 *
633 * @see android.view.ViewGroup
634 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700635public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 private static final boolean DBG = false;
637
638 /**
639 * The logging tag used by this class with android.util.Log.
640 */
641 protected static final String VIEW_LOG_TAG = "View";
642
643 /**
644 * Used to mark a View that has no ID.
645 */
646 public static final int NO_ID = -1;
647
648 /**
649 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
650 * calling setFlags.
651 */
652 private static final int NOT_FOCUSABLE = 0x00000000;
653
654 /**
655 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
656 * setFlags.
657 */
658 private static final int FOCUSABLE = 0x00000001;
659
660 /**
661 * Mask for use with setFlags indicating bits used for focus.
662 */
663 private static final int FOCUSABLE_MASK = 0x00000001;
664
665 /**
666 * This view will adjust its padding to fit sytem windows (e.g. status bar)
667 */
668 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
669
670 /**
671 * This view is visible. Use with {@link #setVisibility}.
672 */
673 public static final int VISIBLE = 0x00000000;
674
675 /**
676 * This view is invisible, but it still takes up space for layout purposes.
677 * Use with {@link #setVisibility}.
678 */
679 public static final int INVISIBLE = 0x00000004;
680
681 /**
682 * This view is invisible, and it doesn't take any space for layout
683 * purposes. Use with {@link #setVisibility}.
684 */
685 public static final int GONE = 0x00000008;
686
687 /**
688 * Mask for use with setFlags indicating bits used for visibility.
689 * {@hide}
690 */
691 static final int VISIBILITY_MASK = 0x0000000C;
692
693 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
694
695 /**
696 * This view is enabled. Intrepretation varies by subclass.
697 * Use with ENABLED_MASK when calling setFlags.
698 * {@hide}
699 */
700 static final int ENABLED = 0x00000000;
701
702 /**
703 * This view is disabled. Intrepretation varies by subclass.
704 * Use with ENABLED_MASK when calling setFlags.
705 * {@hide}
706 */
707 static final int DISABLED = 0x00000020;
708
709 /**
710 * Mask for use with setFlags indicating bits used for indicating whether
711 * this view is enabled
712 * {@hide}
713 */
714 static final int ENABLED_MASK = 0x00000020;
715
716 /**
717 * This view won't draw. {@link #onDraw} won't be called and further
718 * optimizations
719 * will be performed. It is okay to have this flag set and a background.
720 * Use with DRAW_MASK when calling setFlags.
721 * {@hide}
722 */
723 static final int WILL_NOT_DRAW = 0x00000080;
724
725 /**
726 * Mask for use with setFlags indicating bits used for indicating whether
727 * this view is will draw
728 * {@hide}
729 */
730 static final int DRAW_MASK = 0x00000080;
731
732 /**
733 * <p>This view doesn't show scrollbars.</p>
734 * {@hide}
735 */
736 static final int SCROLLBARS_NONE = 0x00000000;
737
738 /**
739 * <p>This view shows horizontal scrollbars.</p>
740 * {@hide}
741 */
742 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
743
744 /**
745 * <p>This view shows vertical scrollbars.</p>
746 * {@hide}
747 */
748 static final int SCROLLBARS_VERTICAL = 0x00000200;
749
750 /**
751 * <p>Mask for use with setFlags indicating bits used for indicating which
752 * scrollbars are enabled.</p>
753 * {@hide}
754 */
755 static final int SCROLLBARS_MASK = 0x00000300;
756
Jeff Brown85a31762010-09-01 17:01:00 -0700757 /**
758 * Indicates that the view should filter touches when its window is obscured.
759 * Refer to the class comments for more information about this security feature.
760 * {@hide}
761 */
762 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
763
764 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765
766 /**
767 * <p>This view doesn't show fading edges.</p>
768 * {@hide}
769 */
770 static final int FADING_EDGE_NONE = 0x00000000;
771
772 /**
773 * <p>This view shows horizontal fading edges.</p>
774 * {@hide}
775 */
776 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
777
778 /**
779 * <p>This view shows vertical fading edges.</p>
780 * {@hide}
781 */
782 static final int FADING_EDGE_VERTICAL = 0x00002000;
783
784 /**
785 * <p>Mask for use with setFlags indicating bits used for indicating which
786 * fading edges are enabled.</p>
787 * {@hide}
788 */
789 static final int FADING_EDGE_MASK = 0x00003000;
790
791 /**
792 * <p>Indicates this view can be clicked. When clickable, a View reacts
793 * to clicks by notifying the OnClickListener.<p>
794 * {@hide}
795 */
796 static final int CLICKABLE = 0x00004000;
797
798 /**
799 * <p>Indicates this view is caching its drawing into a bitmap.</p>
800 * {@hide}
801 */
802 static final int DRAWING_CACHE_ENABLED = 0x00008000;
803
804 /**
805 * <p>Indicates that no icicle should be saved for this view.<p>
806 * {@hide}
807 */
808 static final int SAVE_DISABLED = 0x000010000;
809
810 /**
811 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
812 * property.</p>
813 * {@hide}
814 */
815 static final int SAVE_DISABLED_MASK = 0x000010000;
816
817 /**
818 * <p>Indicates that no drawing cache should ever be created for this view.<p>
819 * {@hide}
820 */
821 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
822
823 /**
824 * <p>Indicates this view can take / keep focus when int touch mode.</p>
825 * {@hide}
826 */
827 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
828
829 /**
830 * <p>Enables low quality mode for the drawing cache.</p>
831 */
832 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
833
834 /**
835 * <p>Enables high quality mode for the drawing cache.</p>
836 */
837 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
838
839 /**
840 * <p>Enables automatic quality mode for the drawing cache.</p>
841 */
842 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
843
844 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
845 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
846 };
847
848 /**
849 * <p>Mask for use with setFlags indicating bits used for the cache
850 * quality property.</p>
851 * {@hide}
852 */
853 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
854
855 /**
856 * <p>
857 * Indicates this view can be long clicked. When long clickable, a View
858 * reacts to long clicks by notifying the OnLongClickListener or showing a
859 * context menu.
860 * </p>
861 * {@hide}
862 */
863 static final int LONG_CLICKABLE = 0x00200000;
864
865 /**
866 * <p>Indicates that this view gets its drawable states from its direct parent
867 * and ignores its original internal states.</p>
868 *
869 * @hide
870 */
871 static final int DUPLICATE_PARENT_STATE = 0x00400000;
872
873 /**
874 * The scrollbar style to display the scrollbars inside the content area,
875 * without increasing the padding. The scrollbars will be overlaid with
876 * translucency on the view's content.
877 */
878 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
879
880 /**
881 * The scrollbar style to display the scrollbars inside the padded area,
882 * increasing the padding of the view. The scrollbars will not overlap the
883 * content area of the view.
884 */
885 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
886
887 /**
888 * The scrollbar style to display the scrollbars at the edge of the view,
889 * without increasing the padding. The scrollbars will be overlaid with
890 * translucency.
891 */
892 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
893
894 /**
895 * The scrollbar style to display the scrollbars at the edge of the view,
896 * increasing the padding of the view. The scrollbars will only overlap the
897 * background, if any.
898 */
899 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
900
901 /**
902 * Mask to check if the scrollbar style is overlay or inset.
903 * {@hide}
904 */
905 static final int SCROLLBARS_INSET_MASK = 0x01000000;
906
907 /**
908 * Mask to check if the scrollbar style is inside or outside.
909 * {@hide}
910 */
911 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
912
913 /**
914 * Mask for scrollbar style.
915 * {@hide}
916 */
917 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
918
919 /**
920 * View flag indicating that the screen should remain on while the
921 * window containing this view is visible to the user. This effectively
922 * takes care of automatically setting the WindowManager's
923 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
924 */
925 public static final int KEEP_SCREEN_ON = 0x04000000;
926
927 /**
928 * View flag indicating whether this view should have sound effects enabled
929 * for events such as clicking and touching.
930 */
931 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
932
933 /**
934 * View flag indicating whether this view should have haptic feedback
935 * enabled for events such as long presses.
936 */
937 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
938
939 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700940 * <p>Indicates that the view hierarchy should stop saving state when
941 * it reaches this view. If state saving is initiated immediately at
942 * the view, it will be allowed.
943 * {@hide}
944 */
945 static final int PARENT_SAVE_DISABLED = 0x20000000;
946
947 /**
948 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
949 * {@hide}
950 */
951 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
952
953 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700954 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
955 * should add all focusable Views regardless if they are focusable in touch mode.
956 */
957 public static final int FOCUSABLES_ALL = 0x00000000;
958
959 /**
960 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
961 * should add only Views focusable in touch mode.
962 */
963 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
964
965 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 * Use with {@link #focusSearch}. Move focus to the previous selectable
967 * item.
968 */
969 public static final int FOCUS_BACKWARD = 0x00000001;
970
971 /**
972 * Use with {@link #focusSearch}. Move focus to the next selectable
973 * item.
974 */
975 public static final int FOCUS_FORWARD = 0x00000002;
976
977 /**
978 * Use with {@link #focusSearch}. Move focus to the left.
979 */
980 public static final int FOCUS_LEFT = 0x00000011;
981
982 /**
983 * Use with {@link #focusSearch}. Move focus up.
984 */
985 public static final int FOCUS_UP = 0x00000021;
986
987 /**
988 * Use with {@link #focusSearch}. Move focus to the right.
989 */
990 public static final int FOCUS_RIGHT = 0x00000042;
991
992 /**
993 * Use with {@link #focusSearch}. Move focus down.
994 */
995 public static final int FOCUS_DOWN = 0x00000082;
996
997 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -0800998 * Bits of {@link #getMeasuredWidthAndState()} and
999 * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1000 */
1001 public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1002
1003 /**
1004 * Bits of {@link #getMeasuredWidthAndState()} and
1005 * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1006 */
1007 public static final int MEASURED_STATE_MASK = 0xff000000;
1008
1009 /**
1010 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1011 * for functions that combine both width and height into a single int,
1012 * such as {@link #getMeasuredState()} and the childState argument of
1013 * {@link #resolveSizeAndState(int, int, int)}.
1014 */
1015 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1016
1017 /**
1018 * Bit of {@link #getMeasuredWidthAndState()} and
1019 * {@link #getMeasuredWidthAndState()} that indicates the measured size
1020 * is smaller that the space the view would like to have.
1021 */
1022 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1023
1024 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 * Base View state sets
1026 */
1027 // Singles
1028 /**
1029 * Indicates the view has no states set. States are used with
1030 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1031 * view depending on its state.
1032 *
1033 * @see android.graphics.drawable.Drawable
1034 * @see #getDrawableState()
1035 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001036 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 /**
1038 * Indicates the view is enabled. States are used with
1039 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1040 * view depending on its state.
1041 *
1042 * @see android.graphics.drawable.Drawable
1043 * @see #getDrawableState()
1044 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001045 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 /**
1047 * Indicates the view is focused. States are used with
1048 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1049 * view depending on its state.
1050 *
1051 * @see android.graphics.drawable.Drawable
1052 * @see #getDrawableState()
1053 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001054 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 /**
1056 * Indicates the view is selected. States are used with
1057 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1058 * view depending on its state.
1059 *
1060 * @see android.graphics.drawable.Drawable
1061 * @see #getDrawableState()
1062 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001063 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 /**
1065 * Indicates the view is pressed. States are used with
1066 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1067 * view depending on its state.
1068 *
1069 * @see android.graphics.drawable.Drawable
1070 * @see #getDrawableState()
1071 * @hide
1072 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001073 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 /**
1075 * Indicates the view's window has focus. States are used with
1076 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1077 * view depending on its state.
1078 *
1079 * @see android.graphics.drawable.Drawable
1080 * @see #getDrawableState()
1081 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001082 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 // Doubles
1084 /**
1085 * Indicates the view is enabled and has the focus.
1086 *
1087 * @see #ENABLED_STATE_SET
1088 * @see #FOCUSED_STATE_SET
1089 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001090 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 /**
1092 * Indicates the view is enabled and selected.
1093 *
1094 * @see #ENABLED_STATE_SET
1095 * @see #SELECTED_STATE_SET
1096 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001097 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 /**
1099 * Indicates the view is enabled and that its window has focus.
1100 *
1101 * @see #ENABLED_STATE_SET
1102 * @see #WINDOW_FOCUSED_STATE_SET
1103 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001104 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 /**
1106 * Indicates the view is focused and selected.
1107 *
1108 * @see #FOCUSED_STATE_SET
1109 * @see #SELECTED_STATE_SET
1110 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001111 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 /**
1113 * Indicates the view has the focus and that its window has the focus.
1114 *
1115 * @see #FOCUSED_STATE_SET
1116 * @see #WINDOW_FOCUSED_STATE_SET
1117 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001118 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 /**
1120 * Indicates the view is selected and that its window has the focus.
1121 *
1122 * @see #SELECTED_STATE_SET
1123 * @see #WINDOW_FOCUSED_STATE_SET
1124 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001125 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 // Triples
1127 /**
1128 * Indicates the view is enabled, focused and selected.
1129 *
1130 * @see #ENABLED_STATE_SET
1131 * @see #FOCUSED_STATE_SET
1132 * @see #SELECTED_STATE_SET
1133 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001134 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 /**
1136 * Indicates the view is enabled, focused and its window has the focus.
1137 *
1138 * @see #ENABLED_STATE_SET
1139 * @see #FOCUSED_STATE_SET
1140 * @see #WINDOW_FOCUSED_STATE_SET
1141 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001142 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 /**
1144 * Indicates the view is enabled, selected and its window has the focus.
1145 *
1146 * @see #ENABLED_STATE_SET
1147 * @see #SELECTED_STATE_SET
1148 * @see #WINDOW_FOCUSED_STATE_SET
1149 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001150 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 /**
1152 * Indicates the view is focused, selected and its window has the focus.
1153 *
1154 * @see #FOCUSED_STATE_SET
1155 * @see #SELECTED_STATE_SET
1156 * @see #WINDOW_FOCUSED_STATE_SET
1157 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001158 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 /**
1160 * Indicates the view is enabled, focused, selected and its window
1161 * has the focus.
1162 *
1163 * @see #ENABLED_STATE_SET
1164 * @see #FOCUSED_STATE_SET
1165 * @see #SELECTED_STATE_SET
1166 * @see #WINDOW_FOCUSED_STATE_SET
1167 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001168 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 /**
1170 * Indicates the view is pressed and its window has the focus.
1171 *
1172 * @see #PRESSED_STATE_SET
1173 * @see #WINDOW_FOCUSED_STATE_SET
1174 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001175 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 /**
1177 * Indicates the view is pressed and selected.
1178 *
1179 * @see #PRESSED_STATE_SET
1180 * @see #SELECTED_STATE_SET
1181 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001182 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 /**
1184 * Indicates the view is pressed, selected and its window has the focus.
1185 *
1186 * @see #PRESSED_STATE_SET
1187 * @see #SELECTED_STATE_SET
1188 * @see #WINDOW_FOCUSED_STATE_SET
1189 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001190 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 /**
1192 * Indicates the view is pressed and focused.
1193 *
1194 * @see #PRESSED_STATE_SET
1195 * @see #FOCUSED_STATE_SET
1196 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001197 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 /**
1199 * Indicates the view is pressed, focused and its window has the focus.
1200 *
1201 * @see #PRESSED_STATE_SET
1202 * @see #FOCUSED_STATE_SET
1203 * @see #WINDOW_FOCUSED_STATE_SET
1204 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001205 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 /**
1207 * Indicates the view is pressed, focused and selected.
1208 *
1209 * @see #PRESSED_STATE_SET
1210 * @see #SELECTED_STATE_SET
1211 * @see #FOCUSED_STATE_SET
1212 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001213 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 /**
1215 * Indicates the view is pressed, focused, selected and its window has the focus.
1216 *
1217 * @see #PRESSED_STATE_SET
1218 * @see #FOCUSED_STATE_SET
1219 * @see #SELECTED_STATE_SET
1220 * @see #WINDOW_FOCUSED_STATE_SET
1221 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001222 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 /**
1224 * Indicates the view is pressed and enabled.
1225 *
1226 * @see #PRESSED_STATE_SET
1227 * @see #ENABLED_STATE_SET
1228 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001229 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 /**
1231 * Indicates the view is pressed, enabled and its window has the focus.
1232 *
1233 * @see #PRESSED_STATE_SET
1234 * @see #ENABLED_STATE_SET
1235 * @see #WINDOW_FOCUSED_STATE_SET
1236 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001237 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 /**
1239 * Indicates the view is pressed, enabled and selected.
1240 *
1241 * @see #PRESSED_STATE_SET
1242 * @see #ENABLED_STATE_SET
1243 * @see #SELECTED_STATE_SET
1244 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001245 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 /**
1247 * Indicates the view is pressed, enabled, selected and its window has the
1248 * focus.
1249 *
1250 * @see #PRESSED_STATE_SET
1251 * @see #ENABLED_STATE_SET
1252 * @see #SELECTED_STATE_SET
1253 * @see #WINDOW_FOCUSED_STATE_SET
1254 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001255 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 /**
1257 * Indicates the view is pressed, enabled and focused.
1258 *
1259 * @see #PRESSED_STATE_SET
1260 * @see #ENABLED_STATE_SET
1261 * @see #FOCUSED_STATE_SET
1262 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001263 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 /**
1265 * Indicates the view is pressed, enabled, focused and its window has the
1266 * focus.
1267 *
1268 * @see #PRESSED_STATE_SET
1269 * @see #ENABLED_STATE_SET
1270 * @see #FOCUSED_STATE_SET
1271 * @see #WINDOW_FOCUSED_STATE_SET
1272 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001273 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 /**
1275 * Indicates the view is pressed, enabled, focused and selected.
1276 *
1277 * @see #PRESSED_STATE_SET
1278 * @see #ENABLED_STATE_SET
1279 * @see #SELECTED_STATE_SET
1280 * @see #FOCUSED_STATE_SET
1281 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001282 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 /**
1284 * Indicates the view is pressed, enabled, focused, selected and its window
1285 * has the focus.
1286 *
1287 * @see #PRESSED_STATE_SET
1288 * @see #ENABLED_STATE_SET
1289 * @see #SELECTED_STATE_SET
1290 * @see #FOCUSED_STATE_SET
1291 * @see #WINDOW_FOCUSED_STATE_SET
1292 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001293 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294
1295 /**
1296 * The order here is very important to {@link #getDrawableState()}
1297 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001298 private static final int[][] VIEW_STATE_SETS;
1299
Romain Guyb051e892010-09-28 19:09:36 -07001300 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1301 static final int VIEW_STATE_SELECTED = 1 << 1;
1302 static final int VIEW_STATE_FOCUSED = 1 << 2;
1303 static final int VIEW_STATE_ENABLED = 1 << 3;
1304 static final int VIEW_STATE_PRESSED = 1 << 4;
1305 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001306 static final int VIEW_STATE_ACCELERATED = 1 << 6;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001307
1308 static final int[] VIEW_STATE_IDS = new int[] {
1309 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1310 R.attr.state_selected, VIEW_STATE_SELECTED,
1311 R.attr.state_focused, VIEW_STATE_FOCUSED,
1312 R.attr.state_enabled, VIEW_STATE_ENABLED,
1313 R.attr.state_pressed, VIEW_STATE_PRESSED,
1314 R.attr.state_activated, VIEW_STATE_ACTIVATED,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001315 R.attr.state_accelerated, VIEW_STATE_ACCELERATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 };
1317
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001318 static {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001319 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1320 throw new IllegalStateException(
1321 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1322 }
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001323 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001324 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001325 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001326 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001327 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001328 orderedIds[i * 2] = viewState;
1329 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001330 }
1331 }
1332 }
Romain Guyb051e892010-09-28 19:09:36 -07001333 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1334 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1335 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001336 int numBits = Integer.bitCount(i);
1337 int[] set = new int[numBits];
1338 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001339 for (int j = 0; j < orderedIds.length; j += 2) {
1340 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001341 set[pos++] = orderedIds[j];
1342 }
1343 }
1344 VIEW_STATE_SETS[i] = set;
1345 }
1346
1347 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1348 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1349 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1350 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1351 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1352 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1353 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1354 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1355 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1356 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1357 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1358 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1359 | VIEW_STATE_FOCUSED];
1360 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1361 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1362 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1363 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1364 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1365 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1366 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1367 | VIEW_STATE_ENABLED];
1368 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1369 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1370 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1371 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1372 | VIEW_STATE_ENABLED];
1373 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1374 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1375 | VIEW_STATE_ENABLED];
1376 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1377 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1378 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1379
1380 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1381 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1382 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1383 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1384 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1385 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1386 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1387 | VIEW_STATE_PRESSED];
1388 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1389 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1390 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1391 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1392 | VIEW_STATE_PRESSED];
1393 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1394 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1395 | VIEW_STATE_PRESSED];
1396 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1397 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1398 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1399 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1400 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1401 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1402 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1403 | VIEW_STATE_PRESSED];
1404 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1405 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1406 | VIEW_STATE_PRESSED];
1407 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1408 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1409 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1410 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1411 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1412 | VIEW_STATE_PRESSED];
1413 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1414 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1415 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1416 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1418 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1419 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1420 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1421 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1422 | VIEW_STATE_PRESSED];
1423 }
1424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 /**
1426 * Used by views that contain lists of items. This state indicates that
1427 * the view is showing the last item.
1428 * @hide
1429 */
1430 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1431 /**
1432 * Used by views that contain lists of items. This state indicates that
1433 * the view is showing the first item.
1434 * @hide
1435 */
1436 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1437 /**
1438 * Used by views that contain lists of items. This state indicates that
1439 * the view is showing the middle item.
1440 * @hide
1441 */
1442 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1443 /**
1444 * Used by views that contain lists of items. This state indicates that
1445 * the view is showing only one item.
1446 * @hide
1447 */
1448 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1449 /**
1450 * Used by views that contain lists of items. This state indicates that
1451 * the view is pressed and showing the last item.
1452 * @hide
1453 */
1454 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1455 /**
1456 * Used by views that contain lists of items. This state indicates that
1457 * the view is pressed and showing the first item.
1458 * @hide
1459 */
1460 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1461 /**
1462 * Used by views that contain lists of items. This state indicates that
1463 * the view is pressed and showing the middle item.
1464 * @hide
1465 */
1466 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1467 /**
1468 * Used by views that contain lists of items. This state indicates that
1469 * the view is pressed and showing only one item.
1470 * @hide
1471 */
1472 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1473
1474 /**
1475 * Temporary Rect currently for use in setBackground(). This will probably
1476 * be extended in the future to hold our own class with more than just
1477 * a Rect. :)
1478 */
1479 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001480
1481 /**
1482 * Map used to store views' tags.
1483 */
1484 private static WeakHashMap<View, SparseArray<Object>> sTags;
1485
1486 /**
1487 * Lock used to access sTags.
1488 */
1489 private static final Object sTagsLock = new Object();
1490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 /**
1492 * The animation currently associated with this view.
1493 * @hide
1494 */
1495 protected Animation mCurrentAnimation = null;
1496
1497 /**
1498 * Width as measured during measure pass.
1499 * {@hide}
1500 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001501 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001502 /*package*/ int mMeasuredWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503
1504 /**
1505 * Height as measured during measure pass.
1506 * {@hide}
1507 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001508 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001509 /*package*/ int mMeasuredHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510
1511 /**
1512 * The view's identifier.
1513 * {@hide}
1514 *
1515 * @see #setId(int)
1516 * @see #getId()
1517 */
1518 @ViewDebug.ExportedProperty(resolveId = true)
1519 int mID = NO_ID;
1520
1521 /**
1522 * The view's tag.
1523 * {@hide}
1524 *
1525 * @see #setTag(Object)
1526 * @see #getTag()
1527 */
1528 protected Object mTag;
1529
1530 // for mPrivateFlags:
1531 /** {@hide} */
1532 static final int WANTS_FOCUS = 0x00000001;
1533 /** {@hide} */
1534 static final int FOCUSED = 0x00000002;
1535 /** {@hide} */
1536 static final int SELECTED = 0x00000004;
1537 /** {@hide} */
1538 static final int IS_ROOT_NAMESPACE = 0x00000008;
1539 /** {@hide} */
1540 static final int HAS_BOUNDS = 0x00000010;
1541 /** {@hide} */
1542 static final int DRAWN = 0x00000020;
1543 /**
1544 * When this flag is set, this view is running an animation on behalf of its
1545 * children and should therefore not cancel invalidate requests, even if they
1546 * lie outside of this view's bounds.
1547 *
1548 * {@hide}
1549 */
1550 static final int DRAW_ANIMATION = 0x00000040;
1551 /** {@hide} */
1552 static final int SKIP_DRAW = 0x00000080;
1553 /** {@hide} */
1554 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1555 /** {@hide} */
1556 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1557 /** {@hide} */
1558 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1559 /** {@hide} */
1560 static final int MEASURED_DIMENSION_SET = 0x00000800;
1561 /** {@hide} */
1562 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001563 /** {@hide} */
1564 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565
1566 private static final int PRESSED = 0x00004000;
1567
1568 /** {@hide} */
1569 static final int DRAWING_CACHE_VALID = 0x00008000;
1570 /**
1571 * Flag used to indicate that this view should be drawn once more (and only once
1572 * more) after its animation has completed.
1573 * {@hide}
1574 */
1575 static final int ANIMATION_STARTED = 0x00010000;
1576
1577 private static final int SAVE_STATE_CALLED = 0x00020000;
1578
1579 /**
1580 * Indicates that the View returned true when onSetAlpha() was called and that
1581 * the alpha must be restored.
1582 * {@hide}
1583 */
1584 static final int ALPHA_SET = 0x00040000;
1585
1586 /**
1587 * Set by {@link #setScrollContainer(boolean)}.
1588 */
1589 static final int SCROLL_CONTAINER = 0x00080000;
1590
1591 /**
1592 * Set by {@link #setScrollContainer(boolean)}.
1593 */
1594 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1595
1596 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001597 * View flag indicating whether this view was invalidated (fully or partially.)
1598 *
1599 * @hide
1600 */
1601 static final int DIRTY = 0x00200000;
1602
1603 /**
1604 * View flag indicating whether this view was invalidated by an opaque
1605 * invalidate request.
1606 *
1607 * @hide
1608 */
1609 static final int DIRTY_OPAQUE = 0x00400000;
1610
1611 /**
1612 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1613 *
1614 * @hide
1615 */
1616 static final int DIRTY_MASK = 0x00600000;
1617
1618 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001619 * Indicates whether the background is opaque.
1620 *
1621 * @hide
1622 */
1623 static final int OPAQUE_BACKGROUND = 0x00800000;
1624
1625 /**
1626 * Indicates whether the scrollbars are opaque.
1627 *
1628 * @hide
1629 */
1630 static final int OPAQUE_SCROLLBARS = 0x01000000;
1631
1632 /**
1633 * Indicates whether the view is opaque.
1634 *
1635 * @hide
1636 */
1637 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001638
1639 /**
1640 * Indicates a prepressed state;
1641 * the short time between ACTION_DOWN and recognizing
1642 * a 'real' press. Prepressed is used to recognize quick taps
1643 * even when they are shorter than ViewConfiguration.getTapTimeout().
1644 *
1645 * @hide
1646 */
1647 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001648
1649 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001650 * Indicates whether the view is temporarily detached.
1651 *
1652 * @hide
1653 */
1654 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001655
1656 /**
1657 * Indicates that we should awaken scroll bars once attached
1658 *
1659 * @hide
1660 */
1661 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001662
1663 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001664 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1665 * for transform operations
1666 *
1667 * @hide
1668 */
Adam Powellf37df072010-09-17 16:22:49 -07001669 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001670
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001671 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001672 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001673
Chet Haasefd2b0022010-08-06 13:08:56 -07001674 /**
Adam Powell637d3372010-08-25 14:37:03 -07001675 * Always allow a user to over-scroll this view, provided it is a
1676 * view that can scroll.
1677 *
1678 * @see #getOverScrollMode()
1679 * @see #setOverScrollMode(int)
1680 */
1681 public static final int OVER_SCROLL_ALWAYS = 0;
1682
1683 /**
1684 * Allow a user to over-scroll this view only if the content is large
1685 * enough to meaningfully scroll, provided it is a view that can scroll.
1686 *
1687 * @see #getOverScrollMode()
1688 * @see #setOverScrollMode(int)
1689 */
1690 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1691
1692 /**
1693 * Never allow a user to over-scroll this view.
1694 *
1695 * @see #getOverScrollMode()
1696 * @see #setOverScrollMode(int)
1697 */
1698 public static final int OVER_SCROLL_NEVER = 2;
1699
1700 /**
1701 * Controls the over-scroll mode for this view.
1702 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1703 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1704 * and {@link #OVER_SCROLL_NEVER}.
1705 */
1706 private int mOverScrollMode;
1707
1708 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 * The parent this view is attached to.
1710 * {@hide}
1711 *
1712 * @see #getParent()
1713 */
1714 protected ViewParent mParent;
1715
1716 /**
1717 * {@hide}
1718 */
1719 AttachInfo mAttachInfo;
1720
1721 /**
1722 * {@hide}
1723 */
Romain Guy809a7f62009-05-14 15:44:42 -07001724 @ViewDebug.ExportedProperty(flagMapping = {
1725 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1726 name = "FORCE_LAYOUT"),
1727 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1728 name = "LAYOUT_REQUIRED"),
1729 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001730 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001731 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1732 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1733 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1734 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1735 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 int mPrivateFlags;
1737
1738 /**
1739 * Count of how many windows this view has been attached to.
1740 */
1741 int mWindowAttachCount;
1742
1743 /**
1744 * The layout parameters associated with this view and used by the parent
1745 * {@link android.view.ViewGroup} to determine how this view should be
1746 * laid out.
1747 * {@hide}
1748 */
1749 protected ViewGroup.LayoutParams mLayoutParams;
1750
1751 /**
1752 * The view flags hold various views states.
1753 * {@hide}
1754 */
1755 @ViewDebug.ExportedProperty
1756 int mViewFlags;
1757
1758 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001759 * The transform matrix for the View. This transform is calculated internally
1760 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1761 * is used by default. Do *not* use this variable directly; instead call
1762 * getMatrix(), which will automatically recalculate the matrix if necessary
1763 * to get the correct matrix based on the latest rotation and scale properties.
1764 */
1765 private final Matrix mMatrix = new Matrix();
1766
1767 /**
1768 * The transform matrix for the View. This transform is calculated internally
1769 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1770 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001771 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001772 * to get the correct matrix based on the latest rotation and scale properties.
1773 */
1774 private Matrix mInverseMatrix;
1775
1776 /**
1777 * An internal variable that tracks whether we need to recalculate the
1778 * transform matrix, based on whether the rotation or scaleX/Y properties
1779 * have changed since the matrix was last calculated.
1780 */
1781 private boolean mMatrixDirty = false;
1782
1783 /**
1784 * An internal variable that tracks whether we need to recalculate the
1785 * transform matrix, based on whether the rotation or scaleX/Y properties
1786 * have changed since the matrix was last calculated.
1787 */
1788 private boolean mInverseMatrixDirty = true;
1789
1790 /**
1791 * A variable that tracks whether we need to recalculate the
1792 * transform matrix, based on whether the rotation or scaleX/Y properties
1793 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001794 * is only valid after a call to updateMatrix() or to a function that
1795 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001796 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001797 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001798
1799 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001800 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1801 */
1802 private Camera mCamera = null;
1803
1804 /**
1805 * This matrix is used when computing the matrix for 3D rotations.
1806 */
1807 private Matrix matrix3D = null;
1808
1809 /**
1810 * These prev values are used to recalculate a centered pivot point when necessary. The
1811 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1812 * set), so thes values are only used then as well.
1813 */
1814 private int mPrevWidth = -1;
1815 private int mPrevHeight = -1;
1816
1817 /**
1818 * Convenience value to check for float values that are close enough to zero to be considered
1819 * zero.
1820 */
Romain Guy2542d192010-08-18 11:47:12 -07001821 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001822
1823 /**
1824 * The degrees rotation around the vertical axis through the pivot point.
1825 */
1826 @ViewDebug.ExportedProperty
1827 private float mRotationY = 0f;
1828
1829 /**
1830 * The degrees rotation around the horizontal axis through the pivot point.
1831 */
1832 @ViewDebug.ExportedProperty
1833 private float mRotationX = 0f;
1834
1835 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001836 * The degrees rotation around the pivot point.
1837 */
1838 @ViewDebug.ExportedProperty
1839 private float mRotation = 0f;
1840
1841 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001842 * The amount of translation of the object away from its left property (post-layout).
1843 */
1844 @ViewDebug.ExportedProperty
1845 private float mTranslationX = 0f;
1846
1847 /**
1848 * The amount of translation of the object away from its top property (post-layout).
1849 */
1850 @ViewDebug.ExportedProperty
1851 private float mTranslationY = 0f;
1852
1853 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001854 * The amount of scale in the x direction around the pivot point. A
1855 * value of 1 means no scaling is applied.
1856 */
1857 @ViewDebug.ExportedProperty
1858 private float mScaleX = 1f;
1859
1860 /**
1861 * The amount of scale in the y direction around the pivot point. A
1862 * value of 1 means no scaling is applied.
1863 */
1864 @ViewDebug.ExportedProperty
1865 private float mScaleY = 1f;
1866
1867 /**
1868 * The amount of scale in the x direction around the pivot point. A
1869 * value of 1 means no scaling is applied.
1870 */
1871 @ViewDebug.ExportedProperty
1872 private float mPivotX = 0f;
1873
1874 /**
1875 * The amount of scale in the y direction around the pivot point. A
1876 * value of 1 means no scaling is applied.
1877 */
1878 @ViewDebug.ExportedProperty
1879 private float mPivotY = 0f;
1880
1881 /**
1882 * The opacity of the View. This is a value from 0 to 1, where 0 means
1883 * completely transparent and 1 means completely opaque.
1884 */
1885 @ViewDebug.ExportedProperty
1886 private float mAlpha = 1f;
1887
1888 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 * The distance in pixels from the left edge of this view's parent
1890 * to the left edge of this view.
1891 * {@hide}
1892 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001893 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 protected int mLeft;
1895 /**
1896 * The distance in pixels from the left edge of this view's parent
1897 * to the right edge of this view.
1898 * {@hide}
1899 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001900 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 protected int mRight;
1902 /**
1903 * The distance in pixels from the top edge of this view's parent
1904 * to the top edge of this view.
1905 * {@hide}
1906 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001907 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 protected int mTop;
1909 /**
1910 * The distance in pixels from the top edge of this view's parent
1911 * to the bottom edge of this view.
1912 * {@hide}
1913 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001914 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 protected int mBottom;
1916
1917 /**
1918 * The offset, in pixels, by which the content of this view is scrolled
1919 * horizontally.
1920 * {@hide}
1921 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001922 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 protected int mScrollX;
1924 /**
1925 * The offset, in pixels, by which the content of this view is scrolled
1926 * vertically.
1927 * {@hide}
1928 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001929 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 protected int mScrollY;
1931
1932 /**
1933 * The left padding in pixels, that is the distance in pixels between the
1934 * left edge of this view and the left edge of its content.
1935 * {@hide}
1936 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001937 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 protected int mPaddingLeft;
1939 /**
1940 * The right padding in pixels, that is the distance in pixels between the
1941 * right edge of this view and the right edge of its content.
1942 * {@hide}
1943 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001944 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 protected int mPaddingRight;
1946 /**
1947 * The top padding in pixels, that is the distance in pixels between the
1948 * top edge of this view and the top edge of its content.
1949 * {@hide}
1950 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001951 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 protected int mPaddingTop;
1953 /**
1954 * The bottom padding in pixels, that is the distance in pixels between the
1955 * bottom edge of this view and the bottom edge of its content.
1956 * {@hide}
1957 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001958 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 protected int mPaddingBottom;
1960
1961 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001962 * Briefly describes the view and is primarily used for accessibility support.
1963 */
1964 private CharSequence mContentDescription;
1965
1966 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 * Cache the paddingRight set by the user to append to the scrollbar's size.
1968 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001969 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 int mUserPaddingRight;
1971
1972 /**
1973 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1974 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001975 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 int mUserPaddingBottom;
1977
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001978 /**
Adam Powell20232d02010-12-08 21:08:53 -08001979 * Cache the paddingLeft set by the user to append to the scrollbar's size.
1980 */
1981 @ViewDebug.ExportedProperty(category = "padding")
1982 int mUserPaddingLeft;
1983
1984 /**
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001985 * @hide
1986 */
1987 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1988 /**
1989 * @hide
1990 */
1991 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992
1993 private Resources mResources = null;
1994
1995 private Drawable mBGDrawable;
1996
1997 private int mBackgroundResource;
1998 private boolean mBackgroundSizeChanged;
1999
2000 /**
2001 * Listener used to dispatch focus change events.
2002 * This field should be made private, so it is hidden from the SDK.
2003 * {@hide}
2004 */
2005 protected OnFocusChangeListener mOnFocusChangeListener;
2006
2007 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002008 * Listeners for layout change events.
2009 */
2010 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2011
2012 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 * Listener used to dispatch click events.
2014 * This field should be made private, so it is hidden from the SDK.
2015 * {@hide}
2016 */
2017 protected OnClickListener mOnClickListener;
2018
2019 /**
2020 * Listener used to dispatch long click events.
2021 * This field should be made private, so it is hidden from the SDK.
2022 * {@hide}
2023 */
2024 protected OnLongClickListener mOnLongClickListener;
2025
2026 /**
2027 * Listener used to build the context menu.
2028 * This field should be made private, so it is hidden from the SDK.
2029 * {@hide}
2030 */
2031 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2032
2033 private OnKeyListener mOnKeyListener;
2034
2035 private OnTouchListener mOnTouchListener;
2036
Chris Tate32affef2010-10-18 15:29:21 -07002037 private OnDragListener mOnDragListener;
2038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 /**
2040 * The application environment this view lives in.
2041 * This field should be made private, so it is hidden from the SDK.
2042 * {@hide}
2043 */
2044 protected Context mContext;
2045
2046 private ScrollabilityCache mScrollCache;
2047
2048 private int[] mDrawableState = null;
2049
Romain Guy02890fd2010-08-06 17:58:44 -07002050 private Bitmap mDrawingCache;
2051 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07002052 private DisplayList mDisplayList;
Romain Guy6c319ca2011-01-11 14:29:25 -08002053 private HardwareLayer mHardwareLayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054
2055 /**
2056 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2057 * the user may specify which view to go to next.
2058 */
2059 private int mNextFocusLeftId = View.NO_ID;
2060
2061 /**
2062 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2063 * the user may specify which view to go to next.
2064 */
2065 private int mNextFocusRightId = View.NO_ID;
2066
2067 /**
2068 * When this view has focus and the next focus is {@link #FOCUS_UP},
2069 * the user may specify which view to go to next.
2070 */
2071 private int mNextFocusUpId = View.NO_ID;
2072
2073 /**
2074 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2075 * the user may specify which view to go to next.
2076 */
2077 private int mNextFocusDownId = View.NO_ID;
2078
Jeff Brown4e6319b2010-12-13 10:36:51 -08002079 /**
2080 * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2081 * the user may specify which view to go to next.
2082 */
2083 int mNextFocusForwardId = View.NO_ID;
2084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08002086 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08002087 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08002088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 private UnsetPressedState mUnsetPressedState;
2090
2091 /**
2092 * Whether the long press's action has been invoked. The tap's action is invoked on the
2093 * up event while a long press is invoked as soon as the long press duration is reached, so
2094 * a long press could be performed before the tap is checked, in which case the tap's action
2095 * should not be invoked.
2096 */
2097 private boolean mHasPerformedLongPress;
2098
2099 /**
2100 * The minimum height of the view. We'll try our best to have the height
2101 * of this view to at least this amount.
2102 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002103 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 private int mMinHeight;
2105
2106 /**
2107 * The minimum width of the view. We'll try our best to have the width
2108 * of this view to at least this amount.
2109 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002110 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 private int mMinWidth;
2112
2113 /**
2114 * The delegate to handle touch events that are physically in this view
2115 * but should be handled by another view.
2116 */
2117 private TouchDelegate mTouchDelegate = null;
2118
2119 /**
2120 * Solid color to use as a background when creating the drawing cache. Enables
2121 * the cache to use 16 bit bitmaps instead of 32 bit.
2122 */
2123 private int mDrawingCacheBackgroundColor = 0;
2124
2125 /**
2126 * Special tree observer used when mAttachInfo is null.
2127 */
2128 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002129
2130 /**
2131 * Cache the touch slop from the context that created the view.
2132 */
2133 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002136 * Cache drag/drop state
2137 *
2138 */
2139 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002140
2141 /**
Christopher Tate02d2b3b2011-01-10 20:43:53 -08002142 * Flag indicating that a drag can cross window boundaries
2143 * @hide
2144 */
2145 public static final int DRAG_FLAG_GLOBAL = 1;
2146
2147 /**
Adam Powell20232d02010-12-08 21:08:53 -08002148 * Position of the vertical scroll bar.
2149 */
2150 private int mVerticalScrollbarPosition;
2151
2152 /**
2153 * Position the scroll bar at the default position as determined by the system.
2154 */
2155 public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2156
2157 /**
2158 * Position the scroll bar along the left edge.
2159 */
2160 public static final int SCROLLBAR_POSITION_LEFT = 1;
2161
2162 /**
2163 * Position the scroll bar along the right edge.
2164 */
2165 public static final int SCROLLBAR_POSITION_RIGHT = 2;
2166
2167 /**
Romain Guy171c5922011-01-06 10:04:23 -08002168 * Indicates that the view does not have a layer.
2169 *
2170 * @see #getLayerType()
2171 * @see #setLayerType(int, android.graphics.Paint)
2172 * @see #LAYER_TYPE_SOFTWARE
2173 * @see #LAYER_TYPE_HARDWARE
2174 */
2175 public static final int LAYER_TYPE_NONE = 0;
2176
2177 /**
2178 * <p>Indicates that the view has a software layer. A software layer is backed
2179 * by a bitmap and causes the view to be rendered using Android's software
2180 * rendering pipeline, even if hardware acceleration is enabled.</p>
2181 *
2182 * <p>Software layers have various usages:</p>
2183 * <p>When the application is not using hardware acceleration, a software layer
2184 * is useful to apply a specific color filter and/or blending mode and/or
2185 * translucency to a view and all its children.</p>
2186 * <p>When the application is using hardware acceleration, a software layer
2187 * is useful to render drawing primitives not supported by the hardware
2188 * accelerated pipeline. It can also be used to cache a complex view tree
2189 * into a texture and reduce the complexity of drawing operations. For instance,
2190 * when animating a complex view tree with a translation, a software layer can
2191 * be used to render the view tree only once.</p>
2192 * <p>Software layers should be avoided when the affected view tree updates
2193 * often. Every update will require to re-render the software layer, which can
2194 * potentially be slow (particularly when hardware acceleration is turned on
2195 * since the layer will have to be uploaded into a hardware texture after every
2196 * update.)</p>
2197 *
2198 * @see #getLayerType()
2199 * @see #setLayerType(int, android.graphics.Paint)
2200 * @see #LAYER_TYPE_NONE
2201 * @see #LAYER_TYPE_HARDWARE
2202 */
2203 public static final int LAYER_TYPE_SOFTWARE = 1;
2204
2205 /**
2206 * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2207 * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2208 * OpenGL hardware) and causes the view to be rendered using Android's hardware
2209 * rendering pipeline, but only if hardware acceleration is turned on for the
2210 * view hierarchy. When hardware acceleration is turned off, hardware layers
2211 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2212 *
2213 * <p>A hardware layer is useful to apply a specific color filter and/or
2214 * blending mode and/or translucency to a view and all its children.</p>
Romain Guy6c319ca2011-01-11 14:29:25 -08002215 * <p>A hardware layer can be used to cache a complex view tree into a
2216 * texture and reduce the complexity of drawing operations. For instance,
2217 * when animating a complex view tree with a translation, a hardware layer can
2218 * be used to render the view tree only once.</p>
Romain Guy171c5922011-01-06 10:04:23 -08002219 * <p>A hardware layer can also be used to increase the rendering quality when
2220 * rotation transformations are applied on a view. It can also be used to
2221 * prevent potential clipping issues when applying 3D transforms on a view.</p>
2222 *
2223 * @see #getLayerType()
2224 * @see #setLayerType(int, android.graphics.Paint)
2225 * @see #LAYER_TYPE_NONE
2226 * @see #LAYER_TYPE_SOFTWARE
2227 */
2228 public static final int LAYER_TYPE_HARDWARE = 2;
2229
Romain Guy3aaff3a2011-01-12 14:18:47 -08002230 @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2231 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2232 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2233 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2234 })
Romain Guy171c5922011-01-06 10:04:23 -08002235 int mLayerType = LAYER_TYPE_NONE;
2236 Paint mLayerPaint;
2237
2238 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 * Simple constructor to use when creating a view from code.
2240 *
2241 * @param context The Context the view is running in, through which it can
2242 * access the current theme, resources, etc.
2243 */
2244 public View(Context context) {
2245 mContext = context;
2246 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002247 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002248 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Adam Powell637d3372010-08-25 14:37:03 -07002249 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
2251
2252 /**
2253 * Constructor that is called when inflating a view from XML. This is called
2254 * when a view is being constructed from an XML file, supplying attributes
2255 * that were specified in the XML file. This version uses a default style of
2256 * 0, so the only attribute values applied are those in the Context's Theme
2257 * and the given AttributeSet.
2258 *
2259 * <p>
2260 * The method onFinishInflate() will be called after all children have been
2261 * added.
2262 *
2263 * @param context The Context the view is running in, through which it can
2264 * access the current theme, resources, etc.
2265 * @param attrs The attributes of the XML tag that is inflating the view.
2266 * @see #View(Context, AttributeSet, int)
2267 */
2268 public View(Context context, AttributeSet attrs) {
2269 this(context, attrs, 0);
2270 }
2271
2272 /**
2273 * Perform inflation from XML and apply a class-specific base style. This
2274 * constructor of View allows subclasses to use their own base style when
2275 * they are inflating. For example, a Button class's constructor would call
2276 * this version of the super class constructor and supply
2277 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2278 * the theme's button style to modify all of the base view attributes (in
2279 * particular its background) as well as the Button class's attributes.
2280 *
2281 * @param context The Context the view is running in, through which it can
2282 * access the current theme, resources, etc.
2283 * @param attrs The attributes of the XML tag that is inflating the view.
2284 * @param defStyle The default style to apply to this view. If 0, no style
2285 * will be applied (beyond what is included in the theme). This may
2286 * either be an attribute resource, whose value will be retrieved
2287 * from the current theme, or an explicit style resource.
2288 * @see #View(Context, AttributeSet)
2289 */
2290 public View(Context context, AttributeSet attrs, int defStyle) {
2291 this(context);
2292
2293 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2294 defStyle, 0);
2295
2296 Drawable background = null;
2297
2298 int leftPadding = -1;
2299 int topPadding = -1;
2300 int rightPadding = -1;
2301 int bottomPadding = -1;
2302
2303 int padding = -1;
2304
2305 int viewFlagValues = 0;
2306 int viewFlagMasks = 0;
2307
2308 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 int x = 0;
2311 int y = 0;
2312
Chet Haase73066682010-11-29 15:55:32 -08002313 float tx = 0;
2314 float ty = 0;
2315 float rotation = 0;
2316 float rotationX = 0;
2317 float rotationY = 0;
2318 float sx = 1f;
2319 float sy = 1f;
2320 boolean transformSet = false;
2321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2323
Adam Powell637d3372010-08-25 14:37:03 -07002324 int overScrollMode = mOverScrollMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 final int N = a.getIndexCount();
2326 for (int i = 0; i < N; i++) {
2327 int attr = a.getIndex(i);
2328 switch (attr) {
2329 case com.android.internal.R.styleable.View_background:
2330 background = a.getDrawable(attr);
2331 break;
2332 case com.android.internal.R.styleable.View_padding:
2333 padding = a.getDimensionPixelSize(attr, -1);
2334 break;
2335 case com.android.internal.R.styleable.View_paddingLeft:
2336 leftPadding = a.getDimensionPixelSize(attr, -1);
2337 break;
2338 case com.android.internal.R.styleable.View_paddingTop:
2339 topPadding = a.getDimensionPixelSize(attr, -1);
2340 break;
2341 case com.android.internal.R.styleable.View_paddingRight:
2342 rightPadding = a.getDimensionPixelSize(attr, -1);
2343 break;
2344 case com.android.internal.R.styleable.View_paddingBottom:
2345 bottomPadding = a.getDimensionPixelSize(attr, -1);
2346 break;
2347 case com.android.internal.R.styleable.View_scrollX:
2348 x = a.getDimensionPixelOffset(attr, 0);
2349 break;
2350 case com.android.internal.R.styleable.View_scrollY:
2351 y = a.getDimensionPixelOffset(attr, 0);
2352 break;
Chet Haase73066682010-11-29 15:55:32 -08002353 case com.android.internal.R.styleable.View_alpha:
2354 setAlpha(a.getFloat(attr, 1f));
2355 break;
2356 case com.android.internal.R.styleable.View_transformPivotX:
2357 setPivotX(a.getDimensionPixelOffset(attr, 0));
2358 break;
2359 case com.android.internal.R.styleable.View_transformPivotY:
2360 setPivotY(a.getDimensionPixelOffset(attr, 0));
2361 break;
2362 case com.android.internal.R.styleable.View_translationX:
2363 tx = a.getDimensionPixelOffset(attr, 0);
2364 transformSet = true;
2365 break;
2366 case com.android.internal.R.styleable.View_translationY:
2367 ty = a.getDimensionPixelOffset(attr, 0);
2368 transformSet = true;
2369 break;
2370 case com.android.internal.R.styleable.View_rotation:
2371 rotation = a.getFloat(attr, 0);
2372 transformSet = true;
2373 break;
2374 case com.android.internal.R.styleable.View_rotationX:
2375 rotationX = a.getFloat(attr, 0);
2376 transformSet = true;
2377 break;
2378 case com.android.internal.R.styleable.View_rotationY:
2379 rotationY = a.getFloat(attr, 0);
2380 transformSet = true;
2381 break;
2382 case com.android.internal.R.styleable.View_scaleX:
2383 sx = a.getFloat(attr, 1f);
2384 transformSet = true;
2385 break;
2386 case com.android.internal.R.styleable.View_scaleY:
2387 sy = a.getFloat(attr, 1f);
2388 transformSet = true;
2389 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 case com.android.internal.R.styleable.View_id:
2391 mID = a.getResourceId(attr, NO_ID);
2392 break;
2393 case com.android.internal.R.styleable.View_tag:
2394 mTag = a.getText(attr);
2395 break;
2396 case com.android.internal.R.styleable.View_fitsSystemWindows:
2397 if (a.getBoolean(attr, false)) {
2398 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2399 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2400 }
2401 break;
2402 case com.android.internal.R.styleable.View_focusable:
2403 if (a.getBoolean(attr, false)) {
2404 viewFlagValues |= FOCUSABLE;
2405 viewFlagMasks |= FOCUSABLE_MASK;
2406 }
2407 break;
2408 case com.android.internal.R.styleable.View_focusableInTouchMode:
2409 if (a.getBoolean(attr, false)) {
2410 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2411 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2412 }
2413 break;
2414 case com.android.internal.R.styleable.View_clickable:
2415 if (a.getBoolean(attr, false)) {
2416 viewFlagValues |= CLICKABLE;
2417 viewFlagMasks |= CLICKABLE;
2418 }
2419 break;
2420 case com.android.internal.R.styleable.View_longClickable:
2421 if (a.getBoolean(attr, false)) {
2422 viewFlagValues |= LONG_CLICKABLE;
2423 viewFlagMasks |= LONG_CLICKABLE;
2424 }
2425 break;
2426 case com.android.internal.R.styleable.View_saveEnabled:
2427 if (!a.getBoolean(attr, true)) {
2428 viewFlagValues |= SAVE_DISABLED;
2429 viewFlagMasks |= SAVE_DISABLED_MASK;
2430 }
2431 break;
2432 case com.android.internal.R.styleable.View_duplicateParentState:
2433 if (a.getBoolean(attr, false)) {
2434 viewFlagValues |= DUPLICATE_PARENT_STATE;
2435 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2436 }
2437 break;
2438 case com.android.internal.R.styleable.View_visibility:
2439 final int visibility = a.getInt(attr, 0);
2440 if (visibility != 0) {
2441 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2442 viewFlagMasks |= VISIBILITY_MASK;
2443 }
2444 break;
2445 case com.android.internal.R.styleable.View_drawingCacheQuality:
2446 final int cacheQuality = a.getInt(attr, 0);
2447 if (cacheQuality != 0) {
2448 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2449 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2450 }
2451 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002452 case com.android.internal.R.styleable.View_contentDescription:
2453 mContentDescription = a.getString(attr);
2454 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2456 if (!a.getBoolean(attr, true)) {
2457 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2458 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2459 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002460 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2462 if (!a.getBoolean(attr, true)) {
2463 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2464 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2465 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002466 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 case R.styleable.View_scrollbars:
2468 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2469 if (scrollbars != SCROLLBARS_NONE) {
2470 viewFlagValues |= scrollbars;
2471 viewFlagMasks |= SCROLLBARS_MASK;
2472 initializeScrollbars(a);
2473 }
2474 break;
2475 case R.styleable.View_fadingEdge:
2476 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2477 if (fadingEdge != FADING_EDGE_NONE) {
2478 viewFlagValues |= fadingEdge;
2479 viewFlagMasks |= FADING_EDGE_MASK;
2480 initializeFadingEdge(a);
2481 }
2482 break;
2483 case R.styleable.View_scrollbarStyle:
2484 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2485 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2486 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2487 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2488 }
2489 break;
2490 case R.styleable.View_isScrollContainer:
2491 setScrollContainer = true;
2492 if (a.getBoolean(attr, false)) {
2493 setScrollContainer(true);
2494 }
2495 break;
2496 case com.android.internal.R.styleable.View_keepScreenOn:
2497 if (a.getBoolean(attr, false)) {
2498 viewFlagValues |= KEEP_SCREEN_ON;
2499 viewFlagMasks |= KEEP_SCREEN_ON;
2500 }
2501 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002502 case R.styleable.View_filterTouchesWhenObscured:
2503 if (a.getBoolean(attr, false)) {
2504 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2505 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2506 }
2507 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 case R.styleable.View_nextFocusLeft:
2509 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2510 break;
2511 case R.styleable.View_nextFocusRight:
2512 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2513 break;
2514 case R.styleable.View_nextFocusUp:
2515 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2516 break;
2517 case R.styleable.View_nextFocusDown:
2518 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2519 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002520 case R.styleable.View_nextFocusForward:
2521 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2522 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 case R.styleable.View_minWidth:
2524 mMinWidth = a.getDimensionPixelSize(attr, 0);
2525 break;
2526 case R.styleable.View_minHeight:
2527 mMinHeight = a.getDimensionPixelSize(attr, 0);
2528 break;
Romain Guy9a817362009-05-01 10:57:14 -07002529 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002530 if (context.isRestricted()) {
2531 throw new IllegalStateException("The android:onClick attribute cannot "
2532 + "be used within a restricted context");
2533 }
2534
Romain Guy9a817362009-05-01 10:57:14 -07002535 final String handlerName = a.getString(attr);
2536 if (handlerName != null) {
2537 setOnClickListener(new OnClickListener() {
2538 private Method mHandler;
2539
2540 public void onClick(View v) {
2541 if (mHandler == null) {
2542 try {
2543 mHandler = getContext().getClass().getMethod(handlerName,
2544 View.class);
2545 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002546 int id = getId();
2547 String idText = id == NO_ID ? "" : " with id '"
2548 + getContext().getResources().getResourceEntryName(
2549 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002550 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002551 handlerName + "(View) in the activity "
2552 + getContext().getClass() + " for onClick handler"
2553 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002554 }
2555 }
2556
2557 try {
2558 mHandler.invoke(getContext(), View.this);
2559 } catch (IllegalAccessException e) {
2560 throw new IllegalStateException("Could not execute non "
2561 + "public method of the activity", e);
2562 } catch (InvocationTargetException e) {
2563 throw new IllegalStateException("Could not execute "
2564 + "method of the activity", e);
2565 }
2566 }
2567 });
2568 }
2569 break;
Adam Powell637d3372010-08-25 14:37:03 -07002570 case R.styleable.View_overScrollMode:
2571 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2572 break;
Adam Powell20232d02010-12-08 21:08:53 -08002573 case R.styleable.View_verticalScrollbarPosition:
2574 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2575 break;
Romain Guy171c5922011-01-06 10:04:23 -08002576 case R.styleable.View_layerType:
2577 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
2578 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 }
2580 }
2581
Adam Powell637d3372010-08-25 14:37:03 -07002582 setOverScrollMode(overScrollMode);
2583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 if (background != null) {
2585 setBackgroundDrawable(background);
2586 }
2587
2588 if (padding >= 0) {
2589 leftPadding = padding;
2590 topPadding = padding;
2591 rightPadding = padding;
2592 bottomPadding = padding;
2593 }
2594
2595 // If the user specified the padding (either with android:padding or
2596 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2597 // use the default padding or the padding from the background drawable
2598 // (stored at this point in mPadding*)
2599 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2600 topPadding >= 0 ? topPadding : mPaddingTop,
2601 rightPadding >= 0 ? rightPadding : mPaddingRight,
2602 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2603
2604 if (viewFlagMasks != 0) {
2605 setFlags(viewFlagValues, viewFlagMasks);
2606 }
2607
2608 // Needs to be called after mViewFlags is set
2609 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2610 recomputePadding();
2611 }
2612
2613 if (x != 0 || y != 0) {
2614 scrollTo(x, y);
2615 }
2616
Chet Haase73066682010-11-29 15:55:32 -08002617 if (transformSet) {
2618 setTranslationX(tx);
2619 setTranslationY(ty);
2620 setRotation(rotation);
2621 setRotationX(rotationX);
2622 setRotationY(rotationY);
2623 setScaleX(sx);
2624 setScaleY(sy);
2625 }
2626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2628 setScrollContainer(true);
2629 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002630
2631 computeOpaqueFlags();
2632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 a.recycle();
2634 }
2635
2636 /**
2637 * Non-public constructor for use in testing
2638 */
2639 View() {
2640 }
2641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 /**
2643 * <p>
2644 * Initializes the fading edges from a given set of styled attributes. This
2645 * method should be called by subclasses that need fading edges and when an
2646 * instance of these subclasses is created programmatically rather than
2647 * being inflated from XML. This method is automatically called when the XML
2648 * is inflated.
2649 * </p>
2650 *
2651 * @param a the styled attributes set to initialize the fading edges from
2652 */
2653 protected void initializeFadingEdge(TypedArray a) {
2654 initScrollCache();
2655
2656 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2657 R.styleable.View_fadingEdgeLength,
2658 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2659 }
2660
2661 /**
2662 * Returns the size of the vertical faded edges used to indicate that more
2663 * content in this view is visible.
2664 *
2665 * @return The size in pixels of the vertical faded edge or 0 if vertical
2666 * faded edges are not enabled for this view.
2667 * @attr ref android.R.styleable#View_fadingEdgeLength
2668 */
2669 public int getVerticalFadingEdgeLength() {
2670 if (isVerticalFadingEdgeEnabled()) {
2671 ScrollabilityCache cache = mScrollCache;
2672 if (cache != null) {
2673 return cache.fadingEdgeLength;
2674 }
2675 }
2676 return 0;
2677 }
2678
2679 /**
2680 * Set the size of the faded edge used to indicate that more content in this
2681 * view is available. Will not change whether the fading edge is enabled; use
2682 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2683 * to enable the fading edge for the vertical or horizontal fading edges.
2684 *
2685 * @param length The size in pixels of the faded edge used to indicate that more
2686 * content in this view is visible.
2687 */
2688 public void setFadingEdgeLength(int length) {
2689 initScrollCache();
2690 mScrollCache.fadingEdgeLength = length;
2691 }
2692
2693 /**
2694 * Returns the size of the horizontal faded edges used to indicate that more
2695 * content in this view is visible.
2696 *
2697 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2698 * faded edges are not enabled for this view.
2699 * @attr ref android.R.styleable#View_fadingEdgeLength
2700 */
2701 public int getHorizontalFadingEdgeLength() {
2702 if (isHorizontalFadingEdgeEnabled()) {
2703 ScrollabilityCache cache = mScrollCache;
2704 if (cache != null) {
2705 return cache.fadingEdgeLength;
2706 }
2707 }
2708 return 0;
2709 }
2710
2711 /**
2712 * Returns the width of the vertical scrollbar.
2713 *
2714 * @return The width in pixels of the vertical scrollbar or 0 if there
2715 * is no vertical scrollbar.
2716 */
2717 public int getVerticalScrollbarWidth() {
2718 ScrollabilityCache cache = mScrollCache;
2719 if (cache != null) {
2720 ScrollBarDrawable scrollBar = cache.scrollBar;
2721 if (scrollBar != null) {
2722 int size = scrollBar.getSize(true);
2723 if (size <= 0) {
2724 size = cache.scrollBarSize;
2725 }
2726 return size;
2727 }
2728 return 0;
2729 }
2730 return 0;
2731 }
2732
2733 /**
2734 * Returns the height of the horizontal scrollbar.
2735 *
2736 * @return The height in pixels of the horizontal scrollbar or 0 if
2737 * there is no horizontal scrollbar.
2738 */
2739 protected int getHorizontalScrollbarHeight() {
2740 ScrollabilityCache cache = mScrollCache;
2741 if (cache != null) {
2742 ScrollBarDrawable scrollBar = cache.scrollBar;
2743 if (scrollBar != null) {
2744 int size = scrollBar.getSize(false);
2745 if (size <= 0) {
2746 size = cache.scrollBarSize;
2747 }
2748 return size;
2749 }
2750 return 0;
2751 }
2752 return 0;
2753 }
2754
2755 /**
2756 * <p>
2757 * Initializes the scrollbars from a given set of styled attributes. This
2758 * method should be called by subclasses that need scrollbars and when an
2759 * instance of these subclasses is created programmatically rather than
2760 * being inflated from XML. This method is automatically called when the XML
2761 * is inflated.
2762 * </p>
2763 *
2764 * @param a the styled attributes set to initialize the scrollbars from
2765 */
2766 protected void initializeScrollbars(TypedArray a) {
2767 initScrollCache();
2768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002770
2771 if (scrollabilityCache.scrollBar == null) {
2772 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2773 }
2774
Romain Guy8bda2482010-03-02 11:42:11 -08002775 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776
Mike Cleronf116bf82009-09-27 19:14:12 -07002777 if (!fadeScrollbars) {
2778 scrollabilityCache.state = ScrollabilityCache.ON;
2779 }
2780 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2781
2782
2783 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2784 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2785 .getScrollBarFadeDuration());
2786 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2787 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2788 ViewConfiguration.getScrollDefaultDelay());
2789
2790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2792 com.android.internal.R.styleable.View_scrollbarSize,
2793 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2794
2795 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2796 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2797
2798 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2799 if (thumb != null) {
2800 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2801 }
2802
2803 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2804 false);
2805 if (alwaysDraw) {
2806 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2807 }
2808
2809 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2810 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2811
2812 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2813 if (thumb != null) {
2814 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2815 }
2816
2817 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2818 false);
2819 if (alwaysDraw) {
2820 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2821 }
2822
2823 // Re-apply user/background padding so that scrollbar(s) get added
2824 recomputePadding();
2825 }
2826
2827 /**
2828 * <p>
2829 * Initalizes the scrollability cache if necessary.
2830 * </p>
2831 */
2832 private void initScrollCache() {
2833 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002834 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 }
2836 }
2837
2838 /**
Adam Powell20232d02010-12-08 21:08:53 -08002839 * Set the position of the vertical scroll bar. Should be one of
2840 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
2841 * {@link #SCROLLBAR_POSITION_RIGHT}.
2842 *
2843 * @param position Where the vertical scroll bar should be positioned.
2844 */
2845 public void setVerticalScrollbarPosition(int position) {
2846 if (mVerticalScrollbarPosition != position) {
2847 mVerticalScrollbarPosition = position;
2848 computeOpaqueFlags();
2849 recomputePadding();
2850 }
2851 }
2852
2853 /**
2854 * @return The position where the vertical scroll bar will show, if applicable.
2855 * @see #setVerticalScrollbarPosition(int)
2856 */
2857 public int getVerticalScrollbarPosition() {
2858 return mVerticalScrollbarPosition;
2859 }
2860
2861 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 * Register a callback to be invoked when focus of this view changed.
2863 *
2864 * @param l The callback that will run.
2865 */
2866 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2867 mOnFocusChangeListener = l;
2868 }
2869
2870 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002871 * Add a listener that will be called when the bounds of the view change due to
2872 * layout processing.
2873 *
2874 * @param listener The listener that will be called when layout bounds change.
2875 */
2876 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2877 if (mOnLayoutChangeListeners == null) {
2878 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2879 }
2880 mOnLayoutChangeListeners.add(listener);
2881 }
2882
2883 /**
2884 * Remove a listener for layout changes.
2885 *
2886 * @param listener The listener for layout bounds change.
2887 */
2888 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2889 if (mOnLayoutChangeListeners == null) {
2890 return;
2891 }
2892 mOnLayoutChangeListeners.remove(listener);
2893 }
2894
2895 /**
2896 * Gets the current list of listeners for layout changes.
Chet Haase21cd1382010-09-01 17:42:29 -07002897 */
2898 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2899 return mOnLayoutChangeListeners;
2900 }
2901
2902 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 * Returns the focus-change callback registered for this view.
2904 *
2905 * @return The callback, or null if one is not registered.
2906 */
2907 public OnFocusChangeListener getOnFocusChangeListener() {
2908 return mOnFocusChangeListener;
2909 }
2910
2911 /**
2912 * Register a callback to be invoked when this view is clicked. If this view is not
2913 * clickable, it becomes clickable.
2914 *
2915 * @param l The callback that will run
2916 *
2917 * @see #setClickable(boolean)
2918 */
2919 public void setOnClickListener(OnClickListener l) {
2920 if (!isClickable()) {
2921 setClickable(true);
2922 }
2923 mOnClickListener = l;
2924 }
2925
2926 /**
2927 * Register a callback to be invoked when this view is clicked and held. If this view is not
2928 * long clickable, it becomes long clickable.
2929 *
2930 * @param l The callback that will run
2931 *
2932 * @see #setLongClickable(boolean)
2933 */
2934 public void setOnLongClickListener(OnLongClickListener l) {
2935 if (!isLongClickable()) {
2936 setLongClickable(true);
2937 }
2938 mOnLongClickListener = l;
2939 }
2940
2941 /**
2942 * Register a callback to be invoked when the context menu for this view is
2943 * being built. If this view is not long clickable, it becomes long clickable.
2944 *
2945 * @param l The callback that will run
2946 *
2947 */
2948 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2949 if (!isLongClickable()) {
2950 setLongClickable(true);
2951 }
2952 mOnCreateContextMenuListener = l;
2953 }
2954
2955 /**
2956 * Call this view's OnClickListener, if it is defined.
2957 *
2958 * @return True there was an assigned OnClickListener that was called, false
2959 * otherwise is returned.
2960 */
2961 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002962 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 if (mOnClickListener != null) {
2965 playSoundEffect(SoundEffectConstants.CLICK);
2966 mOnClickListener.onClick(this);
2967 return true;
2968 }
2969
2970 return false;
2971 }
2972
2973 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002974 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2975 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002977 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 */
2979 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002980 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 boolean handled = false;
2983 if (mOnLongClickListener != null) {
2984 handled = mOnLongClickListener.onLongClick(View.this);
2985 }
2986 if (!handled) {
2987 handled = showContextMenu();
2988 }
2989 if (handled) {
2990 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2991 }
2992 return handled;
2993 }
2994
2995 /**
2996 * Bring up the context menu for this view.
2997 *
2998 * @return Whether a context menu was displayed.
2999 */
3000 public boolean showContextMenu() {
3001 return getParent().showContextMenuForChild(this);
3002 }
3003
3004 /**
Adam Powell6e346362010-07-23 10:18:23 -07003005 * Start an action mode.
3006 *
3007 * @param callback Callback that will control the lifecycle of the action mode
3008 * @return The new action mode if it is started, null otherwise
3009 *
3010 * @see ActionMode
3011 */
3012 public ActionMode startActionMode(ActionMode.Callback callback) {
3013 return getParent().startActionModeForChild(this, callback);
3014 }
3015
3016 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 * Register a callback to be invoked when a key is pressed in this view.
3018 * @param l the key listener to attach to this view
3019 */
3020 public void setOnKeyListener(OnKeyListener l) {
3021 mOnKeyListener = l;
3022 }
3023
3024 /**
3025 * Register a callback to be invoked when a touch event is sent to this view.
3026 * @param l the touch listener to attach to this view
3027 */
3028 public void setOnTouchListener(OnTouchListener l) {
3029 mOnTouchListener = l;
3030 }
3031
3032 /**
Chris Tate32affef2010-10-18 15:29:21 -07003033 * Register a callback to be invoked when a drag event is sent to this view.
3034 * @param l The drag listener to attach to this view
3035 */
3036 public void setOnDragListener(OnDragListener l) {
3037 mOnDragListener = l;
3038 }
3039
3040 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
3042 *
3043 * Note: this does not check whether this {@link View} should get focus, it just
3044 * gives it focus no matter what. It should only be called internally by framework
3045 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3046 *
3047 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
3048 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
3049 * focus moved when requestFocus() is called. It may not always
3050 * apply, in which case use the default View.FOCUS_DOWN.
3051 * @param previouslyFocusedRect The rectangle of the view that had focus
3052 * prior in this View's coordinate system.
3053 */
3054 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3055 if (DBG) {
3056 System.out.println(this + " requestFocus()");
3057 }
3058
3059 if ((mPrivateFlags & FOCUSED) == 0) {
3060 mPrivateFlags |= FOCUSED;
3061
3062 if (mParent != null) {
3063 mParent.requestChildFocus(this, this);
3064 }
3065
3066 onFocusChanged(true, direction, previouslyFocusedRect);
3067 refreshDrawableState();
3068 }
3069 }
3070
3071 /**
3072 * Request that a rectangle of this view be visible on the screen,
3073 * scrolling if necessary just enough.
3074 *
3075 * <p>A View should call this if it maintains some notion of which part
3076 * of its content is interesting. For example, a text editing view
3077 * should call this when its cursor moves.
3078 *
3079 * @param rectangle The rectangle.
3080 * @return Whether any parent scrolled.
3081 */
3082 public boolean requestRectangleOnScreen(Rect rectangle) {
3083 return requestRectangleOnScreen(rectangle, false);
3084 }
3085
3086 /**
3087 * Request that a rectangle of this view be visible on the screen,
3088 * scrolling if necessary just enough.
3089 *
3090 * <p>A View should call this if it maintains some notion of which part
3091 * of its content is interesting. For example, a text editing view
3092 * should call this when its cursor moves.
3093 *
3094 * <p>When <code>immediate</code> is set to true, scrolling will not be
3095 * animated.
3096 *
3097 * @param rectangle The rectangle.
3098 * @param immediate True to forbid animated scrolling, false otherwise
3099 * @return Whether any parent scrolled.
3100 */
3101 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3102 View child = this;
3103 ViewParent parent = mParent;
3104 boolean scrolled = false;
3105 while (parent != null) {
3106 scrolled |= parent.requestChildRectangleOnScreen(child,
3107 rectangle, immediate);
3108
3109 // offset rect so next call has the rectangle in the
3110 // coordinate system of its direct child.
3111 rectangle.offset(child.getLeft(), child.getTop());
3112 rectangle.offset(-child.getScrollX(), -child.getScrollY());
3113
3114 if (!(parent instanceof View)) {
3115 break;
3116 }
Romain Guy8506ab42009-06-11 17:35:47 -07003117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 child = (View) parent;
3119 parent = child.getParent();
3120 }
3121 return scrolled;
3122 }
3123
3124 /**
3125 * Called when this view wants to give up focus. This will cause
3126 * {@link #onFocusChanged} to be called.
3127 */
3128 public void clearFocus() {
3129 if (DBG) {
3130 System.out.println(this + " clearFocus()");
3131 }
3132
3133 if ((mPrivateFlags & FOCUSED) != 0) {
3134 mPrivateFlags &= ~FOCUSED;
3135
3136 if (mParent != null) {
3137 mParent.clearChildFocus(this);
3138 }
3139
3140 onFocusChanged(false, 0, null);
3141 refreshDrawableState();
3142 }
3143 }
3144
3145 /**
3146 * Called to clear the focus of a view that is about to be removed.
3147 * Doesn't call clearChildFocus, which prevents this view from taking
3148 * focus again before it has been removed from the parent
3149 */
3150 void clearFocusForRemoval() {
3151 if ((mPrivateFlags & FOCUSED) != 0) {
3152 mPrivateFlags &= ~FOCUSED;
3153
3154 onFocusChanged(false, 0, null);
3155 refreshDrawableState();
3156 }
3157 }
3158
3159 /**
3160 * Called internally by the view system when a new view is getting focus.
3161 * This is what clears the old focus.
3162 */
3163 void unFocus() {
3164 if (DBG) {
3165 System.out.println(this + " unFocus()");
3166 }
3167
3168 if ((mPrivateFlags & FOCUSED) != 0) {
3169 mPrivateFlags &= ~FOCUSED;
3170
3171 onFocusChanged(false, 0, null);
3172 refreshDrawableState();
3173 }
3174 }
3175
3176 /**
3177 * Returns true if this view has focus iteself, or is the ancestor of the
3178 * view that has focus.
3179 *
3180 * @return True if this view has or contains focus, false otherwise.
3181 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003182 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003183 public boolean hasFocus() {
3184 return (mPrivateFlags & FOCUSED) != 0;
3185 }
3186
3187 /**
3188 * Returns true if this view is focusable or if it contains a reachable View
3189 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3190 * is a View whose parents do not block descendants focus.
3191 *
3192 * Only {@link #VISIBLE} views are considered focusable.
3193 *
3194 * @return True if the view is focusable or if the view contains a focusable
3195 * View, false otherwise.
3196 *
3197 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3198 */
3199 public boolean hasFocusable() {
3200 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3201 }
3202
3203 /**
3204 * Called by the view system when the focus state of this view changes.
3205 * When the focus change event is caused by directional navigation, direction
3206 * and previouslyFocusedRect provide insight into where the focus is coming from.
3207 * When overriding, be sure to call up through to the super class so that
3208 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07003209 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 * @param gainFocus True if the View has focus; false otherwise.
3211 * @param direction The direction focus has moved when requestFocus()
3212 * is called to give this view focus. Values are
Jeff Brown4e6319b2010-12-13 10:36:51 -08003213 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3214 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3215 * It may not always apply, in which case use the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 * @param previouslyFocusedRect The rectangle, in this view's coordinate
3217 * system, of the previously focused view. If applicable, this will be
3218 * passed in as finer grained information about where the focus is coming
3219 * from (in addition to direction). Will be <code>null</code> otherwise.
3220 */
3221 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003222 if (gainFocus) {
3223 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3224 }
3225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 InputMethodManager imm = InputMethodManager.peekInstance();
3227 if (!gainFocus) {
3228 if (isPressed()) {
3229 setPressed(false);
3230 }
3231 if (imm != null && mAttachInfo != null
3232 && mAttachInfo.mHasWindowFocus) {
3233 imm.focusOut(this);
3234 }
Romain Guya2431d02009-04-30 16:30:00 -07003235 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 } else if (imm != null && mAttachInfo != null
3237 && mAttachInfo.mHasWindowFocus) {
3238 imm.focusIn(this);
3239 }
Romain Guy8506ab42009-06-11 17:35:47 -07003240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241 invalidate();
3242 if (mOnFocusChangeListener != null) {
3243 mOnFocusChangeListener.onFocusChange(this, gainFocus);
3244 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003245
3246 if (mAttachInfo != null) {
3247 mAttachInfo.mKeyDispatchState.reset(this);
3248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 }
3250
3251 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07003252 * {@inheritDoc}
3253 */
3254 public void sendAccessibilityEvent(int eventType) {
3255 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3256 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3257 }
3258 }
3259
3260 /**
3261 * {@inheritDoc}
3262 */
3263 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3264 event.setClassName(getClass().getName());
3265 event.setPackageName(getContext().getPackageName());
3266 event.setEnabled(isEnabled());
3267 event.setContentDescription(mContentDescription);
3268
3269 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3270 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3271 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3272 event.setItemCount(focusablesTempList.size());
3273 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3274 focusablesTempList.clear();
3275 }
3276
3277 dispatchPopulateAccessibilityEvent(event);
3278
3279 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3280 }
3281
3282 /**
3283 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3284 * to be populated.
3285 *
3286 * @param event The event.
3287 *
3288 * @return True if the event population was completed.
3289 */
3290 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3291 return false;
3292 }
3293
3294 /**
3295 * Gets the {@link View} description. It briefly describes the view and is
3296 * primarily used for accessibility support. Set this property to enable
3297 * better accessibility support for your application. This is especially
3298 * true for views that do not have textual representation (For example,
3299 * ImageButton).
3300 *
3301 * @return The content descriptiopn.
3302 *
3303 * @attr ref android.R.styleable#View_contentDescription
3304 */
3305 public CharSequence getContentDescription() {
3306 return mContentDescription;
3307 }
3308
3309 /**
3310 * Sets the {@link View} description. It briefly describes the view and is
3311 * primarily used for accessibility support. Set this property to enable
3312 * better accessibility support for your application. This is especially
3313 * true for views that do not have textual representation (For example,
3314 * ImageButton).
3315 *
3316 * @param contentDescription The content description.
3317 *
3318 * @attr ref android.R.styleable#View_contentDescription
3319 */
3320 public void setContentDescription(CharSequence contentDescription) {
3321 mContentDescription = contentDescription;
3322 }
3323
3324 /**
Romain Guya2431d02009-04-30 16:30:00 -07003325 * Invoked whenever this view loses focus, either by losing window focus or by losing
3326 * focus within its window. This method can be used to clear any state tied to the
3327 * focus. For instance, if a button is held pressed with the trackball and the window
3328 * loses focus, this method can be used to cancel the press.
3329 *
3330 * Subclasses of View overriding this method should always call super.onFocusLost().
3331 *
3332 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003333 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003334 *
3335 * @hide pending API council approval
3336 */
3337 protected void onFocusLost() {
3338 resetPressedState();
3339 }
3340
3341 private void resetPressedState() {
3342 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3343 return;
3344 }
3345
3346 if (isPressed()) {
3347 setPressed(false);
3348
3349 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003350 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003351 }
3352 }
3353 }
3354
3355 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 * Returns true if this view has focus
3357 *
3358 * @return True if this view has focus, false otherwise.
3359 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003360 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 public boolean isFocused() {
3362 return (mPrivateFlags & FOCUSED) != 0;
3363 }
3364
3365 /**
3366 * Find the view in the hierarchy rooted at this view that currently has
3367 * focus.
3368 *
3369 * @return The view that currently has focus, or null if no focused view can
3370 * be found.
3371 */
3372 public View findFocus() {
3373 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3374 }
3375
3376 /**
3377 * Change whether this view is one of the set of scrollable containers in
3378 * its window. This will be used to determine whether the window can
3379 * resize or must pan when a soft input area is open -- scrollable
3380 * containers allow the window to use resize mode since the container
3381 * will appropriately shrink.
3382 */
3383 public void setScrollContainer(boolean isScrollContainer) {
3384 if (isScrollContainer) {
3385 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3386 mAttachInfo.mScrollContainers.add(this);
3387 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3388 }
3389 mPrivateFlags |= SCROLL_CONTAINER;
3390 } else {
3391 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3392 mAttachInfo.mScrollContainers.remove(this);
3393 }
3394 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3395 }
3396 }
3397
3398 /**
3399 * Returns the quality of the drawing cache.
3400 *
3401 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3402 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3403 *
3404 * @see #setDrawingCacheQuality(int)
3405 * @see #setDrawingCacheEnabled(boolean)
3406 * @see #isDrawingCacheEnabled()
3407 *
3408 * @attr ref android.R.styleable#View_drawingCacheQuality
3409 */
3410 public int getDrawingCacheQuality() {
3411 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3412 }
3413
3414 /**
3415 * Set the drawing cache quality of this view. This value is used only when the
3416 * drawing cache is enabled
3417 *
3418 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3419 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3420 *
3421 * @see #getDrawingCacheQuality()
3422 * @see #setDrawingCacheEnabled(boolean)
3423 * @see #isDrawingCacheEnabled()
3424 *
3425 * @attr ref android.R.styleable#View_drawingCacheQuality
3426 */
3427 public void setDrawingCacheQuality(int quality) {
3428 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3429 }
3430
3431 /**
3432 * Returns whether the screen should remain on, corresponding to the current
3433 * value of {@link #KEEP_SCREEN_ON}.
3434 *
3435 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3436 *
3437 * @see #setKeepScreenOn(boolean)
3438 *
3439 * @attr ref android.R.styleable#View_keepScreenOn
3440 */
3441 public boolean getKeepScreenOn() {
3442 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3443 }
3444
3445 /**
3446 * Controls whether the screen should remain on, modifying the
3447 * value of {@link #KEEP_SCREEN_ON}.
3448 *
3449 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3450 *
3451 * @see #getKeepScreenOn()
3452 *
3453 * @attr ref android.R.styleable#View_keepScreenOn
3454 */
3455 public void setKeepScreenOn(boolean keepScreenOn) {
3456 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3457 }
3458
3459 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003460 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3461 * @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 -08003462 *
3463 * @attr ref android.R.styleable#View_nextFocusLeft
3464 */
3465 public int getNextFocusLeftId() {
3466 return mNextFocusLeftId;
3467 }
3468
3469 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003470 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3471 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
3472 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 *
3474 * @attr ref android.R.styleable#View_nextFocusLeft
3475 */
3476 public void setNextFocusLeftId(int nextFocusLeftId) {
3477 mNextFocusLeftId = nextFocusLeftId;
3478 }
3479
3480 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003481 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3482 * @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 -08003483 *
3484 * @attr ref android.R.styleable#View_nextFocusRight
3485 */
3486 public int getNextFocusRightId() {
3487 return mNextFocusRightId;
3488 }
3489
3490 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003491 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3492 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
3493 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 *
3495 * @attr ref android.R.styleable#View_nextFocusRight
3496 */
3497 public void setNextFocusRightId(int nextFocusRightId) {
3498 mNextFocusRightId = nextFocusRightId;
3499 }
3500
3501 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003502 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3503 * @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 -08003504 *
3505 * @attr ref android.R.styleable#View_nextFocusUp
3506 */
3507 public int getNextFocusUpId() {
3508 return mNextFocusUpId;
3509 }
3510
3511 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003512 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3513 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
3514 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 *
3516 * @attr ref android.R.styleable#View_nextFocusUp
3517 */
3518 public void setNextFocusUpId(int nextFocusUpId) {
3519 mNextFocusUpId = nextFocusUpId;
3520 }
3521
3522 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003523 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3524 * @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 -08003525 *
3526 * @attr ref android.R.styleable#View_nextFocusDown
3527 */
3528 public int getNextFocusDownId() {
3529 return mNextFocusDownId;
3530 }
3531
3532 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003533 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3534 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
3535 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536 *
3537 * @attr ref android.R.styleable#View_nextFocusDown
3538 */
3539 public void setNextFocusDownId(int nextFocusDownId) {
3540 mNextFocusDownId = nextFocusDownId;
3541 }
3542
3543 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003544 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3545 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3546 *
3547 * @attr ref android.R.styleable#View_nextFocusForward
3548 */
3549 public int getNextFocusForwardId() {
3550 return mNextFocusForwardId;
3551 }
3552
3553 /**
3554 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3555 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
3556 * decide automatically.
3557 *
3558 * @attr ref android.R.styleable#View_nextFocusForward
3559 */
3560 public void setNextFocusForwardId(int nextFocusForwardId) {
3561 mNextFocusForwardId = nextFocusForwardId;
3562 }
3563
3564 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003565 * Returns the visibility of this view and all of its ancestors
3566 *
3567 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3568 */
3569 public boolean isShown() {
3570 View current = this;
3571 //noinspection ConstantConditions
3572 do {
3573 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3574 return false;
3575 }
3576 ViewParent parent = current.mParent;
3577 if (parent == null) {
3578 return false; // We are not attached to the view root
3579 }
3580 if (!(parent instanceof View)) {
3581 return true;
3582 }
3583 current = (View) parent;
3584 } while (current != null);
3585
3586 return false;
3587 }
3588
3589 /**
3590 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3591 * is set
3592 *
3593 * @param insets Insets for system windows
3594 *
3595 * @return True if this view applied the insets, false otherwise
3596 */
3597 protected boolean fitSystemWindows(Rect insets) {
3598 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3599 mPaddingLeft = insets.left;
3600 mPaddingTop = insets.top;
3601 mPaddingRight = insets.right;
3602 mPaddingBottom = insets.bottom;
3603 requestLayout();
3604 return true;
3605 }
3606 return false;
3607 }
3608
3609 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003610 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3611 * @return True if window has FITS_SYSTEM_WINDOWS set
3612 *
3613 * @hide
3614 */
3615 public boolean isFitsSystemWindowsFlagSet() {
3616 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3617 }
3618
3619 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 * Returns the visibility status for this view.
3621 *
3622 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3623 * @attr ref android.R.styleable#View_visibility
3624 */
3625 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003626 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3627 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3628 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 })
3630 public int getVisibility() {
3631 return mViewFlags & VISIBILITY_MASK;
3632 }
3633
3634 /**
3635 * Set the enabled state of this view.
3636 *
3637 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3638 * @attr ref android.R.styleable#View_visibility
3639 */
3640 @RemotableViewMethod
3641 public void setVisibility(int visibility) {
3642 setFlags(visibility, VISIBILITY_MASK);
3643 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3644 }
3645
3646 /**
3647 * Returns the enabled status for this view. The interpretation of the
3648 * enabled state varies by subclass.
3649 *
3650 * @return True if this view is enabled, false otherwise.
3651 */
3652 @ViewDebug.ExportedProperty
3653 public boolean isEnabled() {
3654 return (mViewFlags & ENABLED_MASK) == ENABLED;
3655 }
3656
3657 /**
3658 * Set the enabled state of this view. The interpretation of the enabled
3659 * state varies by subclass.
3660 *
3661 * @param enabled True if this view is enabled, false otherwise.
3662 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003663 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003665 if (enabled == isEnabled()) return;
3666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3668
3669 /*
3670 * The View most likely has to change its appearance, so refresh
3671 * the drawable state.
3672 */
3673 refreshDrawableState();
3674
3675 // Invalidate too, since the default behavior for views is to be
3676 // be drawn at 50% alpha rather than to change the drawable.
3677 invalidate();
3678 }
3679
3680 /**
3681 * Set whether this view can receive the focus.
3682 *
3683 * Setting this to false will also ensure that this view is not focusable
3684 * in touch mode.
3685 *
3686 * @param focusable If true, this view can receive the focus.
3687 *
3688 * @see #setFocusableInTouchMode(boolean)
3689 * @attr ref android.R.styleable#View_focusable
3690 */
3691 public void setFocusable(boolean focusable) {
3692 if (!focusable) {
3693 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3694 }
3695 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3696 }
3697
3698 /**
3699 * Set whether this view can receive focus while in touch mode.
3700 *
3701 * Setting this to true will also ensure that this view is focusable.
3702 *
3703 * @param focusableInTouchMode If true, this view can receive the focus while
3704 * in touch mode.
3705 *
3706 * @see #setFocusable(boolean)
3707 * @attr ref android.R.styleable#View_focusableInTouchMode
3708 */
3709 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3710 // Focusable in touch mode should always be set before the focusable flag
3711 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3712 // which, in touch mode, will not successfully request focus on this view
3713 // because the focusable in touch mode flag is not set
3714 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3715 if (focusableInTouchMode) {
3716 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3717 }
3718 }
3719
3720 /**
3721 * Set whether this view should have sound effects enabled for events such as
3722 * clicking and touching.
3723 *
3724 * <p>You may wish to disable sound effects for a view if you already play sounds,
3725 * for instance, a dial key that plays dtmf tones.
3726 *
3727 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3728 * @see #isSoundEffectsEnabled()
3729 * @see #playSoundEffect(int)
3730 * @attr ref android.R.styleable#View_soundEffectsEnabled
3731 */
3732 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3733 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3734 }
3735
3736 /**
3737 * @return whether this view should have sound effects enabled for events such as
3738 * clicking and touching.
3739 *
3740 * @see #setSoundEffectsEnabled(boolean)
3741 * @see #playSoundEffect(int)
3742 * @attr ref android.R.styleable#View_soundEffectsEnabled
3743 */
3744 @ViewDebug.ExportedProperty
3745 public boolean isSoundEffectsEnabled() {
3746 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3747 }
3748
3749 /**
3750 * Set whether this view should have haptic feedback for events such as
3751 * long presses.
3752 *
3753 * <p>You may wish to disable haptic feedback if your view already controls
3754 * its own haptic feedback.
3755 *
3756 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3757 * @see #isHapticFeedbackEnabled()
3758 * @see #performHapticFeedback(int)
3759 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3760 */
3761 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3762 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3763 }
3764
3765 /**
3766 * @return whether this view should have haptic feedback enabled for events
3767 * long presses.
3768 *
3769 * @see #setHapticFeedbackEnabled(boolean)
3770 * @see #performHapticFeedback(int)
3771 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3772 */
3773 @ViewDebug.ExportedProperty
3774 public boolean isHapticFeedbackEnabled() {
3775 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3776 }
3777
3778 /**
3779 * If this view doesn't do any drawing on its own, set this flag to
3780 * allow further optimizations. By default, this flag is not set on
3781 * View, but could be set on some View subclasses such as ViewGroup.
3782 *
3783 * Typically, if you override {@link #onDraw} you should clear this flag.
3784 *
3785 * @param willNotDraw whether or not this View draw on its own
3786 */
3787 public void setWillNotDraw(boolean willNotDraw) {
3788 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3789 }
3790
3791 /**
3792 * Returns whether or not this View draws on its own.
3793 *
3794 * @return true if this view has nothing to draw, false otherwise
3795 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003796 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797 public boolean willNotDraw() {
3798 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3799 }
3800
3801 /**
3802 * When a View's drawing cache is enabled, drawing is redirected to an
3803 * offscreen bitmap. Some views, like an ImageView, must be able to
3804 * bypass this mechanism if they already draw a single bitmap, to avoid
3805 * unnecessary usage of the memory.
3806 *
3807 * @param willNotCacheDrawing true if this view does not cache its
3808 * drawing, false otherwise
3809 */
3810 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3811 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3812 }
3813
3814 /**
3815 * Returns whether or not this View can cache its drawing or not.
3816 *
3817 * @return true if this view does not cache its drawing, false otherwise
3818 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003819 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 public boolean willNotCacheDrawing() {
3821 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3822 }
3823
3824 /**
3825 * Indicates whether this view reacts to click events or not.
3826 *
3827 * @return true if the view is clickable, false otherwise
3828 *
3829 * @see #setClickable(boolean)
3830 * @attr ref android.R.styleable#View_clickable
3831 */
3832 @ViewDebug.ExportedProperty
3833 public boolean isClickable() {
3834 return (mViewFlags & CLICKABLE) == CLICKABLE;
3835 }
3836
3837 /**
3838 * Enables or disables click events for this view. When a view
3839 * is clickable it will change its state to "pressed" on every click.
3840 * Subclasses should set the view clickable to visually react to
3841 * user's clicks.
3842 *
3843 * @param clickable true to make the view clickable, false otherwise
3844 *
3845 * @see #isClickable()
3846 * @attr ref android.R.styleable#View_clickable
3847 */
3848 public void setClickable(boolean clickable) {
3849 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3850 }
3851
3852 /**
3853 * Indicates whether this view reacts to long click events or not.
3854 *
3855 * @return true if the view is long clickable, false otherwise
3856 *
3857 * @see #setLongClickable(boolean)
3858 * @attr ref android.R.styleable#View_longClickable
3859 */
3860 public boolean isLongClickable() {
3861 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3862 }
3863
3864 /**
3865 * Enables or disables long click events for this view. When a view is long
3866 * clickable it reacts to the user holding down the button for a longer
3867 * duration than a tap. This event can either launch the listener or a
3868 * context menu.
3869 *
3870 * @param longClickable true to make the view long clickable, false otherwise
3871 * @see #isLongClickable()
3872 * @attr ref android.R.styleable#View_longClickable
3873 */
3874 public void setLongClickable(boolean longClickable) {
3875 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3876 }
3877
3878 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003879 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 *
3881 * @see #isClickable()
3882 * @see #setClickable(boolean)
3883 *
3884 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3885 * the View's internal state from a previously set "pressed" state.
3886 */
3887 public void setPressed(boolean pressed) {
3888 if (pressed) {
3889 mPrivateFlags |= PRESSED;
3890 } else {
3891 mPrivateFlags &= ~PRESSED;
3892 }
3893 refreshDrawableState();
3894 dispatchSetPressed(pressed);
3895 }
3896
3897 /**
3898 * Dispatch setPressed to all of this View's children.
3899 *
3900 * @see #setPressed(boolean)
3901 *
3902 * @param pressed The new pressed state
3903 */
3904 protected void dispatchSetPressed(boolean pressed) {
3905 }
3906
3907 /**
3908 * Indicates whether the view is currently in pressed state. Unless
3909 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3910 * the pressed state.
3911 *
3912 * @see #setPressed
3913 * @see #isClickable()
3914 * @see #setClickable(boolean)
3915 *
3916 * @return true if the view is currently pressed, false otherwise
3917 */
3918 public boolean isPressed() {
3919 return (mPrivateFlags & PRESSED) == PRESSED;
3920 }
3921
3922 /**
3923 * Indicates whether this view will save its state (that is,
3924 * whether its {@link #onSaveInstanceState} method will be called).
3925 *
3926 * @return Returns true if the view state saving is enabled, else false.
3927 *
3928 * @see #setSaveEnabled(boolean)
3929 * @attr ref android.R.styleable#View_saveEnabled
3930 */
3931 public boolean isSaveEnabled() {
3932 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3933 }
3934
3935 /**
3936 * Controls whether the saving of this view's state is
3937 * enabled (that is, whether its {@link #onSaveInstanceState} method
3938 * will be called). Note that even if freezing is enabled, the
3939 * view still must have an id assigned to it (via {@link #setId setId()})
3940 * for its state to be saved. This flag can only disable the
3941 * saving of this view; any child views may still have their state saved.
3942 *
3943 * @param enabled Set to false to <em>disable</em> state saving, or true
3944 * (the default) to allow it.
3945 *
3946 * @see #isSaveEnabled()
3947 * @see #setId(int)
3948 * @see #onSaveInstanceState()
3949 * @attr ref android.R.styleable#View_saveEnabled
3950 */
3951 public void setSaveEnabled(boolean enabled) {
3952 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3953 }
3954
Jeff Brown85a31762010-09-01 17:01:00 -07003955 /**
3956 * Gets whether the framework should discard touches when the view's
3957 * window is obscured by another visible window.
3958 * Refer to the {@link View} security documentation for more details.
3959 *
3960 * @return True if touch filtering is enabled.
3961 *
3962 * @see #setFilterTouchesWhenObscured(boolean)
3963 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3964 */
3965 @ViewDebug.ExportedProperty
3966 public boolean getFilterTouchesWhenObscured() {
3967 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3968 }
3969
3970 /**
3971 * Sets whether the framework should discard touches when the view's
3972 * window is obscured by another visible window.
3973 * Refer to the {@link View} security documentation for more details.
3974 *
3975 * @param enabled True if touch filtering should be enabled.
3976 *
3977 * @see #getFilterTouchesWhenObscured
3978 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3979 */
3980 public void setFilterTouchesWhenObscured(boolean enabled) {
3981 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3982 FILTER_TOUCHES_WHEN_OBSCURED);
3983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984
3985 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003986 * Indicates whether the entire hierarchy under this view will save its
3987 * state when a state saving traversal occurs from its parent. The default
3988 * is true; if false, these views will not be saved unless
3989 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3990 *
3991 * @return Returns true if the view state saving from parent is enabled, else false.
3992 *
3993 * @see #setSaveFromParentEnabled(boolean)
3994 */
3995 public boolean isSaveFromParentEnabled() {
3996 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3997 }
3998
3999 /**
4000 * Controls whether the entire hierarchy under this view will save its
4001 * state when a state saving traversal occurs from its parent. The default
4002 * is true; if false, these views will not be saved unless
4003 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4004 *
4005 * @param enabled Set to false to <em>disable</em> state saving, or true
4006 * (the default) to allow it.
4007 *
4008 * @see #isSaveFromParentEnabled()
4009 * @see #setId(int)
4010 * @see #onSaveInstanceState()
4011 */
4012 public void setSaveFromParentEnabled(boolean enabled) {
4013 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4014 }
4015
4016
4017 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 * Returns whether this View is able to take focus.
4019 *
4020 * @return True if this view can take focus, or false otherwise.
4021 * @attr ref android.R.styleable#View_focusable
4022 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004023 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 public final boolean isFocusable() {
4025 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4026 }
4027
4028 /**
4029 * When a view is focusable, it may not want to take focus when in touch mode.
4030 * For example, a button would like focus when the user is navigating via a D-pad
4031 * so that the user can click on it, but once the user starts touching the screen,
4032 * the button shouldn't take focus
4033 * @return Whether the view is focusable in touch mode.
4034 * @attr ref android.R.styleable#View_focusableInTouchMode
4035 */
4036 @ViewDebug.ExportedProperty
4037 public final boolean isFocusableInTouchMode() {
4038 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4039 }
4040
4041 /**
4042 * Find the nearest view in the specified direction that can take focus.
4043 * This does not actually give focus to that view.
4044 *
4045 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4046 *
4047 * @return The nearest focusable in the specified direction, or null if none
4048 * can be found.
4049 */
4050 public View focusSearch(int direction) {
4051 if (mParent != null) {
4052 return mParent.focusSearch(this, direction);
4053 } else {
4054 return null;
4055 }
4056 }
4057
4058 /**
4059 * This method is the last chance for the focused view and its ancestors to
4060 * respond to an arrow key. This is called when the focused view did not
4061 * consume the key internally, nor could the view system find a new view in
4062 * the requested direction to give focus to.
4063 *
4064 * @param focused The currently focused view.
4065 * @param direction The direction focus wants to move. One of FOCUS_UP,
4066 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4067 * @return True if the this view consumed this unhandled move.
4068 */
4069 public boolean dispatchUnhandledMove(View focused, int direction) {
4070 return false;
4071 }
4072
4073 /**
4074 * If a user manually specified the next view id for a particular direction,
Jeff Brown4e6319b2010-12-13 10:36:51 -08004075 * use the root to look up the view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004076 * @param root The root view of the hierarchy containing this view.
Jeff Brown4e6319b2010-12-13 10:36:51 -08004077 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4078 * or FOCUS_BACKWARD.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079 * @return The user specified next view, or null if there is none.
4080 */
4081 View findUserSetNextFocus(View root, int direction) {
4082 switch (direction) {
4083 case FOCUS_LEFT:
4084 if (mNextFocusLeftId == View.NO_ID) return null;
4085 return findViewShouldExist(root, mNextFocusLeftId);
4086 case FOCUS_RIGHT:
4087 if (mNextFocusRightId == View.NO_ID) return null;
4088 return findViewShouldExist(root, mNextFocusRightId);
4089 case FOCUS_UP:
4090 if (mNextFocusUpId == View.NO_ID) return null;
4091 return findViewShouldExist(root, mNextFocusUpId);
4092 case FOCUS_DOWN:
4093 if (mNextFocusDownId == View.NO_ID) return null;
4094 return findViewShouldExist(root, mNextFocusDownId);
Jeff Brown4e6319b2010-12-13 10:36:51 -08004095 case FOCUS_FORWARD:
4096 if (mNextFocusForwardId == View.NO_ID) return null;
4097 return findViewShouldExist(root, mNextFocusForwardId);
4098 case FOCUS_BACKWARD: {
4099 final int id = mID;
4100 return root.findViewByPredicate(new Predicate<View>() {
4101 @Override
4102 public boolean apply(View t) {
4103 return t.mNextFocusForwardId == id;
4104 }
4105 });
4106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 }
4108 return null;
4109 }
4110
4111 private static View findViewShouldExist(View root, int childViewId) {
4112 View result = root.findViewById(childViewId);
4113 if (result == null) {
4114 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4115 + "by user for id " + childViewId);
4116 }
4117 return result;
4118 }
4119
4120 /**
4121 * Find and return all focusable views that are descendants of this view,
4122 * possibly including this view if it is focusable itself.
4123 *
4124 * @param direction The direction of the focus
4125 * @return A list of focusable views
4126 */
4127 public ArrayList<View> getFocusables(int direction) {
4128 ArrayList<View> result = new ArrayList<View>(24);
4129 addFocusables(result, direction);
4130 return result;
4131 }
4132
4133 /**
4134 * Add any focusable views that are descendants of this view (possibly
4135 * including this view if it is focusable itself) to views. If we are in touch mode,
4136 * only add views that are also focusable in touch mode.
4137 *
4138 * @param views Focusable views found so far
4139 * @param direction The direction of the focus
4140 */
4141 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07004142 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144
svetoslavganov75986cf2009-05-14 22:28:01 -07004145 /**
4146 * Adds any focusable views that are descendants of this view (possibly
4147 * including this view if it is focusable itself) to views. This method
4148 * adds all focusable views regardless if we are in touch mode or
4149 * only views focusable in touch mode if we are in touch mode depending on
4150 * the focusable mode paramater.
4151 *
4152 * @param views Focusable views found so far or null if all we are interested is
4153 * the number of focusables.
4154 * @param direction The direction of the focus.
4155 * @param focusableMode The type of focusables to be added.
4156 *
4157 * @see #FOCUSABLES_ALL
4158 * @see #FOCUSABLES_TOUCH_MODE
4159 */
4160 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4161 if (!isFocusable()) {
4162 return;
4163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164
svetoslavganov75986cf2009-05-14 22:28:01 -07004165 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4166 isInTouchMode() && !isFocusableInTouchMode()) {
4167 return;
4168 }
4169
4170 if (views != null) {
4171 views.add(this);
4172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004173 }
4174
4175 /**
4176 * Find and return all touchable views that are descendants of this view,
4177 * possibly including this view if it is touchable itself.
4178 *
4179 * @return A list of touchable views
4180 */
4181 public ArrayList<View> getTouchables() {
4182 ArrayList<View> result = new ArrayList<View>();
4183 addTouchables(result);
4184 return result;
4185 }
4186
4187 /**
4188 * Add any touchable views that are descendants of this view (possibly
4189 * including this view if it is touchable itself) to views.
4190 *
4191 * @param views Touchable views found so far
4192 */
4193 public void addTouchables(ArrayList<View> views) {
4194 final int viewFlags = mViewFlags;
4195
4196 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4197 && (viewFlags & ENABLED_MASK) == ENABLED) {
4198 views.add(this);
4199 }
4200 }
4201
4202 /**
4203 * Call this to try to give focus to a specific view or to one of its
4204 * descendants.
4205 *
4206 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4207 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4208 * while the device is in touch mode.
4209 *
4210 * See also {@link #focusSearch}, which is what you call to say that you
4211 * have focus, and you want your parent to look for the next one.
4212 *
4213 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4214 * {@link #FOCUS_DOWN} and <code>null</code>.
4215 *
4216 * @return Whether this view or one of its descendants actually took focus.
4217 */
4218 public final boolean requestFocus() {
4219 return requestFocus(View.FOCUS_DOWN);
4220 }
4221
4222
4223 /**
4224 * Call this to try to give focus to a specific view or to one of its
4225 * descendants and give it a hint about what direction focus is heading.
4226 *
4227 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4228 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4229 * while the device is in touch mode.
4230 *
4231 * See also {@link #focusSearch}, which is what you call to say that you
4232 * have focus, and you want your parent to look for the next one.
4233 *
4234 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4235 * <code>null</code> set for the previously focused rectangle.
4236 *
4237 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4238 * @return Whether this view or one of its descendants actually took focus.
4239 */
4240 public final boolean requestFocus(int direction) {
4241 return requestFocus(direction, null);
4242 }
4243
4244 /**
4245 * Call this to try to give focus to a specific view or to one of its descendants
4246 * and give it hints about the direction and a specific rectangle that the focus
4247 * is coming from. The rectangle can help give larger views a finer grained hint
4248 * about where focus is coming from, and therefore, where to show selection, or
4249 * forward focus change internally.
4250 *
4251 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4252 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4253 * while the device is in touch mode.
4254 *
4255 * A View will not take focus if it is not visible.
4256 *
4257 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4258 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4259 *
4260 * See also {@link #focusSearch}, which is what you call to say that you
4261 * have focus, and you want your parent to look for the next one.
4262 *
4263 * You may wish to override this method if your custom {@link View} has an internal
4264 * {@link View} that it wishes to forward the request to.
4265 *
4266 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4267 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4268 * to give a finer grained hint about where focus is coming from. May be null
4269 * if there is no hint.
4270 * @return Whether this view or one of its descendants actually took focus.
4271 */
4272 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4273 // need to be focusable
4274 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4275 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4276 return false;
4277 }
4278
4279 // need to be focusable in touch mode if in touch mode
4280 if (isInTouchMode() &&
4281 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4282 return false;
4283 }
4284
4285 // need to not have any parents blocking us
4286 if (hasAncestorThatBlocksDescendantFocus()) {
4287 return false;
4288 }
4289
4290 handleFocusGainInternal(direction, previouslyFocusedRect);
4291 return true;
4292 }
4293
Christopher Tate2c095f32010-10-04 14:13:40 -07004294 /** Gets the ViewRoot, or null if not attached. */
4295 /*package*/ ViewRoot getViewRoot() {
4296 View root = getRootView();
4297 return root != null ? (ViewRoot)root.getParent() : null;
4298 }
4299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 /**
4301 * Call this to try to give focus to a specific view or to one of its descendants. This is a
4302 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4303 * touch mode to request focus when they are touched.
4304 *
4305 * @return Whether this view or one of its descendants actually took focus.
4306 *
4307 * @see #isInTouchMode()
4308 *
4309 */
4310 public final boolean requestFocusFromTouch() {
4311 // Leave touch mode if we need to
4312 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07004313 ViewRoot viewRoot = getViewRoot();
4314 if (viewRoot != null) {
4315 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 }
4317 }
4318 return requestFocus(View.FOCUS_DOWN);
4319 }
4320
4321 /**
4322 * @return Whether any ancestor of this view blocks descendant focus.
4323 */
4324 private boolean hasAncestorThatBlocksDescendantFocus() {
4325 ViewParent ancestor = mParent;
4326 while (ancestor instanceof ViewGroup) {
4327 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4328 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4329 return true;
4330 } else {
4331 ancestor = vgAncestor.getParent();
4332 }
4333 }
4334 return false;
4335 }
4336
4337 /**
Romain Guya440b002010-02-24 15:57:54 -08004338 * @hide
4339 */
4340 public void dispatchStartTemporaryDetach() {
4341 onStartTemporaryDetach();
4342 }
4343
4344 /**
4345 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004346 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4347 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004348 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 */
4350 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004351 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004352 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004353 }
4354
4355 /**
4356 * @hide
4357 */
4358 public void dispatchFinishTemporaryDetach() {
4359 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 }
Romain Guy8506ab42009-06-11 17:35:47 -07004361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 /**
4363 * Called after {@link #onStartTemporaryDetach} when the container is done
4364 * changing the view.
4365 */
4366 public void onFinishTemporaryDetach() {
4367 }
Romain Guy8506ab42009-06-11 17:35:47 -07004368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 /**
4370 * capture information of this view for later analysis: developement only
4371 * check dynamic switch to make sure we only dump view
4372 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4373 */
4374 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004375 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376 return;
4377 }
4378 ViewDebug.dumpCapturedView(subTag, v);
4379 }
4380
4381 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004382 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4383 * for this view's window. Returns null if the view is not currently attached
4384 * to the window. Normally you will not need to use this directly, but
4385 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4386 */
4387 public KeyEvent.DispatcherState getKeyDispatcherState() {
4388 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4389 }
4390
4391 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 * Dispatch a key event before it is processed by any input method
4393 * associated with the view hierarchy. This can be used to intercept
4394 * key events in special situations before the IME consumes them; a
4395 * typical example would be handling the BACK key to update the application's
4396 * UI instead of allowing the IME to see it and close itself.
4397 *
4398 * @param event The key event to be dispatched.
4399 * @return True if the event was handled, false otherwise.
4400 */
4401 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4402 return onKeyPreIme(event.getKeyCode(), event);
4403 }
4404
4405 /**
4406 * Dispatch a key event to the next view on the focus path. This path runs
4407 * from the top of the view tree down to the currently focused view. If this
4408 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4409 * the next node down the focus path. This method also fires any key
4410 * listeners.
4411 *
4412 * @param event The key event to be dispatched.
4413 * @return True if the event was handled, false otherwise.
4414 */
4415 public boolean dispatchKeyEvent(KeyEvent event) {
4416 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004417
Romain Guyf607bdc2010-09-10 19:20:06 -07004418 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419 if (android.util.Config.LOGV) {
4420 captureViewInfo("captureViewKeyEvent", this);
4421 }
4422
Romain Guyf607bdc2010-09-10 19:20:06 -07004423 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004424 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4425 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4426 return true;
4427 }
4428
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004429 return event.dispatch(this, mAttachInfo != null
4430 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004431 }
4432
4433 /**
4434 * Dispatches a key shortcut event.
4435 *
4436 * @param event The key event to be dispatched.
4437 * @return True if the event was handled by the view, false otherwise.
4438 */
4439 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4440 return onKeyShortcut(event.getKeyCode(), event);
4441 }
4442
4443 /**
4444 * Pass the touch screen motion event down to the target view, or this
4445 * view if it is the target.
4446 *
4447 * @param event The motion event to be dispatched.
4448 * @return True if the event was handled by the view, false otherwise.
4449 */
4450 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004451 if (!onFilterTouchEventForSecurity(event)) {
4452 return false;
4453 }
4454
Romain Guyf607bdc2010-09-10 19:20:06 -07004455 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4457 mOnTouchListener.onTouch(this, event)) {
4458 return true;
4459 }
4460 return onTouchEvent(event);
4461 }
4462
4463 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004464 * Filter the touch event to apply security policies.
4465 *
4466 * @param event The motion event to be filtered.
4467 * @return True if the event should be dispatched, false if the event should be dropped.
4468 *
4469 * @see #getFilterTouchesWhenObscured
4470 */
4471 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004472 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004473 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4474 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4475 // Window is obscured, drop this touch.
4476 return false;
4477 }
4478 return true;
4479 }
4480
4481 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 * Pass a trackball motion event down to the focused view.
4483 *
4484 * @param event The motion event to be dispatched.
4485 * @return True if the event was handled by the view, false otherwise.
4486 */
4487 public boolean dispatchTrackballEvent(MotionEvent event) {
4488 //Log.i("view", "view=" + this + ", " + event.toString());
4489 return onTrackballEvent(event);
4490 }
4491
4492 /**
4493 * Called when the window containing this view gains or loses window focus.
4494 * ViewGroups should override to route to their children.
4495 *
4496 * @param hasFocus True if the window containing this view now has focus,
4497 * false otherwise.
4498 */
4499 public void dispatchWindowFocusChanged(boolean hasFocus) {
4500 onWindowFocusChanged(hasFocus);
4501 }
4502
4503 /**
4504 * Called when the window containing this view gains or loses focus. Note
4505 * that this is separate from view focus: to receive key events, both
4506 * your view and its window must have focus. If a window is displayed
4507 * on top of yours that takes input focus, then your own window will lose
4508 * focus but the view focus will remain unchanged.
4509 *
4510 * @param hasWindowFocus True if the window containing this view now has
4511 * focus, false otherwise.
4512 */
4513 public void onWindowFocusChanged(boolean hasWindowFocus) {
4514 InputMethodManager imm = InputMethodManager.peekInstance();
4515 if (!hasWindowFocus) {
4516 if (isPressed()) {
4517 setPressed(false);
4518 }
4519 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4520 imm.focusOut(this);
4521 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004522 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004523 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004524 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4526 imm.focusIn(this);
4527 }
4528 refreshDrawableState();
4529 }
4530
4531 /**
4532 * Returns true if this view is in a window that currently has window focus.
4533 * Note that this is not the same as the view itself having focus.
4534 *
4535 * @return True if this view is in a window that currently has window focus.
4536 */
4537 public boolean hasWindowFocus() {
4538 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4539 }
4540
4541 /**
Adam Powell326d8082009-12-09 15:10:07 -08004542 * Dispatch a view visibility change down the view hierarchy.
4543 * ViewGroups should override to route to their children.
4544 * @param changedView The view whose visibility changed. Could be 'this' or
4545 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004546 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4547 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004548 */
4549 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4550 onVisibilityChanged(changedView, visibility);
4551 }
4552
4553 /**
4554 * Called when the visibility of the view or an ancestor of the view is changed.
4555 * @param changedView The view whose visibility changed. Could be 'this' or
4556 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004557 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4558 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004559 */
4560 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004561 if (visibility == VISIBLE) {
4562 if (mAttachInfo != null) {
4563 initialAwakenScrollBars();
4564 } else {
4565 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4566 }
4567 }
Adam Powell326d8082009-12-09 15:10:07 -08004568 }
4569
4570 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004571 * Dispatch a hint about whether this view is displayed. For instance, when
4572 * a View moves out of the screen, it might receives a display hint indicating
4573 * the view is not displayed. Applications should not <em>rely</em> on this hint
4574 * as there is no guarantee that they will receive one.
4575 *
4576 * @param hint A hint about whether or not this view is displayed:
4577 * {@link #VISIBLE} or {@link #INVISIBLE}.
4578 */
4579 public void dispatchDisplayHint(int hint) {
4580 onDisplayHint(hint);
4581 }
4582
4583 /**
4584 * Gives this view a hint about whether is displayed or not. For instance, when
4585 * a View moves out of the screen, it might receives a display hint indicating
4586 * the view is not displayed. Applications should not <em>rely</em> on this hint
4587 * as there is no guarantee that they will receive one.
4588 *
4589 * @param hint A hint about whether or not this view is displayed:
4590 * {@link #VISIBLE} or {@link #INVISIBLE}.
4591 */
4592 protected void onDisplayHint(int hint) {
4593 }
4594
4595 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 * Dispatch a window visibility change down the view hierarchy.
4597 * ViewGroups should override to route to their children.
4598 *
4599 * @param visibility The new visibility of the window.
4600 *
4601 * @see #onWindowVisibilityChanged
4602 */
4603 public void dispatchWindowVisibilityChanged(int visibility) {
4604 onWindowVisibilityChanged(visibility);
4605 }
4606
4607 /**
4608 * Called when the window containing has change its visibility
4609 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4610 * that this tells you whether or not your window is being made visible
4611 * to the window manager; this does <em>not</em> tell you whether or not
4612 * your window is obscured by other windows on the screen, even if it
4613 * is itself visible.
4614 *
4615 * @param visibility The new visibility of the window.
4616 */
4617 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004618 if (visibility == VISIBLE) {
4619 initialAwakenScrollBars();
4620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 }
4622
4623 /**
4624 * Returns the current visibility of the window this view is attached to
4625 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4626 *
4627 * @return Returns the current visibility of the view's window.
4628 */
4629 public int getWindowVisibility() {
4630 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4631 }
4632
4633 /**
4634 * Retrieve the overall visible display size in which the window this view is
4635 * attached to has been positioned in. This takes into account screen
4636 * decorations above the window, for both cases where the window itself
4637 * is being position inside of them or the window is being placed under
4638 * then and covered insets are used for the window to position its content
4639 * inside. In effect, this tells you the available area where content can
4640 * be placed and remain visible to users.
4641 *
4642 * <p>This function requires an IPC back to the window manager to retrieve
4643 * the requested information, so should not be used in performance critical
4644 * code like drawing.
4645 *
4646 * @param outRect Filled in with the visible display frame. If the view
4647 * is not attached to a window, this is simply the raw display size.
4648 */
4649 public void getWindowVisibleDisplayFrame(Rect outRect) {
4650 if (mAttachInfo != null) {
4651 try {
4652 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4653 } catch (RemoteException e) {
4654 return;
4655 }
4656 // XXX This is really broken, and probably all needs to be done
4657 // in the window manager, and we need to know more about whether
4658 // we want the area behind or in front of the IME.
4659 final Rect insets = mAttachInfo.mVisibleInsets;
4660 outRect.left += insets.left;
4661 outRect.top += insets.top;
4662 outRect.right -= insets.right;
4663 outRect.bottom -= insets.bottom;
4664 return;
4665 }
4666 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4667 outRect.set(0, 0, d.getWidth(), d.getHeight());
4668 }
4669
4670 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004671 * Dispatch a notification about a resource configuration change down
4672 * the view hierarchy.
4673 * ViewGroups should override to route to their children.
4674 *
4675 * @param newConfig The new resource configuration.
4676 *
4677 * @see #onConfigurationChanged
4678 */
4679 public void dispatchConfigurationChanged(Configuration newConfig) {
4680 onConfigurationChanged(newConfig);
4681 }
4682
4683 /**
4684 * Called when the current configuration of the resources being used
4685 * by the application have changed. You can use this to decide when
4686 * to reload resources that can changed based on orientation and other
4687 * configuration characterstics. You only need to use this if you are
4688 * not relying on the normal {@link android.app.Activity} mechanism of
4689 * recreating the activity instance upon a configuration change.
4690 *
4691 * @param newConfig The new resource configuration.
4692 */
4693 protected void onConfigurationChanged(Configuration newConfig) {
4694 }
4695
4696 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004697 * Private function to aggregate all per-view attributes in to the view
4698 * root.
4699 */
4700 void dispatchCollectViewAttributes(int visibility) {
4701 performCollectViewAttributes(visibility);
4702 }
4703
4704 void performCollectViewAttributes(int visibility) {
4705 //noinspection PointlessBitwiseExpression
4706 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4707 == (VISIBLE | KEEP_SCREEN_ON)) {
4708 mAttachInfo.mKeepScreenOn = true;
4709 }
4710 }
4711
4712 void needGlobalAttributesUpdate(boolean force) {
4713 AttachInfo ai = mAttachInfo;
4714 if (ai != null) {
4715 if (ai.mKeepScreenOn || force) {
4716 ai.mRecomputeGlobalAttributes = true;
4717 }
4718 }
4719 }
4720
4721 /**
4722 * Returns whether the device is currently in touch mode. Touch mode is entered
4723 * once the user begins interacting with the device by touch, and affects various
4724 * things like whether focus is always visible to the user.
4725 *
4726 * @return Whether the device is in touch mode.
4727 */
4728 @ViewDebug.ExportedProperty
4729 public boolean isInTouchMode() {
4730 if (mAttachInfo != null) {
4731 return mAttachInfo.mInTouchMode;
4732 } else {
4733 return ViewRoot.isInTouchMode();
4734 }
4735 }
4736
4737 /**
4738 * Returns the context the view is running in, through which it can
4739 * access the current theme, resources, etc.
4740 *
4741 * @return The view's Context.
4742 */
4743 @ViewDebug.CapturedViewProperty
4744 public final Context getContext() {
4745 return mContext;
4746 }
4747
4748 /**
4749 * Handle a key event before it is processed by any input method
4750 * associated with the view hierarchy. This can be used to intercept
4751 * key events in special situations before the IME consumes them; a
4752 * typical example would be handling the BACK key to update the application's
4753 * UI instead of allowing the IME to see it and close itself.
4754 *
4755 * @param keyCode The value in event.getKeyCode().
4756 * @param event Description of the key event.
4757 * @return If you handled the event, return true. If you want to allow the
4758 * event to be handled by the next receiver, return false.
4759 */
4760 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4761 return false;
4762 }
4763
4764 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004765 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
4766 * KeyEvent.Callback.onKeyDown()}: perform press of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004767 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4768 * is released, if the view is enabled and clickable.
4769 *
4770 * @param keyCode A key code that represents the button pressed, from
4771 * {@link android.view.KeyEvent}.
4772 * @param event The KeyEvent object that defines the button action.
4773 */
4774 public boolean onKeyDown(int keyCode, KeyEvent event) {
4775 boolean result = false;
4776
4777 switch (keyCode) {
4778 case KeyEvent.KEYCODE_DPAD_CENTER:
4779 case KeyEvent.KEYCODE_ENTER: {
4780 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4781 return true;
4782 }
4783 // Long clickable items don't necessarily have to be clickable
4784 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4785 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4786 (event.getRepeatCount() == 0)) {
4787 setPressed(true);
4788 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004789 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004790 }
4791 return true;
4792 }
4793 break;
4794 }
4795 }
4796 return result;
4797 }
4798
4799 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004800 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4801 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4802 * the event).
4803 */
4804 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4805 return false;
4806 }
4807
4808 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004809 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
4810 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004811 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4812 * {@link KeyEvent#KEYCODE_ENTER} is released.
4813 *
4814 * @param keyCode A key code that represents the button pressed, from
4815 * {@link android.view.KeyEvent}.
4816 * @param event The KeyEvent object that defines the button action.
4817 */
4818 public boolean onKeyUp(int keyCode, KeyEvent event) {
4819 boolean result = false;
4820
4821 switch (keyCode) {
4822 case KeyEvent.KEYCODE_DPAD_CENTER:
4823 case KeyEvent.KEYCODE_ENTER: {
4824 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4825 return true;
4826 }
4827 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4828 setPressed(false);
4829
4830 if (!mHasPerformedLongPress) {
4831 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004832 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004833
4834 result = performClick();
4835 }
4836 }
4837 break;
4838 }
4839 }
4840 return result;
4841 }
4842
4843 /**
4844 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4845 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4846 * the event).
4847 *
4848 * @param keyCode A key code that represents the button pressed, from
4849 * {@link android.view.KeyEvent}.
4850 * @param repeatCount The number of times the action was made.
4851 * @param event The KeyEvent object that defines the button action.
4852 */
4853 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4854 return false;
4855 }
4856
4857 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08004858 * Called on the focused view when a key shortcut event is not handled.
4859 * Override this method to implement local key shortcuts for the View.
4860 * Key shortcuts can also be implemented by setting the
4861 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004862 *
4863 * @param keyCode The value in event.getKeyCode().
4864 * @param event Description of the key event.
4865 * @return If you handled the event, return true. If you want to allow the
4866 * event to be handled by the next receiver, return false.
4867 */
4868 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4869 return false;
4870 }
4871
4872 /**
4873 * Check whether the called view is a text editor, in which case it
4874 * would make sense to automatically display a soft input window for
4875 * it. Subclasses should override this if they implement
4876 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004877 * a call on that method would return a non-null InputConnection, and
4878 * they are really a first-class editor that the user would normally
4879 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004880 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004881 * <p>The default implementation always returns false. This does
4882 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4883 * will not be called or the user can not otherwise perform edits on your
4884 * view; it is just a hint to the system that this is not the primary
4885 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004886 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004887 * @return Returns true if this view is a text editor, else false.
4888 */
4889 public boolean onCheckIsTextEditor() {
4890 return false;
4891 }
Romain Guy8506ab42009-06-11 17:35:47 -07004892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004893 /**
4894 * Create a new InputConnection for an InputMethod to interact
4895 * with the view. The default implementation returns null, since it doesn't
4896 * support input methods. You can override this to implement such support.
4897 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004898 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004899 * <p>When implementing this, you probably also want to implement
4900 * {@link #onCheckIsTextEditor()} to indicate you will return a
4901 * non-null InputConnection.
4902 *
4903 * @param outAttrs Fill in with attribute information about the connection.
4904 */
4905 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4906 return null;
4907 }
4908
4909 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004910 * Called by the {@link android.view.inputmethod.InputMethodManager}
4911 * when a view who is not the current
4912 * input connection target is trying to make a call on the manager. The
4913 * default implementation returns false; you can override this to return
4914 * true for certain views if you are performing InputConnection proxying
4915 * to them.
4916 * @param view The View that is making the InputMethodManager call.
4917 * @return Return true to allow the call, false to reject.
4918 */
4919 public boolean checkInputConnectionProxy(View view) {
4920 return false;
4921 }
Romain Guy8506ab42009-06-11 17:35:47 -07004922
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004923 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004924 * Show the context menu for this view. It is not safe to hold on to the
4925 * menu after returning from this method.
4926 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004927 * You should normally not overload this method. Overload
4928 * {@link #onCreateContextMenu(ContextMenu)} or define an
4929 * {@link OnCreateContextMenuListener} to add items to the context menu.
4930 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 * @param menu The context menu to populate
4932 */
4933 public void createContextMenu(ContextMenu menu) {
4934 ContextMenuInfo menuInfo = getContextMenuInfo();
4935
4936 // Sets the current menu info so all items added to menu will have
4937 // my extra info set.
4938 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4939
4940 onCreateContextMenu(menu);
4941 if (mOnCreateContextMenuListener != null) {
4942 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4943 }
4944
4945 // Clear the extra information so subsequent items that aren't mine don't
4946 // have my extra info.
4947 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4948
4949 if (mParent != null) {
4950 mParent.createContextMenu(menu);
4951 }
4952 }
4953
4954 /**
4955 * Views should implement this if they have extra information to associate
4956 * with the context menu. The return result is supplied as a parameter to
4957 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4958 * callback.
4959 *
4960 * @return Extra information about the item for which the context menu
4961 * should be shown. This information will vary across different
4962 * subclasses of View.
4963 */
4964 protected ContextMenuInfo getContextMenuInfo() {
4965 return null;
4966 }
4967
4968 /**
4969 * Views should implement this if the view itself is going to add items to
4970 * the context menu.
4971 *
4972 * @param menu the context menu to populate
4973 */
4974 protected void onCreateContextMenu(ContextMenu menu) {
4975 }
4976
4977 /**
4978 * Implement this method to handle trackball motion events. The
4979 * <em>relative</em> movement of the trackball since the last event
4980 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4981 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4982 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4983 * they will often be fractional values, representing the more fine-grained
4984 * movement information available from a trackball).
4985 *
4986 * @param event The motion event.
4987 * @return True if the event was handled, false otherwise.
4988 */
4989 public boolean onTrackballEvent(MotionEvent event) {
4990 return false;
4991 }
4992
4993 /**
4994 * Implement this method to handle touch screen motion events.
4995 *
4996 * @param event The motion event.
4997 * @return True if the event was handled, false otherwise.
4998 */
4999 public boolean onTouchEvent(MotionEvent event) {
5000 final int viewFlags = mViewFlags;
5001
5002 if ((viewFlags & ENABLED_MASK) == DISABLED) {
5003 // A disabled view that is clickable still consumes the touch
5004 // events, it just doesn't respond to them.
5005 return (((viewFlags & CLICKABLE) == CLICKABLE ||
5006 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
5007 }
5008
5009 if (mTouchDelegate != null) {
5010 if (mTouchDelegate.onTouchEvent(event)) {
5011 return true;
5012 }
5013 }
5014
5015 if (((viewFlags & CLICKABLE) == CLICKABLE ||
5016 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
5017 switch (event.getAction()) {
5018 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08005019 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
5020 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005021 // take focus if we don't have it already and we should in
5022 // touch mode.
5023 boolean focusTaken = false;
5024 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
5025 focusTaken = requestFocus();
5026 }
5027
5028 if (!mHasPerformedLongPress) {
5029 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05005030 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031
5032 // Only perform take click actions if we were in the pressed state
5033 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08005034 // Use a Runnable and post this rather than calling
5035 // performClick directly. This lets other visual state
5036 // of the view update before click actions start.
5037 if (mPerformClick == null) {
5038 mPerformClick = new PerformClick();
5039 }
5040 if (!post(mPerformClick)) {
5041 performClick();
5042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005043 }
5044 }
5045
5046 if (mUnsetPressedState == null) {
5047 mUnsetPressedState = new UnsetPressedState();
5048 }
5049
Adam Powelle14579b2009-12-16 18:39:52 -08005050 if (prepressed) {
5051 mPrivateFlags |= PRESSED;
5052 refreshDrawableState();
5053 postDelayed(mUnsetPressedState,
5054 ViewConfiguration.getPressedStateDuration());
5055 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005056 // If the post failed, unpress right now
5057 mUnsetPressedState.run();
5058 }
Adam Powelle14579b2009-12-16 18:39:52 -08005059 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005060 }
5061 break;
5062
5063 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08005064 if (mPendingCheckForTap == null) {
5065 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005066 }
Adam Powelle14579b2009-12-16 18:39:52 -08005067 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08005068 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08005069 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 break;
5071
5072 case MotionEvent.ACTION_CANCEL:
5073 mPrivateFlags &= ~PRESSED;
5074 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08005075 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005076 break;
5077
5078 case MotionEvent.ACTION_MOVE:
5079 final int x = (int) event.getX();
5080 final int y = (int) event.getY();
5081
5082 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07005083 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005084 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08005085 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08005087 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05005088 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089
5090 // Need to switch from pressed to not pressed
5091 mPrivateFlags &= ~PRESSED;
5092 refreshDrawableState();
5093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 }
5095 break;
5096 }
5097 return true;
5098 }
5099
5100 return false;
5101 }
5102
5103 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05005104 * Remove the longpress detection timer.
5105 */
5106 private void removeLongPressCallback() {
5107 if (mPendingCheckForLongPress != null) {
5108 removeCallbacks(mPendingCheckForLongPress);
5109 }
5110 }
Adam Powelle14579b2009-12-16 18:39:52 -08005111
5112 /**
Romain Guya440b002010-02-24 15:57:54 -08005113 * Remove the prepress detection timer.
5114 */
5115 private void removeUnsetPressCallback() {
5116 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
5117 setPressed(false);
5118 removeCallbacks(mUnsetPressedState);
5119 }
5120 }
5121
5122 /**
Adam Powelle14579b2009-12-16 18:39:52 -08005123 * Remove the tap detection timer.
5124 */
5125 private void removeTapCallback() {
5126 if (mPendingCheckForTap != null) {
5127 mPrivateFlags &= ~PREPRESSED;
5128 removeCallbacks(mPendingCheckForTap);
5129 }
5130 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05005131
5132 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005133 * Cancels a pending long press. Your subclass can use this if you
5134 * want the context menu to come up if the user presses and holds
5135 * at the same place, but you don't want it to come up if they press
5136 * and then move around enough to cause scrolling.
5137 */
5138 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05005139 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08005140
5141 /*
5142 * The prepressed state handled by the tap callback is a display
5143 * construct, but the tap callback will post a long press callback
5144 * less its own timeout. Remove it here.
5145 */
5146 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005147 }
5148
5149 /**
5150 * Sets the TouchDelegate for this View.
5151 */
5152 public void setTouchDelegate(TouchDelegate delegate) {
5153 mTouchDelegate = delegate;
5154 }
5155
5156 /**
5157 * Gets the TouchDelegate for this View.
5158 */
5159 public TouchDelegate getTouchDelegate() {
5160 return mTouchDelegate;
5161 }
5162
5163 /**
5164 * Set flags controlling behavior of this view.
5165 *
5166 * @param flags Constant indicating the value which should be set
5167 * @param mask Constant indicating the bit range that should be changed
5168 */
5169 void setFlags(int flags, int mask) {
5170 int old = mViewFlags;
5171 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
5172
5173 int changed = mViewFlags ^ old;
5174 if (changed == 0) {
5175 return;
5176 }
5177 int privateFlags = mPrivateFlags;
5178
5179 /* Check if the FOCUSABLE bit has changed */
5180 if (((changed & FOCUSABLE_MASK) != 0) &&
5181 ((privateFlags & HAS_BOUNDS) !=0)) {
5182 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
5183 && ((privateFlags & FOCUSED) != 0)) {
5184 /* Give up focus if we are no longer focusable */
5185 clearFocus();
5186 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
5187 && ((privateFlags & FOCUSED) == 0)) {
5188 /*
5189 * Tell the view system that we are now available to take focus
5190 * if no one else already has it.
5191 */
5192 if (mParent != null) mParent.focusableViewAvailable(this);
5193 }
5194 }
5195
5196 if ((flags & VISIBILITY_MASK) == VISIBLE) {
5197 if ((changed & VISIBILITY_MASK) != 0) {
5198 /*
5199 * If this view is becoming visible, set the DRAWN flag so that
5200 * the next invalidate() will not be skipped.
5201 */
5202 mPrivateFlags |= DRAWN;
5203
5204 needGlobalAttributesUpdate(true);
5205
5206 // a view becoming visible is worth notifying the parent
5207 // about in case nothing has focus. even if this specific view
5208 // isn't focusable, it may contain something that is, so let
5209 // the root view try to give this focus if nothing else does.
5210 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
5211 mParent.focusableViewAvailable(this);
5212 }
5213 }
5214 }
5215
5216 /* Check if the GONE bit has changed */
5217 if ((changed & GONE) != 0) {
5218 needGlobalAttributesUpdate(false);
5219 requestLayout();
5220 invalidate();
5221
Romain Guyecd80ee2009-12-03 17:13:02 -08005222 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5223 if (hasFocus()) clearFocus();
5224 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 }
5226 if (mAttachInfo != null) {
5227 mAttachInfo.mViewVisibilityChanged = true;
5228 }
5229 }
5230
5231 /* Check if the VISIBLE bit has changed */
5232 if ((changed & INVISIBLE) != 0) {
5233 needGlobalAttributesUpdate(false);
5234 invalidate();
5235
5236 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5237 // root view becoming invisible shouldn't clear focus
5238 if (getRootView() != this) {
5239 clearFocus();
5240 }
5241 }
5242 if (mAttachInfo != null) {
5243 mAttachInfo.mViewVisibilityChanged = true;
5244 }
5245 }
5246
Adam Powell326d8082009-12-09 15:10:07 -08005247 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07005248 if (mParent instanceof ViewGroup) {
5249 ((ViewGroup)mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
5250 }
Adam Powell326d8082009-12-09 15:10:07 -08005251 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5252 }
5253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005254 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5255 destroyDrawingCache();
5256 }
5257
5258 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5259 destroyDrawingCache();
5260 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5261 }
5262
5263 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5264 destroyDrawingCache();
5265 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5266 }
5267
5268 if ((changed & DRAW_MASK) != 0) {
5269 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5270 if (mBGDrawable != null) {
5271 mPrivateFlags &= ~SKIP_DRAW;
5272 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5273 } else {
5274 mPrivateFlags |= SKIP_DRAW;
5275 }
5276 } else {
5277 mPrivateFlags &= ~SKIP_DRAW;
5278 }
5279 requestLayout();
5280 invalidate();
5281 }
5282
5283 if ((changed & KEEP_SCREEN_ON) != 0) {
5284 if (mParent != null) {
5285 mParent.recomputeViewAttributes(this);
5286 }
5287 }
5288 }
5289
5290 /**
5291 * Change the view's z order in the tree, so it's on top of other sibling
5292 * views
5293 */
5294 public void bringToFront() {
5295 if (mParent != null) {
5296 mParent.bringChildToFront(this);
5297 }
5298 }
5299
5300 /**
5301 * This is called in response to an internal scroll in this view (i.e., the
5302 * view scrolled its own contents). This is typically as a result of
5303 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5304 * called.
5305 *
5306 * @param l Current horizontal scroll origin.
5307 * @param t Current vertical scroll origin.
5308 * @param oldl Previous horizontal scroll origin.
5309 * @param oldt Previous vertical scroll origin.
5310 */
5311 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5312 mBackgroundSizeChanged = true;
5313
5314 final AttachInfo ai = mAttachInfo;
5315 if (ai != null) {
5316 ai.mViewScrollChanged = true;
5317 }
5318 }
5319
5320 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005321 * Interface definition for a callback to be invoked when the layout bounds of a view
5322 * changes due to layout processing.
5323 */
5324 public interface OnLayoutChangeListener {
5325 /**
5326 * Called when the focus state of a view has changed.
5327 *
5328 * @param v The view whose state has changed.
5329 * @param left The new value of the view's left property.
5330 * @param top The new value of the view's top property.
5331 * @param right The new value of the view's right property.
5332 * @param bottom The new value of the view's bottom property.
5333 * @param oldLeft The previous value of the view's left property.
5334 * @param oldTop The previous value of the view's top property.
5335 * @param oldRight The previous value of the view's right property.
5336 * @param oldBottom The previous value of the view's bottom property.
5337 */
5338 void onLayoutChange(View v, int left, int top, int right, int bottom,
5339 int oldLeft, int oldTop, int oldRight, int oldBottom);
5340 }
5341
5342 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005343 * This is called during layout when the size of this view has changed. If
5344 * you were just added to the view hierarchy, you're called with the old
5345 * values of 0.
5346 *
5347 * @param w Current width of this view.
5348 * @param h Current height of this view.
5349 * @param oldw Old width of this view.
5350 * @param oldh Old height of this view.
5351 */
5352 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5353 }
5354
5355 /**
5356 * Called by draw to draw the child views. This may be overridden
5357 * by derived classes to gain control just before its children are drawn
5358 * (but after its own view has been drawn).
5359 * @param canvas the canvas on which to draw the view
5360 */
5361 protected void dispatchDraw(Canvas canvas) {
5362 }
5363
5364 /**
5365 * Gets the parent of this view. Note that the parent is a
5366 * ViewParent and not necessarily a View.
5367 *
5368 * @return Parent of this view.
5369 */
5370 public final ViewParent getParent() {
5371 return mParent;
5372 }
5373
5374 /**
5375 * Return the scrolled left position of this view. This is the left edge of
5376 * the displayed part of your view. You do not need to draw any pixels
5377 * farther left, since those are outside of the frame of your view on
5378 * screen.
5379 *
5380 * @return The left edge of the displayed part of your view, in pixels.
5381 */
5382 public final int getScrollX() {
5383 return mScrollX;
5384 }
5385
5386 /**
5387 * Return the scrolled top position of this view. This is the top edge of
5388 * the displayed part of your view. You do not need to draw any pixels above
5389 * it, since those are outside of the frame of your view on screen.
5390 *
5391 * @return The top edge of the displayed part of your view, in pixels.
5392 */
5393 public final int getScrollY() {
5394 return mScrollY;
5395 }
5396
5397 /**
5398 * Return the width of the your view.
5399 *
5400 * @return The width of your view, in pixels.
5401 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005402 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005403 public final int getWidth() {
5404 return mRight - mLeft;
5405 }
5406
5407 /**
5408 * Return the height of your view.
5409 *
5410 * @return The height of your view, in pixels.
5411 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005412 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005413 public final int getHeight() {
5414 return mBottom - mTop;
5415 }
5416
5417 /**
5418 * Return the visible drawing bounds of your view. Fills in the output
5419 * rectangle with the values from getScrollX(), getScrollY(),
5420 * getWidth(), and getHeight().
5421 *
5422 * @param outRect The (scrolled) drawing bounds of the view.
5423 */
5424 public void getDrawingRect(Rect outRect) {
5425 outRect.left = mScrollX;
5426 outRect.top = mScrollY;
5427 outRect.right = mScrollX + (mRight - mLeft);
5428 outRect.bottom = mScrollY + (mBottom - mTop);
5429 }
5430
5431 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005432 * Like {@link #getMeasuredWidthAndState()}, but only returns the
5433 * raw width component (that is the result is masked by
5434 * {@link #MEASURED_SIZE_MASK}).
5435 *
5436 * @return The raw measured width of this view.
5437 */
5438 public final int getMeasuredWidth() {
5439 return mMeasuredWidth & MEASURED_SIZE_MASK;
5440 }
5441
5442 /**
5443 * Return the full width measurement information for this view as computed
5444 * by the most recent call to {@link #measure}. This result is a bit mask
5445 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 * This should be used during measurement and layout calculations only. Use
5447 * {@link #getWidth()} to see how wide a view is after layout.
5448 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005449 * @return The measured width of this view as a bit mask.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08005451 public final int getMeasuredWidthAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 return mMeasuredWidth;
5453 }
5454
5455 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005456 * Like {@link #getMeasuredHeightAndState()}, but only returns the
5457 * raw width component (that is the result is masked by
5458 * {@link #MEASURED_SIZE_MASK}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005460 * @return The raw measured height of this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005461 */
5462 public final int getMeasuredHeight() {
Dianne Hackborn189ee182010-12-02 21:48:53 -08005463 return mMeasuredHeight & MEASURED_SIZE_MASK;
5464 }
5465
5466 /**
5467 * Return the full height measurement information for this view as computed
5468 * by the most recent call to {@link #measure}. This result is a bit mask
5469 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5470 * This should be used during measurement and layout calculations only. Use
5471 * {@link #getHeight()} to see how wide a view is after layout.
5472 *
5473 * @return The measured width of this view as a bit mask.
5474 */
5475 public final int getMeasuredHeightAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 return mMeasuredHeight;
5477 }
5478
5479 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005480 * Return only the state bits of {@link #getMeasuredWidthAndState()}
5481 * and {@link #getMeasuredHeightAndState()}, combined into one integer.
5482 * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
5483 * and the height component is at the shifted bits
5484 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
5485 */
5486 public final int getMeasuredState() {
5487 return (mMeasuredWidth&MEASURED_STATE_MASK)
5488 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
5489 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
5490 }
5491
5492 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005493 * The transform matrix of this view, which is calculated based on the current
5494 * roation, scale, and pivot properties.
5495 *
5496 * @see #getRotation()
5497 * @see #getScaleX()
5498 * @see #getScaleY()
5499 * @see #getPivotX()
5500 * @see #getPivotY()
5501 * @return The current transform matrix for the view
5502 */
5503 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005504 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005505 return mMatrix;
5506 }
5507
5508 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005509 * Utility function to determine if the value is far enough away from zero to be
5510 * considered non-zero.
5511 * @param value A floating point value to check for zero-ness
5512 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5513 */
5514 private static boolean nonzero(float value) {
5515 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5516 }
5517
5518 /**
Jeff Brown86671742010-09-30 20:00:15 -07005519 * Returns true if the transform matrix is the identity matrix.
5520 * Recomputes the matrix if necessary.
Romain Guy33e72ae2010-07-17 12:40:29 -07005521 *
5522 * @return True if the transform matrix is the identity matrix, false otherwise.
5523 */
Jeff Brown86671742010-09-30 20:00:15 -07005524 final boolean hasIdentityMatrix() {
5525 updateMatrix();
5526 return mMatrixIsIdentity;
5527 }
5528
5529 /**
5530 * Recomputes the transform matrix if necessary.
5531 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005532 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005533 if (mMatrixDirty) {
5534 // transform-related properties have changed since the last time someone
5535 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005536
5537 // Figure out if we need to update the pivot point
5538 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005539 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005540 mPrevWidth = mRight - mLeft;
5541 mPrevHeight = mBottom - mTop;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -08005542 mPivotX = mPrevWidth / 2f;
5543 mPivotY = mPrevHeight / 2f;
Chet Haasefd2b0022010-08-06 13:08:56 -07005544 }
5545 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005546 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005547 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5548 mMatrix.setTranslate(mTranslationX, mTranslationY);
5549 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5550 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5551 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005552 if (mCamera == null) {
5553 mCamera = new Camera();
5554 matrix3D = new Matrix();
5555 }
5556 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005557 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005558 mCamera.rotateX(mRotationX);
5559 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005560 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005561 mCamera.getMatrix(matrix3D);
5562 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005563 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005564 mMatrix.postConcat(matrix3D);
5565 mCamera.restore();
5566 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005567 mMatrixDirty = false;
5568 mMatrixIsIdentity = mMatrix.isIdentity();
5569 mInverseMatrixDirty = true;
5570 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005571 }
5572
5573 /**
5574 * Utility method to retrieve the inverse of the current mMatrix property.
5575 * We cache the matrix to avoid recalculating it when transform properties
5576 * have not changed.
5577 *
5578 * @return The inverse of the current matrix of this view.
5579 */
Jeff Brown86671742010-09-30 20:00:15 -07005580 final Matrix getInverseMatrix() {
5581 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005582 if (mInverseMatrixDirty) {
5583 if (mInverseMatrix == null) {
5584 mInverseMatrix = new Matrix();
5585 }
5586 mMatrix.invert(mInverseMatrix);
5587 mInverseMatrixDirty = false;
5588 }
5589 return mInverseMatrix;
5590 }
5591
5592 /**
5593 * The degrees that the view is rotated around the pivot point.
5594 *
5595 * @see #getPivotX()
5596 * @see #getPivotY()
5597 * @return The degrees of rotation.
5598 */
5599 public float getRotation() {
5600 return mRotation;
5601 }
5602
5603 /**
Chet Haase897247b2010-09-09 14:54:47 -07005604 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5605 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005606 *
5607 * @param rotation The degrees of rotation.
5608 * @see #getPivotX()
5609 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005610 *
5611 * @attr ref android.R.styleable#View_rotation
Chet Haasec3aa3612010-06-17 08:50:37 -07005612 */
5613 public void setRotation(float rotation) {
5614 if (mRotation != rotation) {
5615 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005616 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005617 mRotation = rotation;
5618 mMatrixDirty = true;
5619 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005620 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005621 }
5622 }
5623
5624 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005625 * The degrees that the view is rotated around the vertical axis through the pivot point.
5626 *
5627 * @see #getPivotX()
5628 * @see #getPivotY()
5629 * @return The degrees of Y rotation.
5630 */
5631 public float getRotationY() {
5632 return mRotationY;
5633 }
5634
5635 /**
Chet Haase897247b2010-09-09 14:54:47 -07005636 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5637 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5638 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005639 *
5640 * @param rotationY The degrees of Y rotation.
5641 * @see #getPivotX()
5642 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005643 *
5644 * @attr ref android.R.styleable#View_rotationY
Chet Haasefd2b0022010-08-06 13:08:56 -07005645 */
5646 public void setRotationY(float rotationY) {
5647 if (mRotationY != rotationY) {
5648 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005649 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005650 mRotationY = rotationY;
5651 mMatrixDirty = true;
5652 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005653 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005654 }
5655 }
5656
5657 /**
5658 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5659 *
5660 * @see #getPivotX()
5661 * @see #getPivotY()
5662 * @return The degrees of X rotation.
5663 */
5664 public float getRotationX() {
5665 return mRotationX;
5666 }
5667
5668 /**
Chet Haase897247b2010-09-09 14:54:47 -07005669 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5670 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5671 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005672 *
5673 * @param rotationX The degrees of X rotation.
5674 * @see #getPivotX()
5675 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005676 *
5677 * @attr ref android.R.styleable#View_rotationX
Chet Haasefd2b0022010-08-06 13:08:56 -07005678 */
5679 public void setRotationX(float rotationX) {
5680 if (mRotationX != rotationX) {
5681 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005682 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005683 mRotationX = rotationX;
5684 mMatrixDirty = true;
5685 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005686 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005687 }
5688 }
5689
5690 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005691 * The amount that the view is scaled in x around the pivot point, as a proportion of
5692 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5693 *
Joe Onorato93162322010-09-16 15:42:01 -04005694 * <p>By default, this is 1.0f.
5695 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005696 * @see #getPivotX()
5697 * @see #getPivotY()
5698 * @return The scaling factor.
5699 */
5700 public float getScaleX() {
5701 return mScaleX;
5702 }
5703
5704 /**
5705 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5706 * the view's unscaled width. A value of 1 means that no scaling is applied.
5707 *
5708 * @param scaleX The scaling factor.
5709 * @see #getPivotX()
5710 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005711 *
5712 * @attr ref android.R.styleable#View_scaleX
Chet Haasec3aa3612010-06-17 08:50:37 -07005713 */
5714 public void setScaleX(float scaleX) {
5715 if (mScaleX != scaleX) {
5716 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005717 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005718 mScaleX = scaleX;
5719 mMatrixDirty = true;
5720 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005721 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005722 }
5723 }
5724
5725 /**
5726 * The amount that the view is scaled in y around the pivot point, as a proportion of
5727 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5728 *
Joe Onorato93162322010-09-16 15:42:01 -04005729 * <p>By default, this is 1.0f.
5730 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005731 * @see #getPivotX()
5732 * @see #getPivotY()
5733 * @return The scaling factor.
5734 */
5735 public float getScaleY() {
5736 return mScaleY;
5737 }
5738
5739 /**
5740 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5741 * the view's unscaled width. A value of 1 means that no scaling is applied.
5742 *
5743 * @param scaleY The scaling factor.
5744 * @see #getPivotX()
5745 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005746 *
5747 * @attr ref android.R.styleable#View_scaleY
Chet Haasec3aa3612010-06-17 08:50:37 -07005748 */
5749 public void setScaleY(float scaleY) {
5750 if (mScaleY != scaleY) {
5751 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005752 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005753 mScaleY = scaleY;
5754 mMatrixDirty = true;
5755 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005756 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005757 }
5758 }
5759
5760 /**
5761 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5762 * and {@link #setScaleX(float) scaled}.
5763 *
5764 * @see #getRotation()
5765 * @see #getScaleX()
5766 * @see #getScaleY()
5767 * @see #getPivotY()
5768 * @return The x location of the pivot point.
5769 */
5770 public float getPivotX() {
5771 return mPivotX;
5772 }
5773
5774 /**
5775 * Sets the x location of the point around which the view is
5776 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005777 * By default, the pivot point is centered on the object.
5778 * Setting this property disables this behavior and causes the view to use only the
5779 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005780 *
5781 * @param pivotX The x location of the pivot point.
5782 * @see #getRotation()
5783 * @see #getScaleX()
5784 * @see #getScaleY()
5785 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005786 *
5787 * @attr ref android.R.styleable#View_transformPivotX
Chet Haasec3aa3612010-06-17 08:50:37 -07005788 */
5789 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005790 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005791 if (mPivotX != pivotX) {
5792 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005793 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005794 mPivotX = pivotX;
5795 mMatrixDirty = true;
5796 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005797 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005798 }
5799 }
5800
5801 /**
5802 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5803 * and {@link #setScaleY(float) scaled}.
5804 *
5805 * @see #getRotation()
5806 * @see #getScaleX()
5807 * @see #getScaleY()
5808 * @see #getPivotY()
5809 * @return The y location of the pivot point.
5810 */
5811 public float getPivotY() {
5812 return mPivotY;
5813 }
5814
5815 /**
5816 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005817 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5818 * Setting this property disables this behavior and causes the view to use only the
5819 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005820 *
5821 * @param pivotY The y location of the pivot point.
5822 * @see #getRotation()
5823 * @see #getScaleX()
5824 * @see #getScaleY()
5825 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005826 *
5827 * @attr ref android.R.styleable#View_transformPivotY
Chet Haasec3aa3612010-06-17 08:50:37 -07005828 */
5829 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005830 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005831 if (mPivotY != pivotY) {
5832 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005833 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005834 mPivotY = pivotY;
5835 mMatrixDirty = true;
5836 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005837 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005838 }
5839 }
5840
5841 /**
5842 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5843 * completely transparent and 1 means the view is completely opaque.
5844 *
Joe Onorato93162322010-09-16 15:42:01 -04005845 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005846 * @return The opacity of the view.
5847 */
5848 public float getAlpha() {
5849 return mAlpha;
5850 }
5851
5852 /**
Romain Guy171c5922011-01-06 10:04:23 -08005853 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5854 * completely transparent and 1 means the view is completely opaque.</p>
5855 *
5856 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
5857 * responsible for applying the opacity itself. Otherwise, calling this method is
5858 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
5859 * setting a hardware layer.</p>
Chet Haasec3aa3612010-06-17 08:50:37 -07005860 *
5861 * @param alpha The opacity of the view.
Chet Haase73066682010-11-29 15:55:32 -08005862 *
Romain Guy171c5922011-01-06 10:04:23 -08005863 * @see #setLayerType(int, android.graphics.Paint)
5864 *
Chet Haase73066682010-11-29 15:55:32 -08005865 * @attr ref android.R.styleable#View_alpha
Chet Haasec3aa3612010-06-17 08:50:37 -07005866 */
5867 public void setAlpha(float alpha) {
5868 mAlpha = alpha;
Chet Haaseed032702010-10-01 14:05:54 -07005869 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07005870 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005871 // subclass is handling alpha - don't optimize rendering cache invalidation
5872 invalidate();
5873 } else {
Romain Guya3496a92010-10-12 11:53:24 -07005874 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005875 invalidate(false);
5876 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005877 }
5878
5879 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 * Top position of this view relative to its parent.
5881 *
5882 * @return The top of this view, in pixels.
5883 */
5884 @ViewDebug.CapturedViewProperty
5885 public final int getTop() {
5886 return mTop;
5887 }
5888
5889 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005890 * Sets the top position of this view relative to its parent. This method is meant to be called
5891 * by the layout system and should not generally be called otherwise, because the property
5892 * may be changed at any time by the layout.
5893 *
5894 * @param top The top of this view, in pixels.
5895 */
5896 public final void setTop(int top) {
5897 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07005898 updateMatrix();
5899 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005900 final ViewParent p = mParent;
5901 if (p != null && mAttachInfo != null) {
5902 final Rect r = mAttachInfo.mTmpInvalRect;
5903 int minTop;
5904 int yLoc;
5905 if (top < mTop) {
5906 minTop = top;
5907 yLoc = top - mTop;
5908 } else {
5909 minTop = mTop;
5910 yLoc = 0;
5911 }
5912 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5913 p.invalidateChild(this, r);
5914 }
5915 } else {
5916 // Double-invalidation is necessary to capture view's old and new areas
5917 invalidate();
5918 }
5919
Chet Haaseed032702010-10-01 14:05:54 -07005920 int width = mRight - mLeft;
5921 int oldHeight = mBottom - mTop;
5922
Chet Haase21cd1382010-09-01 17:42:29 -07005923 mTop = top;
5924
Chet Haaseed032702010-10-01 14:05:54 -07005925 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5926
Chet Haase21cd1382010-09-01 17:42:29 -07005927 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005928 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5929 // A change in dimension means an auto-centered pivot point changes, too
5930 mMatrixDirty = true;
5931 }
Chet Haase21cd1382010-09-01 17:42:29 -07005932 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5933 invalidate();
5934 }
Chet Haase55dbb652010-12-21 20:15:08 -08005935 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07005936 }
5937 }
5938
5939 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 * Bottom position of this view relative to its parent.
5941 *
5942 * @return The bottom of this view, in pixels.
5943 */
5944 @ViewDebug.CapturedViewProperty
5945 public final int getBottom() {
5946 return mBottom;
5947 }
5948
5949 /**
Michael Jurkadab559a2011-01-04 20:31:51 -08005950 * True if this view has changed since the last time being drawn.
5951 *
5952 * @return The dirty state of this view.
5953 */
5954 public boolean isDirty() {
5955 return (mPrivateFlags & DIRTY_MASK) != 0;
5956 }
5957
5958 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005959 * Sets the bottom position of this view relative to its parent. This method is meant to be
5960 * called by the layout system and should not generally be called otherwise, because the
5961 * property may be changed at any time by the layout.
5962 *
5963 * @param bottom The bottom of this view, in pixels.
5964 */
5965 public final void setBottom(int bottom) {
5966 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07005967 updateMatrix();
5968 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005969 final ViewParent p = mParent;
5970 if (p != null && mAttachInfo != null) {
5971 final Rect r = mAttachInfo.mTmpInvalRect;
5972 int maxBottom;
5973 if (bottom < mBottom) {
5974 maxBottom = mBottom;
5975 } else {
5976 maxBottom = bottom;
5977 }
5978 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5979 p.invalidateChild(this, r);
5980 }
5981 } else {
5982 // Double-invalidation is necessary to capture view's old and new areas
5983 invalidate();
5984 }
5985
Chet Haaseed032702010-10-01 14:05:54 -07005986 int width = mRight - mLeft;
5987 int oldHeight = mBottom - mTop;
5988
Chet Haase21cd1382010-09-01 17:42:29 -07005989 mBottom = bottom;
5990
Chet Haaseed032702010-10-01 14:05:54 -07005991 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5992
Chet Haase21cd1382010-09-01 17:42:29 -07005993 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005994 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5995 // A change in dimension means an auto-centered pivot point changes, too
5996 mMatrixDirty = true;
5997 }
Chet Haase21cd1382010-09-01 17:42:29 -07005998 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5999 invalidate();
6000 }
Chet Haase55dbb652010-12-21 20:15:08 -08006001 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006002 }
6003 }
6004
6005 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 * Left position of this view relative to its parent.
6007 *
6008 * @return The left edge of this view, in pixels.
6009 */
6010 @ViewDebug.CapturedViewProperty
6011 public final int getLeft() {
6012 return mLeft;
6013 }
6014
6015 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006016 * Sets the left position of this view relative to its parent. This method is meant to be called
6017 * by the layout system and should not generally be called otherwise, because the property
6018 * may be changed at any time by the layout.
6019 *
6020 * @param left The bottom of this view, in pixels.
6021 */
6022 public final void setLeft(int left) {
6023 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07006024 updateMatrix();
6025 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006026 final ViewParent p = mParent;
6027 if (p != null && mAttachInfo != null) {
6028 final Rect r = mAttachInfo.mTmpInvalRect;
6029 int minLeft;
6030 int xLoc;
6031 if (left < mLeft) {
6032 minLeft = left;
6033 xLoc = left - mLeft;
6034 } else {
6035 minLeft = mLeft;
6036 xLoc = 0;
6037 }
6038 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
6039 p.invalidateChild(this, r);
6040 }
6041 } else {
6042 // Double-invalidation is necessary to capture view's old and new areas
6043 invalidate();
6044 }
6045
Chet Haaseed032702010-10-01 14:05:54 -07006046 int oldWidth = mRight - mLeft;
6047 int height = mBottom - mTop;
6048
Chet Haase21cd1382010-09-01 17:42:29 -07006049 mLeft = left;
6050
Chet Haaseed032702010-10-01 14:05:54 -07006051 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6052
Chet Haase21cd1382010-09-01 17:42:29 -07006053 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006054 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6055 // A change in dimension means an auto-centered pivot point changes, too
6056 mMatrixDirty = true;
6057 }
Chet Haase21cd1382010-09-01 17:42:29 -07006058 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6059 invalidate();
6060 }
Chet Haase55dbb652010-12-21 20:15:08 -08006061 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006062 }
6063 }
6064
6065 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 * Right position of this view relative to its parent.
6067 *
6068 * @return The right edge of this view, in pixels.
6069 */
6070 @ViewDebug.CapturedViewProperty
6071 public final int getRight() {
6072 return mRight;
6073 }
6074
6075 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006076 * Sets the right position of this view relative to its parent. This method is meant to be called
6077 * by the layout system and should not generally be called otherwise, because the property
6078 * may be changed at any time by the layout.
6079 *
6080 * @param right The bottom of this view, in pixels.
6081 */
6082 public final void setRight(int right) {
6083 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07006084 updateMatrix();
6085 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006086 final ViewParent p = mParent;
6087 if (p != null && mAttachInfo != null) {
6088 final Rect r = mAttachInfo.mTmpInvalRect;
6089 int maxRight;
6090 if (right < mRight) {
6091 maxRight = mRight;
6092 } else {
6093 maxRight = right;
6094 }
6095 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
6096 p.invalidateChild(this, r);
6097 }
6098 } else {
6099 // Double-invalidation is necessary to capture view's old and new areas
6100 invalidate();
6101 }
6102
Chet Haaseed032702010-10-01 14:05:54 -07006103 int oldWidth = mRight - mLeft;
6104 int height = mBottom - mTop;
6105
Chet Haase21cd1382010-09-01 17:42:29 -07006106 mRight = right;
6107
Chet Haaseed032702010-10-01 14:05:54 -07006108 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6109
Chet Haase21cd1382010-09-01 17:42:29 -07006110 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006111 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6112 // A change in dimension means an auto-centered pivot point changes, too
6113 mMatrixDirty = true;
6114 }
Chet Haase21cd1382010-09-01 17:42:29 -07006115 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6116 invalidate();
6117 }
Chet Haase55dbb652010-12-21 20:15:08 -08006118 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006119 }
6120 }
6121
6122 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006123 * The visual x position of this view, in pixels. This is equivalent to the
6124 * {@link #setTranslationX(float) translationX} property plus the current
6125 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07006126 *
Chet Haasedf030d22010-07-30 17:22:38 -07006127 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006128 */
Chet Haasedf030d22010-07-30 17:22:38 -07006129 public float getX() {
6130 return mLeft + mTranslationX;
6131 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006132
Chet Haasedf030d22010-07-30 17:22:38 -07006133 /**
6134 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
6135 * {@link #setTranslationX(float) translationX} property to be the difference between
6136 * the x value passed in and the current {@link #getLeft() left} property.
6137 *
6138 * @param x The visual x position of this view, in pixels.
6139 */
6140 public void setX(float x) {
6141 setTranslationX(x - mLeft);
6142 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006143
Chet Haasedf030d22010-07-30 17:22:38 -07006144 /**
6145 * The visual y position of this view, in pixels. This is equivalent to the
6146 * {@link #setTranslationY(float) translationY} property plus the current
6147 * {@link #getTop() top} property.
6148 *
6149 * @return The visual y position of this view, in pixels.
6150 */
6151 public float getY() {
6152 return mTop + mTranslationY;
6153 }
6154
6155 /**
6156 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
6157 * {@link #setTranslationY(float) translationY} property to be the difference between
6158 * the y value passed in and the current {@link #getTop() top} property.
6159 *
6160 * @param y The visual y position of this view, in pixels.
6161 */
6162 public void setY(float y) {
6163 setTranslationY(y - mTop);
6164 }
6165
6166
6167 /**
6168 * The horizontal location of this view relative to its {@link #getLeft() left} position.
6169 * This position is post-layout, in addition to wherever the object's
6170 * layout placed it.
6171 *
6172 * @return The horizontal position of this view relative to its left position, in pixels.
6173 */
6174 public float getTranslationX() {
6175 return mTranslationX;
6176 }
6177
6178 /**
6179 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
6180 * This effectively positions the object post-layout, in addition to wherever the object's
6181 * layout placed it.
6182 *
6183 * @param translationX The horizontal position of this view relative to its left position,
6184 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006185 *
6186 * @attr ref android.R.styleable#View_translationX
Chet Haasedf030d22010-07-30 17:22:38 -07006187 */
6188 public void setTranslationX(float translationX) {
6189 if (mTranslationX != translationX) {
6190 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006191 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006192 mTranslationX = translationX;
6193 mMatrixDirty = true;
6194 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006195 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006196 }
6197 }
6198
6199 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006200 * The horizontal location of this view relative to its {@link #getTop() top} position.
6201 * This position is post-layout, in addition to wherever the object's
6202 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006203 *
Chet Haasedf030d22010-07-30 17:22:38 -07006204 * @return The vertical position of this view relative to its top position,
6205 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006206 */
Chet Haasedf030d22010-07-30 17:22:38 -07006207 public float getTranslationY() {
6208 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07006209 }
6210
6211 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006212 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
6213 * This effectively positions the object post-layout, in addition to wherever the object's
6214 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006215 *
Chet Haasedf030d22010-07-30 17:22:38 -07006216 * @param translationY The vertical position of this view relative to its top position,
6217 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006218 *
6219 * @attr ref android.R.styleable#View_translationY
Chet Haasec3aa3612010-06-17 08:50:37 -07006220 */
Chet Haasedf030d22010-07-30 17:22:38 -07006221 public void setTranslationY(float translationY) {
6222 if (mTranslationY != translationY) {
6223 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006224 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006225 mTranslationY = translationY;
6226 mMatrixDirty = true;
6227 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006228 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006229 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006230 }
6231
6232 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 * Hit rectangle in parent's coordinates
6234 *
6235 * @param outRect The hit rectangle of the view.
6236 */
6237 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07006238 updateMatrix();
6239 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006240 outRect.set(mLeft, mTop, mRight, mBottom);
6241 } else {
6242 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07006243 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07006244 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07006245 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
6246 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07006247 }
6248 }
6249
6250 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07006251 * Determines whether the given point, in local coordinates is inside the view.
6252 */
6253 /*package*/ final boolean pointInView(float localX, float localY) {
6254 return localX >= 0 && localX < (mRight - mLeft)
6255 && localY >= 0 && localY < (mBottom - mTop);
6256 }
6257
6258 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07006259 * Utility method to determine whether the given point, in local coordinates,
6260 * is inside the view, where the area of the view is expanded by the slop factor.
6261 * This method is called while processing touch-move events to determine if the event
6262 * is still within the view.
6263 */
6264 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07006265 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07006266 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 }
6268
6269 /**
6270 * When a view has focus and the user navigates away from it, the next view is searched for
6271 * starting from the rectangle filled in by this method.
6272 *
6273 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
6274 * view maintains some idea of internal selection, such as a cursor, or a selected row
6275 * or column, you should override this method and fill in a more specific rectangle.
6276 *
6277 * @param r The rectangle to fill in, in this view's coordinates.
6278 */
6279 public void getFocusedRect(Rect r) {
6280 getDrawingRect(r);
6281 }
6282
6283 /**
6284 * If some part of this view is not clipped by any of its parents, then
6285 * return that area in r in global (root) coordinates. To convert r to local
6286 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
6287 * -globalOffset.y)) If the view is completely clipped or translated out,
6288 * return false.
6289 *
6290 * @param r If true is returned, r holds the global coordinates of the
6291 * visible portion of this view.
6292 * @param globalOffset If true is returned, globalOffset holds the dx,dy
6293 * between this view and its root. globalOffet may be null.
6294 * @return true if r is non-empty (i.e. part of the view is visible at the
6295 * root level.
6296 */
6297 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6298 int width = mRight - mLeft;
6299 int height = mBottom - mTop;
6300 if (width > 0 && height > 0) {
6301 r.set(0, 0, width, height);
6302 if (globalOffset != null) {
6303 globalOffset.set(-mScrollX, -mScrollY);
6304 }
6305 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6306 }
6307 return false;
6308 }
6309
6310 public final boolean getGlobalVisibleRect(Rect r) {
6311 return getGlobalVisibleRect(r, null);
6312 }
6313
6314 public final boolean getLocalVisibleRect(Rect r) {
6315 Point offset = new Point();
6316 if (getGlobalVisibleRect(r, offset)) {
6317 r.offset(-offset.x, -offset.y); // make r local
6318 return true;
6319 }
6320 return false;
6321 }
6322
6323 /**
6324 * Offset this view's vertical location by the specified number of pixels.
6325 *
6326 * @param offset the number of pixels to offset the view by
6327 */
6328 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006329 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006330 updateMatrix();
6331 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006332 final ViewParent p = mParent;
6333 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006334 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006335 int minTop;
6336 int maxBottom;
6337 int yLoc;
6338 if (offset < 0) {
6339 minTop = mTop + offset;
6340 maxBottom = mBottom;
6341 yLoc = offset;
6342 } else {
6343 minTop = mTop;
6344 maxBottom = mBottom + offset;
6345 yLoc = 0;
6346 }
6347 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6348 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006349 }
6350 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006351 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006352 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006353
Chet Haasec3aa3612010-06-17 08:50:37 -07006354 mTop += offset;
6355 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006356
Chet Haasec3aa3612010-06-17 08:50:37 -07006357 if (!mMatrixIsIdentity) {
6358 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006359 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006360 }
6361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 }
6363
6364 /**
6365 * Offset this view's horizontal location by the specified amount of pixels.
6366 *
6367 * @param offset the numer of pixels to offset the view by
6368 */
6369 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006370 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006371 updateMatrix();
6372 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006373 final ViewParent p = mParent;
6374 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006375 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006376 int minLeft;
6377 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006378 if (offset < 0) {
6379 minLeft = mLeft + offset;
6380 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006381 } else {
6382 minLeft = mLeft;
6383 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006384 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006385 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07006386 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006387 }
6388 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006389 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006390 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006391
Chet Haasec3aa3612010-06-17 08:50:37 -07006392 mLeft += offset;
6393 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006394
Chet Haasec3aa3612010-06-17 08:50:37 -07006395 if (!mMatrixIsIdentity) {
6396 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006397 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006398 }
6399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 }
6401
6402 /**
6403 * Get the LayoutParams associated with this view. All views should have
6404 * layout parameters. These supply parameters to the <i>parent</i> of this
6405 * view specifying how it should be arranged. There are many subclasses of
6406 * ViewGroup.LayoutParams, and these correspond to the different subclasses
6407 * of ViewGroup that are responsible for arranging their children.
6408 * @return The LayoutParams associated with this view
6409 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07006410 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 public ViewGroup.LayoutParams getLayoutParams() {
6412 return mLayoutParams;
6413 }
6414
6415 /**
6416 * Set the layout parameters associated with this view. These supply
6417 * parameters to the <i>parent</i> of this view specifying how it should be
6418 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6419 * correspond to the different subclasses of ViewGroup that are responsible
6420 * for arranging their children.
6421 *
6422 * @param params the layout parameters for this view
6423 */
6424 public void setLayoutParams(ViewGroup.LayoutParams params) {
6425 if (params == null) {
6426 throw new NullPointerException("params == null");
6427 }
6428 mLayoutParams = params;
6429 requestLayout();
6430 }
6431
6432 /**
6433 * Set the scrolled position of your view. This will cause a call to
6434 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6435 * invalidated.
6436 * @param x the x position to scroll to
6437 * @param y the y position to scroll to
6438 */
6439 public void scrollTo(int x, int y) {
6440 if (mScrollX != x || mScrollY != y) {
6441 int oldX = mScrollX;
6442 int oldY = mScrollY;
6443 mScrollX = x;
6444 mScrollY = y;
6445 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006446 if (!awakenScrollBars()) {
6447 invalidate();
6448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 }
6450 }
6451
6452 /**
6453 * Move the scrolled position of your view. This will cause a call to
6454 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6455 * invalidated.
6456 * @param x the amount of pixels to scroll by horizontally
6457 * @param y the amount of pixels to scroll by vertically
6458 */
6459 public void scrollBy(int x, int y) {
6460 scrollTo(mScrollX + x, mScrollY + y);
6461 }
6462
6463 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006464 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6465 * animation to fade the scrollbars out after a default delay. If a subclass
6466 * provides animated scrolling, the start delay should equal the duration
6467 * of the scrolling animation.</p>
6468 *
6469 * <p>The animation starts only if at least one of the scrollbars is
6470 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6471 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6472 * this method returns true, and false otherwise. If the animation is
6473 * started, this method calls {@link #invalidate()}; in that case the
6474 * caller should not call {@link #invalidate()}.</p>
6475 *
6476 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006477 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006478 *
6479 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6480 * and {@link #scrollTo(int, int)}.</p>
6481 *
6482 * @return true if the animation is played, false otherwise
6483 *
6484 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006485 * @see #scrollBy(int, int)
6486 * @see #scrollTo(int, int)
6487 * @see #isHorizontalScrollBarEnabled()
6488 * @see #isVerticalScrollBarEnabled()
6489 * @see #setHorizontalScrollBarEnabled(boolean)
6490 * @see #setVerticalScrollBarEnabled(boolean)
6491 */
6492 protected boolean awakenScrollBars() {
6493 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006494 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006495 }
6496
6497 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006498 * Trigger the scrollbars to draw.
6499 * This method differs from awakenScrollBars() only in its default duration.
6500 * initialAwakenScrollBars() will show the scroll bars for longer than
6501 * usual to give the user more of a chance to notice them.
6502 *
6503 * @return true if the animation is played, false otherwise.
6504 */
6505 private boolean initialAwakenScrollBars() {
6506 return mScrollCache != null &&
6507 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6508 }
6509
6510 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006511 * <p>
6512 * Trigger the scrollbars to draw. When invoked this method starts an
6513 * animation to fade the scrollbars out after a fixed delay. If a subclass
6514 * provides animated scrolling, the start delay should equal the duration of
6515 * the scrolling animation.
6516 * </p>
6517 *
6518 * <p>
6519 * The animation starts only if at least one of the scrollbars is enabled,
6520 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6521 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6522 * this method returns true, and false otherwise. If the animation is
6523 * started, this method calls {@link #invalidate()}; in that case the caller
6524 * should not call {@link #invalidate()}.
6525 * </p>
6526 *
6527 * <p>
6528 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006529 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006530 * </p>
6531 *
6532 * @param startDelay the delay, in milliseconds, after which the animation
6533 * should start; when the delay is 0, the animation starts
6534 * immediately
6535 * @return true if the animation is played, false otherwise
6536 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006537 * @see #scrollBy(int, int)
6538 * @see #scrollTo(int, int)
6539 * @see #isHorizontalScrollBarEnabled()
6540 * @see #isVerticalScrollBarEnabled()
6541 * @see #setHorizontalScrollBarEnabled(boolean)
6542 * @see #setVerticalScrollBarEnabled(boolean)
6543 */
6544 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006545 return awakenScrollBars(startDelay, true);
6546 }
6547
6548 /**
6549 * <p>
6550 * Trigger the scrollbars to draw. When invoked this method starts an
6551 * animation to fade the scrollbars out after a fixed delay. If a subclass
6552 * provides animated scrolling, the start delay should equal the duration of
6553 * the scrolling animation.
6554 * </p>
6555 *
6556 * <p>
6557 * The animation starts only if at least one of the scrollbars is enabled,
6558 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6559 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6560 * this method returns true, and false otherwise. If the animation is
6561 * started, this method calls {@link #invalidate()} if the invalidate parameter
6562 * is set to true; in that case the caller
6563 * should not call {@link #invalidate()}.
6564 * </p>
6565 *
6566 * <p>
6567 * This method should be invoked everytime a subclass directly updates the
6568 * scroll parameters.
6569 * </p>
6570 *
6571 * @param startDelay the delay, in milliseconds, after which the animation
6572 * should start; when the delay is 0, the animation starts
6573 * immediately
6574 *
6575 * @param invalidate Wheter this method should call invalidate
6576 *
6577 * @return true if the animation is played, false otherwise
6578 *
6579 * @see #scrollBy(int, int)
6580 * @see #scrollTo(int, int)
6581 * @see #isHorizontalScrollBarEnabled()
6582 * @see #isVerticalScrollBarEnabled()
6583 * @see #setHorizontalScrollBarEnabled(boolean)
6584 * @see #setVerticalScrollBarEnabled(boolean)
6585 */
6586 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006587 final ScrollabilityCache scrollCache = mScrollCache;
6588
6589 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6590 return false;
6591 }
6592
6593 if (scrollCache.scrollBar == null) {
6594 scrollCache.scrollBar = new ScrollBarDrawable();
6595 }
6596
6597 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6598
Mike Cleron290947b2009-09-29 18:34:32 -07006599 if (invalidate) {
6600 // Invalidate to show the scrollbars
6601 invalidate();
6602 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006603
6604 if (scrollCache.state == ScrollabilityCache.OFF) {
6605 // FIXME: this is copied from WindowManagerService.
6606 // We should get this value from the system when it
6607 // is possible to do so.
6608 final int KEY_REPEAT_FIRST_DELAY = 750;
6609 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6610 }
6611
6612 // Tell mScrollCache when we should start fading. This may
6613 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006614 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006615 scrollCache.fadeStartTime = fadeStartTime;
6616 scrollCache.state = ScrollabilityCache.ON;
6617
6618 // Schedule our fader to run, unscheduling any old ones first
6619 if (mAttachInfo != null) {
6620 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6621 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6622 }
6623
6624 return true;
6625 }
6626
6627 return false;
6628 }
6629
6630 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 * Mark the the area defined by dirty as needing to be drawn. If the view is
6632 * visible, {@link #onDraw} will be called at some point in the future.
6633 * This must be called from a UI thread. To call from a non-UI thread, call
6634 * {@link #postInvalidate()}.
6635 *
6636 * WARNING: This method is destructive to dirty.
6637 * @param dirty the rectangle representing the bounds of the dirty region
6638 */
6639 public void invalidate(Rect dirty) {
6640 if (ViewDebug.TRACE_HIERARCHY) {
6641 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6642 }
6643
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006644 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6645 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6647 final ViewParent p = mParent;
6648 final AttachInfo ai = mAttachInfo;
Romain Guyaf636eb2010-12-09 17:47:21 -08006649 if (p != null && ai != null && ai.mHardwareAccelerated) {
6650 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6651 // with a null dirty rect, which tells the ViewRoot to redraw everything
6652 p.invalidateChild(this, null);
6653 return;
6654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 if (p != null && ai != null) {
6656 final int scrollX = mScrollX;
6657 final int scrollY = mScrollY;
6658 final Rect r = ai.mTmpInvalRect;
6659 r.set(dirty.left - scrollX, dirty.top - scrollY,
6660 dirty.right - scrollX, dirty.bottom - scrollY);
6661 mParent.invalidateChild(this, r);
6662 }
6663 }
6664 }
6665
6666 /**
6667 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6668 * The coordinates of the dirty rect are relative to the view.
6669 * If the view is visible, {@link #onDraw} will be called at some point
6670 * in the future. This must be called from a UI thread. To call
6671 * from a non-UI thread, call {@link #postInvalidate()}.
6672 * @param l the left position of the dirty region
6673 * @param t the top position of the dirty region
6674 * @param r the right position of the dirty region
6675 * @param b the bottom position of the dirty region
6676 */
6677 public void invalidate(int l, int t, int r, int b) {
6678 if (ViewDebug.TRACE_HIERARCHY) {
6679 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6680 }
6681
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006682 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6683 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006684 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6685 final ViewParent p = mParent;
6686 final AttachInfo ai = mAttachInfo;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006687 if (p != null && ai != null && ai.mHardwareAccelerated) {
6688 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6689 // with a null dirty rect, which tells the ViewRoot to redraw everything
6690 p.invalidateChild(this, null);
6691 return;
6692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 if (p != null && ai != null && l < r && t < b) {
6694 final int scrollX = mScrollX;
6695 final int scrollY = mScrollY;
6696 final Rect tmpr = ai.mTmpInvalRect;
6697 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6698 p.invalidateChild(this, tmpr);
6699 }
6700 }
6701 }
6702
6703 /**
6704 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6705 * be called at some point in the future. This must be called from a
6706 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6707 */
6708 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006709 invalidate(true);
6710 }
6711
6712 /**
6713 * This is where the invalidate() work actually happens. A full invalidate()
6714 * causes the drawing cache to be invalidated, but this function can be called with
6715 * invalidateCache set to false to skip that invalidation step for cases that do not
6716 * need it (for example, a component that remains at the same dimensions with the same
6717 * content).
6718 *
6719 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6720 * well. This is usually true for a full invalidate, but may be set to false if the
6721 * View's contents or dimensions have not changed.
6722 */
6723 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 if (ViewDebug.TRACE_HIERARCHY) {
6725 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6726 }
6727
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006728 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6729 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID)) {
Chet Haaseed032702010-10-01 14:05:54 -07006730 mPrivateFlags &= ~DRAWN;
6731 if (invalidateCache) {
6732 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006735 final ViewParent p = mParent;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006736 if (p != null && ai != null && ai.mHardwareAccelerated) {
6737 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6738 // with a null dirty rect, which tells the ViewRoot to redraw everything
6739 p.invalidateChild(this, null);
6740 return;
6741 }
Michael Jurkaebefea42010-11-15 16:04:01 -08006742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006743 if (p != null && ai != null) {
6744 final Rect r = ai.mTmpInvalRect;
6745 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6746 // Don't call invalidate -- we don't want to internally scroll
6747 // our own bounds
6748 p.invalidateChild(this, r);
6749 }
6750 }
6751 }
6752
6753 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006754 * Indicates whether this View is opaque. An opaque View guarantees that it will
6755 * draw all the pixels overlapping its bounds using a fully opaque color.
6756 *
6757 * Subclasses of View should override this method whenever possible to indicate
6758 * whether an instance is opaque. Opaque Views are treated in a special way by
6759 * the View hierarchy, possibly allowing it to perform optimizations during
6760 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006761 *
Romain Guy24443ea2009-05-11 11:56:30 -07006762 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006763 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006764 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006765 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006766 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6767 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006768 }
6769
Adam Powell20232d02010-12-08 21:08:53 -08006770 /**
6771 * @hide
6772 */
6773 protected void computeOpaqueFlags() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006774 // Opaque if:
6775 // - Has a background
6776 // - Background is opaque
6777 // - Doesn't have scrollbars or scrollbars are inside overlay
6778
6779 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6780 mPrivateFlags |= OPAQUE_BACKGROUND;
6781 } else {
6782 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6783 }
6784
6785 final int flags = mViewFlags;
6786 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6787 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6788 mPrivateFlags |= OPAQUE_SCROLLBARS;
6789 } else {
6790 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6791 }
6792 }
6793
6794 /**
6795 * @hide
6796 */
6797 protected boolean hasOpaqueScrollbars() {
6798 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006799 }
6800
6801 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 * @return A handler associated with the thread running the View. This
6803 * handler can be used to pump events in the UI events queue.
6804 */
6805 public Handler getHandler() {
6806 if (mAttachInfo != null) {
6807 return mAttachInfo.mHandler;
6808 }
6809 return null;
6810 }
6811
6812 /**
6813 * Causes the Runnable to be added to the message queue.
6814 * The runnable will be run on the user interface thread.
6815 *
6816 * @param action The Runnable that will be executed.
6817 *
6818 * @return Returns true if the Runnable was successfully placed in to the
6819 * message queue. Returns false on failure, usually because the
6820 * looper processing the message queue is exiting.
6821 */
6822 public boolean post(Runnable action) {
6823 Handler handler;
6824 if (mAttachInfo != null) {
6825 handler = mAttachInfo.mHandler;
6826 } else {
6827 // Assume that post will succeed later
6828 ViewRoot.getRunQueue().post(action);
6829 return true;
6830 }
6831
6832 return handler.post(action);
6833 }
6834
6835 /**
6836 * Causes the Runnable to be added to the message queue, to be run
6837 * after the specified amount of time elapses.
6838 * The runnable will be run on the user interface thread.
6839 *
6840 * @param action The Runnable that will be executed.
6841 * @param delayMillis The delay (in milliseconds) until the Runnable
6842 * will be executed.
6843 *
6844 * @return true if the Runnable was successfully placed in to the
6845 * message queue. Returns false on failure, usually because the
6846 * looper processing the message queue is exiting. Note that a
6847 * result of true does not mean the Runnable will be processed --
6848 * if the looper is quit before the delivery time of the message
6849 * occurs then the message will be dropped.
6850 */
6851 public boolean postDelayed(Runnable action, long delayMillis) {
6852 Handler handler;
6853 if (mAttachInfo != null) {
6854 handler = mAttachInfo.mHandler;
6855 } else {
6856 // Assume that post will succeed later
6857 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6858 return true;
6859 }
6860
6861 return handler.postDelayed(action, delayMillis);
6862 }
6863
6864 /**
6865 * Removes the specified Runnable from the message queue.
6866 *
6867 * @param action The Runnable to remove from the message handling queue
6868 *
6869 * @return true if this view could ask the Handler to remove the Runnable,
6870 * false otherwise. When the returned value is true, the Runnable
6871 * may or may not have been actually removed from the message queue
6872 * (for instance, if the Runnable was not in the queue already.)
6873 */
6874 public boolean removeCallbacks(Runnable action) {
6875 Handler handler;
6876 if (mAttachInfo != null) {
6877 handler = mAttachInfo.mHandler;
6878 } else {
6879 // Assume that post will succeed later
6880 ViewRoot.getRunQueue().removeCallbacks(action);
6881 return true;
6882 }
6883
6884 handler.removeCallbacks(action);
6885 return true;
6886 }
6887
6888 /**
6889 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6890 * Use this to invalidate the View from a non-UI thread.
6891 *
6892 * @see #invalidate()
6893 */
6894 public void postInvalidate() {
6895 postInvalidateDelayed(0);
6896 }
6897
6898 /**
6899 * Cause an invalidate of the specified area to happen on a subsequent cycle
6900 * through the event loop. Use this to invalidate the View from a non-UI thread.
6901 *
6902 * @param left The left coordinate of the rectangle to invalidate.
6903 * @param top The top coordinate of the rectangle to invalidate.
6904 * @param right The right coordinate of the rectangle to invalidate.
6905 * @param bottom The bottom coordinate of the rectangle to invalidate.
6906 *
6907 * @see #invalidate(int, int, int, int)
6908 * @see #invalidate(Rect)
6909 */
6910 public void postInvalidate(int left, int top, int right, int bottom) {
6911 postInvalidateDelayed(0, left, top, right, bottom);
6912 }
6913
6914 /**
6915 * Cause an invalidate to happen on a subsequent cycle through the event
6916 * loop. Waits for the specified amount of time.
6917 *
6918 * @param delayMilliseconds the duration in milliseconds to delay the
6919 * invalidation by
6920 */
6921 public void postInvalidateDelayed(long delayMilliseconds) {
6922 // We try only with the AttachInfo because there's no point in invalidating
6923 // if we are not attached to our window
6924 if (mAttachInfo != null) {
6925 Message msg = Message.obtain();
6926 msg.what = AttachInfo.INVALIDATE_MSG;
6927 msg.obj = this;
6928 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6929 }
6930 }
6931
6932 /**
6933 * Cause an invalidate of the specified area to happen on a subsequent cycle
6934 * through the event loop. Waits for the specified amount of time.
6935 *
6936 * @param delayMilliseconds the duration in milliseconds to delay the
6937 * invalidation by
6938 * @param left The left coordinate of the rectangle to invalidate.
6939 * @param top The top coordinate of the rectangle to invalidate.
6940 * @param right The right coordinate of the rectangle to invalidate.
6941 * @param bottom The bottom coordinate of the rectangle to invalidate.
6942 */
6943 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6944 int right, int bottom) {
6945
6946 // We try only with the AttachInfo because there's no point in invalidating
6947 // if we are not attached to our window
6948 if (mAttachInfo != null) {
6949 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6950 info.target = this;
6951 info.left = left;
6952 info.top = top;
6953 info.right = right;
6954 info.bottom = bottom;
6955
6956 final Message msg = Message.obtain();
6957 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6958 msg.obj = info;
6959 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6960 }
6961 }
6962
6963 /**
6964 * Called by a parent to request that a child update its values for mScrollX
6965 * and mScrollY if necessary. This will typically be done if the child is
6966 * animating a scroll using a {@link android.widget.Scroller Scroller}
6967 * object.
6968 */
6969 public void computeScroll() {
6970 }
6971
6972 /**
6973 * <p>Indicate whether the horizontal edges are faded when the view is
6974 * scrolled horizontally.</p>
6975 *
6976 * @return true if the horizontal edges should are faded on scroll, false
6977 * otherwise
6978 *
6979 * @see #setHorizontalFadingEdgeEnabled(boolean)
6980 * @attr ref android.R.styleable#View_fadingEdge
6981 */
6982 public boolean isHorizontalFadingEdgeEnabled() {
6983 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6984 }
6985
6986 /**
6987 * <p>Define whether the horizontal edges should be faded when this view
6988 * is scrolled horizontally.</p>
6989 *
6990 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6991 * be faded when the view is scrolled
6992 * horizontally
6993 *
6994 * @see #isHorizontalFadingEdgeEnabled()
6995 * @attr ref android.R.styleable#View_fadingEdge
6996 */
6997 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6998 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6999 if (horizontalFadingEdgeEnabled) {
7000 initScrollCache();
7001 }
7002
7003 mViewFlags ^= FADING_EDGE_HORIZONTAL;
7004 }
7005 }
7006
7007 /**
7008 * <p>Indicate whether the vertical edges are faded when the view is
7009 * scrolled horizontally.</p>
7010 *
7011 * @return true if the vertical edges should are faded on scroll, false
7012 * otherwise
7013 *
7014 * @see #setVerticalFadingEdgeEnabled(boolean)
7015 * @attr ref android.R.styleable#View_fadingEdge
7016 */
7017 public boolean isVerticalFadingEdgeEnabled() {
7018 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
7019 }
7020
7021 /**
7022 * <p>Define whether the vertical edges should be faded when this view
7023 * is scrolled vertically.</p>
7024 *
7025 * @param verticalFadingEdgeEnabled true if the vertical edges should
7026 * be faded when the view is scrolled
7027 * vertically
7028 *
7029 * @see #isVerticalFadingEdgeEnabled()
7030 * @attr ref android.R.styleable#View_fadingEdge
7031 */
7032 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
7033 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
7034 if (verticalFadingEdgeEnabled) {
7035 initScrollCache();
7036 }
7037
7038 mViewFlags ^= FADING_EDGE_VERTICAL;
7039 }
7040 }
7041
7042 /**
7043 * Returns the strength, or intensity, of the top faded edge. The strength is
7044 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7045 * returns 0.0 or 1.0 but no value in between.
7046 *
7047 * Subclasses should override this method to provide a smoother fade transition
7048 * when scrolling occurs.
7049 *
7050 * @return the intensity of the top fade as a float between 0.0f and 1.0f
7051 */
7052 protected float getTopFadingEdgeStrength() {
7053 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
7054 }
7055
7056 /**
7057 * Returns the strength, or intensity, of the bottom faded edge. The strength is
7058 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7059 * returns 0.0 or 1.0 but no value in between.
7060 *
7061 * Subclasses should override this method to provide a smoother fade transition
7062 * when scrolling occurs.
7063 *
7064 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
7065 */
7066 protected float getBottomFadingEdgeStrength() {
7067 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
7068 computeVerticalScrollRange() ? 1.0f : 0.0f;
7069 }
7070
7071 /**
7072 * Returns the strength, or intensity, of the left faded edge. The strength is
7073 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7074 * returns 0.0 or 1.0 but no value in between.
7075 *
7076 * Subclasses should override this method to provide a smoother fade transition
7077 * when scrolling occurs.
7078 *
7079 * @return the intensity of the left fade as a float between 0.0f and 1.0f
7080 */
7081 protected float getLeftFadingEdgeStrength() {
7082 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
7083 }
7084
7085 /**
7086 * Returns the strength, or intensity, of the right faded edge. The strength is
7087 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7088 * returns 0.0 or 1.0 but no value in between.
7089 *
7090 * Subclasses should override this method to provide a smoother fade transition
7091 * when scrolling occurs.
7092 *
7093 * @return the intensity of the right fade as a float between 0.0f and 1.0f
7094 */
7095 protected float getRightFadingEdgeStrength() {
7096 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
7097 computeHorizontalScrollRange() ? 1.0f : 0.0f;
7098 }
7099
7100 /**
7101 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
7102 * scrollbar is not drawn by default.</p>
7103 *
7104 * @return true if the horizontal scrollbar should be painted, false
7105 * otherwise
7106 *
7107 * @see #setHorizontalScrollBarEnabled(boolean)
7108 */
7109 public boolean isHorizontalScrollBarEnabled() {
7110 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7111 }
7112
7113 /**
7114 * <p>Define whether the horizontal scrollbar should be drawn or not. The
7115 * scrollbar is not drawn by default.</p>
7116 *
7117 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
7118 * be painted
7119 *
7120 * @see #isHorizontalScrollBarEnabled()
7121 */
7122 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
7123 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
7124 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007125 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007126 recomputePadding();
7127 }
7128 }
7129
7130 /**
7131 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
7132 * scrollbar is not drawn by default.</p>
7133 *
7134 * @return true if the vertical scrollbar should be painted, false
7135 * otherwise
7136 *
7137 * @see #setVerticalScrollBarEnabled(boolean)
7138 */
7139 public boolean isVerticalScrollBarEnabled() {
7140 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
7141 }
7142
7143 /**
7144 * <p>Define whether the vertical scrollbar should be drawn or not. The
7145 * scrollbar is not drawn by default.</p>
7146 *
7147 * @param verticalScrollBarEnabled true if the vertical scrollbar should
7148 * be painted
7149 *
7150 * @see #isVerticalScrollBarEnabled()
7151 */
7152 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
7153 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
7154 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007155 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007156 recomputePadding();
7157 }
7158 }
7159
Adam Powell20232d02010-12-08 21:08:53 -08007160 /**
7161 * @hide
7162 */
7163 protected void recomputePadding() {
7164 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007165 }
Mike Cleronfe81d382009-09-28 14:22:16 -07007166
7167 /**
7168 * Define whether scrollbars will fade when the view is not scrolling.
7169 *
7170 * @param fadeScrollbars wheter to enable fading
7171 *
7172 */
7173 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
7174 initScrollCache();
7175 final ScrollabilityCache scrollabilityCache = mScrollCache;
7176 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07007177 if (fadeScrollbars) {
7178 scrollabilityCache.state = ScrollabilityCache.OFF;
7179 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07007180 scrollabilityCache.state = ScrollabilityCache.ON;
7181 }
7182 }
7183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07007185 *
7186 * Returns true if scrollbars will fade when this view is not scrolling
7187 *
7188 * @return true if scrollbar fading is enabled
7189 */
7190 public boolean isScrollbarFadingEnabled() {
7191 return mScrollCache != null && mScrollCache.fadeScrollBars;
7192 }
7193
7194 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007195 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
7196 * inset. When inset, they add to the padding of the view. And the scrollbars
7197 * can be drawn inside the padding area or on the edge of the view. For example,
7198 * if a view has a background drawable and you want to draw the scrollbars
7199 * inside the padding specified by the drawable, you can use
7200 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
7201 * appear at the edge of the view, ignoring the padding, then you can use
7202 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
7203 * @param style the style of the scrollbars. Should be one of
7204 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
7205 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
7206 * @see #SCROLLBARS_INSIDE_OVERLAY
7207 * @see #SCROLLBARS_INSIDE_INSET
7208 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7209 * @see #SCROLLBARS_OUTSIDE_INSET
7210 */
7211 public void setScrollBarStyle(int style) {
7212 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
7213 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07007214 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 recomputePadding();
7216 }
7217 }
7218
7219 /**
7220 * <p>Returns the current scrollbar style.</p>
7221 * @return the current scrollbar style
7222 * @see #SCROLLBARS_INSIDE_OVERLAY
7223 * @see #SCROLLBARS_INSIDE_INSET
7224 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7225 * @see #SCROLLBARS_OUTSIDE_INSET
7226 */
7227 public int getScrollBarStyle() {
7228 return mViewFlags & SCROLLBARS_STYLE_MASK;
7229 }
7230
7231 /**
7232 * <p>Compute the horizontal range that the horizontal scrollbar
7233 * represents.</p>
7234 *
7235 * <p>The range is expressed in arbitrary units that must be the same as the
7236 * units used by {@link #computeHorizontalScrollExtent()} and
7237 * {@link #computeHorizontalScrollOffset()}.</p>
7238 *
7239 * <p>The default range is the drawing width of this view.</p>
7240 *
7241 * @return the total horizontal range represented by the horizontal
7242 * scrollbar
7243 *
7244 * @see #computeHorizontalScrollExtent()
7245 * @see #computeHorizontalScrollOffset()
7246 * @see android.widget.ScrollBarDrawable
7247 */
7248 protected int computeHorizontalScrollRange() {
7249 return getWidth();
7250 }
7251
7252 /**
7253 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7254 * within the horizontal range. This value is used to compute the position
7255 * of the thumb within the scrollbar's track.</p>
7256 *
7257 * <p>The range is expressed in arbitrary units that must be the same as the
7258 * units used by {@link #computeHorizontalScrollRange()} and
7259 * {@link #computeHorizontalScrollExtent()}.</p>
7260 *
7261 * <p>The default offset is the scroll offset of this view.</p>
7262 *
7263 * @return the horizontal offset of the scrollbar's thumb
7264 *
7265 * @see #computeHorizontalScrollRange()
7266 * @see #computeHorizontalScrollExtent()
7267 * @see android.widget.ScrollBarDrawable
7268 */
7269 protected int computeHorizontalScrollOffset() {
7270 return mScrollX;
7271 }
7272
7273 /**
7274 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7275 * within the horizontal range. This value is used to compute the length
7276 * of the thumb within the scrollbar's track.</p>
7277 *
7278 * <p>The range is expressed in arbitrary units that must be the same as the
7279 * units used by {@link #computeHorizontalScrollRange()} and
7280 * {@link #computeHorizontalScrollOffset()}.</p>
7281 *
7282 * <p>The default extent is the drawing width of this view.</p>
7283 *
7284 * @return the horizontal extent of the scrollbar's thumb
7285 *
7286 * @see #computeHorizontalScrollRange()
7287 * @see #computeHorizontalScrollOffset()
7288 * @see android.widget.ScrollBarDrawable
7289 */
7290 protected int computeHorizontalScrollExtent() {
7291 return getWidth();
7292 }
7293
7294 /**
7295 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7296 *
7297 * <p>The range is expressed in arbitrary units that must be the same as the
7298 * units used by {@link #computeVerticalScrollExtent()} and
7299 * {@link #computeVerticalScrollOffset()}.</p>
7300 *
7301 * @return the total vertical range represented by the vertical scrollbar
7302 *
7303 * <p>The default range is the drawing height of this view.</p>
7304 *
7305 * @see #computeVerticalScrollExtent()
7306 * @see #computeVerticalScrollOffset()
7307 * @see android.widget.ScrollBarDrawable
7308 */
7309 protected int computeVerticalScrollRange() {
7310 return getHeight();
7311 }
7312
7313 /**
7314 * <p>Compute the vertical offset of the vertical scrollbar's thumb
7315 * within the horizontal range. This value is used to compute the position
7316 * of the thumb within the scrollbar's track.</p>
7317 *
7318 * <p>The range is expressed in arbitrary units that must be the same as the
7319 * units used by {@link #computeVerticalScrollRange()} and
7320 * {@link #computeVerticalScrollExtent()}.</p>
7321 *
7322 * <p>The default offset is the scroll offset of this view.</p>
7323 *
7324 * @return the vertical offset of the scrollbar's thumb
7325 *
7326 * @see #computeVerticalScrollRange()
7327 * @see #computeVerticalScrollExtent()
7328 * @see android.widget.ScrollBarDrawable
7329 */
7330 protected int computeVerticalScrollOffset() {
7331 return mScrollY;
7332 }
7333
7334 /**
7335 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7336 * within the vertical range. This value is used to compute the length
7337 * of the thumb within the scrollbar's track.</p>
7338 *
7339 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08007340 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007341 * {@link #computeVerticalScrollOffset()}.</p>
7342 *
7343 * <p>The default extent is the drawing height of this view.</p>
7344 *
7345 * @return the vertical extent of the scrollbar's thumb
7346 *
7347 * @see #computeVerticalScrollRange()
7348 * @see #computeVerticalScrollOffset()
7349 * @see android.widget.ScrollBarDrawable
7350 */
7351 protected int computeVerticalScrollExtent() {
7352 return getHeight();
7353 }
7354
7355 /**
7356 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7357 * scrollbars are painted only if they have been awakened first.</p>
7358 *
7359 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07007360 *
7361 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007362 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08007363 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007364 // scrollbars are drawn only when the animation is running
7365 final ScrollabilityCache cache = mScrollCache;
7366 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007367
7368 int state = cache.state;
7369
7370 if (state == ScrollabilityCache.OFF) {
7371 return;
7372 }
7373
7374 boolean invalidate = false;
7375
7376 if (state == ScrollabilityCache.FADING) {
7377 // We're fading -- get our fade interpolation
7378 if (cache.interpolatorValues == null) {
7379 cache.interpolatorValues = new float[1];
7380 }
7381
7382 float[] values = cache.interpolatorValues;
7383
7384 // Stops the animation if we're done
7385 if (cache.scrollBarInterpolator.timeToValues(values) ==
7386 Interpolator.Result.FREEZE_END) {
7387 cache.state = ScrollabilityCache.OFF;
7388 } else {
7389 cache.scrollBar.setAlpha(Math.round(values[0]));
7390 }
7391
7392 // This will make the scroll bars inval themselves after
7393 // drawing. We only want this when we're fading so that
7394 // we prevent excessive redraws
7395 invalidate = true;
7396 } else {
7397 // We're just on -- but we may have been fading before so
7398 // reset alpha
7399 cache.scrollBar.setAlpha(255);
7400 }
7401
7402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007403 final int viewFlags = mViewFlags;
7404
7405 final boolean drawHorizontalScrollBar =
7406 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7407 final boolean drawVerticalScrollBar =
7408 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7409 && !isVerticalScrollBarHidden();
7410
7411 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7412 final int width = mRight - mLeft;
7413 final int height = mBottom - mTop;
7414
7415 final ScrollBarDrawable scrollBar = cache.scrollBar;
7416 int size = scrollBar.getSize(false);
7417 if (size <= 0) {
7418 size = cache.scrollBarSize;
7419 }
7420
Mike Reede8853fc2009-09-04 14:01:48 -04007421 final int scrollX = mScrollX;
7422 final int scrollY = mScrollY;
7423 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7424
Mike Cleronf116bf82009-09-27 19:14:12 -07007425 int left, top, right, bottom;
7426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007427 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007428 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04007429 computeHorizontalScrollOffset(),
7430 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04007431 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07007432 getVerticalScrollbarWidth() : 0;
7433 top = scrollY + height - size - (mUserPaddingBottom & inside);
7434 left = scrollX + (mPaddingLeft & inside);
7435 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7436 bottom = top + size;
7437 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7438 if (invalidate) {
7439 invalidate(left, top, right, bottom);
7440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 }
7442
7443 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04007444 scrollBar.setParameters(computeVerticalScrollRange(),
7445 computeVerticalScrollOffset(),
7446 computeVerticalScrollExtent(), true);
Adam Powell20232d02010-12-08 21:08:53 -08007447 switch (mVerticalScrollbarPosition) {
7448 default:
7449 case SCROLLBAR_POSITION_DEFAULT:
7450 case SCROLLBAR_POSITION_RIGHT:
7451 left = scrollX + width - size - (mUserPaddingRight & inside);
7452 break;
7453 case SCROLLBAR_POSITION_LEFT:
7454 left = scrollX + (mUserPaddingLeft & inside);
7455 break;
7456 }
Mike Cleronf116bf82009-09-27 19:14:12 -07007457 top = scrollY + (mPaddingTop & inside);
7458 right = left + size;
7459 bottom = scrollY + height - (mUserPaddingBottom & inside);
7460 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7461 if (invalidate) {
7462 invalidate(left, top, right, bottom);
7463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007464 }
7465 }
7466 }
7467 }
Romain Guy8506ab42009-06-11 17:35:47 -07007468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007469 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007470 * 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 -08007471 * FastScroller is visible.
7472 * @return whether to temporarily hide the vertical scrollbar
7473 * @hide
7474 */
7475 protected boolean isVerticalScrollBarHidden() {
7476 return false;
7477 }
7478
7479 /**
7480 * <p>Draw the horizontal scrollbar if
7481 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7482 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 * @param canvas the canvas on which to draw the scrollbar
7484 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007485 *
7486 * @see #isHorizontalScrollBarEnabled()
7487 * @see #computeHorizontalScrollRange()
7488 * @see #computeHorizontalScrollExtent()
7489 * @see #computeHorizontalScrollOffset()
7490 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007491 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007492 */
Romain Guy8fb95422010-08-17 18:38:51 -07007493 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7494 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007495 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007496 scrollBar.draw(canvas);
7497 }
Mike Reede8853fc2009-09-04 14:01:48 -04007498
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007499 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007500 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7501 * returns true.</p>
7502 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007503 * @param canvas the canvas on which to draw the scrollbar
7504 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007505 *
7506 * @see #isVerticalScrollBarEnabled()
7507 * @see #computeVerticalScrollRange()
7508 * @see #computeVerticalScrollExtent()
7509 * @see #computeVerticalScrollOffset()
7510 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007511 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007512 */
Romain Guy8fb95422010-08-17 18:38:51 -07007513 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7514 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007515 scrollBar.setBounds(l, t, r, b);
7516 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007517 }
7518
7519 /**
7520 * Implement this to do your drawing.
7521 *
7522 * @param canvas the canvas on which the background will be drawn
7523 */
7524 protected void onDraw(Canvas canvas) {
7525 }
7526
7527 /*
7528 * Caller is responsible for calling requestLayout if necessary.
7529 * (This allows addViewInLayout to not request a new layout.)
7530 */
7531 void assignParent(ViewParent parent) {
7532 if (mParent == null) {
7533 mParent = parent;
7534 } else if (parent == null) {
7535 mParent = null;
7536 } else {
7537 throw new RuntimeException("view " + this + " being added, but"
7538 + " it already has a parent");
7539 }
7540 }
7541
7542 /**
7543 * This is called when the view is attached to a window. At this point it
7544 * has a Surface and will start drawing. Note that this function is
7545 * guaranteed to be called before {@link #onDraw}, however it may be called
7546 * any time before the first onDraw -- including before or after
7547 * {@link #onMeasure}.
7548 *
7549 * @see #onDetachedFromWindow()
7550 */
7551 protected void onAttachedToWindow() {
7552 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7553 mParent.requestTransparentRegion(this);
7554 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007555 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7556 initialAwakenScrollBars();
7557 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7558 }
Chet Haasea9b61ac2010-12-20 07:40:25 -08007559 jumpDrawablesToCurrentState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 }
7561
7562 /**
7563 * This is called when the view is detached from a window. At this point it
7564 * no longer has a surface for drawing.
7565 *
7566 * @see #onAttachedToWindow()
7567 */
7568 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007569 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guy6c319ca2011-01-11 14:29:25 -08007570
Romain Guya440b002010-02-24 15:57:54 -08007571 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007572 removeLongPressCallback();
Romain Guy6c319ca2011-01-11 14:29:25 -08007573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 destroyDrawingCache();
Romain Guy6c319ca2011-01-11 14:29:25 -08007575
7576 if (mHardwareLayer != null) {
7577 mHardwareLayer.destroy();
7578 mHardwareLayer = null;
7579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007580 }
7581
7582 /**
7583 * @return The number of times this view has been attached to a window
7584 */
7585 protected int getWindowAttachCount() {
7586 return mWindowAttachCount;
7587 }
7588
7589 /**
7590 * Retrieve a unique token identifying the window this view is attached to.
7591 * @return Return the window's token for use in
7592 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7593 */
7594 public IBinder getWindowToken() {
7595 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7596 }
7597
7598 /**
7599 * Retrieve a unique token identifying the top-level "real" window of
7600 * the window that this view is attached to. That is, this is like
7601 * {@link #getWindowToken}, except if the window this view in is a panel
7602 * window (attached to another containing window), then the token of
7603 * the containing window is returned instead.
7604 *
7605 * @return Returns the associated window token, either
7606 * {@link #getWindowToken()} or the containing window's token.
7607 */
7608 public IBinder getApplicationWindowToken() {
7609 AttachInfo ai = mAttachInfo;
7610 if (ai != null) {
7611 IBinder appWindowToken = ai.mPanelParentWindowToken;
7612 if (appWindowToken == null) {
7613 appWindowToken = ai.mWindowToken;
7614 }
7615 return appWindowToken;
7616 }
7617 return null;
7618 }
7619
7620 /**
7621 * Retrieve private session object this view hierarchy is using to
7622 * communicate with the window manager.
7623 * @return the session object to communicate with the window manager
7624 */
7625 /*package*/ IWindowSession getWindowSession() {
7626 return mAttachInfo != null ? mAttachInfo.mSession : null;
7627 }
7628
7629 /**
7630 * @param info the {@link android.view.View.AttachInfo} to associated with
7631 * this view
7632 */
7633 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7634 //System.out.println("Attached! " + this);
7635 mAttachInfo = info;
7636 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007637 // We will need to evaluate the drawable state at least once.
7638 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007639 if (mFloatingTreeObserver != null) {
7640 info.mTreeObserver.merge(mFloatingTreeObserver);
7641 mFloatingTreeObserver = null;
7642 }
7643 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7644 mAttachInfo.mScrollContainers.add(this);
7645 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7646 }
7647 performCollectViewAttributes(visibility);
7648 onAttachedToWindow();
7649 int vis = info.mWindowVisibility;
7650 if (vis != GONE) {
7651 onWindowVisibilityChanged(vis);
7652 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007653 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7654 // If nobody has evaluated the drawable state yet, then do it now.
7655 refreshDrawableState();
7656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007657 }
7658
7659 void dispatchDetachedFromWindow() {
7660 //System.out.println("Detached! " + this);
7661 AttachInfo info = mAttachInfo;
7662 if (info != null) {
7663 int vis = info.mWindowVisibility;
7664 if (vis != GONE) {
7665 onWindowVisibilityChanged(GONE);
7666 }
7667 }
7668
7669 onDetachedFromWindow();
7670 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7671 mAttachInfo.mScrollContainers.remove(this);
7672 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7673 }
7674 mAttachInfo = null;
7675 }
7676
7677 /**
7678 * Store this view hierarchy's frozen state into the given container.
7679 *
7680 * @param container The SparseArray in which to save the view's state.
7681 *
7682 * @see #restoreHierarchyState
7683 * @see #dispatchSaveInstanceState
7684 * @see #onSaveInstanceState
7685 */
7686 public void saveHierarchyState(SparseArray<Parcelable> container) {
7687 dispatchSaveInstanceState(container);
7688 }
7689
7690 /**
7691 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7692 * May be overridden to modify how freezing happens to a view's children; for example, some
7693 * views may want to not store state for their children.
7694 *
7695 * @param container The SparseArray in which to save the view's state.
7696 *
7697 * @see #dispatchRestoreInstanceState
7698 * @see #saveHierarchyState
7699 * @see #onSaveInstanceState
7700 */
7701 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7702 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7703 mPrivateFlags &= ~SAVE_STATE_CALLED;
7704 Parcelable state = onSaveInstanceState();
7705 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7706 throw new IllegalStateException(
7707 "Derived class did not call super.onSaveInstanceState()");
7708 }
7709 if (state != null) {
7710 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7711 // + ": " + state);
7712 container.put(mID, state);
7713 }
7714 }
7715 }
7716
7717 /**
7718 * Hook allowing a view to generate a representation of its internal state
7719 * that can later be used to create a new instance with that same state.
7720 * This state should only contain information that is not persistent or can
7721 * not be reconstructed later. For example, you will never store your
7722 * current position on screen because that will be computed again when a
7723 * new instance of the view is placed in its view hierarchy.
7724 * <p>
7725 * Some examples of things you may store here: the current cursor position
7726 * in a text view (but usually not the text itself since that is stored in a
7727 * content provider or other persistent storage), the currently selected
7728 * item in a list view.
7729 *
7730 * @return Returns a Parcelable object containing the view's current dynamic
7731 * state, or null if there is nothing interesting to save. The
7732 * default implementation returns null.
7733 * @see #onRestoreInstanceState
7734 * @see #saveHierarchyState
7735 * @see #dispatchSaveInstanceState
7736 * @see #setSaveEnabled(boolean)
7737 */
7738 protected Parcelable onSaveInstanceState() {
7739 mPrivateFlags |= SAVE_STATE_CALLED;
7740 return BaseSavedState.EMPTY_STATE;
7741 }
7742
7743 /**
7744 * Restore this view hierarchy's frozen state from the given container.
7745 *
7746 * @param container The SparseArray which holds previously frozen states.
7747 *
7748 * @see #saveHierarchyState
7749 * @see #dispatchRestoreInstanceState
7750 * @see #onRestoreInstanceState
7751 */
7752 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7753 dispatchRestoreInstanceState(container);
7754 }
7755
7756 /**
7757 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7758 * children. May be overridden to modify how restoreing happens to a view's children; for
7759 * example, some views may want to not store state for their children.
7760 *
7761 * @param container The SparseArray which holds previously saved state.
7762 *
7763 * @see #dispatchSaveInstanceState
7764 * @see #restoreHierarchyState
7765 * @see #onRestoreInstanceState
7766 */
7767 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7768 if (mID != NO_ID) {
7769 Parcelable state = container.get(mID);
7770 if (state != null) {
7771 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7772 // + ": " + state);
7773 mPrivateFlags &= ~SAVE_STATE_CALLED;
7774 onRestoreInstanceState(state);
7775 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7776 throw new IllegalStateException(
7777 "Derived class did not call super.onRestoreInstanceState()");
7778 }
7779 }
7780 }
7781 }
7782
7783 /**
7784 * Hook allowing a view to re-apply a representation of its internal state that had previously
7785 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7786 * null state.
7787 *
7788 * @param state The frozen state that had previously been returned by
7789 * {@link #onSaveInstanceState}.
7790 *
7791 * @see #onSaveInstanceState
7792 * @see #restoreHierarchyState
7793 * @see #dispatchRestoreInstanceState
7794 */
7795 protected void onRestoreInstanceState(Parcelable state) {
7796 mPrivateFlags |= SAVE_STATE_CALLED;
7797 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007798 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7799 + "received " + state.getClass().toString() + " instead. This usually happens "
7800 + "when two views of different type have the same id in the same hierarchy. "
7801 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7802 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803 }
7804 }
7805
7806 /**
7807 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7808 *
7809 * @return the drawing start time in milliseconds
7810 */
7811 public long getDrawingTime() {
7812 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7813 }
7814
7815 /**
7816 * <p>Enables or disables the duplication of the parent's state into this view. When
7817 * duplication is enabled, this view gets its drawable state from its parent rather
7818 * than from its own internal properties.</p>
7819 *
7820 * <p>Note: in the current implementation, setting this property to true after the
7821 * view was added to a ViewGroup might have no effect at all. This property should
7822 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7823 *
7824 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7825 * property is enabled, an exception will be thrown.</p>
Gilles Debunnefb817032011-01-13 13:52:49 -08007826 *
7827 * <p>Note: if the child view uses and updates additionnal states which are unknown to the
7828 * parent, these states should not be affected by this method.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007829 *
7830 * @param enabled True to enable duplication of the parent's drawable state, false
7831 * to disable it.
7832 *
7833 * @see #getDrawableState()
7834 * @see #isDuplicateParentStateEnabled()
7835 */
7836 public void setDuplicateParentStateEnabled(boolean enabled) {
7837 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7838 }
7839
7840 /**
7841 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7842 *
7843 * @return True if this view's drawable state is duplicated from the parent,
7844 * false otherwise
7845 *
7846 * @see #getDrawableState()
7847 * @see #setDuplicateParentStateEnabled(boolean)
7848 */
7849 public boolean isDuplicateParentStateEnabled() {
7850 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7851 }
7852
7853 /**
Romain Guy171c5922011-01-06 10:04:23 -08007854 * <p>Specifies the type of layer backing this view. The layer can be
7855 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
7856 * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
7857 *
7858 * <p>A layer is associated with an optional {@link android.graphics.Paint}
7859 * instance that controls how the layer is composed on screen. The following
7860 * properties of the paint are taken into account when composing the layer:</p>
7861 * <ul>
7862 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
7863 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
7864 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
7865 * </ul>
7866 *
7867 * <p>If this view has an alpha value set to < 1.0 by calling
7868 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
7869 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
7870 * equivalent to setting a hardware layer on this view and providing a paint with
7871 * the desired alpha value.<p>
7872 *
7873 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
7874 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
7875 * for more information on when and how to use layers.</p>
7876 *
7877 * @param layerType The ype of layer to use with this view, must be one of
7878 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
7879 * {@link #LAYER_TYPE_HARDWARE}
7880 * @param paint The paint used to compose the layer. This argument is optional
7881 * and can be null. It is ignored when the layer type is
7882 * {@link #LAYER_TYPE_NONE}
7883 *
7884 * @see #getLayerType()
7885 * @see #LAYER_TYPE_NONE
7886 * @see #LAYER_TYPE_SOFTWARE
7887 * @see #LAYER_TYPE_HARDWARE
7888 * @see #setAlpha(float)
7889 *
7890 * @attr ref android.R.styleable#View_layerType
7891 */
7892 public void setLayerType(int layerType, Paint paint) {
7893 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
7894 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
7895 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
7896 }
Romain Guy6c319ca2011-01-11 14:29:25 -08007897
7898 if (layerType == mLayerType) return;
Romain Guy171c5922011-01-06 10:04:23 -08007899
7900 // Destroy any previous software drawing cache if needed
Romain Guy6c319ca2011-01-11 14:29:25 -08007901 switch (mLayerType) {
7902 case LAYER_TYPE_SOFTWARE:
7903 if (mDrawingCache != null) {
7904 mDrawingCache.recycle();
7905 mDrawingCache = null;
7906 }
7907
7908 if (mUnscaledDrawingCache != null) {
7909 mUnscaledDrawingCache.recycle();
7910 mUnscaledDrawingCache = null;
7911 }
7912 break;
7913 case LAYER_TYPE_HARDWARE:
7914 if (mHardwareLayer != null) {
7915 mHardwareLayer.destroy();
7916 mHardwareLayer = null;
7917 }
7918 break;
7919 default:
7920 break;
Romain Guy171c5922011-01-06 10:04:23 -08007921 }
7922
7923 mLayerType = layerType;
7924 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
7925
Romain Guy6c319ca2011-01-11 14:29:25 -08007926 // TODO: Make sure we invalidate the parent's display list
Romain Guy171c5922011-01-06 10:04:23 -08007927 invalidate();
7928 }
7929
7930 /**
7931 * Indicates what type of layer is currently associated with this view. By default
7932 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
7933 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
7934 * for more information on the different types of layers.
7935 *
7936 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
7937 * {@link #LAYER_TYPE_HARDWARE}
7938 *
7939 * @see #setLayerType(int, android.graphics.Paint)
7940 * @see #LAYER_TYPE_NONE
7941 * @see #LAYER_TYPE_SOFTWARE
7942 * @see #LAYER_TYPE_HARDWARE
7943 */
7944 public int getLayerType() {
7945 return mLayerType;
7946 }
Romain Guy6c319ca2011-01-11 14:29:25 -08007947
7948 /**
7949 * <p>Returns a hardware layer that can be used to draw this view again
7950 * without executing its draw method.</p>
7951 *
7952 * @return A HardwareLayer ready to render, or null if an error occurred.
7953 */
7954 HardwareLayer getHardwareLayer(Canvas currentCanvas) {
7955 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
7956 return null;
7957 }
7958
7959 final int width = mRight - mLeft;
7960 final int height = mBottom - mTop;
7961
7962 if (width == 0 || height == 0) {
7963 return null;
7964 }
7965
7966 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
7967 if (mHardwareLayer == null) {
7968 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
7969 width, height, isOpaque());
7970 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
7971 mHardwareLayer.resize(width, height);
7972 }
7973
7974 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
7975 try {
7976 canvas.setViewport(width, height);
7977 canvas.onPreDraw();
7978
7979 computeScroll();
7980 canvas.translate(-mScrollX, -mScrollY);
7981
7982 final int restoreCount = canvas.save();
7983
7984 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
7985
7986 // Fast path for layouts with no backgrounds
7987 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7988 mPrivateFlags &= ~DIRTY_MASK;
7989 dispatchDraw(canvas);
7990 } else {
7991 draw(canvas);
7992 }
7993
7994 canvas.restoreToCount(restoreCount);
7995 } finally {
7996 canvas.onPostDraw();
7997 mHardwareLayer.end(currentCanvas);
7998 }
7999 }
8000
8001 return mHardwareLayer;
8002 }
Romain Guy171c5922011-01-06 10:04:23 -08008003
8004 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
8006 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
8007 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
8008 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
8009 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
8010 * null.</p>
Romain Guy171c5922011-01-06 10:04:23 -08008011 *
8012 * <p>Enabling the drawing cache is similar to
8013 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
8014 * acceleration is turned off. When hardware acceleration is turned on enabling the
8015 * drawing cache has either no effect or the cache used at drawing time is not a bitmap.
8016 * This API can however be used to manually generate a bitmap copy of this view.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 *
8018 * @param enabled true to enable the drawing cache, false otherwise
8019 *
8020 * @see #isDrawingCacheEnabled()
8021 * @see #getDrawingCache()
8022 * @see #buildDrawingCache()
Romain Guy171c5922011-01-06 10:04:23 -08008023 * @see #setLayerType(int, android.graphics.Paint)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 */
8025 public void setDrawingCacheEnabled(boolean enabled) {
8026 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
8027 }
8028
8029 /**
8030 * <p>Indicates whether the drawing cache is enabled for this view.</p>
8031 *
8032 * @return true if the drawing cache is enabled
8033 *
8034 * @see #setDrawingCacheEnabled(boolean)
8035 * @see #getDrawingCache()
8036 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07008037 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 public boolean isDrawingCacheEnabled() {
8039 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
8040 }
8041
8042 /**
Romain Guyb051e892010-09-28 19:09:36 -07008043 * <p>Returns a display list that can be used to draw this view again
8044 * without executing its draw method.</p>
8045 *
8046 * @return A DisplayList ready to replay, or null if caching is not enabled.
8047 */
8048 DisplayList getDisplayList() {
8049 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8050 return null;
8051 }
Romain Guyb051e892010-09-28 19:09:36 -07008052 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8053 return null;
8054 }
8055
8056 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
Chet Haase9e90a992011-01-04 16:23:21 -08008057 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
8058 mDisplayList == null || !mDisplayList.isValid())) {
Romain Guyb051e892010-09-28 19:09:36 -07008059
Chet Haase9e90a992011-01-04 16:23:21 -08008060 if (mDisplayList == null) {
8061 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
8062 }
Romain Guyb051e892010-09-28 19:09:36 -07008063
8064 final HardwareCanvas canvas = mDisplayList.start();
8065 try {
8066 int width = mRight - mLeft;
8067 int height = mBottom - mTop;
8068
8069 canvas.setViewport(width, height);
8070 canvas.onPreDraw();
8071
8072 final int restoreCount = canvas.save();
8073
Romain Guy2fe9a8f2010-10-04 20:17:01 -07008074 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07008075
8076 // Fast path for layouts with no backgrounds
8077 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8078 mPrivateFlags &= ~DIRTY_MASK;
8079 dispatchDraw(canvas);
8080 } else {
8081 draw(canvas);
8082 }
8083
8084 canvas.restoreToCount(restoreCount);
8085 } finally {
8086 canvas.onPostDraw();
8087
8088 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07008089 }
8090 }
8091
8092 return mDisplayList;
8093 }
8094
8095 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008096 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
8097 *
8098 * @return A non-scaled bitmap representing this view or null if cache is disabled.
8099 *
8100 * @see #getDrawingCache(boolean)
8101 */
8102 public Bitmap getDrawingCache() {
8103 return getDrawingCache(false);
8104 }
8105
8106 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008107 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
8108 * is null when caching is disabled. If caching is enabled and the cache is not ready,
8109 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
8110 * draw from the cache when the cache is enabled. To benefit from the cache, you must
8111 * request the drawing cache by calling this method and draw it on screen if the
8112 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008113 *
8114 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8115 * this method will create a bitmap of the same size as this view. Because this bitmap
8116 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8117 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8118 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8119 * size than the view. This implies that your application must be able to handle this
8120 * size.</p>
8121 *
8122 * @param autoScale Indicates whether the generated bitmap should be scaled based on
8123 * the current density of the screen when the application is in compatibility
8124 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008125 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008126 * @return A bitmap representing this view or null if cache is disabled.
8127 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 * @see #setDrawingCacheEnabled(boolean)
8129 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07008130 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008131 * @see #destroyDrawingCache()
8132 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008133 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008134 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8135 return null;
8136 }
8137 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008138 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008139 }
Romain Guy02890fd2010-08-06 17:58:44 -07008140 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 }
8142
8143 /**
8144 * <p>Frees the resources used by the drawing cache. If you call
8145 * {@link #buildDrawingCache()} manually without calling
8146 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8147 * should cleanup the cache with this method afterwards.</p>
8148 *
8149 * @see #setDrawingCacheEnabled(boolean)
8150 * @see #buildDrawingCache()
8151 * @see #getDrawingCache()
8152 */
8153 public void destroyDrawingCache() {
8154 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008155 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008156 mDrawingCache = null;
8157 }
Romain Guyfbd8f692009-06-26 14:51:58 -07008158 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008159 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07008160 mUnscaledDrawingCache = null;
8161 }
Romain Guyb051e892010-09-28 19:09:36 -07008162 if (mDisplayList != null) {
Chet Haase9e90a992011-01-04 16:23:21 -08008163 mDisplayList.invalidate();
Romain Guyb051e892010-09-28 19:09:36 -07008164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 }
8166
8167 /**
8168 * Setting a solid background color for the drawing cache's bitmaps will improve
8169 * perfromance and memory usage. Note, though that this should only be used if this
8170 * view will always be drawn on top of a solid color.
8171 *
8172 * @param color The background color to use for the drawing cache's bitmap
8173 *
8174 * @see #setDrawingCacheEnabled(boolean)
8175 * @see #buildDrawingCache()
8176 * @see #getDrawingCache()
8177 */
8178 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08008179 if (color != mDrawingCacheBackgroundColor) {
8180 mDrawingCacheBackgroundColor = color;
8181 mPrivateFlags &= ~DRAWING_CACHE_VALID;
8182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008183 }
8184
8185 /**
8186 * @see #setDrawingCacheBackgroundColor(int)
8187 *
8188 * @return The background color to used for the drawing cache's bitmap
8189 */
8190 public int getDrawingCacheBackgroundColor() {
8191 return mDrawingCacheBackgroundColor;
8192 }
8193
8194 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008195 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
8196 *
8197 * @see #buildDrawingCache(boolean)
8198 */
8199 public void buildDrawingCache() {
8200 buildDrawingCache(false);
8201 }
8202
8203 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008204 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
8205 *
8206 * <p>If you call {@link #buildDrawingCache()} manually without calling
8207 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8208 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008209 *
8210 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8211 * this method will create a bitmap of the same size as this view. Because this bitmap
8212 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8213 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8214 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8215 * size than the view. This implies that your application must be able to handle this
8216 * size.</p>
Romain Guy0d9275e2010-10-26 14:22:30 -07008217 *
8218 * <p>You should avoid calling this method when hardware acceleration is enabled. If
8219 * you do not need the drawing cache bitmap, calling this method will increase memory
8220 * usage and cause the view to be rendered in software once, thus negatively impacting
8221 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 *
8223 * @see #getDrawingCache()
8224 * @see #destroyDrawingCache()
8225 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008226 public void buildDrawingCache(boolean autoScale) {
8227 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07008228 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008229
8230 if (ViewDebug.TRACE_HIERARCHY) {
8231 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
8232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008233
Romain Guy8506ab42009-06-11 17:35:47 -07008234 int width = mRight - mLeft;
8235 int height = mBottom - mTop;
8236
8237 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07008238 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07008239
Romain Guye1123222009-06-29 14:24:56 -07008240 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008241 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
8242 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07008243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008244
8245 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07008246 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08008247 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008248
8249 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07008250 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08008251 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008252 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
8253 destroyDrawingCache();
8254 return;
8255 }
8256
8257 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07008258 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259
8260 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008261 Bitmap.Config quality;
8262 if (!opaque) {
8263 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
8264 case DRAWING_CACHE_QUALITY_AUTO:
8265 quality = Bitmap.Config.ARGB_8888;
8266 break;
8267 case DRAWING_CACHE_QUALITY_LOW:
8268 quality = Bitmap.Config.ARGB_4444;
8269 break;
8270 case DRAWING_CACHE_QUALITY_HIGH:
8271 quality = Bitmap.Config.ARGB_8888;
8272 break;
8273 default:
8274 quality = Bitmap.Config.ARGB_8888;
8275 break;
8276 }
8277 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07008278 // Optimization for translucent windows
8279 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08008280 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008281 }
8282
8283 // Try to cleanup memory
8284 if (bitmap != null) bitmap.recycle();
8285
8286 try {
8287 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07008288 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07008289 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07008290 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008291 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07008292 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008293 }
Adam Powell26153a32010-11-08 15:22:27 -08008294 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008295 } catch (OutOfMemoryError e) {
8296 // If there is not enough memory to create the bitmap cache, just
8297 // ignore the issue as bitmap caches are not required to draw the
8298 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07008299 if (autoScale) {
8300 mDrawingCache = null;
8301 } else {
8302 mUnscaledDrawingCache = null;
8303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 return;
8305 }
8306
8307 clear = drawingCacheBackgroundColor != 0;
8308 }
8309
8310 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008311 if (attachInfo != null) {
8312 canvas = attachInfo.mCanvas;
8313 if (canvas == null) {
8314 canvas = new Canvas();
8315 }
8316 canvas.setBitmap(bitmap);
8317 // Temporarily clobber the cached Canvas in case one of our children
8318 // is also using a drawing cache. Without this, the children would
8319 // steal the canvas by attaching their own bitmap to it and bad, bad
8320 // thing would happen (invisible views, corrupted drawings, etc.)
8321 attachInfo.mCanvas = null;
8322 } else {
8323 // This case should hopefully never or seldom happen
8324 canvas = new Canvas(bitmap);
8325 }
8326
8327 if (clear) {
8328 bitmap.eraseColor(drawingCacheBackgroundColor);
8329 }
8330
8331 computeScroll();
8332 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07008333
Romain Guye1123222009-06-29 14:24:56 -07008334 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008335 final float scale = attachInfo.mApplicationScale;
8336 canvas.scale(scale, scale);
8337 }
8338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008339 canvas.translate(-mScrollX, -mScrollY);
8340
Romain Guy5bcdff42009-05-14 21:27:18 -07008341 mPrivateFlags |= DRAWN;
Romain Guy171c5922011-01-06 10:04:23 -08008342 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
8343 mLayerType != LAYER_TYPE_NONE) {
Romain Guy0d9275e2010-10-26 14:22:30 -07008344 mPrivateFlags |= DRAWING_CACHE_VALID;
8345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346
8347 // Fast path for layouts with no backgrounds
8348 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8349 if (ViewDebug.TRACE_HIERARCHY) {
8350 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8351 }
Romain Guy5bcdff42009-05-14 21:27:18 -07008352 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008353 dispatchDraw(canvas);
8354 } else {
8355 draw(canvas);
8356 }
8357
8358 canvas.restoreToCount(restoreCount);
8359
8360 if (attachInfo != null) {
8361 // Restore the cached Canvas for our siblings
8362 attachInfo.mCanvas = canvas;
8363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008364 }
8365 }
8366
8367 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008368 * Create a snapshot of the view into a bitmap. We should probably make
8369 * some form of this public, but should think about the API.
8370 */
Romain Guy223ff5c2010-03-02 17:07:47 -08008371 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008372 int width = mRight - mLeft;
8373 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008374
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008375 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07008376 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008377 width = (int) ((width * scale) + 0.5f);
8378 height = (int) ((height * scale) + 0.5f);
8379
Romain Guy8c11e312009-09-14 15:15:30 -07008380 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008381 if (bitmap == null) {
8382 throw new OutOfMemoryError();
8383 }
8384
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008385 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8386
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008387 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008388 if (attachInfo != null) {
8389 canvas = attachInfo.mCanvas;
8390 if (canvas == null) {
8391 canvas = new Canvas();
8392 }
8393 canvas.setBitmap(bitmap);
8394 // Temporarily clobber the cached Canvas in case one of our children
8395 // is also using a drawing cache. Without this, the children would
8396 // steal the canvas by attaching their own bitmap to it and bad, bad
8397 // things would happen (invisible views, corrupted drawings, etc.)
8398 attachInfo.mCanvas = null;
8399 } else {
8400 // This case should hopefully never or seldom happen
8401 canvas = new Canvas(bitmap);
8402 }
8403
Romain Guy5bcdff42009-05-14 21:27:18 -07008404 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008405 bitmap.eraseColor(backgroundColor);
8406 }
8407
8408 computeScroll();
8409 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008410 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008411 canvas.translate(-mScrollX, -mScrollY);
8412
Romain Guy5bcdff42009-05-14 21:27:18 -07008413 // Temporarily remove the dirty mask
8414 int flags = mPrivateFlags;
8415 mPrivateFlags &= ~DIRTY_MASK;
8416
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008417 // Fast path for layouts with no backgrounds
8418 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8419 dispatchDraw(canvas);
8420 } else {
8421 draw(canvas);
8422 }
8423
Romain Guy5bcdff42009-05-14 21:27:18 -07008424 mPrivateFlags = flags;
8425
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008426 canvas.restoreToCount(restoreCount);
8427
8428 if (attachInfo != null) {
8429 // Restore the cached Canvas for our siblings
8430 attachInfo.mCanvas = canvas;
8431 }
Romain Guy8506ab42009-06-11 17:35:47 -07008432
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008433 return bitmap;
8434 }
8435
8436 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008437 * Indicates whether this View is currently in edit mode. A View is usually
8438 * in edit mode when displayed within a developer tool. For instance, if
8439 * this View is being drawn by a visual user interface builder, this method
8440 * should return true.
8441 *
8442 * Subclasses should check the return value of this method to provide
8443 * different behaviors if their normal behavior might interfere with the
8444 * host environment. For instance: the class spawns a thread in its
8445 * constructor, the drawing code relies on device-specific features, etc.
8446 *
8447 * This method is usually checked in the drawing code of custom widgets.
8448 *
8449 * @return True if this View is in edit mode, false otherwise.
8450 */
8451 public boolean isInEditMode() {
8452 return false;
8453 }
8454
8455 /**
8456 * If the View draws content inside its padding and enables fading edges,
8457 * it needs to support padding offsets. Padding offsets are added to the
8458 * fading edges to extend the length of the fade so that it covers pixels
8459 * drawn inside the padding.
8460 *
8461 * Subclasses of this class should override this method if they need
8462 * to draw content inside the padding.
8463 *
8464 * @return True if padding offset must be applied, false otherwise.
8465 *
8466 * @see #getLeftPaddingOffset()
8467 * @see #getRightPaddingOffset()
8468 * @see #getTopPaddingOffset()
8469 * @see #getBottomPaddingOffset()
8470 *
8471 * @since CURRENT
8472 */
8473 protected boolean isPaddingOffsetRequired() {
8474 return false;
8475 }
8476
8477 /**
8478 * Amount by which to extend the left fading region. Called only when
8479 * {@link #isPaddingOffsetRequired()} returns true.
8480 *
8481 * @return The left padding offset in pixels.
8482 *
8483 * @see #isPaddingOffsetRequired()
8484 *
8485 * @since CURRENT
8486 */
8487 protected int getLeftPaddingOffset() {
8488 return 0;
8489 }
8490
8491 /**
8492 * Amount by which to extend the right fading region. Called only when
8493 * {@link #isPaddingOffsetRequired()} returns true.
8494 *
8495 * @return The right padding offset in pixels.
8496 *
8497 * @see #isPaddingOffsetRequired()
8498 *
8499 * @since CURRENT
8500 */
8501 protected int getRightPaddingOffset() {
8502 return 0;
8503 }
8504
8505 /**
8506 * Amount by which to extend the top fading region. Called only when
8507 * {@link #isPaddingOffsetRequired()} returns true.
8508 *
8509 * @return The top padding offset in pixels.
8510 *
8511 * @see #isPaddingOffsetRequired()
8512 *
8513 * @since CURRENT
8514 */
8515 protected int getTopPaddingOffset() {
8516 return 0;
8517 }
8518
8519 /**
8520 * Amount by which to extend the bottom fading region. Called only when
8521 * {@link #isPaddingOffsetRequired()} returns true.
8522 *
8523 * @return The bottom padding offset in pixels.
8524 *
8525 * @see #isPaddingOffsetRequired()
8526 *
8527 * @since CURRENT
8528 */
8529 protected int getBottomPaddingOffset() {
8530 return 0;
8531 }
8532
8533 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008534 * <p>Indicates whether this view is attached to an hardware accelerated
8535 * window or not.</p>
8536 *
8537 * <p>Even if this method returns true, it does not mean that every call
8538 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8539 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8540 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8541 * window is hardware accelerated,
8542 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8543 * return false, and this method will return true.</p>
8544 *
8545 * @return True if the view is attached to a window and the window is
8546 * hardware accelerated; false in any other case.
8547 */
8548 public boolean isHardwareAccelerated() {
8549 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8550 }
8551
8552 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008553 * Manually render this view (and all of its children) to the given Canvas.
8554 * The view must have already done a full layout before this function is
Chet Haasec75ec332010-12-17 07:44:30 -08008555 * called. When implementing a view, implement {@link #onDraw} instead of
8556 * overriding this method. If you do need to override this method, call
8557 * the superclass version.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008558 *
8559 * @param canvas The Canvas to which the View is rendered.
8560 */
8561 public void draw(Canvas canvas) {
8562 if (ViewDebug.TRACE_HIERARCHY) {
8563 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8564 }
8565
Romain Guy5bcdff42009-05-14 21:27:18 -07008566 final int privateFlags = mPrivateFlags;
8567 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8568 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8569 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008571 /*
8572 * Draw traversal performs several drawing steps which must be executed
8573 * in the appropriate order:
8574 *
8575 * 1. Draw the background
8576 * 2. If necessary, save the canvas' layers to prepare for fading
8577 * 3. Draw view's content
8578 * 4. Draw children
8579 * 5. If necessary, draw the fading edges and restore layers
8580 * 6. Draw decorations (scrollbars for instance)
8581 */
8582
8583 // Step 1, draw the background, if needed
8584 int saveCount;
8585
Romain Guy24443ea2009-05-11 11:56:30 -07008586 if (!dirtyOpaque) {
8587 final Drawable background = mBGDrawable;
8588 if (background != null) {
8589 final int scrollX = mScrollX;
8590 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591
Romain Guy24443ea2009-05-11 11:56:30 -07008592 if (mBackgroundSizeChanged) {
8593 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8594 mBackgroundSizeChanged = false;
8595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596
Romain Guy24443ea2009-05-11 11:56:30 -07008597 if ((scrollX | scrollY) == 0) {
8598 background.draw(canvas);
8599 } else {
8600 canvas.translate(scrollX, scrollY);
8601 background.draw(canvas);
8602 canvas.translate(-scrollX, -scrollY);
8603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008604 }
8605 }
8606
8607 // skip step 2 & 5 if possible (common case)
8608 final int viewFlags = mViewFlags;
8609 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8610 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8611 if (!verticalEdges && !horizontalEdges) {
8612 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008613 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008614
8615 // Step 4, draw the children
8616 dispatchDraw(canvas);
8617
8618 // Step 6, draw decorations (scrollbars)
8619 onDrawScrollBars(canvas);
8620
8621 // we're done...
8622 return;
8623 }
8624
8625 /*
8626 * Here we do the full fledged routine...
8627 * (this is an uncommon case where speed matters less,
8628 * this is why we repeat some of the tests that have been
8629 * done above)
8630 */
8631
8632 boolean drawTop = false;
8633 boolean drawBottom = false;
8634 boolean drawLeft = false;
8635 boolean drawRight = false;
8636
8637 float topFadeStrength = 0.0f;
8638 float bottomFadeStrength = 0.0f;
8639 float leftFadeStrength = 0.0f;
8640 float rightFadeStrength = 0.0f;
8641
8642 // Step 2, save the canvas' layers
8643 int paddingLeft = mPaddingLeft;
8644 int paddingTop = mPaddingTop;
8645
8646 final boolean offsetRequired = isPaddingOffsetRequired();
8647 if (offsetRequired) {
8648 paddingLeft += getLeftPaddingOffset();
8649 paddingTop += getTopPaddingOffset();
8650 }
8651
8652 int left = mScrollX + paddingLeft;
8653 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8654 int top = mScrollY + paddingTop;
8655 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8656
8657 if (offsetRequired) {
8658 right += getRightPaddingOffset();
8659 bottom += getBottomPaddingOffset();
8660 }
8661
8662 final ScrollabilityCache scrollabilityCache = mScrollCache;
8663 int length = scrollabilityCache.fadingEdgeLength;
8664
8665 // clip the fade length if top and bottom fades overlap
8666 // overlapping fades produce odd-looking artifacts
8667 if (verticalEdges && (top + length > bottom - length)) {
8668 length = (bottom - top) / 2;
8669 }
8670
8671 // also clip horizontal fades if necessary
8672 if (horizontalEdges && (left + length > right - length)) {
8673 length = (right - left) / 2;
8674 }
8675
8676 if (verticalEdges) {
8677 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008678 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008679 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008680 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008681 }
8682
8683 if (horizontalEdges) {
8684 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008685 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008687 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 }
8689
8690 saveCount = canvas.getSaveCount();
8691
8692 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008693 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008694 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8695
8696 if (drawTop) {
8697 canvas.saveLayer(left, top, right, top + length, null, flags);
8698 }
8699
8700 if (drawBottom) {
8701 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8702 }
8703
8704 if (drawLeft) {
8705 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8706 }
8707
8708 if (drawRight) {
8709 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8710 }
8711 } else {
8712 scrollabilityCache.setFadeColor(solidColor);
8713 }
8714
8715 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008716 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008717
8718 // Step 4, draw the children
8719 dispatchDraw(canvas);
8720
8721 // Step 5, draw the fade effect and restore layers
8722 final Paint p = scrollabilityCache.paint;
8723 final Matrix matrix = scrollabilityCache.matrix;
8724 final Shader fade = scrollabilityCache.shader;
8725 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8726
8727 if (drawTop) {
8728 matrix.setScale(1, fadeHeight * topFadeStrength);
8729 matrix.postTranslate(left, top);
8730 fade.setLocalMatrix(matrix);
8731 canvas.drawRect(left, top, right, top + length, p);
8732 }
8733
8734 if (drawBottom) {
8735 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8736 matrix.postRotate(180);
8737 matrix.postTranslate(left, bottom);
8738 fade.setLocalMatrix(matrix);
8739 canvas.drawRect(left, bottom - length, right, bottom, p);
8740 }
8741
8742 if (drawLeft) {
8743 matrix.setScale(1, fadeHeight * leftFadeStrength);
8744 matrix.postRotate(-90);
8745 matrix.postTranslate(left, top);
8746 fade.setLocalMatrix(matrix);
8747 canvas.drawRect(left, top, left + length, bottom, p);
8748 }
8749
8750 if (drawRight) {
8751 matrix.setScale(1, fadeHeight * rightFadeStrength);
8752 matrix.postRotate(90);
8753 matrix.postTranslate(right, top);
8754 fade.setLocalMatrix(matrix);
8755 canvas.drawRect(right - length, top, right, bottom, p);
8756 }
8757
8758 canvas.restoreToCount(saveCount);
8759
8760 // Step 6, draw decorations (scrollbars)
8761 onDrawScrollBars(canvas);
8762 }
8763
8764 /**
8765 * Override this if your view is known to always be drawn on top of a solid color background,
8766 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8767 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8768 * should be set to 0xFF.
8769 *
8770 * @see #setVerticalFadingEdgeEnabled
8771 * @see #setHorizontalFadingEdgeEnabled
8772 *
8773 * @return The known solid color background for this view, or 0 if the color may vary
8774 */
8775 public int getSolidColor() {
8776 return 0;
8777 }
8778
8779 /**
8780 * Build a human readable string representation of the specified view flags.
8781 *
8782 * @param flags the view flags to convert to a string
8783 * @return a String representing the supplied flags
8784 */
8785 private static String printFlags(int flags) {
8786 String output = "";
8787 int numFlags = 0;
8788 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8789 output += "TAKES_FOCUS";
8790 numFlags++;
8791 }
8792
8793 switch (flags & VISIBILITY_MASK) {
8794 case INVISIBLE:
8795 if (numFlags > 0) {
8796 output += " ";
8797 }
8798 output += "INVISIBLE";
8799 // USELESS HERE numFlags++;
8800 break;
8801 case GONE:
8802 if (numFlags > 0) {
8803 output += " ";
8804 }
8805 output += "GONE";
8806 // USELESS HERE numFlags++;
8807 break;
8808 default:
8809 break;
8810 }
8811 return output;
8812 }
8813
8814 /**
8815 * Build a human readable string representation of the specified private
8816 * view flags.
8817 *
8818 * @param privateFlags the private view flags to convert to a string
8819 * @return a String representing the supplied flags
8820 */
8821 private static String printPrivateFlags(int privateFlags) {
8822 String output = "";
8823 int numFlags = 0;
8824
8825 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8826 output += "WANTS_FOCUS";
8827 numFlags++;
8828 }
8829
8830 if ((privateFlags & FOCUSED) == FOCUSED) {
8831 if (numFlags > 0) {
8832 output += " ";
8833 }
8834 output += "FOCUSED";
8835 numFlags++;
8836 }
8837
8838 if ((privateFlags & SELECTED) == SELECTED) {
8839 if (numFlags > 0) {
8840 output += " ";
8841 }
8842 output += "SELECTED";
8843 numFlags++;
8844 }
8845
8846 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8847 if (numFlags > 0) {
8848 output += " ";
8849 }
8850 output += "IS_ROOT_NAMESPACE";
8851 numFlags++;
8852 }
8853
8854 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8855 if (numFlags > 0) {
8856 output += " ";
8857 }
8858 output += "HAS_BOUNDS";
8859 numFlags++;
8860 }
8861
8862 if ((privateFlags & DRAWN) == DRAWN) {
8863 if (numFlags > 0) {
8864 output += " ";
8865 }
8866 output += "DRAWN";
8867 // USELESS HERE numFlags++;
8868 }
8869 return output;
8870 }
8871
8872 /**
8873 * <p>Indicates whether or not this view's layout will be requested during
8874 * the next hierarchy layout pass.</p>
8875 *
8876 * @return true if the layout will be forced during next layout pass
8877 */
8878 public boolean isLayoutRequested() {
8879 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8880 }
8881
8882 /**
8883 * Assign a size and position to a view and all of its
8884 * descendants
8885 *
8886 * <p>This is the second phase of the layout mechanism.
8887 * (The first is measuring). In this phase, each parent calls
8888 * layout on all of its children to position them.
8889 * This is typically done using the child measurements
Chet Haase9c087442011-01-12 16:20:16 -08008890 * that were stored in the measure pass().</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008891 *
Chet Haase9c087442011-01-12 16:20:16 -08008892 * <p>Derived classes should not override this method.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008893 * Derived classes with children should override
8894 * onLayout. In that method, they should
Chet Haase9c087442011-01-12 16:20:16 -08008895 * call layout on each of their children.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008896 *
8897 * @param l Left position, relative to parent
8898 * @param t Top position, relative to parent
8899 * @param r Right position, relative to parent
8900 * @param b Bottom position, relative to parent
8901 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008902 @SuppressWarnings({"unchecked"})
Chet Haase9c087442011-01-12 16:20:16 -08008903 public void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008904 int oldL = mLeft;
8905 int oldT = mTop;
8906 int oldB = mBottom;
8907 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008908 boolean changed = setFrame(l, t, r, b);
8909 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8910 if (ViewDebug.TRACE_HIERARCHY) {
8911 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8912 }
8913
8914 onLayout(changed, l, t, r, b);
8915 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008916
8917 if (mOnLayoutChangeListeners != null) {
8918 ArrayList<OnLayoutChangeListener> listenersCopy =
8919 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8920 int numListeners = listenersCopy.size();
8921 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07008922 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07008923 }
8924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008925 }
8926 mPrivateFlags &= ~FORCE_LAYOUT;
8927 }
8928
8929 /**
8930 * Called from layout when this view should
8931 * assign a size and position to each of its children.
8932 *
8933 * Derived classes with children should override
8934 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008935 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 * @param changed This is a new size or position for this view
8937 * @param left Left position, relative to parent
8938 * @param top Top position, relative to parent
8939 * @param right Right position, relative to parent
8940 * @param bottom Bottom position, relative to parent
8941 */
8942 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8943 }
8944
8945 /**
8946 * Assign a size and position to this view.
8947 *
8948 * This is called from layout.
8949 *
8950 * @param left Left position, relative to parent
8951 * @param top Top position, relative to parent
8952 * @param right Right position, relative to parent
8953 * @param bottom Bottom position, relative to parent
8954 * @return true if the new size and position are different than the
8955 * previous ones
8956 * {@hide}
8957 */
8958 protected boolean setFrame(int left, int top, int right, int bottom) {
8959 boolean changed = false;
8960
8961 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008962 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008963 + right + "," + bottom + ")");
8964 }
8965
8966 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8967 changed = true;
8968
8969 // Remember our drawn bit
8970 int drawn = mPrivateFlags & DRAWN;
8971
8972 // Invalidate our old position
8973 invalidate();
8974
8975
8976 int oldWidth = mRight - mLeft;
8977 int oldHeight = mBottom - mTop;
8978
8979 mLeft = left;
8980 mTop = top;
8981 mRight = right;
8982 mBottom = bottom;
8983
8984 mPrivateFlags |= HAS_BOUNDS;
8985
8986 int newWidth = right - left;
8987 int newHeight = bottom - top;
8988
8989 if (newWidth != oldWidth || newHeight != oldHeight) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08008990 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8991 // A change in dimension means an auto-centered pivot point changes, too
8992 mMatrixDirty = true;
8993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008994 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8995 }
8996
8997 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8998 // If we are visible, force the DRAWN bit to on so that
8999 // this invalidate will go through (at least to our parent).
9000 // This is because someone may have invalidated this view
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009001 // before this call to setFrame came in, thereby clearing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009002 // the DRAWN bit.
9003 mPrivateFlags |= DRAWN;
9004 invalidate();
9005 }
9006
9007 // Reset drawn bit to original value (invalidate turns it off)
9008 mPrivateFlags |= drawn;
9009
9010 mBackgroundSizeChanged = true;
9011 }
9012 return changed;
9013 }
9014
9015 /**
9016 * Finalize inflating a view from XML. This is called as the last phase
9017 * of inflation, after all child views have been added.
9018 *
9019 * <p>Even if the subclass overrides onFinishInflate, they should always be
9020 * sure to call the super method, so that we get called.
9021 */
9022 protected void onFinishInflate() {
9023 }
9024
9025 /**
9026 * Returns the resources associated with this view.
9027 *
9028 * @return Resources object.
9029 */
9030 public Resources getResources() {
9031 return mResources;
9032 }
9033
9034 /**
9035 * Invalidates the specified Drawable.
9036 *
9037 * @param drawable the drawable to invalidate
9038 */
9039 public void invalidateDrawable(Drawable drawable) {
9040 if (verifyDrawable(drawable)) {
9041 final Rect dirty = drawable.getBounds();
9042 final int scrollX = mScrollX;
9043 final int scrollY = mScrollY;
9044
9045 invalidate(dirty.left + scrollX, dirty.top + scrollY,
9046 dirty.right + scrollX, dirty.bottom + scrollY);
9047 }
9048 }
9049
9050 /**
9051 * Schedules an action on a drawable to occur at a specified time.
9052 *
9053 * @param who the recipient of the action
9054 * @param what the action to run on the drawable
9055 * @param when the time at which the action must occur. Uses the
9056 * {@link SystemClock#uptimeMillis} timebase.
9057 */
9058 public void scheduleDrawable(Drawable who, Runnable what, long when) {
9059 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9060 mAttachInfo.mHandler.postAtTime(what, who, when);
9061 }
9062 }
9063
9064 /**
9065 * Cancels a scheduled action on a drawable.
9066 *
9067 * @param who the recipient of the action
9068 * @param what the action to cancel
9069 */
9070 public void unscheduleDrawable(Drawable who, Runnable what) {
9071 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9072 mAttachInfo.mHandler.removeCallbacks(what, who);
9073 }
9074 }
9075
9076 /**
9077 * Unschedule any events associated with the given Drawable. This can be
9078 * used when selecting a new Drawable into a view, so that the previous
9079 * one is completely unscheduled.
9080 *
9081 * @param who The Drawable to unschedule.
9082 *
9083 * @see #drawableStateChanged
9084 */
9085 public void unscheduleDrawable(Drawable who) {
9086 if (mAttachInfo != null) {
9087 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
9088 }
9089 }
9090
9091 /**
9092 * If your view subclass is displaying its own Drawable objects, it should
9093 * override this function and return true for any Drawable it is
9094 * displaying. This allows animations for those drawables to be
9095 * scheduled.
9096 *
9097 * <p>Be sure to call through to the super class when overriding this
9098 * function.
9099 *
9100 * @param who The Drawable to verify. Return true if it is one you are
9101 * displaying, else return the result of calling through to the
9102 * super class.
9103 *
9104 * @return boolean If true than the Drawable is being displayed in the
9105 * view; else false and it is not allowed to animate.
9106 *
9107 * @see #unscheduleDrawable
9108 * @see #drawableStateChanged
9109 */
9110 protected boolean verifyDrawable(Drawable who) {
9111 return who == mBGDrawable;
9112 }
9113
9114 /**
9115 * This function is called whenever the state of the view changes in such
9116 * a way that it impacts the state of drawables being shown.
9117 *
9118 * <p>Be sure to call through to the superclass when overriding this
9119 * function.
9120 *
9121 * @see Drawable#setState
9122 */
9123 protected void drawableStateChanged() {
9124 Drawable d = mBGDrawable;
9125 if (d != null && d.isStateful()) {
9126 d.setState(getDrawableState());
9127 }
9128 }
9129
9130 /**
9131 * Call this to force a view to update its drawable state. This will cause
9132 * drawableStateChanged to be called on this view. Views that are interested
9133 * in the new state should call getDrawableState.
9134 *
9135 * @see #drawableStateChanged
9136 * @see #getDrawableState
9137 */
9138 public void refreshDrawableState() {
9139 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9140 drawableStateChanged();
9141
9142 ViewParent parent = mParent;
9143 if (parent != null) {
9144 parent.childDrawableStateChanged(this);
9145 }
9146 }
9147
9148 /**
9149 * Return an array of resource IDs of the drawable states representing the
9150 * current state of the view.
9151 *
9152 * @return The current drawable state
9153 *
9154 * @see Drawable#setState
9155 * @see #drawableStateChanged
9156 * @see #onCreateDrawableState
9157 */
9158 public final int[] getDrawableState() {
9159 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
9160 return mDrawableState;
9161 } else {
9162 mDrawableState = onCreateDrawableState(0);
9163 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
9164 return mDrawableState;
9165 }
9166 }
9167
9168 /**
9169 * Generate the new {@link android.graphics.drawable.Drawable} state for
9170 * this view. This is called by the view
9171 * system when the cached Drawable state is determined to be invalid. To
9172 * retrieve the current state, you should use {@link #getDrawableState}.
9173 *
9174 * @param extraSpace if non-zero, this is the number of extra entries you
9175 * would like in the returned array in which you can place your own
9176 * states.
9177 *
9178 * @return Returns an array holding the current {@link Drawable} state of
9179 * the view.
9180 *
9181 * @see #mergeDrawableStates
9182 */
9183 protected int[] onCreateDrawableState(int extraSpace) {
9184 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
9185 mParent instanceof View) {
9186 return ((View) mParent).onCreateDrawableState(extraSpace);
9187 }
9188
9189 int[] drawableState;
9190
9191 int privateFlags = mPrivateFlags;
9192
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009193 int viewStateIndex = 0;
9194 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
9195 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
9196 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07009197 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009198 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
9199 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08009200 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
9201 // This is set if HW acceleration is requested, even if the current
9202 // process doesn't allow it. This is just to allow app preview
9203 // windows to better match their app.
9204 viewStateIndex |= VIEW_STATE_ACCELERATED;
9205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009206
9207 drawableState = VIEW_STATE_SETS[viewStateIndex];
9208
9209 //noinspection ConstantIfStatement
9210 if (false) {
9211 Log.i("View", "drawableStateIndex=" + viewStateIndex);
9212 Log.i("View", toString()
9213 + " pressed=" + ((privateFlags & PRESSED) != 0)
9214 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
9215 + " fo=" + hasFocus()
9216 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009217 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009218 + ": " + Arrays.toString(drawableState));
9219 }
9220
9221 if (extraSpace == 0) {
9222 return drawableState;
9223 }
9224
9225 final int[] fullState;
9226 if (drawableState != null) {
9227 fullState = new int[drawableState.length + extraSpace];
9228 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
9229 } else {
9230 fullState = new int[extraSpace];
9231 }
9232
9233 return fullState;
9234 }
9235
9236 /**
9237 * Merge your own state values in <var>additionalState</var> into the base
9238 * state values <var>baseState</var> that were returned by
9239 * {@link #onCreateDrawableState}.
9240 *
9241 * @param baseState The base state values returned by
9242 * {@link #onCreateDrawableState}, which will be modified to also hold your
9243 * own additional state values.
9244 *
9245 * @param additionalState The additional state values you would like
9246 * added to <var>baseState</var>; this array is not modified.
9247 *
9248 * @return As a convenience, the <var>baseState</var> array you originally
9249 * passed into the function is returned.
9250 *
9251 * @see #onCreateDrawableState
9252 */
9253 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
9254 final int N = baseState.length;
9255 int i = N - 1;
9256 while (i >= 0 && baseState[i] == 0) {
9257 i--;
9258 }
9259 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
9260 return baseState;
9261 }
9262
9263 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07009264 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
9265 * on all Drawable objects associated with this view.
9266 */
9267 public void jumpDrawablesToCurrentState() {
9268 if (mBGDrawable != null) {
9269 mBGDrawable.jumpToCurrentState();
9270 }
9271 }
9272
9273 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009274 * Sets the background color for this view.
9275 * @param color the color of the background
9276 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009277 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009278 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07009279 if (mBGDrawable instanceof ColorDrawable) {
9280 ((ColorDrawable) mBGDrawable).setColor(color);
9281 } else {
9282 setBackgroundDrawable(new ColorDrawable(color));
9283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009284 }
9285
9286 /**
9287 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07009288 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009289 * @param resid The identifier of the resource.
9290 * @attr ref android.R.styleable#View_background
9291 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009292 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009293 public void setBackgroundResource(int resid) {
9294 if (resid != 0 && resid == mBackgroundResource) {
9295 return;
9296 }
9297
9298 Drawable d= null;
9299 if (resid != 0) {
9300 d = mResources.getDrawable(resid);
9301 }
9302 setBackgroundDrawable(d);
9303
9304 mBackgroundResource = resid;
9305 }
9306
9307 /**
9308 * Set the background to a given Drawable, or remove the background. If the
9309 * background has padding, this View's padding is set to the background's
9310 * padding. However, when a background is removed, this View's padding isn't
9311 * touched. If setting the padding is desired, please use
9312 * {@link #setPadding(int, int, int, int)}.
9313 *
9314 * @param d The Drawable to use as the background, or null to remove the
9315 * background
9316 */
9317 public void setBackgroundDrawable(Drawable d) {
9318 boolean requestLayout = false;
9319
9320 mBackgroundResource = 0;
9321
9322 /*
9323 * Regardless of whether we're setting a new background or not, we want
9324 * to clear the previous drawable.
9325 */
9326 if (mBGDrawable != null) {
9327 mBGDrawable.setCallback(null);
9328 unscheduleDrawable(mBGDrawable);
9329 }
9330
9331 if (d != null) {
9332 Rect padding = sThreadLocal.get();
9333 if (padding == null) {
9334 padding = new Rect();
9335 sThreadLocal.set(padding);
9336 }
9337 if (d.getPadding(padding)) {
9338 setPadding(padding.left, padding.top, padding.right, padding.bottom);
9339 }
9340
9341 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
9342 // if it has a different minimum size, we should layout again
9343 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9344 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9345 requestLayout = true;
9346 }
9347
9348 d.setCallback(this);
9349 if (d.isStateful()) {
9350 d.setState(getDrawableState());
9351 }
9352 d.setVisible(getVisibility() == VISIBLE, false);
9353 mBGDrawable = d;
9354
9355 if ((mPrivateFlags & SKIP_DRAW) != 0) {
9356 mPrivateFlags &= ~SKIP_DRAW;
9357 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9358 requestLayout = true;
9359 }
9360 } else {
9361 /* Remove the background */
9362 mBGDrawable = null;
9363
9364 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9365 /*
9366 * This view ONLY drew the background before and we're removing
9367 * the background, so now it won't draw anything
9368 * (hence we SKIP_DRAW)
9369 */
9370 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9371 mPrivateFlags |= SKIP_DRAW;
9372 }
9373
9374 /*
9375 * When the background is set, we try to apply its padding to this
9376 * View. When the background is removed, we don't touch this View's
9377 * padding. This is noted in the Javadocs. Hence, we don't need to
9378 * requestLayout(), the invalidate() below is sufficient.
9379 */
9380
9381 // The old background's minimum size could have affected this
9382 // View's layout, so let's requestLayout
9383 requestLayout = true;
9384 }
9385
Romain Guy8f1344f52009-05-15 16:03:59 -07009386 computeOpaqueFlags();
9387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009388 if (requestLayout) {
9389 requestLayout();
9390 }
9391
9392 mBackgroundSizeChanged = true;
9393 invalidate();
9394 }
9395
9396 /**
9397 * Gets the background drawable
9398 * @return The drawable used as the background for this view, if any.
9399 */
9400 public Drawable getBackground() {
9401 return mBGDrawable;
9402 }
9403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009404 /**
9405 * Sets the padding. The view may add on the space required to display
9406 * the scrollbars, depending on the style and visibility of the scrollbars.
9407 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9408 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9409 * from the values set in this call.
9410 *
9411 * @attr ref android.R.styleable#View_padding
9412 * @attr ref android.R.styleable#View_paddingBottom
9413 * @attr ref android.R.styleable#View_paddingLeft
9414 * @attr ref android.R.styleable#View_paddingRight
9415 * @attr ref android.R.styleable#View_paddingTop
9416 * @param left the left padding in pixels
9417 * @param top the top padding in pixels
9418 * @param right the right padding in pixels
9419 * @param bottom the bottom padding in pixels
9420 */
9421 public void setPadding(int left, int top, int right, int bottom) {
9422 boolean changed = false;
9423
Adam Powell20232d02010-12-08 21:08:53 -08009424 mUserPaddingLeft = left;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009425 mUserPaddingRight = right;
9426 mUserPaddingBottom = bottom;
9427
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009428 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07009429
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009430 // Common case is there are no scroll bars.
9431 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009432 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
Adam Powell20232d02010-12-08 21:08:53 -08009433 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9434 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009435 ? 0 : getVerticalScrollbarWidth();
Adam Powell20232d02010-12-08 21:08:53 -08009436 switch (mVerticalScrollbarPosition) {
9437 case SCROLLBAR_POSITION_DEFAULT:
9438 case SCROLLBAR_POSITION_RIGHT:
9439 right += offset;
9440 break;
9441 case SCROLLBAR_POSITION_LEFT:
9442 left += offset;
9443 break;
9444 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009445 }
Adam Powell20232d02010-12-08 21:08:53 -08009446 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009447 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9448 ? 0 : getHorizontalScrollbarHeight();
9449 }
9450 }
Romain Guy8506ab42009-06-11 17:35:47 -07009451
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009452 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009453 changed = true;
9454 mPaddingLeft = left;
9455 }
9456 if (mPaddingTop != top) {
9457 changed = true;
9458 mPaddingTop = top;
9459 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009460 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009461 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009462 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009463 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009464 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009465 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009466 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009467 }
9468
9469 if (changed) {
9470 requestLayout();
9471 }
9472 }
9473
9474 /**
9475 * Returns the top padding of this view.
9476 *
9477 * @return the top padding in pixels
9478 */
9479 public int getPaddingTop() {
9480 return mPaddingTop;
9481 }
9482
9483 /**
9484 * Returns the bottom padding of this view. If there are inset and enabled
9485 * scrollbars, this value may include the space required to display the
9486 * scrollbars as well.
9487 *
9488 * @return the bottom padding in pixels
9489 */
9490 public int getPaddingBottom() {
9491 return mPaddingBottom;
9492 }
9493
9494 /**
9495 * Returns the left padding of this view. If there are inset and enabled
9496 * scrollbars, this value may include the space required to display the
9497 * scrollbars as well.
9498 *
9499 * @return the left padding in pixels
9500 */
9501 public int getPaddingLeft() {
9502 return mPaddingLeft;
9503 }
9504
9505 /**
9506 * Returns the right padding of this view. If there are inset and enabled
9507 * scrollbars, this value may include the space required to display the
9508 * scrollbars as well.
9509 *
9510 * @return the right padding in pixels
9511 */
9512 public int getPaddingRight() {
9513 return mPaddingRight;
9514 }
9515
9516 /**
9517 * Changes the selection state of this view. A view can be selected or not.
9518 * Note that selection is not the same as focus. Views are typically
9519 * selected in the context of an AdapterView like ListView or GridView;
9520 * the selected view is the view that is highlighted.
9521 *
9522 * @param selected true if the view must be selected, false otherwise
9523 */
9524 public void setSelected(boolean selected) {
9525 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9526 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009527 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009528 invalidate();
9529 refreshDrawableState();
9530 dispatchSetSelected(selected);
9531 }
9532 }
9533
9534 /**
9535 * Dispatch setSelected to all of this View's children.
9536 *
9537 * @see #setSelected(boolean)
9538 *
9539 * @param selected The new selected state
9540 */
9541 protected void dispatchSetSelected(boolean selected) {
9542 }
9543
9544 /**
9545 * Indicates the selection state of this view.
9546 *
9547 * @return true if the view is selected, false otherwise
9548 */
9549 @ViewDebug.ExportedProperty
9550 public boolean isSelected() {
9551 return (mPrivateFlags & SELECTED) != 0;
9552 }
9553
9554 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009555 * Changes the activated state of this view. A view can be activated or not.
9556 * Note that activation is not the same as selection. Selection is
9557 * a transient property, representing the view (hierarchy) the user is
9558 * currently interacting with. Activation is a longer-term state that the
9559 * user can move views in and out of. For example, in a list view with
9560 * single or multiple selection enabled, the views in the current selection
9561 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9562 * here.) The activated state is propagated down to children of the view it
9563 * is set on.
9564 *
9565 * @param activated true if the view must be activated, false otherwise
9566 */
9567 public void setActivated(boolean activated) {
9568 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9569 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
9570 invalidate();
9571 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009572 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009573 }
9574 }
9575
9576 /**
9577 * Dispatch setActivated to all of this View's children.
9578 *
9579 * @see #setActivated(boolean)
9580 *
9581 * @param activated The new activated state
9582 */
9583 protected void dispatchSetActivated(boolean activated) {
9584 }
9585
9586 /**
9587 * Indicates the activation state of this view.
9588 *
9589 * @return true if the view is activated, false otherwise
9590 */
9591 @ViewDebug.ExportedProperty
9592 public boolean isActivated() {
9593 return (mPrivateFlags & ACTIVATED) != 0;
9594 }
9595
9596 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009597 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9598 * observer can be used to get notifications when global events, like
9599 * layout, happen.
9600 *
9601 * The returned ViewTreeObserver observer is not guaranteed to remain
9602 * valid for the lifetime of this View. If the caller of this method keeps
9603 * a long-lived reference to ViewTreeObserver, it should always check for
9604 * the return value of {@link ViewTreeObserver#isAlive()}.
9605 *
9606 * @return The ViewTreeObserver for this view's hierarchy.
9607 */
9608 public ViewTreeObserver getViewTreeObserver() {
9609 if (mAttachInfo != null) {
9610 return mAttachInfo.mTreeObserver;
9611 }
9612 if (mFloatingTreeObserver == null) {
9613 mFloatingTreeObserver = new ViewTreeObserver();
9614 }
9615 return mFloatingTreeObserver;
9616 }
9617
9618 /**
9619 * <p>Finds the topmost view in the current view hierarchy.</p>
9620 *
9621 * @return the topmost view containing this view
9622 */
9623 public View getRootView() {
9624 if (mAttachInfo != null) {
9625 final View v = mAttachInfo.mRootView;
9626 if (v != null) {
9627 return v;
9628 }
9629 }
Romain Guy8506ab42009-06-11 17:35:47 -07009630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009631 View parent = this;
9632
9633 while (parent.mParent != null && parent.mParent instanceof View) {
9634 parent = (View) parent.mParent;
9635 }
9636
9637 return parent;
9638 }
9639
9640 /**
9641 * <p>Computes the coordinates of this view on the screen. The argument
9642 * must be an array of two integers. After the method returns, the array
9643 * contains the x and y location in that order.</p>
9644 *
9645 * @param location an array of two integers in which to hold the coordinates
9646 */
9647 public void getLocationOnScreen(int[] location) {
9648 getLocationInWindow(location);
9649
9650 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009651 if (info != null) {
9652 location[0] += info.mWindowLeft;
9653 location[1] += info.mWindowTop;
9654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009655 }
9656
9657 /**
9658 * <p>Computes the coordinates of this view in its window. The argument
9659 * must be an array of two integers. After the method returns, the array
9660 * contains the x and y location in that order.</p>
9661 *
9662 * @param location an array of two integers in which to hold the coordinates
9663 */
9664 public void getLocationInWindow(int[] location) {
9665 if (location == null || location.length < 2) {
9666 throw new IllegalArgumentException("location must be an array of "
9667 + "two integers");
9668 }
9669
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009670 location[0] = mLeft + (int) (mTranslationX + 0.5f);
9671 location[1] = mTop + (int) (mTranslationY + 0.5f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009672
9673 ViewParent viewParent = mParent;
9674 while (viewParent instanceof View) {
9675 final View view = (View)viewParent;
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009676 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
9677 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009678 viewParent = view.mParent;
9679 }
Romain Guy8506ab42009-06-11 17:35:47 -07009680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009681 if (viewParent instanceof ViewRoot) {
9682 // *cough*
9683 final ViewRoot vr = (ViewRoot)viewParent;
9684 location[1] -= vr.mCurScrollY;
9685 }
9686 }
9687
9688 /**
9689 * {@hide}
9690 * @param id the id of the view to be found
9691 * @return the view of the specified id, null if cannot be found
9692 */
9693 protected View findViewTraversal(int id) {
9694 if (id == mID) {
9695 return this;
9696 }
9697 return null;
9698 }
9699
9700 /**
9701 * {@hide}
9702 * @param tag the tag of the view to be found
9703 * @return the view of specified tag, null if cannot be found
9704 */
9705 protected View findViewWithTagTraversal(Object tag) {
9706 if (tag != null && tag.equals(mTag)) {
9707 return this;
9708 }
9709 return null;
9710 }
9711
9712 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009713 * {@hide}
9714 * @param predicate The predicate to evaluate.
9715 * @return The first view that matches the predicate or null.
9716 */
9717 protected View findViewByPredicateTraversal(Predicate<View> predicate) {
9718 if (predicate.apply(this)) {
9719 return this;
9720 }
9721 return null;
9722 }
9723
9724 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009725 * Look for a child view with the given id. If this view has the given
9726 * id, return this view.
9727 *
9728 * @param id The id to search for.
9729 * @return The view that has the given id in the hierarchy or null
9730 */
9731 public final View findViewById(int id) {
9732 if (id < 0) {
9733 return null;
9734 }
9735 return findViewTraversal(id);
9736 }
9737
9738 /**
9739 * Look for a child view with the given tag. If this view has the given
9740 * tag, return this view.
9741 *
9742 * @param tag The tag to search for, using "tag.equals(getTag())".
9743 * @return The View that has the given tag in the hierarchy or null
9744 */
9745 public final View findViewWithTag(Object tag) {
9746 if (tag == null) {
9747 return null;
9748 }
9749 return findViewWithTagTraversal(tag);
9750 }
9751
9752 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009753 * {@hide}
9754 * Look for a child view that matches the specified predicate.
9755 * If this view matches the predicate, return this view.
9756 *
9757 * @param predicate The predicate to evaluate.
9758 * @return The first view that matches the predicate or null.
9759 */
9760 public final View findViewByPredicate(Predicate<View> predicate) {
9761 return findViewByPredicateTraversal(predicate);
9762 }
9763
9764 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009765 * Sets the identifier for this view. The identifier does not have to be
9766 * unique in this view's hierarchy. The identifier should be a positive
9767 * number.
9768 *
9769 * @see #NO_ID
9770 * @see #getId
9771 * @see #findViewById
9772 *
9773 * @param id a number used to identify the view
9774 *
9775 * @attr ref android.R.styleable#View_id
9776 */
9777 public void setId(int id) {
9778 mID = id;
9779 }
9780
9781 /**
9782 * {@hide}
9783 *
9784 * @param isRoot true if the view belongs to the root namespace, false
9785 * otherwise
9786 */
9787 public void setIsRootNamespace(boolean isRoot) {
9788 if (isRoot) {
9789 mPrivateFlags |= IS_ROOT_NAMESPACE;
9790 } else {
9791 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9792 }
9793 }
9794
9795 /**
9796 * {@hide}
9797 *
9798 * @return true if the view belongs to the root namespace, false otherwise
9799 */
9800 public boolean isRootNamespace() {
9801 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9802 }
9803
9804 /**
9805 * Returns this view's identifier.
9806 *
9807 * @return a positive integer used to identify the view or {@link #NO_ID}
9808 * if the view has no ID
9809 *
9810 * @see #setId
9811 * @see #findViewById
9812 * @attr ref android.R.styleable#View_id
9813 */
9814 @ViewDebug.CapturedViewProperty
9815 public int getId() {
9816 return mID;
9817 }
9818
9819 /**
9820 * Returns this view's tag.
9821 *
9822 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07009823 *
9824 * @see #setTag(Object)
9825 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009826 */
9827 @ViewDebug.ExportedProperty
9828 public Object getTag() {
9829 return mTag;
9830 }
9831
9832 /**
9833 * Sets the tag associated with this view. A tag can be used to mark
9834 * a view in its hierarchy and does not have to be unique within the
9835 * hierarchy. Tags can also be used to store data within a view without
9836 * resorting to another data structure.
9837 *
9838 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07009839 *
9840 * @see #getTag()
9841 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009842 */
9843 public void setTag(final Object tag) {
9844 mTag = tag;
9845 }
9846
9847 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009848 * Returns the tag associated with this view and the specified key.
9849 *
9850 * @param key The key identifying the tag
9851 *
9852 * @return the Object stored in this view as a tag
9853 *
9854 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009855 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009856 */
9857 public Object getTag(int key) {
9858 SparseArray<Object> tags = null;
9859 synchronized (sTagsLock) {
9860 if (sTags != null) {
9861 tags = sTags.get(this);
9862 }
9863 }
9864
9865 if (tags != null) return tags.get(key);
9866 return null;
9867 }
9868
9869 /**
9870 * Sets a tag associated with this view and a key. A tag can be used
9871 * to mark a view in its hierarchy and does not have to be unique within
9872 * the hierarchy. Tags can also be used to store data within a view
9873 * without resorting to another data structure.
9874 *
9875 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009876 * application to ensure it is unique (see the <a
9877 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9878 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009879 * the Android framework or not associated with any package will cause
9880 * an {@link IllegalArgumentException} to be thrown.
9881 *
9882 * @param key The key identifying the tag
9883 * @param tag An Object to tag the view with
9884 *
9885 * @throws IllegalArgumentException If they specified key is not valid
9886 *
9887 * @see #setTag(Object)
9888 * @see #getTag(int)
9889 */
9890 public void setTag(int key, final Object tag) {
9891 // If the package id is 0x00 or 0x01, it's either an undefined package
9892 // or a framework id
9893 if ((key >>> 24) < 2) {
9894 throw new IllegalArgumentException("The key must be an application-specific "
9895 + "resource id.");
9896 }
9897
9898 setTagInternal(this, key, tag);
9899 }
9900
9901 /**
9902 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9903 * framework id.
9904 *
9905 * @hide
9906 */
9907 public void setTagInternal(int key, Object tag) {
9908 if ((key >>> 24) != 0x1) {
9909 throw new IllegalArgumentException("The key must be a framework-specific "
9910 + "resource id.");
9911 }
9912
Romain Guy8506ab42009-06-11 17:35:47 -07009913 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009914 }
9915
9916 private static void setTagInternal(View view, int key, Object tag) {
9917 SparseArray<Object> tags = null;
9918 synchronized (sTagsLock) {
9919 if (sTags == null) {
9920 sTags = new WeakHashMap<View, SparseArray<Object>>();
9921 } else {
9922 tags = sTags.get(view);
9923 }
9924 }
9925
9926 if (tags == null) {
9927 tags = new SparseArray<Object>(2);
9928 synchronized (sTagsLock) {
9929 sTags.put(view, tags);
9930 }
9931 }
9932
9933 tags.put(key, tag);
9934 }
9935
9936 /**
Romain Guy13922e02009-05-12 17:56:14 -07009937 * @param consistency The type of consistency. See ViewDebug for more information.
9938 *
9939 * @hide
9940 */
9941 protected boolean dispatchConsistencyCheck(int consistency) {
9942 return onConsistencyCheck(consistency);
9943 }
9944
9945 /**
9946 * Method that subclasses should implement to check their consistency. The type of
9947 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009948 *
Romain Guy13922e02009-05-12 17:56:14 -07009949 * @param consistency The type of consistency. See ViewDebug for more information.
9950 *
9951 * @throws IllegalStateException if the view is in an inconsistent state.
9952 *
9953 * @hide
9954 */
9955 protected boolean onConsistencyCheck(int consistency) {
9956 boolean result = true;
9957
9958 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9959 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9960
9961 if (checkLayout) {
9962 if (getParent() == null) {
9963 result = false;
9964 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9965 "View " + this + " does not have a parent.");
9966 }
9967
9968 if (mAttachInfo == null) {
9969 result = false;
9970 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9971 "View " + this + " is not attached to a window.");
9972 }
9973 }
9974
9975 if (checkDrawing) {
9976 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9977 // from their draw() method
9978
9979 if ((mPrivateFlags & DRAWN) != DRAWN &&
9980 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9981 result = false;
9982 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9983 "View " + this + " was invalidated but its drawing cache is valid.");
9984 }
9985 }
9986
9987 return result;
9988 }
9989
9990 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009991 * Prints information about this view in the log output, with the tag
9992 * {@link #VIEW_LOG_TAG}.
9993 *
9994 * @hide
9995 */
9996 public void debug() {
9997 debug(0);
9998 }
9999
10000 /**
10001 * Prints information about this view in the log output, with the tag
10002 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
10003 * indentation defined by the <code>depth</code>.
10004 *
10005 * @param depth the indentation level
10006 *
10007 * @hide
10008 */
10009 protected void debug(int depth) {
10010 String output = debugIndent(depth - 1);
10011
10012 output += "+ " + this;
10013 int id = getId();
10014 if (id != -1) {
10015 output += " (id=" + id + ")";
10016 }
10017 Object tag = getTag();
10018 if (tag != null) {
10019 output += " (tag=" + tag + ")";
10020 }
10021 Log.d(VIEW_LOG_TAG, output);
10022
10023 if ((mPrivateFlags & FOCUSED) != 0) {
10024 output = debugIndent(depth) + " FOCUSED";
10025 Log.d(VIEW_LOG_TAG, output);
10026 }
10027
10028 output = debugIndent(depth);
10029 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
10030 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
10031 + "} ";
10032 Log.d(VIEW_LOG_TAG, output);
10033
10034 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
10035 || mPaddingBottom != 0) {
10036 output = debugIndent(depth);
10037 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
10038 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
10039 Log.d(VIEW_LOG_TAG, output);
10040 }
10041
10042 output = debugIndent(depth);
10043 output += "mMeasureWidth=" + mMeasuredWidth +
10044 " mMeasureHeight=" + mMeasuredHeight;
10045 Log.d(VIEW_LOG_TAG, output);
10046
10047 output = debugIndent(depth);
10048 if (mLayoutParams == null) {
10049 output += "BAD! no layout params";
10050 } else {
10051 output = mLayoutParams.debug(output);
10052 }
10053 Log.d(VIEW_LOG_TAG, output);
10054
10055 output = debugIndent(depth);
10056 output += "flags={";
10057 output += View.printFlags(mViewFlags);
10058 output += "}";
10059 Log.d(VIEW_LOG_TAG, output);
10060
10061 output = debugIndent(depth);
10062 output += "privateFlags={";
10063 output += View.printPrivateFlags(mPrivateFlags);
10064 output += "}";
10065 Log.d(VIEW_LOG_TAG, output);
10066 }
10067
10068 /**
10069 * Creates an string of whitespaces used for indentation.
10070 *
10071 * @param depth the indentation level
10072 * @return a String containing (depth * 2 + 3) * 2 white spaces
10073 *
10074 * @hide
10075 */
10076 protected static String debugIndent(int depth) {
10077 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
10078 for (int i = 0; i < (depth * 2) + 3; i++) {
10079 spaces.append(' ').append(' ');
10080 }
10081 return spaces.toString();
10082 }
10083
10084 /**
10085 * <p>Return the offset of the widget's text baseline from the widget's top
10086 * boundary. If this widget does not support baseline alignment, this
10087 * method returns -1. </p>
10088 *
10089 * @return the offset of the baseline within the widget's bounds or -1
10090 * if baseline alignment is not supported
10091 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -070010092 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010093 public int getBaseline() {
10094 return -1;
10095 }
10096
10097 /**
10098 * Call this when something has changed which has invalidated the
10099 * layout of this view. This will schedule a layout pass of the view
10100 * tree.
10101 */
10102 public void requestLayout() {
10103 if (ViewDebug.TRACE_HIERARCHY) {
10104 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
10105 }
10106
10107 mPrivateFlags |= FORCE_LAYOUT;
10108
10109 if (mParent != null && !mParent.isLayoutRequested()) {
10110 mParent.requestLayout();
10111 }
10112 }
10113
10114 /**
10115 * Forces this view to be laid out during the next layout pass.
10116 * This method does not call requestLayout() or forceLayout()
10117 * on the parent.
10118 */
10119 public void forceLayout() {
10120 mPrivateFlags |= FORCE_LAYOUT;
10121 }
10122
10123 /**
10124 * <p>
10125 * This is called to find out how big a view should be. The parent
10126 * supplies constraint information in the width and height parameters.
10127 * </p>
10128 *
10129 * <p>
10130 * The actual mesurement work of a view is performed in
10131 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
10132 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
10133 * </p>
10134 *
10135 *
10136 * @param widthMeasureSpec Horizontal space requirements as imposed by the
10137 * parent
10138 * @param heightMeasureSpec Vertical space requirements as imposed by the
10139 * parent
10140 *
10141 * @see #onMeasure(int, int)
10142 */
10143 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
10144 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
10145 widthMeasureSpec != mOldWidthMeasureSpec ||
10146 heightMeasureSpec != mOldHeightMeasureSpec) {
10147
10148 // first clears the measured dimension flag
10149 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
10150
10151 if (ViewDebug.TRACE_HIERARCHY) {
10152 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
10153 }
10154
10155 // measure ourselves, this should set the measured dimension flag back
10156 onMeasure(widthMeasureSpec, heightMeasureSpec);
10157
10158 // flag not set, setMeasuredDimension() was not invoked, we raise
10159 // an exception to warn the developer
10160 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
10161 throw new IllegalStateException("onMeasure() did not set the"
10162 + " measured dimension by calling"
10163 + " setMeasuredDimension()");
10164 }
10165
10166 mPrivateFlags |= LAYOUT_REQUIRED;
10167 }
10168
10169 mOldWidthMeasureSpec = widthMeasureSpec;
10170 mOldHeightMeasureSpec = heightMeasureSpec;
10171 }
10172
10173 /**
10174 * <p>
10175 * Measure the view and its content to determine the measured width and the
10176 * measured height. This method is invoked by {@link #measure(int, int)} and
10177 * should be overriden by subclasses to provide accurate and efficient
10178 * measurement of their contents.
10179 * </p>
10180 *
10181 * <p>
10182 * <strong>CONTRACT:</strong> When overriding this method, you
10183 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
10184 * measured width and height of this view. Failure to do so will trigger an
10185 * <code>IllegalStateException</code>, thrown by
10186 * {@link #measure(int, int)}. Calling the superclass'
10187 * {@link #onMeasure(int, int)} is a valid use.
10188 * </p>
10189 *
10190 * <p>
10191 * The base class implementation of measure defaults to the background size,
10192 * unless a larger size is allowed by the MeasureSpec. Subclasses should
10193 * override {@link #onMeasure(int, int)} to provide better measurements of
10194 * their content.
10195 * </p>
10196 *
10197 * <p>
10198 * If this method is overridden, it is the subclass's responsibility to make
10199 * sure the measured height and width are at least the view's minimum height
10200 * and width ({@link #getSuggestedMinimumHeight()} and
10201 * {@link #getSuggestedMinimumWidth()}).
10202 * </p>
10203 *
10204 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
10205 * The requirements are encoded with
10206 * {@link android.view.View.MeasureSpec}.
10207 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
10208 * The requirements are encoded with
10209 * {@link android.view.View.MeasureSpec}.
10210 *
10211 * @see #getMeasuredWidth()
10212 * @see #getMeasuredHeight()
10213 * @see #setMeasuredDimension(int, int)
10214 * @see #getSuggestedMinimumHeight()
10215 * @see #getSuggestedMinimumWidth()
10216 * @see android.view.View.MeasureSpec#getMode(int)
10217 * @see android.view.View.MeasureSpec#getSize(int)
10218 */
10219 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10220 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
10221 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
10222 }
10223
10224 /**
10225 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
10226 * measured width and measured height. Failing to do so will trigger an
10227 * exception at measurement time.</p>
10228 *
Dianne Hackborn189ee182010-12-02 21:48:53 -080010229 * @param measuredWidth The measured width of this view. May be a complex
10230 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10231 * {@link #MEASURED_STATE_TOO_SMALL}.
10232 * @param measuredHeight The measured height of this view. May be a complex
10233 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10234 * {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010235 */
10236 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
10237 mMeasuredWidth = measuredWidth;
10238 mMeasuredHeight = measuredHeight;
10239
10240 mPrivateFlags |= MEASURED_DIMENSION_SET;
10241 }
10242
10243 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -080010244 * Merge two states as returned by {@link #getMeasuredState()}.
10245 * @param curState The current state as returned from a view or the result
10246 * of combining multiple views.
10247 * @param newState The new view state to combine.
10248 * @return Returns a new integer reflecting the combination of the two
10249 * states.
10250 */
10251 public static int combineMeasuredStates(int curState, int newState) {
10252 return curState | newState;
10253 }
10254
10255 /**
10256 * Version of {@link #resolveSizeAndState(int, int, int)}
10257 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
10258 */
10259 public static int resolveSize(int size, int measureSpec) {
10260 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
10261 }
10262
10263 /**
10264 * Utility to reconcile a desired size and state, with constraints imposed
10265 * by a MeasureSpec. Will take the desired size, unless a different size
10266 * is imposed by the constraints. The returned value is a compound integer,
10267 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
10268 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
10269 * size is smaller than the size the view wants to be.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010270 *
10271 * @param size How big the view wants to be
10272 * @param measureSpec Constraints imposed by the parent
Dianne Hackborn189ee182010-12-02 21:48:53 -080010273 * @return Size information bit mask as defined by
10274 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010275 */
Dianne Hackborn189ee182010-12-02 21:48:53 -080010276 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010277 int result = size;
10278 int specMode = MeasureSpec.getMode(measureSpec);
10279 int specSize = MeasureSpec.getSize(measureSpec);
10280 switch (specMode) {
10281 case MeasureSpec.UNSPECIFIED:
10282 result = size;
10283 break;
10284 case MeasureSpec.AT_MOST:
Dianne Hackborn189ee182010-12-02 21:48:53 -080010285 if (specSize < size) {
10286 result = specSize | MEASURED_STATE_TOO_SMALL;
10287 } else {
10288 result = size;
10289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010290 break;
10291 case MeasureSpec.EXACTLY:
10292 result = specSize;
10293 break;
10294 }
Dianne Hackborn189ee182010-12-02 21:48:53 -080010295 return result | (childMeasuredState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010296 }
10297
10298 /**
10299 * Utility to return a default size. Uses the supplied size if the
10300 * MeasureSpec imposed no contraints. Will get larger if allowed
10301 * by the MeasureSpec.
10302 *
10303 * @param size Default size for this view
10304 * @param measureSpec Constraints imposed by the parent
10305 * @return The size this view should be.
10306 */
10307 public static int getDefaultSize(int size, int measureSpec) {
10308 int result = size;
10309 int specMode = MeasureSpec.getMode(measureSpec);
10310 int specSize = MeasureSpec.getSize(measureSpec);
10311
10312 switch (specMode) {
10313 case MeasureSpec.UNSPECIFIED:
10314 result = size;
10315 break;
10316 case MeasureSpec.AT_MOST:
10317 case MeasureSpec.EXACTLY:
10318 result = specSize;
10319 break;
10320 }
10321 return result;
10322 }
10323
10324 /**
10325 * Returns the suggested minimum height that the view should use. This
10326 * returns the maximum of the view's minimum height
10327 * and the background's minimum height
10328 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10329 * <p>
10330 * When being used in {@link #onMeasure(int, int)}, the caller should still
10331 * ensure the returned height is within the requirements of the parent.
10332 *
10333 * @return The suggested minimum height of the view.
10334 */
10335 protected int getSuggestedMinimumHeight() {
10336 int suggestedMinHeight = mMinHeight;
10337
10338 if (mBGDrawable != null) {
10339 final int bgMinHeight = mBGDrawable.getMinimumHeight();
10340 if (suggestedMinHeight < bgMinHeight) {
10341 suggestedMinHeight = bgMinHeight;
10342 }
10343 }
10344
10345 return suggestedMinHeight;
10346 }
10347
10348 /**
10349 * Returns the suggested minimum width that the view should use. This
10350 * returns the maximum of the view's minimum width)
10351 * and the background's minimum width
10352 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10353 * <p>
10354 * When being used in {@link #onMeasure(int, int)}, the caller should still
10355 * ensure the returned width is within the requirements of the parent.
10356 *
10357 * @return The suggested minimum width of the view.
10358 */
10359 protected int getSuggestedMinimumWidth() {
10360 int suggestedMinWidth = mMinWidth;
10361
10362 if (mBGDrawable != null) {
10363 final int bgMinWidth = mBGDrawable.getMinimumWidth();
10364 if (suggestedMinWidth < bgMinWidth) {
10365 suggestedMinWidth = bgMinWidth;
10366 }
10367 }
10368
10369 return suggestedMinWidth;
10370 }
10371
10372 /**
10373 * Sets the minimum height of the view. It is not guaranteed the view will
10374 * be able to achieve this minimum height (for example, if its parent layout
10375 * constrains it with less available height).
10376 *
10377 * @param minHeight The minimum height the view will try to be.
10378 */
10379 public void setMinimumHeight(int minHeight) {
10380 mMinHeight = minHeight;
10381 }
10382
10383 /**
10384 * Sets the minimum width of the view. It is not guaranteed the view will
10385 * be able to achieve this minimum width (for example, if its parent layout
10386 * constrains it with less available width).
10387 *
10388 * @param minWidth The minimum width the view will try to be.
10389 */
10390 public void setMinimumWidth(int minWidth) {
10391 mMinWidth = minWidth;
10392 }
10393
10394 /**
10395 * Get the animation currently associated with this view.
10396 *
10397 * @return The animation that is currently playing or
10398 * scheduled to play for this view.
10399 */
10400 public Animation getAnimation() {
10401 return mCurrentAnimation;
10402 }
10403
10404 /**
10405 * Start the specified animation now.
10406 *
10407 * @param animation the animation to start now
10408 */
10409 public void startAnimation(Animation animation) {
10410 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10411 setAnimation(animation);
10412 invalidate();
10413 }
10414
10415 /**
10416 * Cancels any animations for this view.
10417 */
10418 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -080010419 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -080010420 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -080010421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010422 mCurrentAnimation = null;
10423 }
10424
10425 /**
10426 * Sets the next animation to play for this view.
10427 * If you want the animation to play immediately, use
10428 * startAnimation. This method provides allows fine-grained
10429 * control over the start time and invalidation, but you
10430 * must make sure that 1) the animation has a start time set, and
10431 * 2) the view will be invalidated when the animation is supposed to
10432 * start.
10433 *
10434 * @param animation The next animation, or null.
10435 */
10436 public void setAnimation(Animation animation) {
10437 mCurrentAnimation = animation;
10438 if (animation != null) {
10439 animation.reset();
10440 }
10441 }
10442
10443 /**
10444 * Invoked by a parent ViewGroup to notify the start of the animation
10445 * currently associated with this view. If you override this method,
10446 * always call super.onAnimationStart();
10447 *
10448 * @see #setAnimation(android.view.animation.Animation)
10449 * @see #getAnimation()
10450 */
10451 protected void onAnimationStart() {
10452 mPrivateFlags |= ANIMATION_STARTED;
10453 }
10454
10455 /**
10456 * Invoked by a parent ViewGroup to notify the end of the animation
10457 * currently associated with this view. If you override this method,
10458 * always call super.onAnimationEnd();
10459 *
10460 * @see #setAnimation(android.view.animation.Animation)
10461 * @see #getAnimation()
10462 */
10463 protected void onAnimationEnd() {
10464 mPrivateFlags &= ~ANIMATION_STARTED;
10465 }
10466
10467 /**
10468 * Invoked if there is a Transform that involves alpha. Subclass that can
10469 * draw themselves with the specified alpha should return true, and then
10470 * respect that alpha when their onDraw() is called. If this returns false
10471 * then the view may be redirected to draw into an offscreen buffer to
10472 * fulfill the request, which will look fine, but may be slower than if the
10473 * subclass handles it internally. The default implementation returns false.
10474 *
10475 * @param alpha The alpha (0..255) to apply to the view's drawing
10476 * @return true if the view can draw with the specified alpha.
10477 */
10478 protected boolean onSetAlpha(int alpha) {
10479 return false;
10480 }
10481
10482 /**
10483 * This is used by the RootView to perform an optimization when
10484 * the view hierarchy contains one or several SurfaceView.
10485 * SurfaceView is always considered transparent, but its children are not,
10486 * therefore all View objects remove themselves from the global transparent
10487 * region (passed as a parameter to this function).
10488 *
10489 * @param region The transparent region for this ViewRoot (window).
10490 *
10491 * @return Returns true if the effective visibility of the view at this
10492 * point is opaque, regardless of the transparent region; returns false
10493 * if it is possible for underlying windows to be seen behind the view.
10494 *
10495 * {@hide}
10496 */
10497 public boolean gatherTransparentRegion(Region region) {
10498 final AttachInfo attachInfo = mAttachInfo;
10499 if (region != null && attachInfo != null) {
10500 final int pflags = mPrivateFlags;
10501 if ((pflags & SKIP_DRAW) == 0) {
10502 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10503 // remove it from the transparent region.
10504 final int[] location = attachInfo.mTransparentLocation;
10505 getLocationInWindow(location);
10506 region.op(location[0], location[1], location[0] + mRight - mLeft,
10507 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10508 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10509 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10510 // exists, so we remove the background drawable's non-transparent
10511 // parts from this transparent region.
10512 applyDrawableToTransparentRegion(mBGDrawable, region);
10513 }
10514 }
10515 return true;
10516 }
10517
10518 /**
10519 * Play a sound effect for this view.
10520 *
10521 * <p>The framework will play sound effects for some built in actions, such as
10522 * clicking, but you may wish to play these effects in your widget,
10523 * for instance, for internal navigation.
10524 *
10525 * <p>The sound effect will only be played if sound effects are enabled by the user, and
10526 * {@link #isSoundEffectsEnabled()} is true.
10527 *
10528 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10529 */
10530 public void playSoundEffect(int soundConstant) {
10531 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10532 return;
10533 }
10534 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10535 }
10536
10537 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010538 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010539 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010540 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010541 *
10542 * <p>The framework will provide haptic feedback for some built in actions,
10543 * such as long presses, but you may wish to provide feedback for your
10544 * own widget.
10545 *
10546 * <p>The feedback will only be performed if
10547 * {@link #isHapticFeedbackEnabled()} is true.
10548 *
10549 * @param feedbackConstant One of the constants defined in
10550 * {@link HapticFeedbackConstants}
10551 */
10552 public boolean performHapticFeedback(int feedbackConstant) {
10553 return performHapticFeedback(feedbackConstant, 0);
10554 }
10555
10556 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010557 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010558 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010559 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010560 *
10561 * @param feedbackConstant One of the constants defined in
10562 * {@link HapticFeedbackConstants}
10563 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10564 */
10565 public boolean performHapticFeedback(int feedbackConstant, int flags) {
10566 if (mAttachInfo == null) {
10567 return false;
10568 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010569 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010570 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010571 && !isHapticFeedbackEnabled()) {
10572 return false;
10573 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010574 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10575 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010576 }
10577
10578 /**
Christopher Tate2c095f32010-10-04 14:13:40 -070010579 * !!! TODO: real docs
10580 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010581 * The base class implementation makes the shadow the same size and appearance
Christopher Tate2c095f32010-10-04 14:13:40 -070010582 * as the view itself, and positions it with its center at the touch point.
10583 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010584 public static class DragShadowBuilder {
Christopher Tatea0374192010-10-05 13:06:41 -070010585 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010586
10587 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010588 * Construct a shadow builder object for use with the given view.
Christopher Tate2c095f32010-10-04 14:13:40 -070010589 * @param view
10590 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010591 public DragShadowBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010592 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010593 }
10594
Chris Tate6b391282010-10-14 15:48:59 -070010595 final public View getView() {
10596 return mView.get();
10597 }
10598
Christopher Tate2c095f32010-10-04 14:13:40 -070010599 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010600 * Provide the draggable-shadow metrics for the operation: the dimensions of
10601 * the shadow image itself, and the point within that shadow that should
Christopher Tate2c095f32010-10-04 14:13:40 -070010602 * be centered under the touch location while dragging.
10603 * <p>
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010604 * The default implementation sets the dimensions of the shadow to be the
10605 * same as the dimensions of the View itself and centers the shadow under
Christopher Tate2c095f32010-10-04 14:13:40 -070010606 * the touch point.
10607 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010608 * @param shadowSize The application should set the {@code x} member of this
10609 * parameter to the desired shadow width, and the {@code y} member to
Christopher Tate2c095f32010-10-04 14:13:40 -070010610 * the desired height.
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010611 * @param shadowTouchPoint The application should set this point to be the
10612 * location within the shadow that should track directly underneath
Christopher Tate2c095f32010-10-04 14:13:40 -070010613 * the touch point on the screen during a drag.
10614 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010615 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070010616 final View view = mView.get();
10617 if (view != null) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010618 shadowSize.set(view.getWidth(), view.getHeight());
10619 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
Christopher Tatea0374192010-10-05 13:06:41 -070010620 } else {
10621 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10622 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010623 }
10624
10625 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010626 * Draw the shadow image for the upcoming drag. The shadow canvas was
10627 * created with the dimensions supplied by the
10628 * {@link #onProvideShadowMetrics(Point, Point)} callback.
Christopher Tate2c095f32010-10-04 14:13:40 -070010629 *
10630 * @param canvas
10631 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010632 public void onDrawShadow(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070010633 final View view = mView.get();
10634 if (view != null) {
10635 view.draw(canvas);
10636 } else {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010637 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
Christopher Tatea0374192010-10-05 13:06:41 -070010638 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010639 }
10640 }
10641
10642 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010643 * Drag and drop. App calls startDrag(), then callbacks to the shadow builder's
10644 * {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} and
10645 * {@link DragShadowBuilder#onDrawShadow(Canvas)} methods happen, then the drag
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010646 * operation is handed over to the OS.
Christopher Tatea53146c2010-09-07 11:57:52 -070010647 * !!! TODO: real docs
Christopher Tate407b4e92010-11-30 17:14:08 -080010648 *
10649 * @param data !!! TODO
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010650 * @param shadowBuilder !!! TODO
Christopher Tate407b4e92010-11-30 17:14:08 -080010651 * @param myLocalState An arbitrary object that will be passed as part of every DragEvent
10652 * delivered to the calling application during the course of the current drag operation.
10653 * This object is private to the application that called startDrag(), and is not
10654 * visible to other applications. It provides a lightweight way for the application to
10655 * propagate information from the initiator to the recipient of a drag within its own
10656 * application; for example, to help disambiguate between 'copy' and 'move' semantics.
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010657 * @param flags Flags affecting the drag operation. At present no flags are defined;
10658 * pass 0 for this parameter.
Christopher Tate407b4e92010-11-30 17:14:08 -080010659 * @return {@code true} if the drag operation was initiated successfully; {@code false} if
10660 * an error prevented the drag from taking place.
Christopher Tatea53146c2010-09-07 11:57:52 -070010661 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010662 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010663 Object myLocalState, int flags) {
Christopher Tate2c095f32010-10-04 14:13:40 -070010664 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010665 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
Christopher Tatea53146c2010-09-07 11:57:52 -070010666 }
10667 boolean okay = false;
10668
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010669 Point shadowSize = new Point();
10670 Point shadowTouchPoint = new Point();
10671 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
Christopher Tate2c095f32010-10-04 14:13:40 -070010672
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010673 if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
10674 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
10675 throw new IllegalStateException("Drag shadow dimensions must not be negative");
Christopher Tate2c095f32010-10-04 14:13:40 -070010676 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010677
Chris Tatea32dcf72010-10-14 12:13:50 -070010678 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010679 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
10680 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
Chris Tatea32dcf72010-10-14 12:13:50 -070010681 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010682 Surface surface = new Surface();
10683 try {
10684 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010685 flags, shadowSize.x, shadowSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070010686 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070010687 + " surface=" + surface);
10688 if (token != null) {
10689 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070010690 try {
Chris Tate6b391282010-10-14 15:48:59 -070010691 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010692 shadowBuilder.onDrawShadow(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070010693 } finally {
10694 surface.unlockCanvasAndPost(canvas);
10695 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010696
Christopher Tate407b4e92010-11-30 17:14:08 -080010697 final ViewRoot root = getViewRoot();
10698
10699 // Cache the local state object for delivery with DragEvents
10700 root.setLocalDragState(myLocalState);
10701
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010702 // repurpose 'shadowSize' for the last touch point
10703 root.getLastTouchPoint(shadowSize);
Christopher Tate2c095f32010-10-04 14:13:40 -070010704
Christopher Tatea53146c2010-09-07 11:57:52 -070010705 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010706 shadowSize.x, shadowSize.y,
10707 shadowTouchPoint.x, shadowTouchPoint.y, data);
Christopher Tate2c095f32010-10-04 14:13:40 -070010708 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070010709 }
10710 } catch (Exception e) {
10711 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
10712 surface.destroy();
10713 }
10714
10715 return okay;
10716 }
10717
Christopher Tatea53146c2010-09-07 11:57:52 -070010718 /**
10719 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
10720 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
10721 *
10722 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
10723 * being dragged. onDragEvent() should return 'true' if the view can handle
10724 * a drop of that content. A view that returns 'false' here will receive no
10725 * further calls to onDragEvent() about the drag/drop operation.
10726 *
10727 * For DRAG_ENTERED, event.getClipDescription() describes the content being
10728 * dragged. This will be the same content description passed in the
10729 * DRAG_STARTED_EVENT invocation.
10730 *
10731 * For DRAG_EXITED, event.getClipDescription() describes the content being
10732 * dragged. This will be the same content description passed in the
10733 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
10734 * drag-acceptance visual state.
10735 *
10736 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10737 * coordinates of the current drag point. The view must return 'true' if it
10738 * can accept a drop of the current drag content, false otherwise.
10739 *
10740 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10741 * within the view; also, event.getClipData() returns the full data payload
10742 * being dropped. The view should return 'true' if it consumed the dropped
10743 * content, 'false' if it did not.
10744 *
10745 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
10746 * to its normal visual state.
10747 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010748 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070010749 return false;
10750 }
10751
10752 /**
10753 * Views typically don't need to override dispatchDragEvent(); it just calls
Chris Tate32affef2010-10-18 15:29:21 -070010754 * onDragEvent(event) and passes the result up appropriately.
Christopher Tatea53146c2010-09-07 11:57:52 -070010755 */
10756 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070010757 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10758 && mOnDragListener.onDrag(this, event)) {
10759 return true;
10760 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010761 return onDragEvent(event);
10762 }
10763
10764 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070010765 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
10766 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070010767 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070010768 */
10769 public void onCloseSystemDialogs(String reason) {
10770 }
10771
10772 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010773 * Given a Drawable whose bounds have been set to draw into this view,
10774 * update a Region being computed for {@link #gatherTransparentRegion} so
10775 * that any non-transparent parts of the Drawable are removed from the
10776 * given transparent region.
10777 *
10778 * @param dr The Drawable whose transparency is to be applied to the region.
10779 * @param region A Region holding the current transparency information,
10780 * where any parts of the region that are set are considered to be
10781 * transparent. On return, this region will be modified to have the
10782 * transparency information reduced by the corresponding parts of the
10783 * Drawable that are not transparent.
10784 * {@hide}
10785 */
10786 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
10787 if (DBG) {
10788 Log.i("View", "Getting transparent region for: " + this);
10789 }
10790 final Region r = dr.getTransparentRegion();
10791 final Rect db = dr.getBounds();
10792 final AttachInfo attachInfo = mAttachInfo;
10793 if (r != null && attachInfo != null) {
10794 final int w = getRight()-getLeft();
10795 final int h = getBottom()-getTop();
10796 if (db.left > 0) {
10797 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
10798 r.op(0, 0, db.left, h, Region.Op.UNION);
10799 }
10800 if (db.right < w) {
10801 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
10802 r.op(db.right, 0, w, h, Region.Op.UNION);
10803 }
10804 if (db.top > 0) {
10805 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
10806 r.op(0, 0, w, db.top, Region.Op.UNION);
10807 }
10808 if (db.bottom < h) {
10809 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
10810 r.op(0, db.bottom, w, h, Region.Op.UNION);
10811 }
10812 final int[] location = attachInfo.mTransparentLocation;
10813 getLocationInWindow(location);
10814 r.translate(location[0], location[1]);
10815 region.op(r, Region.Op.INTERSECT);
10816 } else {
10817 region.op(db, Region.Op.DIFFERENCE);
10818 }
10819 }
10820
Adam Powelle14579b2009-12-16 18:39:52 -080010821 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010822 mHasPerformedLongPress = false;
10823
10824 if (mPendingCheckForLongPress == null) {
10825 mPendingCheckForLongPress = new CheckForLongPress();
10826 }
10827 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080010828 postDelayed(mPendingCheckForLongPress,
10829 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010830 }
10831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010832 /**
10833 * Inflate a view from an XML resource. This convenience method wraps the {@link
10834 * LayoutInflater} class, which provides a full range of options for view inflation.
10835 *
10836 * @param context The Context object for your activity or application.
10837 * @param resource The resource ID to inflate
10838 * @param root A view group that will be the parent. Used to properly inflate the
10839 * layout_* parameters.
10840 * @see LayoutInflater
10841 */
10842 public static View inflate(Context context, int resource, ViewGroup root) {
10843 LayoutInflater factory = LayoutInflater.from(context);
10844 return factory.inflate(resource, root);
10845 }
Romain Guy33e72ae2010-07-17 12:40:29 -070010846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010847 /**
Adam Powell637d3372010-08-25 14:37:03 -070010848 * Scroll the view with standard behavior for scrolling beyond the normal
10849 * content boundaries. Views that call this method should override
10850 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
10851 * results of an over-scroll operation.
10852 *
10853 * Views can use this method to handle any touch or fling-based scrolling.
10854 *
10855 * @param deltaX Change in X in pixels
10856 * @param deltaY Change in Y in pixels
10857 * @param scrollX Current X scroll value in pixels before applying deltaX
10858 * @param scrollY Current Y scroll value in pixels before applying deltaY
10859 * @param scrollRangeX Maximum content scroll range along the X axis
10860 * @param scrollRangeY Maximum content scroll range along the Y axis
10861 * @param maxOverScrollX Number of pixels to overscroll by in either direction
10862 * along the X axis.
10863 * @param maxOverScrollY Number of pixels to overscroll by in either direction
10864 * along the Y axis.
10865 * @param isTouchEvent true if this scroll operation is the result of a touch event.
10866 * @return true if scrolling was clamped to an over-scroll boundary along either
10867 * axis, false otherwise.
10868 */
10869 protected boolean overScrollBy(int deltaX, int deltaY,
10870 int scrollX, int scrollY,
10871 int scrollRangeX, int scrollRangeY,
10872 int maxOverScrollX, int maxOverScrollY,
10873 boolean isTouchEvent) {
10874 final int overScrollMode = mOverScrollMode;
10875 final boolean canScrollHorizontal =
10876 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
10877 final boolean canScrollVertical =
10878 computeVerticalScrollRange() > computeVerticalScrollExtent();
10879 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
10880 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
10881 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
10882 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
10883
10884 int newScrollX = scrollX + deltaX;
10885 if (!overScrollHorizontal) {
10886 maxOverScrollX = 0;
10887 }
10888
10889 int newScrollY = scrollY + deltaY;
10890 if (!overScrollVertical) {
10891 maxOverScrollY = 0;
10892 }
10893
10894 // Clamp values if at the limits and record
10895 final int left = -maxOverScrollX;
10896 final int right = maxOverScrollX + scrollRangeX;
10897 final int top = -maxOverScrollY;
10898 final int bottom = maxOverScrollY + scrollRangeY;
10899
10900 boolean clampedX = false;
10901 if (newScrollX > right) {
10902 newScrollX = right;
10903 clampedX = true;
10904 } else if (newScrollX < left) {
10905 newScrollX = left;
10906 clampedX = true;
10907 }
10908
10909 boolean clampedY = false;
10910 if (newScrollY > bottom) {
10911 newScrollY = bottom;
10912 clampedY = true;
10913 } else if (newScrollY < top) {
10914 newScrollY = top;
10915 clampedY = true;
10916 }
10917
10918 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
10919
10920 return clampedX || clampedY;
10921 }
10922
10923 /**
10924 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
10925 * respond to the results of an over-scroll operation.
10926 *
10927 * @param scrollX New X scroll value in pixels
10928 * @param scrollY New Y scroll value in pixels
10929 * @param clampedX True if scrollX was clamped to an over-scroll boundary
10930 * @param clampedY True if scrollY was clamped to an over-scroll boundary
10931 */
10932 protected void onOverScrolled(int scrollX, int scrollY,
10933 boolean clampedX, boolean clampedY) {
10934 // Intentionally empty.
10935 }
10936
10937 /**
10938 * Returns the over-scroll mode for this view. The result will be
10939 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10940 * (allow over-scrolling only if the view content is larger than the container),
10941 * or {@link #OVER_SCROLL_NEVER}.
10942 *
10943 * @return This view's over-scroll mode.
10944 */
10945 public int getOverScrollMode() {
10946 return mOverScrollMode;
10947 }
10948
10949 /**
10950 * Set the over-scroll mode for this view. Valid over-scroll modes are
10951 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10952 * (allow over-scrolling only if the view content is larger than the container),
10953 * or {@link #OVER_SCROLL_NEVER}.
10954 *
10955 * Setting the over-scroll mode of a view will have an effect only if the
10956 * view is capable of scrolling.
10957 *
10958 * @param overScrollMode The new over-scroll mode for this view.
10959 */
10960 public void setOverScrollMode(int overScrollMode) {
10961 if (overScrollMode != OVER_SCROLL_ALWAYS &&
10962 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
10963 overScrollMode != OVER_SCROLL_NEVER) {
10964 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
10965 }
10966 mOverScrollMode = overScrollMode;
10967 }
10968
10969 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010970 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
10971 * Each MeasureSpec represents a requirement for either the width or the height.
10972 * A MeasureSpec is comprised of a size and a mode. There are three possible
10973 * modes:
10974 * <dl>
10975 * <dt>UNSPECIFIED</dt>
10976 * <dd>
10977 * The parent has not imposed any constraint on the child. It can be whatever size
10978 * it wants.
10979 * </dd>
10980 *
10981 * <dt>EXACTLY</dt>
10982 * <dd>
10983 * The parent has determined an exact size for the child. The child is going to be
10984 * given those bounds regardless of how big it wants to be.
10985 * </dd>
10986 *
10987 * <dt>AT_MOST</dt>
10988 * <dd>
10989 * The child can be as large as it wants up to the specified size.
10990 * </dd>
10991 * </dl>
10992 *
10993 * MeasureSpecs are implemented as ints to reduce object allocation. This class
10994 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
10995 */
10996 public static class MeasureSpec {
10997 private static final int MODE_SHIFT = 30;
10998 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
10999
11000 /**
11001 * Measure specification mode: The parent has not imposed any constraint
11002 * on the child. It can be whatever size it wants.
11003 */
11004 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
11005
11006 /**
11007 * Measure specification mode: The parent has determined an exact size
11008 * for the child. The child is going to be given those bounds regardless
11009 * of how big it wants to be.
11010 */
11011 public static final int EXACTLY = 1 << MODE_SHIFT;
11012
11013 /**
11014 * Measure specification mode: The child can be as large as it wants up
11015 * to the specified size.
11016 */
11017 public static final int AT_MOST = 2 << MODE_SHIFT;
11018
11019 /**
11020 * Creates a measure specification based on the supplied size and mode.
11021 *
11022 * The mode must always be one of the following:
11023 * <ul>
11024 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
11025 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
11026 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
11027 * </ul>
11028 *
11029 * @param size the size of the measure specification
11030 * @param mode the mode of the measure specification
11031 * @return the measure specification based on size and mode
11032 */
11033 public static int makeMeasureSpec(int size, int mode) {
11034 return size + mode;
11035 }
11036
11037 /**
11038 * Extracts the mode from the supplied measure specification.
11039 *
11040 * @param measureSpec the measure specification to extract the mode from
11041 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
11042 * {@link android.view.View.MeasureSpec#AT_MOST} or
11043 * {@link android.view.View.MeasureSpec#EXACTLY}
11044 */
11045 public static int getMode(int measureSpec) {
11046 return (measureSpec & MODE_MASK);
11047 }
11048
11049 /**
11050 * Extracts the size from the supplied measure specification.
11051 *
11052 * @param measureSpec the measure specification to extract the size from
11053 * @return the size in pixels defined in the supplied measure specification
11054 */
11055 public static int getSize(int measureSpec) {
11056 return (measureSpec & ~MODE_MASK);
11057 }
11058
11059 /**
11060 * Returns a String representation of the specified measure
11061 * specification.
11062 *
11063 * @param measureSpec the measure specification to convert to a String
11064 * @return a String with the following format: "MeasureSpec: MODE SIZE"
11065 */
11066 public static String toString(int measureSpec) {
11067 int mode = getMode(measureSpec);
11068 int size = getSize(measureSpec);
11069
11070 StringBuilder sb = new StringBuilder("MeasureSpec: ");
11071
11072 if (mode == UNSPECIFIED)
11073 sb.append("UNSPECIFIED ");
11074 else if (mode == EXACTLY)
11075 sb.append("EXACTLY ");
11076 else if (mode == AT_MOST)
11077 sb.append("AT_MOST ");
11078 else
11079 sb.append(mode).append(" ");
11080
11081 sb.append(size);
11082 return sb.toString();
11083 }
11084 }
11085
11086 class CheckForLongPress implements Runnable {
11087
11088 private int mOriginalWindowAttachCount;
11089
11090 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011091 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011092 && mOriginalWindowAttachCount == mWindowAttachCount) {
11093 if (performLongClick()) {
11094 mHasPerformedLongPress = true;
11095 }
11096 }
11097 }
11098
11099 public void rememberWindowAttachCount() {
11100 mOriginalWindowAttachCount = mWindowAttachCount;
11101 }
11102 }
Adam Powelle14579b2009-12-16 18:39:52 -080011103
11104 private final class CheckForTap implements Runnable {
11105 public void run() {
11106 mPrivateFlags &= ~PREPRESSED;
11107 mPrivateFlags |= PRESSED;
11108 refreshDrawableState();
11109 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
11110 postCheckForLongClick(ViewConfiguration.getTapTimeout());
11111 }
11112 }
11113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114
Adam Powella35d7682010-03-12 14:48:13 -080011115 private final class PerformClick implements Runnable {
11116 public void run() {
11117 performClick();
11118 }
11119 }
11120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011121 /**
11122 * Interface definition for a callback to be invoked when a key event is
11123 * dispatched to this view. The callback will be invoked before the key
11124 * event is given to the view.
11125 */
11126 public interface OnKeyListener {
11127 /**
11128 * Called when a key is dispatched to a view. This allows listeners to
11129 * get a chance to respond before the target view.
11130 *
11131 * @param v The view the key has been dispatched to.
11132 * @param keyCode The code for the physical key that was pressed
11133 * @param event The KeyEvent object containing full information about
11134 * the event.
11135 * @return True if the listener has consumed the event, false otherwise.
11136 */
11137 boolean onKey(View v, int keyCode, KeyEvent event);
11138 }
11139
11140 /**
11141 * Interface definition for a callback to be invoked when a touch event is
11142 * dispatched to this view. The callback will be invoked before the touch
11143 * event is given to the view.
11144 */
11145 public interface OnTouchListener {
11146 /**
11147 * Called when a touch event is dispatched to a view. This allows listeners to
11148 * get a chance to respond before the target view.
11149 *
11150 * @param v The view the touch event has been dispatched to.
11151 * @param event The MotionEvent object containing full information about
11152 * the event.
11153 * @return True if the listener has consumed the event, false otherwise.
11154 */
11155 boolean onTouch(View v, MotionEvent event);
11156 }
11157
11158 /**
11159 * Interface definition for a callback to be invoked when a view has been clicked and held.
11160 */
11161 public interface OnLongClickListener {
11162 /**
11163 * Called when a view has been clicked and held.
11164 *
11165 * @param v The view that was clicked and held.
11166 *
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -080011167 * @return true if the callback consumed the long click, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011168 */
11169 boolean onLongClick(View v);
11170 }
11171
11172 /**
Chris Tate32affef2010-10-18 15:29:21 -070011173 * Interface definition for a callback to be invoked when a drag is being dispatched
11174 * to this view. The callback will be invoked before the hosting view's own
11175 * onDrag(event) method. If the listener wants to fall back to the hosting view's
11176 * onDrag(event) behavior, it should return 'false' from this callback.
11177 */
11178 public interface OnDragListener {
11179 /**
11180 * Called when a drag event is dispatched to a view. This allows listeners
11181 * to get a chance to override base View behavior.
11182 *
11183 * @param v The view the drag has been dispatched to.
11184 * @param event The DragEvent object containing full information
11185 * about the event.
11186 * @return true if the listener consumed the DragEvent, false in order to fall
11187 * back to the view's default handling.
11188 */
11189 boolean onDrag(View v, DragEvent event);
11190 }
11191
11192 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011193 * Interface definition for a callback to be invoked when the focus state of
11194 * a view changed.
11195 */
11196 public interface OnFocusChangeListener {
11197 /**
11198 * Called when the focus state of a view has changed.
11199 *
11200 * @param v The view whose state has changed.
11201 * @param hasFocus The new focus state of v.
11202 */
11203 void onFocusChange(View v, boolean hasFocus);
11204 }
11205
11206 /**
11207 * Interface definition for a callback to be invoked when a view is clicked.
11208 */
11209 public interface OnClickListener {
11210 /**
11211 * Called when a view has been clicked.
11212 *
11213 * @param v The view that was clicked.
11214 */
11215 void onClick(View v);
11216 }
11217
11218 /**
11219 * Interface definition for a callback to be invoked when the context menu
11220 * for this view is being built.
11221 */
11222 public interface OnCreateContextMenuListener {
11223 /**
11224 * Called when the context menu for this view is being built. It is not
11225 * safe to hold onto the menu after this method returns.
11226 *
11227 * @param menu The context menu that is being built
11228 * @param v The view for which the context menu is being built
11229 * @param menuInfo Extra information about the item for which the
11230 * context menu should be shown. This information will vary
11231 * depending on the class of v.
11232 */
11233 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
11234 }
11235
11236 private final class UnsetPressedState implements Runnable {
11237 public void run() {
11238 setPressed(false);
11239 }
11240 }
11241
11242 /**
11243 * Base class for derived classes that want to save and restore their own
11244 * state in {@link android.view.View#onSaveInstanceState()}.
11245 */
11246 public static class BaseSavedState extends AbsSavedState {
11247 /**
11248 * Constructor used when reading from a parcel. Reads the state of the superclass.
11249 *
11250 * @param source
11251 */
11252 public BaseSavedState(Parcel source) {
11253 super(source);
11254 }
11255
11256 /**
11257 * Constructor called by derived classes when creating their SavedState objects
11258 *
11259 * @param superState The state of the superclass of this view
11260 */
11261 public BaseSavedState(Parcelable superState) {
11262 super(superState);
11263 }
11264
11265 public static final Parcelable.Creator<BaseSavedState> CREATOR =
11266 new Parcelable.Creator<BaseSavedState>() {
11267 public BaseSavedState createFromParcel(Parcel in) {
11268 return new BaseSavedState(in);
11269 }
11270
11271 public BaseSavedState[] newArray(int size) {
11272 return new BaseSavedState[size];
11273 }
11274 };
11275 }
11276
11277 /**
11278 * A set of information given to a view when it is attached to its parent
11279 * window.
11280 */
11281 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282 interface Callbacks {
11283 void playSoundEffect(int effectId);
11284 boolean performHapticFeedback(int effectId, boolean always);
11285 }
11286
11287 /**
11288 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11289 * to a Handler. This class contains the target (View) to invalidate and
11290 * the coordinates of the dirty rectangle.
11291 *
11292 * For performance purposes, this class also implements a pool of up to
11293 * POOL_LIMIT objects that get reused. This reduces memory allocations
11294 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011295 */
Romain Guyd928d682009-03-31 17:52:16 -070011296 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070011298 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11299 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070011300 public InvalidateInfo newInstance() {
11301 return new InvalidateInfo();
11302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011303
Romain Guyd928d682009-03-31 17:52:16 -070011304 public void onAcquired(InvalidateInfo element) {
11305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011306
Romain Guyd928d682009-03-31 17:52:16 -070011307 public void onReleased(InvalidateInfo element) {
11308 }
11309 }, POOL_LIMIT)
11310 );
11311
11312 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313
11314 View target;
11315
11316 int left;
11317 int top;
11318 int right;
11319 int bottom;
11320
Romain Guyd928d682009-03-31 17:52:16 -070011321 public void setNextPoolable(InvalidateInfo element) {
11322 mNext = element;
11323 }
11324
11325 public InvalidateInfo getNextPoolable() {
11326 return mNext;
11327 }
11328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011329 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070011330 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 }
11332
11333 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070011334 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011335 }
11336 }
11337
11338 final IWindowSession mSession;
11339
11340 final IWindow mWindow;
11341
11342 final IBinder mWindowToken;
11343
11344 final Callbacks mRootCallbacks;
11345
11346 /**
11347 * The top view of the hierarchy.
11348 */
11349 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070011350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011351 IBinder mPanelParentWindowToken;
11352 Surface mSurface;
11353
Romain Guyb051e892010-09-28 19:09:36 -070011354 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080011355 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070011356 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070011357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011358 /**
Romain Guy8506ab42009-06-11 17:35:47 -070011359 * Scale factor used by the compatibility mode
11360 */
11361 float mApplicationScale;
11362
11363 /**
11364 * Indicates whether the application is in compatibility mode
11365 */
11366 boolean mScalingRequired;
11367
11368 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 * Left position of this view's window
11370 */
11371 int mWindowLeft;
11372
11373 /**
11374 * Top position of this view's window
11375 */
11376 int mWindowTop;
11377
11378 /**
Adam Powell26153a32010-11-08 15:22:27 -080011379 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070011380 */
Adam Powell26153a32010-11-08 15:22:27 -080011381 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070011382
11383 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011384 * For windows that are full-screen but using insets to layout inside
11385 * of the screen decorations, these are the current insets for the
11386 * content of the window.
11387 */
11388 final Rect mContentInsets = new Rect();
11389
11390 /**
11391 * For windows that are full-screen but using insets to layout inside
11392 * of the screen decorations, these are the current insets for the
11393 * actual visible parts of the window.
11394 */
11395 final Rect mVisibleInsets = new Rect();
11396
11397 /**
11398 * The internal insets given by this window. This value is
11399 * supplied by the client (through
11400 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11401 * be given to the window manager when changed to be used in laying
11402 * out windows behind it.
11403 */
11404 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11405 = new ViewTreeObserver.InternalInsetsInfo();
11406
11407 /**
11408 * All views in the window's hierarchy that serve as scroll containers,
11409 * used to determine if the window can be resized or must be panned
11410 * to adjust for a soft input area.
11411 */
11412 final ArrayList<View> mScrollContainers = new ArrayList<View>();
11413
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070011414 final KeyEvent.DispatcherState mKeyDispatchState
11415 = new KeyEvent.DispatcherState();
11416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011417 /**
11418 * Indicates whether the view's window currently has the focus.
11419 */
11420 boolean mHasWindowFocus;
11421
11422 /**
11423 * The current visibility of the window.
11424 */
11425 int mWindowVisibility;
11426
11427 /**
11428 * Indicates the time at which drawing started to occur.
11429 */
11430 long mDrawingTime;
11431
11432 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070011433 * Indicates whether or not ignoring the DIRTY_MASK flags.
11434 */
11435 boolean mIgnoreDirtyState;
11436
11437 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011438 * Indicates whether the view's window is currently in touch mode.
11439 */
11440 boolean mInTouchMode;
11441
11442 /**
11443 * Indicates that ViewRoot should trigger a global layout change
11444 * the next time it performs a traversal
11445 */
11446 boolean mRecomputeGlobalAttributes;
11447
11448 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 * Set during a traveral if any views want to keep the screen on.
11450 */
11451 boolean mKeepScreenOn;
11452
11453 /**
11454 * Set if the visibility of any views has changed.
11455 */
11456 boolean mViewVisibilityChanged;
11457
11458 /**
11459 * Set to true if a view has been scrolled.
11460 */
11461 boolean mViewScrollChanged;
11462
11463 /**
11464 * Global to the view hierarchy used as a temporary for dealing with
11465 * x/y points in the transparent region computations.
11466 */
11467 final int[] mTransparentLocation = new int[2];
11468
11469 /**
11470 * Global to the view hierarchy used as a temporary for dealing with
11471 * x/y points in the ViewGroup.invalidateChild implementation.
11472 */
11473 final int[] mInvalidateChildLocation = new int[2];
11474
Chet Haasec3aa3612010-06-17 08:50:37 -070011475
11476 /**
11477 * Global to the view hierarchy used as a temporary for dealing with
11478 * x/y location when view is transformed.
11479 */
11480 final float[] mTmpTransformLocation = new float[2];
11481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011482 /**
11483 * The view tree observer used to dispatch global events like
11484 * layout, pre-draw, touch mode change, etc.
11485 */
11486 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11487
11488 /**
11489 * A Canvas used by the view hierarchy to perform bitmap caching.
11490 */
11491 Canvas mCanvas;
11492
11493 /**
11494 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11495 * handler can be used to pump events in the UI events queue.
11496 */
11497 final Handler mHandler;
11498
11499 /**
11500 * Identifier for messages requesting the view to be invalidated.
11501 * Such messages should be sent to {@link #mHandler}.
11502 */
11503 static final int INVALIDATE_MSG = 0x1;
11504
11505 /**
11506 * Identifier for messages requesting the view to invalidate a region.
11507 * Such messages should be sent to {@link #mHandler}.
11508 */
11509 static final int INVALIDATE_RECT_MSG = 0x2;
11510
11511 /**
11512 * Temporary for use in computing invalidate rectangles while
11513 * calling up the hierarchy.
11514 */
11515 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070011516
11517 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070011518 * Temporary for use in computing hit areas with transformed views
11519 */
11520 final RectF mTmpTransformRect = new RectF();
11521
11522 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070011523 * Temporary list for use in collecting focusable descendents of a view.
11524 */
11525 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011527 /**
11528 * Creates a new set of attachment information with the specified
11529 * events handler and thread.
11530 *
11531 * @param handler the events handler the view must use
11532 */
11533 AttachInfo(IWindowSession session, IWindow window,
11534 Handler handler, Callbacks effectPlayer) {
11535 mSession = session;
11536 mWindow = window;
11537 mWindowToken = window.asBinder();
11538 mHandler = handler;
11539 mRootCallbacks = effectPlayer;
11540 }
11541 }
11542
11543 /**
11544 * <p>ScrollabilityCache holds various fields used by a View when scrolling
11545 * is supported. This avoids keeping too many unused fields in most
11546 * instances of View.</p>
11547 */
Mike Cleronf116bf82009-09-27 19:14:12 -070011548 private static class ScrollabilityCache implements Runnable {
11549
11550 /**
11551 * Scrollbars are not visible
11552 */
11553 public static final int OFF = 0;
11554
11555 /**
11556 * Scrollbars are visible
11557 */
11558 public static final int ON = 1;
11559
11560 /**
11561 * Scrollbars are fading away
11562 */
11563 public static final int FADING = 2;
11564
11565 public boolean fadeScrollBars;
11566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011567 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070011568 public int scrollBarDefaultDelayBeforeFade;
11569 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011570
11571 public int scrollBarSize;
11572 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070011573 public float[] interpolatorValues;
11574 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011575
11576 public final Paint paint;
11577 public final Matrix matrix;
11578 public Shader shader;
11579
Mike Cleronf116bf82009-09-27 19:14:12 -070011580 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11581
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011582 private static final float[] OPAQUE = { 255 };
11583 private static final float[] TRANSPARENT = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070011584
11585 /**
11586 * When fading should start. This time moves into the future every time
11587 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11588 */
11589 public long fadeStartTime;
11590
11591
11592 /**
11593 * The current state of the scrollbars: ON, OFF, or FADING
11594 */
11595 public int state = OFF;
11596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011597 private int mLastColor;
11598
Mike Cleronf116bf82009-09-27 19:14:12 -070011599 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011600 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11601 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070011602 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11603 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011604
11605 paint = new Paint();
11606 matrix = new Matrix();
11607 // use use a height of 1, and then wack the matrix each time we
11608 // actually use it.
11609 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011611 paint.setShader(shader);
11612 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070011613 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011614 }
Romain Guy8506ab42009-06-11 17:35:47 -070011615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011616 public void setFadeColor(int color) {
11617 if (color != 0 && color != mLastColor) {
11618 mLastColor = color;
11619 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070011620
Romain Guye55e1a72009-08-27 10:42:26 -070011621 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11622 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011624 paint.setShader(shader);
11625 // Restore the default transfer mode (src_over)
11626 paint.setXfermode(null);
11627 }
11628 }
Mike Cleronf116bf82009-09-27 19:14:12 -070011629
11630 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070011631 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070011632 if (now >= fadeStartTime) {
11633
11634 // the animation fades the scrollbars out by changing
11635 // the opacity (alpha) from fully opaque to fully
11636 // transparent
11637 int nextFrame = (int) now;
11638 int framesCount = 0;
11639
11640 Interpolator interpolator = scrollBarInterpolator;
11641
11642 // Start opaque
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011643 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
Mike Cleronf116bf82009-09-27 19:14:12 -070011644
11645 // End transparent
11646 nextFrame += scrollBarFadeDuration;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011647 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
Mike Cleronf116bf82009-09-27 19:14:12 -070011648
11649 state = FADING;
11650
11651 // Kick off the fade animation
11652 host.invalidate();
11653 }
11654 }
11655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011656 }
11657}