blob: 7e968d7d0896c6e97060d1848d2c1e964b4427b3 [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;
svetoslavganov75986cf2009-05-14 22:28:01 -070061import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070065import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070066import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.view.inputmethod.InputConnection;
68import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.widget.ScrollBarDrawable;
70
Christopher Tatea0374192010-10-05 13:06:41 -070071import java.lang.ref.WeakReference;
svetoslavganov75986cf2009-05-14 22:28:01 -070072import java.lang.reflect.InvocationTargetException;
73import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import java.util.ArrayList;
75import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070076import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070077import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
79/**
80 * <p>
81 * This class represents the basic building block for user interface components. A View
82 * occupies a rectangular area on the screen and is responsible for drawing and
83 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070084 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
86 * are invisible containers that hold other Views (or other ViewGroups) and define
87 * their layout properties.
88 * </p>
89 *
90 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070091 * <p>For an introduction to using this class to develop your
92 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070094 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
102 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
103 * </p>
104 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700105 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 * <a name="Using"></a>
107 * <h3>Using Views</h3>
108 * <p>
109 * All of the views in a window are arranged in a single tree. You can add views
110 * either from code or by specifying a tree of views in one or more XML layout
111 * files. There are many specialized subclasses of views that act as controls or
112 * are capable of displaying text, images, or other content.
113 * </p>
114 * <p>
115 * Once you have created a tree of views, there are typically a few types of
116 * common operations you may wish to perform:
117 * <ul>
118 * <li><strong>Set properties:</strong> for example setting the text of a
119 * {@link android.widget.TextView}. The available properties and the methods
120 * that set them will vary among the different subclasses of views. Note that
121 * properties that are known at build time can be set in the XML layout
122 * files.</li>
123 * <li><strong>Set focus:</strong> The framework will handled moving focus in
124 * response to user input. To force focus to a specific view, call
125 * {@link #requestFocus}.</li>
126 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
127 * that will be notified when something interesting happens to the view. For
128 * example, all views will let you set a listener to be notified when the view
129 * gains or loses focus. You can register such a listener using
130 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
131 * specialized listeners. For example, a Button exposes a listener to notify
132 * clients when the button is clicked.</li>
133 * <li><strong>Set visibility:</strong> You can hide or show views using
134 * {@link #setVisibility}.</li>
135 * </ul>
136 * </p>
137 * <p><em>
138 * Note: The Android framework is responsible for measuring, laying out and
139 * drawing views. You should not call methods that perform these actions on
140 * views yourself unless you are actually implementing a
141 * {@link android.view.ViewGroup}.
142 * </em></p>
143 *
144 * <a name="Lifecycle"></a>
145 * <h3>Implementing a Custom View</h3>
146 *
147 * <p>
148 * To implement a custom view, you will usually begin by providing overrides for
149 * some of the standard methods that the framework calls on all views. You do
150 * not need to override all of these methods. In fact, you can start by just
151 * overriding {@link #onDraw(android.graphics.Canvas)}.
152 * <table border="2" width="85%" align="center" cellpadding="5">
153 * <thead>
154 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
155 * </thead>
156 *
157 * <tbody>
158 * <tr>
159 * <td rowspan="2">Creation</td>
160 * <td>Constructors</td>
161 * <td>There is a form of the constructor that are called when the view
162 * is created from code and a form that is called when the view is
163 * inflated from a layout file. The second form should parse and apply
164 * any attributes defined in the layout file.
165 * </td>
166 * </tr>
167 * <tr>
168 * <td><code>{@link #onFinishInflate()}</code></td>
169 * <td>Called after a view and all of its children has been inflated
170 * from XML.</td>
171 * </tr>
172 *
173 * <tr>
174 * <td rowspan="3">Layout</td>
175 * <td><code>{@link #onMeasure}</code></td>
176 * <td>Called to determine the size requirements for this view and all
177 * of its children.
178 * </td>
179 * </tr>
180 * <tr>
181 * <td><code>{@link #onLayout}</code></td>
182 * <td>Called when this view should assign a size and position to all
183 * of its children.
184 * </td>
185 * </tr>
186 * <tr>
187 * <td><code>{@link #onSizeChanged}</code></td>
188 * <td>Called when the size of this view has changed.
189 * </td>
190 * </tr>
191 *
192 * <tr>
193 * <td>Drawing</td>
194 * <td><code>{@link #onDraw}</code></td>
195 * <td>Called when the view should render its content.
196 * </td>
197 * </tr>
198 *
199 * <tr>
200 * <td rowspan="4">Event processing</td>
201 * <td><code>{@link #onKeyDown}</code></td>
202 * <td>Called when a new key event occurs.
203 * </td>
204 * </tr>
205 * <tr>
206 * <td><code>{@link #onKeyUp}</code></td>
207 * <td>Called when a key up event occurs.
208 * </td>
209 * </tr>
210 * <tr>
211 * <td><code>{@link #onTrackballEvent}</code></td>
212 * <td>Called when a trackball motion event occurs.
213 * </td>
214 * </tr>
215 * <tr>
216 * <td><code>{@link #onTouchEvent}</code></td>
217 * <td>Called when a touch screen motion event occurs.
218 * </td>
219 * </tr>
220 *
221 * <tr>
222 * <td rowspan="2">Focus</td>
223 * <td><code>{@link #onFocusChanged}</code></td>
224 * <td>Called when the view gains or loses focus.
225 * </td>
226 * </tr>
227 *
228 * <tr>
229 * <td><code>{@link #onWindowFocusChanged}</code></td>
230 * <td>Called when the window containing the view gains or loses focus.
231 * </td>
232 * </tr>
233 *
234 * <tr>
235 * <td rowspan="3">Attaching</td>
236 * <td><code>{@link #onAttachedToWindow()}</code></td>
237 * <td>Called when the view is attached to a window.
238 * </td>
239 * </tr>
240 *
241 * <tr>
242 * <td><code>{@link #onDetachedFromWindow}</code></td>
243 * <td>Called when the view is detached from its window.
244 * </td>
245 * </tr>
246 *
247 * <tr>
248 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
249 * <td>Called when the visibility of the window containing the view
250 * has changed.
251 * </td>
252 * </tr>
253 * </tbody>
254 *
255 * </table>
256 * </p>
257 *
258 * <a name="IDs"></a>
259 * <h3>IDs</h3>
260 * Views may have an integer id associated with them. These ids are typically
261 * assigned in the layout XML files, and are used to find specific views within
262 * the view tree. A common pattern is to:
263 * <ul>
264 * <li>Define a Button in the layout file and assign it a unique ID.
265 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700266 * &lt;Button
267 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 * android:layout_width="wrap_content"
269 * android:layout_height="wrap_content"
270 * android:text="@string/my_button_text"/&gt;
271 * </pre></li>
272 * <li>From the onCreate method of an Activity, find the Button
273 * <pre class="prettyprint">
274 * Button myButton = (Button) findViewById(R.id.my_button);
275 * </pre></li>
276 * </ul>
277 * <p>
278 * View IDs need not be unique throughout the tree, but it is good practice to
279 * ensure that they are at least unique within the part of the tree you are
280 * searching.
281 * </p>
282 *
283 * <a name="Position"></a>
284 * <h3>Position</h3>
285 * <p>
286 * The geometry of a view is that of a rectangle. A view has a location,
287 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
288 * two dimensions, expressed as a width and a height. The unit for location
289 * and dimensions is the pixel.
290 * </p>
291 *
292 * <p>
293 * It is possible to retrieve the location of a view by invoking the methods
294 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
295 * coordinate of the rectangle representing the view. The latter returns the
296 * top, or Y, coordinate of the rectangle representing the view. These methods
297 * both return the location of the view relative to its parent. For instance,
298 * when getLeft() returns 20, that means the view is located 20 pixels to the
299 * right of the left edge of its direct parent.
300 * </p>
301 *
302 * <p>
303 * In addition, several convenience methods are offered to avoid unnecessary
304 * computations, namely {@link #getRight()} and {@link #getBottom()}.
305 * These methods return the coordinates of the right and bottom edges of the
306 * rectangle representing the view. For instance, calling {@link #getRight()}
307 * is similar to the following computation: <code>getLeft() + getWidth()</code>
308 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
309 * </p>
310 *
311 * <a name="SizePaddingMargins"></a>
312 * <h3>Size, padding and margins</h3>
313 * <p>
314 * The size of a view is expressed with a width and a height. A view actually
315 * possess two pairs of width and height values.
316 * </p>
317 *
318 * <p>
319 * The first pair is known as <em>measured width</em> and
320 * <em>measured height</em>. These dimensions define how big a view wants to be
321 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
322 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
323 * and {@link #getMeasuredHeight()}.
324 * </p>
325 *
326 * <p>
327 * The second pair is simply known as <em>width</em> and <em>height</em>, or
328 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
329 * dimensions define the actual size of the view on screen, at drawing time and
330 * after layout. These values may, but do not have to, be different from the
331 * measured width and height. The width and height can be obtained by calling
332 * {@link #getWidth()} and {@link #getHeight()}.
333 * </p>
334 *
335 * <p>
336 * To measure its dimensions, a view takes into account its padding. The padding
337 * is expressed in pixels for the left, top, right and bottom parts of the view.
338 * Padding can be used to offset the content of the view by a specific amount of
339 * pixels. For instance, a left padding of 2 will push the view's content by
340 * 2 pixels to the right of the left edge. Padding can be set using the
341 * {@link #setPadding(int, int, int, int)} method and queried by calling
342 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
343 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
344 * </p>
345 *
346 * <p>
347 * Even though a view can define a padding, it does not provide any support for
348 * margins. However, view groups provide such a support. Refer to
349 * {@link android.view.ViewGroup} and
350 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
351 * </p>
352 *
353 * <a name="Layout"></a>
354 * <h3>Layout</h3>
355 * <p>
356 * Layout is a two pass process: a measure pass and a layout pass. The measuring
357 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
358 * of the view tree. Each view pushes dimension specifications down the tree
359 * during the recursion. At the end of the measure pass, every view has stored
360 * its measurements. The second pass happens in
361 * {@link #layout(int,int,int,int)} and is also top-down. During
362 * this pass each parent is responsible for positioning all of its children
363 * using the sizes computed in the measure pass.
364 * </p>
365 *
366 * <p>
367 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
368 * {@link #getMeasuredHeight()} values must be set, along with those for all of
369 * that view's descendants. A view's measured width and measured height values
370 * must respect the constraints imposed by the view's parents. This guarantees
371 * that at the end of the measure pass, all parents accept all of their
372 * children's measurements. A parent view may call measure() more than once on
373 * its children. For example, the parent may measure each child once with
374 * unspecified dimensions to find out how big they want to be, then call
375 * measure() on them again with actual numbers if the sum of all the children's
376 * unconstrained sizes is too big or too small.
377 * </p>
378 *
379 * <p>
380 * The measure pass uses two classes to communicate dimensions. The
381 * {@link MeasureSpec} class is used by views to tell their parents how they
382 * want to be measured and positioned. The base LayoutParams class just
383 * describes how big the view wants to be for both width and height. For each
384 * dimension, it can specify one of:
385 * <ul>
386 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800387 * <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 -0800388 * (minus padding)
389 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
390 * enclose its content (plus padding).
391 * </ul>
392 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
393 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
394 * an X and Y value.
395 * </p>
396 *
397 * <p>
398 * MeasureSpecs are used to push requirements down the tree from parent to
399 * child. A MeasureSpec can be in one of three modes:
400 * <ul>
401 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
402 * of a child view. For example, a LinearLayout may call measure() on its child
403 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
404 * tall the child view wants to be given a width of 240 pixels.
405 * <li>EXACTLY: This is used by the parent to impose an exact size on the
406 * child. The child must use this size, and guarantee that all of its
407 * descendants will fit within this size.
408 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
409 * child. The child must gurantee that it and all of its descendants will fit
410 * within this size.
411 * </ul>
412 * </p>
413 *
414 * <p>
415 * To intiate a layout, call {@link #requestLayout}. This method is typically
416 * called by a view on itself when it believes that is can no longer fit within
417 * its current bounds.
418 * </p>
419 *
420 * <a name="Drawing"></a>
421 * <h3>Drawing</h3>
422 * <p>
423 * Drawing is handled by walking the tree and rendering each view that
424 * intersects the the invalid region. Because the tree is traversed in-order,
425 * this means that parents will draw before (i.e., behind) their children, with
426 * siblings drawn in the order they appear in the tree.
427 * If you set a background drawable for a View, then the View will draw it for you
428 * before calling back to its <code>onDraw()</code> method.
429 * </p>
430 *
431 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700432 * 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 -0800433 * </p>
434 *
435 * <p>
436 * To force a view to draw, call {@link #invalidate()}.
437 * </p>
438 *
439 * <a name="EventHandlingThreading"></a>
440 * <h3>Event Handling and Threading</h3>
441 * <p>
442 * The basic cycle of a view is as follows:
443 * <ol>
444 * <li>An event comes in and is dispatched to the appropriate view. The view
445 * handles the event and notifies any listeners.</li>
446 * <li>If in the course of processing the event, the view's bounds may need
447 * to be changed, the view will call {@link #requestLayout()}.</li>
448 * <li>Similarly, if in the course of processing the event the view's appearance
449 * may need to be changed, the view will call {@link #invalidate()}.</li>
450 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
451 * the framework will take care of measuring, laying out, and drawing the tree
452 * as appropriate.</li>
453 * </ol>
454 * </p>
455 *
456 * <p><em>Note: The entire view tree is single threaded. You must always be on
457 * the UI thread when calling any method on any view.</em>
458 * If you are doing work on other threads and want to update the state of a view
459 * from that thread, you should use a {@link Handler}.
460 * </p>
461 *
462 * <a name="FocusHandling"></a>
463 * <h3>Focus Handling</h3>
464 * <p>
465 * The framework will handle routine focus movement in response to user input.
466 * This includes changing the focus as views are removed or hidden, or as new
467 * views become available. Views indicate their willingness to take focus
468 * through the {@link #isFocusable} method. To change whether a view can take
469 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
470 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
471 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
472 * </p>
473 * <p>
474 * Focus movement is based on an algorithm which finds the nearest neighbor in a
475 * given direction. In rare cases, the default algorithm may not match the
476 * intended behavior of the developer. In these situations, you can provide
477 * explicit overrides by using these XML attributes in the layout file:
478 * <pre>
479 * nextFocusDown
480 * nextFocusLeft
481 * nextFocusRight
482 * nextFocusUp
483 * </pre>
484 * </p>
485 *
486 *
487 * <p>
488 * To get a particular view to take focus, call {@link #requestFocus()}.
489 * </p>
490 *
491 * <a name="TouchMode"></a>
492 * <h3>Touch Mode</h3>
493 * <p>
494 * When a user is navigating a user interface via directional keys such as a D-pad, it is
495 * necessary to give focus to actionable items such as buttons so the user can see
496 * what will take input. If the device has touch capabilities, however, and the user
497 * begins interacting with the interface by touching it, it is no longer necessary to
498 * always highlight, or give focus to, a particular view. This motivates a mode
499 * for interaction named 'touch mode'.
500 * </p>
501 * <p>
502 * For a touch capable device, once the user touches the screen, the device
503 * will enter touch mode. From this point onward, only views for which
504 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
505 * Other views that are touchable, like buttons, will not take focus when touched; they will
506 * only fire the on click listeners.
507 * </p>
508 * <p>
509 * Any time a user hits a directional key, such as a D-pad direction, the view device will
510 * exit touch mode, and find a view to take focus, so that the user may resume interacting
511 * with the user interface without touching the screen again.
512 * </p>
513 * <p>
514 * The touch mode state is maintained across {@link android.app.Activity}s. Call
515 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
516 * </p>
517 *
518 * <a name="Scrolling"></a>
519 * <h3>Scrolling</h3>
520 * <p>
521 * The framework provides basic support for views that wish to internally
522 * scroll their content. This includes keeping track of the X and Y scroll
523 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700524 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
525 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 * </p>
527 *
528 * <a name="Tags"></a>
529 * <h3>Tags</h3>
530 * <p>
531 * Unlike IDs, tags are not used to identify views. Tags are essentially an
532 * extra piece of information that can be associated with a view. They are most
533 * often used as a convenience to store data related to views in the views
534 * themselves rather than by putting them in a separate structure.
535 * </p>
536 *
537 * <a name="Animation"></a>
538 * <h3>Animation</h3>
539 * <p>
540 * You can attach an {@link Animation} object to a view using
541 * {@link #setAnimation(Animation)} or
542 * {@link #startAnimation(Animation)}. The animation can alter the scale,
543 * rotation, translation and alpha of a view over time. If the animation is
544 * attached to a view that has children, the animation will affect the entire
545 * subtree rooted by that node. When an animation is started, the framework will
546 * take care of redrawing the appropriate views until the animation completes.
547 * </p>
Romain Guy171c5922011-01-06 10:04:23 -0800548 * <p>
549 * Starting with Android 3.0, the preferred way of animating views is to use the
550 * {@link android.animation} package APIs.
551 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 *
Jeff Brown85a31762010-09-01 17:01:00 -0700553 * <a name="Security"></a>
554 * <h3>Security</h3>
555 * <p>
556 * Sometimes it is essential that an application be able to verify that an action
557 * is being performed with the full knowledge and consent of the user, such as
558 * granting a permission request, making a purchase or clicking on an advertisement.
559 * Unfortunately, a malicious application could try to spoof the user into
560 * performing these actions, unaware, by concealing the intended purpose of the view.
561 * As a remedy, the framework offers a touch filtering mechanism that can be used to
562 * improve the security of views that provide access to sensitive functionality.
563 * </p><p>
564 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
Jeff Brown49ed71d2010-12-06 17:13:33 -0800565 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework
Jeff Brown85a31762010-09-01 17:01:00 -0700566 * will discard touches that are received whenever the view's window is obscured by
567 * another visible window. As a result, the view will not receive touches whenever a
568 * toast, dialog or other window appears above the view's window.
569 * </p><p>
570 * For more fine-grained control over security, consider overriding the
571 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
572 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
573 * </p>
574 *
Romain Guy171c5922011-01-06 10:04:23 -0800575 * @attr ref android.R.styleable#View_alpha
Romain Guyd6a463a2009-05-21 23:10:10 -0700576 * @attr ref android.R.styleable#View_background
577 * @attr ref android.R.styleable#View_clickable
578 * @attr ref android.R.styleable#View_contentDescription
579 * @attr ref android.R.styleable#View_drawingCacheQuality
580 * @attr ref android.R.styleable#View_duplicateParentState
581 * @attr ref android.R.styleable#View_id
582 * @attr ref android.R.styleable#View_fadingEdge
583 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700584 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700586 * @attr ref android.R.styleable#View_isScrollContainer
587 * @attr ref android.R.styleable#View_focusable
588 * @attr ref android.R.styleable#View_focusableInTouchMode
589 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
590 * @attr ref android.R.styleable#View_keepScreenOn
Romain Guy171c5922011-01-06 10:04:23 -0800591 * @attr ref android.R.styleable#View_layerType
Romain Guyd6a463a2009-05-21 23:10:10 -0700592 * @attr ref android.R.styleable#View_longClickable
593 * @attr ref android.R.styleable#View_minHeight
594 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 * @attr ref android.R.styleable#View_nextFocusDown
596 * @attr ref android.R.styleable#View_nextFocusLeft
597 * @attr ref android.R.styleable#View_nextFocusRight
598 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700599 * @attr ref android.R.styleable#View_onClick
600 * @attr ref android.R.styleable#View_padding
601 * @attr ref android.R.styleable#View_paddingBottom
602 * @attr ref android.R.styleable#View_paddingLeft
603 * @attr ref android.R.styleable#View_paddingRight
604 * @attr ref android.R.styleable#View_paddingTop
605 * @attr ref android.R.styleable#View_saveEnabled
Chet Haase73066682010-11-29 15:55:32 -0800606 * @attr ref android.R.styleable#View_rotation
607 * @attr ref android.R.styleable#View_rotationX
608 * @attr ref android.R.styleable#View_rotationY
609 * @attr ref android.R.styleable#View_scaleX
610 * @attr ref android.R.styleable#View_scaleY
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 * @attr ref android.R.styleable#View_scrollX
612 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700613 * @attr ref android.R.styleable#View_scrollbarSize
614 * @attr ref android.R.styleable#View_scrollbarStyle
615 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700616 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
617 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
619 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 * @attr ref android.R.styleable#View_scrollbarThumbVertical
621 * @attr ref android.R.styleable#View_scrollbarTrackVertical
622 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700624 * @attr ref android.R.styleable#View_soundEffectsEnabled
625 * @attr ref android.R.styleable#View_tag
Chet Haase73066682010-11-29 15:55:32 -0800626 * @attr ref android.R.styleable#View_transformPivotX
627 * @attr ref android.R.styleable#View_transformPivotY
628 * @attr ref android.R.styleable#View_translationX
629 * @attr ref android.R.styleable#View_translationY
Romain Guyd6a463a2009-05-21 23:10:10 -0700630 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 *
632 * @see android.view.ViewGroup
633 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700634public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 private static final boolean DBG = false;
636
637 /**
638 * The logging tag used by this class with android.util.Log.
639 */
640 protected static final String VIEW_LOG_TAG = "View";
641
642 /**
643 * Used to mark a View that has no ID.
644 */
645 public static final int NO_ID = -1;
646
647 /**
648 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
649 * calling setFlags.
650 */
651 private static final int NOT_FOCUSABLE = 0x00000000;
652
653 /**
654 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
655 * setFlags.
656 */
657 private static final int FOCUSABLE = 0x00000001;
658
659 /**
660 * Mask for use with setFlags indicating bits used for focus.
661 */
662 private static final int FOCUSABLE_MASK = 0x00000001;
663
664 /**
665 * This view will adjust its padding to fit sytem windows (e.g. status bar)
666 */
667 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
668
669 /**
670 * This view is visible. Use with {@link #setVisibility}.
671 */
672 public static final int VISIBLE = 0x00000000;
673
674 /**
675 * This view is invisible, but it still takes up space for layout purposes.
676 * Use with {@link #setVisibility}.
677 */
678 public static final int INVISIBLE = 0x00000004;
679
680 /**
681 * This view is invisible, and it doesn't take any space for layout
682 * purposes. Use with {@link #setVisibility}.
683 */
684 public static final int GONE = 0x00000008;
685
686 /**
687 * Mask for use with setFlags indicating bits used for visibility.
688 * {@hide}
689 */
690 static final int VISIBILITY_MASK = 0x0000000C;
691
692 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
693
694 /**
695 * This view is enabled. Intrepretation varies by subclass.
696 * Use with ENABLED_MASK when calling setFlags.
697 * {@hide}
698 */
699 static final int ENABLED = 0x00000000;
700
701 /**
702 * This view is disabled. Intrepretation varies by subclass.
703 * Use with ENABLED_MASK when calling setFlags.
704 * {@hide}
705 */
706 static final int DISABLED = 0x00000020;
707
708 /**
709 * Mask for use with setFlags indicating bits used for indicating whether
710 * this view is enabled
711 * {@hide}
712 */
713 static final int ENABLED_MASK = 0x00000020;
714
715 /**
716 * This view won't draw. {@link #onDraw} won't be called and further
717 * optimizations
718 * will be performed. It is okay to have this flag set and a background.
719 * Use with DRAW_MASK when calling setFlags.
720 * {@hide}
721 */
722 static final int WILL_NOT_DRAW = 0x00000080;
723
724 /**
725 * Mask for use with setFlags indicating bits used for indicating whether
726 * this view is will draw
727 * {@hide}
728 */
729 static final int DRAW_MASK = 0x00000080;
730
731 /**
732 * <p>This view doesn't show scrollbars.</p>
733 * {@hide}
734 */
735 static final int SCROLLBARS_NONE = 0x00000000;
736
737 /**
738 * <p>This view shows horizontal scrollbars.</p>
739 * {@hide}
740 */
741 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
742
743 /**
744 * <p>This view shows vertical scrollbars.</p>
745 * {@hide}
746 */
747 static final int SCROLLBARS_VERTICAL = 0x00000200;
748
749 /**
750 * <p>Mask for use with setFlags indicating bits used for indicating which
751 * scrollbars are enabled.</p>
752 * {@hide}
753 */
754 static final int SCROLLBARS_MASK = 0x00000300;
755
Jeff Brown85a31762010-09-01 17:01:00 -0700756 /**
757 * Indicates that the view should filter touches when its window is obscured.
758 * Refer to the class comments for more information about this security feature.
759 * {@hide}
760 */
761 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
762
763 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764
765 /**
766 * <p>This view doesn't show fading edges.</p>
767 * {@hide}
768 */
769 static final int FADING_EDGE_NONE = 0x00000000;
770
771 /**
772 * <p>This view shows horizontal fading edges.</p>
773 * {@hide}
774 */
775 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
776
777 /**
778 * <p>This view shows vertical fading edges.</p>
779 * {@hide}
780 */
781 static final int FADING_EDGE_VERTICAL = 0x00002000;
782
783 /**
784 * <p>Mask for use with setFlags indicating bits used for indicating which
785 * fading edges are enabled.</p>
786 * {@hide}
787 */
788 static final int FADING_EDGE_MASK = 0x00003000;
789
790 /**
791 * <p>Indicates this view can be clicked. When clickable, a View reacts
792 * to clicks by notifying the OnClickListener.<p>
793 * {@hide}
794 */
795 static final int CLICKABLE = 0x00004000;
796
797 /**
798 * <p>Indicates this view is caching its drawing into a bitmap.</p>
799 * {@hide}
800 */
801 static final int DRAWING_CACHE_ENABLED = 0x00008000;
802
803 /**
804 * <p>Indicates that no icicle should be saved for this view.<p>
805 * {@hide}
806 */
807 static final int SAVE_DISABLED = 0x000010000;
808
809 /**
810 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
811 * property.</p>
812 * {@hide}
813 */
814 static final int SAVE_DISABLED_MASK = 0x000010000;
815
816 /**
817 * <p>Indicates that no drawing cache should ever be created for this view.<p>
818 * {@hide}
819 */
820 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
821
822 /**
823 * <p>Indicates this view can take / keep focus when int touch mode.</p>
824 * {@hide}
825 */
826 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
827
828 /**
829 * <p>Enables low quality mode for the drawing cache.</p>
830 */
831 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
832
833 /**
834 * <p>Enables high quality mode for the drawing cache.</p>
835 */
836 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
837
838 /**
839 * <p>Enables automatic quality mode for the drawing cache.</p>
840 */
841 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
842
843 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
844 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
845 };
846
847 /**
848 * <p>Mask for use with setFlags indicating bits used for the cache
849 * quality property.</p>
850 * {@hide}
851 */
852 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
853
854 /**
855 * <p>
856 * Indicates this view can be long clicked. When long clickable, a View
857 * reacts to long clicks by notifying the OnLongClickListener or showing a
858 * context menu.
859 * </p>
860 * {@hide}
861 */
862 static final int LONG_CLICKABLE = 0x00200000;
863
864 /**
865 * <p>Indicates that this view gets its drawable states from its direct parent
866 * and ignores its original internal states.</p>
867 *
868 * @hide
869 */
870 static final int DUPLICATE_PARENT_STATE = 0x00400000;
871
872 /**
873 * The scrollbar style to display the scrollbars inside the content area,
874 * without increasing the padding. The scrollbars will be overlaid with
875 * translucency on the view's content.
876 */
877 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
878
879 /**
880 * The scrollbar style to display the scrollbars inside the padded area,
881 * increasing the padding of the view. The scrollbars will not overlap the
882 * content area of the view.
883 */
884 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
885
886 /**
887 * The scrollbar style to display the scrollbars at the edge of the view,
888 * without increasing the padding. The scrollbars will be overlaid with
889 * translucency.
890 */
891 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
892
893 /**
894 * The scrollbar style to display the scrollbars at the edge of the view,
895 * increasing the padding of the view. The scrollbars will only overlap the
896 * background, if any.
897 */
898 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
899
900 /**
901 * Mask to check if the scrollbar style is overlay or inset.
902 * {@hide}
903 */
904 static final int SCROLLBARS_INSET_MASK = 0x01000000;
905
906 /**
907 * Mask to check if the scrollbar style is inside or outside.
908 * {@hide}
909 */
910 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
911
912 /**
913 * Mask for scrollbar style.
914 * {@hide}
915 */
916 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
917
918 /**
919 * View flag indicating that the screen should remain on while the
920 * window containing this view is visible to the user. This effectively
921 * takes care of automatically setting the WindowManager's
922 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
923 */
924 public static final int KEEP_SCREEN_ON = 0x04000000;
925
926 /**
927 * View flag indicating whether this view should have sound effects enabled
928 * for events such as clicking and touching.
929 */
930 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
931
932 /**
933 * View flag indicating whether this view should have haptic feedback
934 * enabled for events such as long presses.
935 */
936 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
937
938 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700939 * <p>Indicates that the view hierarchy should stop saving state when
940 * it reaches this view. If state saving is initiated immediately at
941 * the view, it will be allowed.
942 * {@hide}
943 */
944 static final int PARENT_SAVE_DISABLED = 0x20000000;
945
946 /**
947 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
948 * {@hide}
949 */
950 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
951
952 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700953 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
954 * should add all focusable Views regardless if they are focusable in touch mode.
955 */
956 public static final int FOCUSABLES_ALL = 0x00000000;
957
958 /**
959 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
960 * should add only Views focusable in touch mode.
961 */
962 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
963
964 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 * Use with {@link #focusSearch}. Move focus to the previous selectable
966 * item.
967 */
968 public static final int FOCUS_BACKWARD = 0x00000001;
969
970 /**
971 * Use with {@link #focusSearch}. Move focus to the next selectable
972 * item.
973 */
974 public static final int FOCUS_FORWARD = 0x00000002;
975
976 /**
977 * Use with {@link #focusSearch}. Move focus to the left.
978 */
979 public static final int FOCUS_LEFT = 0x00000011;
980
981 /**
982 * Use with {@link #focusSearch}. Move focus up.
983 */
984 public static final int FOCUS_UP = 0x00000021;
985
986 /**
987 * Use with {@link #focusSearch}. Move focus to the right.
988 */
989 public static final int FOCUS_RIGHT = 0x00000042;
990
991 /**
992 * Use with {@link #focusSearch}. Move focus down.
993 */
994 public static final int FOCUS_DOWN = 0x00000082;
995
996 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -0800997 * Bits of {@link #getMeasuredWidthAndState()} and
998 * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
999 */
1000 public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1001
1002 /**
1003 * Bits of {@link #getMeasuredWidthAndState()} and
1004 * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1005 */
1006 public static final int MEASURED_STATE_MASK = 0xff000000;
1007
1008 /**
1009 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1010 * for functions that combine both width and height into a single int,
1011 * such as {@link #getMeasuredState()} and the childState argument of
1012 * {@link #resolveSizeAndState(int, int, int)}.
1013 */
1014 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1015
1016 /**
1017 * Bit of {@link #getMeasuredWidthAndState()} and
1018 * {@link #getMeasuredWidthAndState()} that indicates the measured size
1019 * is smaller that the space the view would like to have.
1020 */
1021 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1022
1023 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 * Base View state sets
1025 */
1026 // Singles
1027 /**
1028 * Indicates the view has no states set. States are used with
1029 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1030 * view depending on its state.
1031 *
1032 * @see android.graphics.drawable.Drawable
1033 * @see #getDrawableState()
1034 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001035 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 /**
1037 * Indicates the view is enabled. States are used with
1038 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1039 * view depending on its state.
1040 *
1041 * @see android.graphics.drawable.Drawable
1042 * @see #getDrawableState()
1043 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001044 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 /**
1046 * Indicates the view is focused. States are used with
1047 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1048 * view depending on its state.
1049 *
1050 * @see android.graphics.drawable.Drawable
1051 * @see #getDrawableState()
1052 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001053 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 /**
1055 * Indicates the view is selected. States are used with
1056 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1057 * view depending on its state.
1058 *
1059 * @see android.graphics.drawable.Drawable
1060 * @see #getDrawableState()
1061 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001062 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 /**
1064 * Indicates the view is pressed. States are used with
1065 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1066 * view depending on its state.
1067 *
1068 * @see android.graphics.drawable.Drawable
1069 * @see #getDrawableState()
1070 * @hide
1071 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001072 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 /**
1074 * Indicates the view's window has focus. States are used with
1075 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1076 * view depending on its state.
1077 *
1078 * @see android.graphics.drawable.Drawable
1079 * @see #getDrawableState()
1080 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001081 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 // Doubles
1083 /**
1084 * Indicates the view is enabled and has the focus.
1085 *
1086 * @see #ENABLED_STATE_SET
1087 * @see #FOCUSED_STATE_SET
1088 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001089 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 /**
1091 * Indicates the view is enabled and selected.
1092 *
1093 * @see #ENABLED_STATE_SET
1094 * @see #SELECTED_STATE_SET
1095 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001096 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 /**
1098 * Indicates the view is enabled and that its window has focus.
1099 *
1100 * @see #ENABLED_STATE_SET
1101 * @see #WINDOW_FOCUSED_STATE_SET
1102 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001103 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 /**
1105 * Indicates the view is focused and selected.
1106 *
1107 * @see #FOCUSED_STATE_SET
1108 * @see #SELECTED_STATE_SET
1109 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001110 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 /**
1112 * Indicates the view has the focus and that its window has the focus.
1113 *
1114 * @see #FOCUSED_STATE_SET
1115 * @see #WINDOW_FOCUSED_STATE_SET
1116 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001117 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 /**
1119 * Indicates the view is selected and that its window has the focus.
1120 *
1121 * @see #SELECTED_STATE_SET
1122 * @see #WINDOW_FOCUSED_STATE_SET
1123 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001124 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 // Triples
1126 /**
1127 * Indicates the view is enabled, focused and selected.
1128 *
1129 * @see #ENABLED_STATE_SET
1130 * @see #FOCUSED_STATE_SET
1131 * @see #SELECTED_STATE_SET
1132 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001133 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 /**
1135 * Indicates the view is enabled, focused and its window has the focus.
1136 *
1137 * @see #ENABLED_STATE_SET
1138 * @see #FOCUSED_STATE_SET
1139 * @see #WINDOW_FOCUSED_STATE_SET
1140 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001141 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 /**
1143 * Indicates the view is enabled, selected and its window has the focus.
1144 *
1145 * @see #ENABLED_STATE_SET
1146 * @see #SELECTED_STATE_SET
1147 * @see #WINDOW_FOCUSED_STATE_SET
1148 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001149 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 /**
1151 * Indicates the view is focused, selected and its window has the focus.
1152 *
1153 * @see #FOCUSED_STATE_SET
1154 * @see #SELECTED_STATE_SET
1155 * @see #WINDOW_FOCUSED_STATE_SET
1156 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001157 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 /**
1159 * Indicates the view is enabled, focused, selected and its window
1160 * has the focus.
1161 *
1162 * @see #ENABLED_STATE_SET
1163 * @see #FOCUSED_STATE_SET
1164 * @see #SELECTED_STATE_SET
1165 * @see #WINDOW_FOCUSED_STATE_SET
1166 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001167 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 /**
1169 * Indicates the view is pressed and its window has the focus.
1170 *
1171 * @see #PRESSED_STATE_SET
1172 * @see #WINDOW_FOCUSED_STATE_SET
1173 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001174 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 /**
1176 * Indicates the view is pressed and selected.
1177 *
1178 * @see #PRESSED_STATE_SET
1179 * @see #SELECTED_STATE_SET
1180 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001181 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 /**
1183 * Indicates the view is pressed, selected and its window has the focus.
1184 *
1185 * @see #PRESSED_STATE_SET
1186 * @see #SELECTED_STATE_SET
1187 * @see #WINDOW_FOCUSED_STATE_SET
1188 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001189 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 /**
1191 * Indicates the view is pressed and focused.
1192 *
1193 * @see #PRESSED_STATE_SET
1194 * @see #FOCUSED_STATE_SET
1195 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001196 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 /**
1198 * Indicates the view is pressed, focused and its window has the focus.
1199 *
1200 * @see #PRESSED_STATE_SET
1201 * @see #FOCUSED_STATE_SET
1202 * @see #WINDOW_FOCUSED_STATE_SET
1203 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001204 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 /**
1206 * Indicates the view is pressed, focused and selected.
1207 *
1208 * @see #PRESSED_STATE_SET
1209 * @see #SELECTED_STATE_SET
1210 * @see #FOCUSED_STATE_SET
1211 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001212 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 /**
1214 * Indicates the view is pressed, focused, selected and its window has the focus.
1215 *
1216 * @see #PRESSED_STATE_SET
1217 * @see #FOCUSED_STATE_SET
1218 * @see #SELECTED_STATE_SET
1219 * @see #WINDOW_FOCUSED_STATE_SET
1220 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001221 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 /**
1223 * Indicates the view is pressed and enabled.
1224 *
1225 * @see #PRESSED_STATE_SET
1226 * @see #ENABLED_STATE_SET
1227 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001228 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 /**
1230 * Indicates the view is pressed, enabled and its window has the focus.
1231 *
1232 * @see #PRESSED_STATE_SET
1233 * @see #ENABLED_STATE_SET
1234 * @see #WINDOW_FOCUSED_STATE_SET
1235 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001236 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 /**
1238 * Indicates the view is pressed, enabled and selected.
1239 *
1240 * @see #PRESSED_STATE_SET
1241 * @see #ENABLED_STATE_SET
1242 * @see #SELECTED_STATE_SET
1243 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001244 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 /**
1246 * Indicates the view is pressed, enabled, selected and its window has the
1247 * focus.
1248 *
1249 * @see #PRESSED_STATE_SET
1250 * @see #ENABLED_STATE_SET
1251 * @see #SELECTED_STATE_SET
1252 * @see #WINDOW_FOCUSED_STATE_SET
1253 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001254 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 /**
1256 * Indicates the view is pressed, enabled and focused.
1257 *
1258 * @see #PRESSED_STATE_SET
1259 * @see #ENABLED_STATE_SET
1260 * @see #FOCUSED_STATE_SET
1261 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001262 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 /**
1264 * Indicates the view is pressed, enabled, focused and its window has the
1265 * focus.
1266 *
1267 * @see #PRESSED_STATE_SET
1268 * @see #ENABLED_STATE_SET
1269 * @see #FOCUSED_STATE_SET
1270 * @see #WINDOW_FOCUSED_STATE_SET
1271 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001272 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 /**
1274 * Indicates the view is pressed, enabled, focused and selected.
1275 *
1276 * @see #PRESSED_STATE_SET
1277 * @see #ENABLED_STATE_SET
1278 * @see #SELECTED_STATE_SET
1279 * @see #FOCUSED_STATE_SET
1280 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001281 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 /**
1283 * Indicates the view is pressed, enabled, focused, selected and its window
1284 * has the focus.
1285 *
1286 * @see #PRESSED_STATE_SET
1287 * @see #ENABLED_STATE_SET
1288 * @see #SELECTED_STATE_SET
1289 * @see #FOCUSED_STATE_SET
1290 * @see #WINDOW_FOCUSED_STATE_SET
1291 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001292 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293
1294 /**
1295 * The order here is very important to {@link #getDrawableState()}
1296 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001297 private static final int[][] VIEW_STATE_SETS;
1298
Romain Guyb051e892010-09-28 19:09:36 -07001299 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1300 static final int VIEW_STATE_SELECTED = 1 << 1;
1301 static final int VIEW_STATE_FOCUSED = 1 << 2;
1302 static final int VIEW_STATE_ENABLED = 1 << 3;
1303 static final int VIEW_STATE_PRESSED = 1 << 4;
1304 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001305 static final int VIEW_STATE_ACCELERATED = 1 << 6;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001306
1307 static final int[] VIEW_STATE_IDS = new int[] {
1308 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1309 R.attr.state_selected, VIEW_STATE_SELECTED,
1310 R.attr.state_focused, VIEW_STATE_FOCUSED,
1311 R.attr.state_enabled, VIEW_STATE_ENABLED,
1312 R.attr.state_pressed, VIEW_STATE_PRESSED,
1313 R.attr.state_activated, VIEW_STATE_ACTIVATED,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001314 R.attr.state_accelerated, VIEW_STATE_ACCELERATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 };
1316
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001317 static {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001318 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1319 throw new IllegalStateException(
1320 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1321 }
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001322 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001323 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001324 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001325 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001326 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001327 orderedIds[i * 2] = viewState;
1328 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001329 }
1330 }
1331 }
Romain Guyb051e892010-09-28 19:09:36 -07001332 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1333 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1334 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001335 int numBits = Integer.bitCount(i);
1336 int[] set = new int[numBits];
1337 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001338 for (int j = 0; j < orderedIds.length; j += 2) {
1339 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001340 set[pos++] = orderedIds[j];
1341 }
1342 }
1343 VIEW_STATE_SETS[i] = set;
1344 }
1345
1346 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1347 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1348 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1349 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1350 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1351 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1352 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1353 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1354 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1355 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1356 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1357 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1358 | VIEW_STATE_FOCUSED];
1359 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1360 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1361 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1362 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1363 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1364 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1365 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1366 | VIEW_STATE_ENABLED];
1367 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1368 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1369 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1370 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1371 | VIEW_STATE_ENABLED];
1372 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1373 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1374 | VIEW_STATE_ENABLED];
1375 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1376 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1377 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1378
1379 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1380 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1381 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1382 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1383 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1384 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1385 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1386 | VIEW_STATE_PRESSED];
1387 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1388 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1389 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1390 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1391 | VIEW_STATE_PRESSED];
1392 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1393 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1394 | VIEW_STATE_PRESSED];
1395 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1396 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1397 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1398 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1399 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1400 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1401 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1402 | VIEW_STATE_PRESSED];
1403 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1404 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1405 | VIEW_STATE_PRESSED];
1406 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1407 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1408 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1409 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1410 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1411 | VIEW_STATE_PRESSED];
1412 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1413 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1414 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1415 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1416 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1417 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1418 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1421 | VIEW_STATE_PRESSED];
1422 }
1423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 /**
1425 * Used by views that contain lists of items. This state indicates that
1426 * the view is showing the last item.
1427 * @hide
1428 */
1429 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1430 /**
1431 * Used by views that contain lists of items. This state indicates that
1432 * the view is showing the first item.
1433 * @hide
1434 */
1435 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1436 /**
1437 * Used by views that contain lists of items. This state indicates that
1438 * the view is showing the middle item.
1439 * @hide
1440 */
1441 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1442 /**
1443 * Used by views that contain lists of items. This state indicates that
1444 * the view is showing only one item.
1445 * @hide
1446 */
1447 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1448 /**
1449 * Used by views that contain lists of items. This state indicates that
1450 * the view is pressed and showing the last item.
1451 * @hide
1452 */
1453 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1454 /**
1455 * Used by views that contain lists of items. This state indicates that
1456 * the view is pressed and showing the first item.
1457 * @hide
1458 */
1459 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1460 /**
1461 * Used by views that contain lists of items. This state indicates that
1462 * the view is pressed and showing the middle item.
1463 * @hide
1464 */
1465 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1466 /**
1467 * Used by views that contain lists of items. This state indicates that
1468 * the view is pressed and showing only one item.
1469 * @hide
1470 */
1471 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1472
1473 /**
1474 * Temporary Rect currently for use in setBackground(). This will probably
1475 * be extended in the future to hold our own class with more than just
1476 * a Rect. :)
1477 */
1478 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001479
1480 /**
1481 * Map used to store views' tags.
1482 */
1483 private static WeakHashMap<View, SparseArray<Object>> sTags;
1484
1485 /**
1486 * Lock used to access sTags.
1487 */
1488 private static final Object sTagsLock = new Object();
1489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 /**
1491 * The animation currently associated with this view.
1492 * @hide
1493 */
1494 protected Animation mCurrentAnimation = null;
1495
1496 /**
1497 * Width as measured during measure pass.
1498 * {@hide}
1499 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001500 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001501 /*package*/ int mMeasuredWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502
1503 /**
1504 * Height as measured during measure pass.
1505 * {@hide}
1506 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001507 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001508 /*package*/ int mMeasuredHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509
1510 /**
Chet Haasedaf98e92011-01-10 14:10:36 -08001511 * Flag to indicate that this view was marked INVALIDATED, or had its display list
1512 * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1513 * its display list. This flag, used only when hw accelerated, allows us to clear the
1514 * flag while retaining this information until it's needed (at getDisplayList() time and
1515 * in drawChild(), when we decide to draw a view's children's display lists into our own).
1516 *
1517 * {@hide}
1518 */
1519 boolean mRecreateDisplayList = false;
1520
1521 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 * The view's identifier.
1523 * {@hide}
1524 *
1525 * @see #setId(int)
1526 * @see #getId()
1527 */
1528 @ViewDebug.ExportedProperty(resolveId = true)
1529 int mID = NO_ID;
1530
1531 /**
1532 * The view's tag.
1533 * {@hide}
1534 *
1535 * @see #setTag(Object)
1536 * @see #getTag()
1537 */
1538 protected Object mTag;
1539
1540 // for mPrivateFlags:
1541 /** {@hide} */
1542 static final int WANTS_FOCUS = 0x00000001;
1543 /** {@hide} */
1544 static final int FOCUSED = 0x00000002;
1545 /** {@hide} */
1546 static final int SELECTED = 0x00000004;
1547 /** {@hide} */
1548 static final int IS_ROOT_NAMESPACE = 0x00000008;
1549 /** {@hide} */
1550 static final int HAS_BOUNDS = 0x00000010;
1551 /** {@hide} */
1552 static final int DRAWN = 0x00000020;
1553 /**
1554 * When this flag is set, this view is running an animation on behalf of its
1555 * children and should therefore not cancel invalidate requests, even if they
1556 * lie outside of this view's bounds.
1557 *
1558 * {@hide}
1559 */
1560 static final int DRAW_ANIMATION = 0x00000040;
1561 /** {@hide} */
1562 static final int SKIP_DRAW = 0x00000080;
1563 /** {@hide} */
1564 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1565 /** {@hide} */
1566 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1567 /** {@hide} */
1568 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1569 /** {@hide} */
1570 static final int MEASURED_DIMENSION_SET = 0x00000800;
1571 /** {@hide} */
1572 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001573 /** {@hide} */
1574 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575
1576 private static final int PRESSED = 0x00004000;
1577
1578 /** {@hide} */
1579 static final int DRAWING_CACHE_VALID = 0x00008000;
1580 /**
1581 * Flag used to indicate that this view should be drawn once more (and only once
1582 * more) after its animation has completed.
1583 * {@hide}
1584 */
1585 static final int ANIMATION_STARTED = 0x00010000;
1586
1587 private static final int SAVE_STATE_CALLED = 0x00020000;
1588
1589 /**
1590 * Indicates that the View returned true when onSetAlpha() was called and that
1591 * the alpha must be restored.
1592 * {@hide}
1593 */
1594 static final int ALPHA_SET = 0x00040000;
1595
1596 /**
1597 * Set by {@link #setScrollContainer(boolean)}.
1598 */
1599 static final int SCROLL_CONTAINER = 0x00080000;
1600
1601 /**
1602 * Set by {@link #setScrollContainer(boolean)}.
1603 */
1604 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1605
1606 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001607 * View flag indicating whether this view was invalidated (fully or partially.)
1608 *
1609 * @hide
1610 */
1611 static final int DIRTY = 0x00200000;
1612
1613 /**
1614 * View flag indicating whether this view was invalidated by an opaque
1615 * invalidate request.
1616 *
1617 * @hide
1618 */
1619 static final int DIRTY_OPAQUE = 0x00400000;
1620
1621 /**
1622 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1623 *
1624 * @hide
1625 */
1626 static final int DIRTY_MASK = 0x00600000;
1627
1628 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001629 * Indicates whether the background is opaque.
1630 *
1631 * @hide
1632 */
1633 static final int OPAQUE_BACKGROUND = 0x00800000;
1634
1635 /**
1636 * Indicates whether the scrollbars are opaque.
1637 *
1638 * @hide
1639 */
1640 static final int OPAQUE_SCROLLBARS = 0x01000000;
1641
1642 /**
1643 * Indicates whether the view is opaque.
1644 *
1645 * @hide
1646 */
1647 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001648
1649 /**
1650 * Indicates a prepressed state;
1651 * the short time between ACTION_DOWN and recognizing
1652 * a 'real' press. Prepressed is used to recognize quick taps
1653 * even when they are shorter than ViewConfiguration.getTapTimeout().
1654 *
1655 * @hide
1656 */
1657 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001658
1659 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001660 * Indicates whether the view is temporarily detached.
1661 *
1662 * @hide
1663 */
1664 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001665
1666 /**
1667 * Indicates that we should awaken scroll bars once attached
1668 *
1669 * @hide
1670 */
1671 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001672
1673 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001674 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1675 * for transform operations
1676 *
1677 * @hide
1678 */
Adam Powellf37df072010-09-17 16:22:49 -07001679 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001680
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001681 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001682 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001683
Chet Haasefd2b0022010-08-06 13:08:56 -07001684 /**
Chet Haasedaf98e92011-01-10 14:10:36 -08001685 * Indicates that this view was specifically invalidated, not just dirtied because some
1686 * child view was invalidated. The flag is used to determine when we need to recreate
1687 * a view's display list (as opposed to just returning a reference to its existing
1688 * display list).
1689 *
1690 * @hide
1691 */
1692 static final int INVALIDATED = 0x80000000;
1693
1694 /**
Adam Powell637d3372010-08-25 14:37:03 -07001695 * Always allow a user to over-scroll this view, provided it is a
1696 * view that can scroll.
1697 *
1698 * @see #getOverScrollMode()
1699 * @see #setOverScrollMode(int)
1700 */
1701 public static final int OVER_SCROLL_ALWAYS = 0;
1702
1703 /**
1704 * Allow a user to over-scroll this view only if the content is large
1705 * enough to meaningfully scroll, provided it is a view that can scroll.
1706 *
1707 * @see #getOverScrollMode()
1708 * @see #setOverScrollMode(int)
1709 */
1710 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1711
1712 /**
1713 * Never allow a user to over-scroll this view.
1714 *
1715 * @see #getOverScrollMode()
1716 * @see #setOverScrollMode(int)
1717 */
1718 public static final int OVER_SCROLL_NEVER = 2;
1719
1720 /**
Joe Onorato664644d2011-01-23 17:53:23 -08001721 * View has requested the status bar to be visible (the default).
1722 *
Romain Guy0fd89bf2011-01-26 15:41:30 -08001723 * @see #setSystemUiVisibility(int)
Joe Onorato664644d2011-01-23 17:53:23 -08001724 */
1725 public static final int STATUS_BAR_VISIBLE = 0;
1726
1727 /**
1728 * View has requested the status bar to be visible (the default).
1729 *
Romain Guy0fd89bf2011-01-26 15:41:30 -08001730 * @see #setSystemUiVisibility(int)
Joe Onorato664644d2011-01-23 17:53:23 -08001731 */
1732 public static final int STATUS_BAR_HIDDEN = 0x00000001;
1733
1734 /**
Adam Powell637d3372010-08-25 14:37:03 -07001735 * Controls the over-scroll mode for this view.
1736 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1737 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1738 * and {@link #OVER_SCROLL_NEVER}.
1739 */
1740 private int mOverScrollMode;
1741
1742 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 * The parent this view is attached to.
1744 * {@hide}
1745 *
1746 * @see #getParent()
1747 */
1748 protected ViewParent mParent;
1749
1750 /**
1751 * {@hide}
1752 */
1753 AttachInfo mAttachInfo;
1754
1755 /**
1756 * {@hide}
1757 */
Romain Guy809a7f62009-05-14 15:44:42 -07001758 @ViewDebug.ExportedProperty(flagMapping = {
1759 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1760 name = "FORCE_LAYOUT"),
1761 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1762 name = "LAYOUT_REQUIRED"),
1763 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001764 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001765 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1766 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1767 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1768 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1769 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 int mPrivateFlags;
1771
1772 /**
Joe Onorato664644d2011-01-23 17:53:23 -08001773 * This view's request for the visibility of the status bar.
1774 * @hide
1775 */
1776 int mSystemUiVisibility;
1777
1778 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 * Count of how many windows this view has been attached to.
1780 */
1781 int mWindowAttachCount;
1782
1783 /**
1784 * The layout parameters associated with this view and used by the parent
1785 * {@link android.view.ViewGroup} to determine how this view should be
1786 * laid out.
1787 * {@hide}
1788 */
1789 protected ViewGroup.LayoutParams mLayoutParams;
1790
1791 /**
1792 * The view flags hold various views states.
1793 * {@hide}
1794 */
1795 @ViewDebug.ExportedProperty
1796 int mViewFlags;
1797
1798 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001799 * The transform matrix for the View. This transform is calculated internally
1800 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1801 * is used by default. Do *not* use this variable directly; instead call
1802 * getMatrix(), which will automatically recalculate the matrix if necessary
1803 * to get the correct matrix based on the latest rotation and scale properties.
1804 */
1805 private final Matrix mMatrix = new Matrix();
1806
1807 /**
1808 * The transform matrix for the View. This transform is calculated internally
1809 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1810 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001811 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001812 * to get the correct matrix based on the latest rotation and scale properties.
1813 */
1814 private Matrix mInverseMatrix;
1815
1816 /**
1817 * An internal variable that tracks whether we need to recalculate the
1818 * transform matrix, based on whether the rotation or scaleX/Y properties
1819 * have changed since the matrix was last calculated.
1820 */
1821 private boolean mMatrixDirty = false;
1822
1823 /**
1824 * An internal variable that tracks whether we need to recalculate the
1825 * transform matrix, based on whether the rotation or scaleX/Y properties
1826 * have changed since the matrix was last calculated.
1827 */
1828 private boolean mInverseMatrixDirty = true;
1829
1830 /**
1831 * A variable that tracks whether we need to recalculate the
1832 * transform matrix, based on whether the rotation or scaleX/Y properties
1833 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001834 * is only valid after a call to updateMatrix() or to a function that
1835 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001836 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001837 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001838
1839 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001840 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1841 */
1842 private Camera mCamera = null;
1843
1844 /**
1845 * This matrix is used when computing the matrix for 3D rotations.
1846 */
1847 private Matrix matrix3D = null;
1848
1849 /**
1850 * These prev values are used to recalculate a centered pivot point when necessary. The
1851 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1852 * set), so thes values are only used then as well.
1853 */
1854 private int mPrevWidth = -1;
1855 private int mPrevHeight = -1;
1856
Romain Guyc5d55862011-01-21 19:01:46 -08001857 private boolean mLastIsOpaque;
1858
Chet Haasefd2b0022010-08-06 13:08:56 -07001859 /**
1860 * Convenience value to check for float values that are close enough to zero to be considered
1861 * zero.
1862 */
Romain Guy2542d192010-08-18 11:47:12 -07001863 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001864
1865 /**
1866 * The degrees rotation around the vertical axis through the pivot point.
1867 */
1868 @ViewDebug.ExportedProperty
1869 private float mRotationY = 0f;
1870
1871 /**
1872 * The degrees rotation around the horizontal axis through the pivot point.
1873 */
1874 @ViewDebug.ExportedProperty
1875 private float mRotationX = 0f;
1876
1877 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001878 * The degrees rotation around the pivot point.
1879 */
1880 @ViewDebug.ExportedProperty
1881 private float mRotation = 0f;
1882
1883 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001884 * The amount of translation of the object away from its left property (post-layout).
1885 */
1886 @ViewDebug.ExportedProperty
1887 private float mTranslationX = 0f;
1888
1889 /**
1890 * The amount of translation of the object away from its top property (post-layout).
1891 */
1892 @ViewDebug.ExportedProperty
1893 private float mTranslationY = 0f;
1894
1895 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001896 * The amount of scale in the x direction around the pivot point. A
1897 * value of 1 means no scaling is applied.
1898 */
1899 @ViewDebug.ExportedProperty
1900 private float mScaleX = 1f;
1901
1902 /**
1903 * The amount of scale in the y direction around the pivot point. A
1904 * value of 1 means no scaling is applied.
1905 */
1906 @ViewDebug.ExportedProperty
1907 private float mScaleY = 1f;
1908
1909 /**
1910 * The amount of scale in the x direction around the pivot point. A
1911 * value of 1 means no scaling is applied.
1912 */
1913 @ViewDebug.ExportedProperty
1914 private float mPivotX = 0f;
1915
1916 /**
1917 * The amount of scale in the y direction around the pivot point. A
1918 * value of 1 means no scaling is applied.
1919 */
1920 @ViewDebug.ExportedProperty
1921 private float mPivotY = 0f;
1922
1923 /**
1924 * The opacity of the View. This is a value from 0 to 1, where 0 means
1925 * completely transparent and 1 means completely opaque.
1926 */
1927 @ViewDebug.ExportedProperty
1928 private float mAlpha = 1f;
1929
1930 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 * The distance in pixels from the left edge of this view's parent
1932 * to the left edge of this view.
1933 * {@hide}
1934 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001935 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 protected int mLeft;
1937 /**
1938 * The distance in pixels from the left edge of this view's parent
1939 * to the right edge of this view.
1940 * {@hide}
1941 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001942 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 protected int mRight;
1944 /**
1945 * The distance in pixels from the top edge of this view's parent
1946 * to the top edge of this view.
1947 * {@hide}
1948 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001949 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 protected int mTop;
1951 /**
1952 * The distance in pixels from the top edge of this view's parent
1953 * to the bottom edge of this view.
1954 * {@hide}
1955 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001956 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 protected int mBottom;
1958
1959 /**
1960 * The offset, in pixels, by which the content of this view is scrolled
1961 * horizontally.
1962 * {@hide}
1963 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001964 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 protected int mScrollX;
1966 /**
1967 * The offset, in pixels, by which the content of this view is scrolled
1968 * vertically.
1969 * {@hide}
1970 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001971 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 protected int mScrollY;
1973
1974 /**
1975 * The left padding in pixels, that is the distance in pixels between the
1976 * left edge of this view and the left edge of its content.
1977 * {@hide}
1978 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001979 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 protected int mPaddingLeft;
1981 /**
1982 * The right padding in pixels, that is the distance in pixels between the
1983 * right edge of this view and the right edge of its content.
1984 * {@hide}
1985 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001986 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 protected int mPaddingRight;
1988 /**
1989 * The top padding in pixels, that is the distance in pixels between the
1990 * top edge of this view and the top edge of its content.
1991 * {@hide}
1992 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001993 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 protected int mPaddingTop;
1995 /**
1996 * The bottom padding in pixels, that is the distance in pixels between the
1997 * bottom edge of this view and the bottom edge of its content.
1998 * {@hide}
1999 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002000 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 protected int mPaddingBottom;
2002
2003 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002004 * Briefly describes the view and is primarily used for accessibility support.
2005 */
2006 private CharSequence mContentDescription;
2007
2008 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 * Cache the paddingRight set by the user to append to the scrollbar's size.
2010 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002011 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 int mUserPaddingRight;
2013
2014 /**
2015 * Cache the paddingBottom set by the user to append to the scrollbar's size.
2016 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002017 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 int mUserPaddingBottom;
2019
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002020 /**
Adam Powell20232d02010-12-08 21:08:53 -08002021 * Cache the paddingLeft set by the user to append to the scrollbar's size.
2022 */
2023 @ViewDebug.ExportedProperty(category = "padding")
2024 int mUserPaddingLeft;
2025
2026 /**
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002027 * @hide
2028 */
2029 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2030 /**
2031 * @hide
2032 */
2033 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034
2035 private Resources mResources = null;
2036
2037 private Drawable mBGDrawable;
2038
2039 private int mBackgroundResource;
2040 private boolean mBackgroundSizeChanged;
2041
2042 /**
2043 * Listener used to dispatch focus change events.
2044 * This field should be made private, so it is hidden from the SDK.
2045 * {@hide}
2046 */
2047 protected OnFocusChangeListener mOnFocusChangeListener;
2048
2049 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002050 * Listeners for layout change events.
2051 */
2052 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2053
2054 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 * Listener used to dispatch click events.
2056 * This field should be made private, so it is hidden from the SDK.
2057 * {@hide}
2058 */
2059 protected OnClickListener mOnClickListener;
2060
2061 /**
2062 * Listener used to dispatch long click events.
2063 * This field should be made private, so it is hidden from the SDK.
2064 * {@hide}
2065 */
2066 protected OnLongClickListener mOnLongClickListener;
2067
2068 /**
2069 * Listener used to build the context menu.
2070 * This field should be made private, so it is hidden from the SDK.
2071 * {@hide}
2072 */
2073 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2074
2075 private OnKeyListener mOnKeyListener;
2076
2077 private OnTouchListener mOnTouchListener;
2078
Chris Tate32affef2010-10-18 15:29:21 -07002079 private OnDragListener mOnDragListener;
2080
Joe Onorato664644d2011-01-23 17:53:23 -08002081 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 /**
2084 * The application environment this view lives in.
2085 * This field should be made private, so it is hidden from the SDK.
2086 * {@hide}
2087 */
2088 protected Context mContext;
2089
2090 private ScrollabilityCache mScrollCache;
2091
2092 private int[] mDrawableState = null;
2093
Romain Guy02890fd2010-08-06 17:58:44 -07002094 private Bitmap mDrawingCache;
2095 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07002096 private DisplayList mDisplayList;
Romain Guy6c319ca2011-01-11 14:29:25 -08002097 private HardwareLayer mHardwareLayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098
2099 /**
2100 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2101 * the user may specify which view to go to next.
2102 */
2103 private int mNextFocusLeftId = View.NO_ID;
2104
2105 /**
2106 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2107 * the user may specify which view to go to next.
2108 */
2109 private int mNextFocusRightId = View.NO_ID;
2110
2111 /**
2112 * When this view has focus and the next focus is {@link #FOCUS_UP},
2113 * the user may specify which view to go to next.
2114 */
2115 private int mNextFocusUpId = View.NO_ID;
2116
2117 /**
2118 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2119 * the user may specify which view to go to next.
2120 */
2121 private int mNextFocusDownId = View.NO_ID;
2122
Jeff Brown4e6319b2010-12-13 10:36:51 -08002123 /**
2124 * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2125 * the user may specify which view to go to next.
2126 */
2127 int mNextFocusForwardId = View.NO_ID;
2128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08002130 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08002131 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08002132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 private UnsetPressedState mUnsetPressedState;
2134
2135 /**
2136 * Whether the long press's action has been invoked. The tap's action is invoked on the
2137 * up event while a long press is invoked as soon as the long press duration is reached, so
2138 * a long press could be performed before the tap is checked, in which case the tap's action
2139 * should not be invoked.
2140 */
2141 private boolean mHasPerformedLongPress;
2142
2143 /**
2144 * The minimum height of the view. We'll try our best to have the height
2145 * of this view to at least this amount.
2146 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002147 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 private int mMinHeight;
2149
2150 /**
2151 * The minimum width of the view. We'll try our best to have the width
2152 * of this view to at least this amount.
2153 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002154 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 private int mMinWidth;
2156
2157 /**
2158 * The delegate to handle touch events that are physically in this view
2159 * but should be handled by another view.
2160 */
2161 private TouchDelegate mTouchDelegate = null;
2162
2163 /**
2164 * Solid color to use as a background when creating the drawing cache. Enables
2165 * the cache to use 16 bit bitmaps instead of 32 bit.
2166 */
2167 private int mDrawingCacheBackgroundColor = 0;
2168
2169 /**
2170 * Special tree observer used when mAttachInfo is null.
2171 */
2172 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002173
2174 /**
2175 * Cache the touch slop from the context that created the view.
2176 */
2177 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002180 * Cache drag/drop state
2181 *
2182 */
2183 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002184
2185 /**
Christopher Tate251602f2011-01-28 17:54:12 -08002186 * Flag indicating that a drag can cross window boundaries. When
2187 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2188 * with this flag set, all visible applications will be able to participate
2189 * in the drag operation and receive the dragged content.
Christopher Tate02d2b3b2011-01-10 20:43:53 -08002190 */
2191 public static final int DRAG_FLAG_GLOBAL = 1;
2192
2193 /**
Adam Powell20232d02010-12-08 21:08:53 -08002194 * Position of the vertical scroll bar.
2195 */
2196 private int mVerticalScrollbarPosition;
2197
2198 /**
2199 * Position the scroll bar at the default position as determined by the system.
2200 */
2201 public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2202
2203 /**
2204 * Position the scroll bar along the left edge.
2205 */
2206 public static final int SCROLLBAR_POSITION_LEFT = 1;
2207
2208 /**
2209 * Position the scroll bar along the right edge.
2210 */
2211 public static final int SCROLLBAR_POSITION_RIGHT = 2;
2212
2213 /**
Romain Guy171c5922011-01-06 10:04:23 -08002214 * Indicates that the view does not have a layer.
2215 *
2216 * @see #getLayerType()
2217 * @see #setLayerType(int, android.graphics.Paint)
2218 * @see #LAYER_TYPE_SOFTWARE
2219 * @see #LAYER_TYPE_HARDWARE
2220 */
2221 public static final int LAYER_TYPE_NONE = 0;
2222
2223 /**
2224 * <p>Indicates that the view has a software layer. A software layer is backed
2225 * by a bitmap and causes the view to be rendered using Android's software
2226 * rendering pipeline, even if hardware acceleration is enabled.</p>
2227 *
2228 * <p>Software layers have various usages:</p>
2229 * <p>When the application is not using hardware acceleration, a software layer
2230 * is useful to apply a specific color filter and/or blending mode and/or
2231 * translucency to a view and all its children.</p>
2232 * <p>When the application is using hardware acceleration, a software layer
2233 * is useful to render drawing primitives not supported by the hardware
2234 * accelerated pipeline. It can also be used to cache a complex view tree
2235 * into a texture and reduce the complexity of drawing operations. For instance,
2236 * when animating a complex view tree with a translation, a software layer can
2237 * be used to render the view tree only once.</p>
2238 * <p>Software layers should be avoided when the affected view tree updates
2239 * often. Every update will require to re-render the software layer, which can
2240 * potentially be slow (particularly when hardware acceleration is turned on
2241 * since the layer will have to be uploaded into a hardware texture after every
2242 * update.)</p>
2243 *
2244 * @see #getLayerType()
2245 * @see #setLayerType(int, android.graphics.Paint)
2246 * @see #LAYER_TYPE_NONE
2247 * @see #LAYER_TYPE_HARDWARE
2248 */
2249 public static final int LAYER_TYPE_SOFTWARE = 1;
2250
2251 /**
2252 * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2253 * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2254 * OpenGL hardware) and causes the view to be rendered using Android's hardware
2255 * rendering pipeline, but only if hardware acceleration is turned on for the
2256 * view hierarchy. When hardware acceleration is turned off, hardware layers
2257 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2258 *
2259 * <p>A hardware layer is useful to apply a specific color filter and/or
2260 * blending mode and/or translucency to a view and all its children.</p>
Romain Guy6c319ca2011-01-11 14:29:25 -08002261 * <p>A hardware layer can be used to cache a complex view tree into a
2262 * texture and reduce the complexity of drawing operations. For instance,
2263 * when animating a complex view tree with a translation, a hardware layer can
2264 * be used to render the view tree only once.</p>
Romain Guy171c5922011-01-06 10:04:23 -08002265 * <p>A hardware layer can also be used to increase the rendering quality when
2266 * rotation transformations are applied on a view. It can also be used to
2267 * prevent potential clipping issues when applying 3D transforms on a view.</p>
2268 *
2269 * @see #getLayerType()
2270 * @see #setLayerType(int, android.graphics.Paint)
2271 * @see #LAYER_TYPE_NONE
2272 * @see #LAYER_TYPE_SOFTWARE
2273 */
2274 public static final int LAYER_TYPE_HARDWARE = 2;
2275
Romain Guy3aaff3a2011-01-12 14:18:47 -08002276 @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2277 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2278 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2279 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2280 })
Romain Guy171c5922011-01-06 10:04:23 -08002281 int mLayerType = LAYER_TYPE_NONE;
2282 Paint mLayerPaint;
2283
2284 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 * Simple constructor to use when creating a view from code.
2286 *
2287 * @param context The Context the view is running in, through which it can
2288 * access the current theme, resources, etc.
2289 */
2290 public View(Context context) {
2291 mContext = context;
2292 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002293 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002294 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Adam Powell637d3372010-08-25 14:37:03 -07002295 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 }
2297
2298 /**
2299 * Constructor that is called when inflating a view from XML. This is called
2300 * when a view is being constructed from an XML file, supplying attributes
2301 * that were specified in the XML file. This version uses a default style of
2302 * 0, so the only attribute values applied are those in the Context's Theme
2303 * and the given AttributeSet.
2304 *
2305 * <p>
2306 * The method onFinishInflate() will be called after all children have been
2307 * added.
2308 *
2309 * @param context The Context the view is running in, through which it can
2310 * access the current theme, resources, etc.
2311 * @param attrs The attributes of the XML tag that is inflating the view.
2312 * @see #View(Context, AttributeSet, int)
2313 */
2314 public View(Context context, AttributeSet attrs) {
2315 this(context, attrs, 0);
2316 }
2317
2318 /**
2319 * Perform inflation from XML and apply a class-specific base style. This
2320 * constructor of View allows subclasses to use their own base style when
2321 * they are inflating. For example, a Button class's constructor would call
2322 * this version of the super class constructor and supply
2323 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2324 * the theme's button style to modify all of the base view attributes (in
2325 * particular its background) as well as the Button class's attributes.
2326 *
2327 * @param context The Context the view is running in, through which it can
2328 * access the current theme, resources, etc.
2329 * @param attrs The attributes of the XML tag that is inflating the view.
2330 * @param defStyle The default style to apply to this view. If 0, no style
2331 * will be applied (beyond what is included in the theme). This may
2332 * either be an attribute resource, whose value will be retrieved
2333 * from the current theme, or an explicit style resource.
2334 * @see #View(Context, AttributeSet)
2335 */
2336 public View(Context context, AttributeSet attrs, int defStyle) {
2337 this(context);
2338
2339 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2340 defStyle, 0);
2341
2342 Drawable background = null;
2343
2344 int leftPadding = -1;
2345 int topPadding = -1;
2346 int rightPadding = -1;
2347 int bottomPadding = -1;
2348
2349 int padding = -1;
2350
2351 int viewFlagValues = 0;
2352 int viewFlagMasks = 0;
2353
2354 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 int x = 0;
2357 int y = 0;
2358
Chet Haase73066682010-11-29 15:55:32 -08002359 float tx = 0;
2360 float ty = 0;
2361 float rotation = 0;
2362 float rotationX = 0;
2363 float rotationY = 0;
2364 float sx = 1f;
2365 float sy = 1f;
2366 boolean transformSet = false;
2367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2369
Adam Powell637d3372010-08-25 14:37:03 -07002370 int overScrollMode = mOverScrollMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 final int N = a.getIndexCount();
2372 for (int i = 0; i < N; i++) {
2373 int attr = a.getIndex(i);
2374 switch (attr) {
2375 case com.android.internal.R.styleable.View_background:
2376 background = a.getDrawable(attr);
2377 break;
2378 case com.android.internal.R.styleable.View_padding:
2379 padding = a.getDimensionPixelSize(attr, -1);
2380 break;
2381 case com.android.internal.R.styleable.View_paddingLeft:
2382 leftPadding = a.getDimensionPixelSize(attr, -1);
2383 break;
2384 case com.android.internal.R.styleable.View_paddingTop:
2385 topPadding = a.getDimensionPixelSize(attr, -1);
2386 break;
2387 case com.android.internal.R.styleable.View_paddingRight:
2388 rightPadding = a.getDimensionPixelSize(attr, -1);
2389 break;
2390 case com.android.internal.R.styleable.View_paddingBottom:
2391 bottomPadding = a.getDimensionPixelSize(attr, -1);
2392 break;
2393 case com.android.internal.R.styleable.View_scrollX:
2394 x = a.getDimensionPixelOffset(attr, 0);
2395 break;
2396 case com.android.internal.R.styleable.View_scrollY:
2397 y = a.getDimensionPixelOffset(attr, 0);
2398 break;
Chet Haase73066682010-11-29 15:55:32 -08002399 case com.android.internal.R.styleable.View_alpha:
2400 setAlpha(a.getFloat(attr, 1f));
2401 break;
2402 case com.android.internal.R.styleable.View_transformPivotX:
2403 setPivotX(a.getDimensionPixelOffset(attr, 0));
2404 break;
2405 case com.android.internal.R.styleable.View_transformPivotY:
2406 setPivotY(a.getDimensionPixelOffset(attr, 0));
2407 break;
2408 case com.android.internal.R.styleable.View_translationX:
2409 tx = a.getDimensionPixelOffset(attr, 0);
2410 transformSet = true;
2411 break;
2412 case com.android.internal.R.styleable.View_translationY:
2413 ty = a.getDimensionPixelOffset(attr, 0);
2414 transformSet = true;
2415 break;
2416 case com.android.internal.R.styleable.View_rotation:
2417 rotation = a.getFloat(attr, 0);
2418 transformSet = true;
2419 break;
2420 case com.android.internal.R.styleable.View_rotationX:
2421 rotationX = a.getFloat(attr, 0);
2422 transformSet = true;
2423 break;
2424 case com.android.internal.R.styleable.View_rotationY:
2425 rotationY = a.getFloat(attr, 0);
2426 transformSet = true;
2427 break;
2428 case com.android.internal.R.styleable.View_scaleX:
2429 sx = a.getFloat(attr, 1f);
2430 transformSet = true;
2431 break;
2432 case com.android.internal.R.styleable.View_scaleY:
2433 sy = a.getFloat(attr, 1f);
2434 transformSet = true;
2435 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 case com.android.internal.R.styleable.View_id:
2437 mID = a.getResourceId(attr, NO_ID);
2438 break;
2439 case com.android.internal.R.styleable.View_tag:
2440 mTag = a.getText(attr);
2441 break;
2442 case com.android.internal.R.styleable.View_fitsSystemWindows:
2443 if (a.getBoolean(attr, false)) {
2444 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2445 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2446 }
2447 break;
2448 case com.android.internal.R.styleable.View_focusable:
2449 if (a.getBoolean(attr, false)) {
2450 viewFlagValues |= FOCUSABLE;
2451 viewFlagMasks |= FOCUSABLE_MASK;
2452 }
2453 break;
2454 case com.android.internal.R.styleable.View_focusableInTouchMode:
2455 if (a.getBoolean(attr, false)) {
2456 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2457 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2458 }
2459 break;
2460 case com.android.internal.R.styleable.View_clickable:
2461 if (a.getBoolean(attr, false)) {
2462 viewFlagValues |= CLICKABLE;
2463 viewFlagMasks |= CLICKABLE;
2464 }
2465 break;
2466 case com.android.internal.R.styleable.View_longClickable:
2467 if (a.getBoolean(attr, false)) {
2468 viewFlagValues |= LONG_CLICKABLE;
2469 viewFlagMasks |= LONG_CLICKABLE;
2470 }
2471 break;
2472 case com.android.internal.R.styleable.View_saveEnabled:
2473 if (!a.getBoolean(attr, true)) {
2474 viewFlagValues |= SAVE_DISABLED;
2475 viewFlagMasks |= SAVE_DISABLED_MASK;
2476 }
2477 break;
2478 case com.android.internal.R.styleable.View_duplicateParentState:
2479 if (a.getBoolean(attr, false)) {
2480 viewFlagValues |= DUPLICATE_PARENT_STATE;
2481 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2482 }
2483 break;
2484 case com.android.internal.R.styleable.View_visibility:
2485 final int visibility = a.getInt(attr, 0);
2486 if (visibility != 0) {
2487 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2488 viewFlagMasks |= VISIBILITY_MASK;
2489 }
2490 break;
2491 case com.android.internal.R.styleable.View_drawingCacheQuality:
2492 final int cacheQuality = a.getInt(attr, 0);
2493 if (cacheQuality != 0) {
2494 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2495 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2496 }
2497 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002498 case com.android.internal.R.styleable.View_contentDescription:
2499 mContentDescription = a.getString(attr);
2500 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2502 if (!a.getBoolean(attr, true)) {
2503 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2504 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2505 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002506 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2508 if (!a.getBoolean(attr, true)) {
2509 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2510 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2511 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002512 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 case R.styleable.View_scrollbars:
2514 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2515 if (scrollbars != SCROLLBARS_NONE) {
2516 viewFlagValues |= scrollbars;
2517 viewFlagMasks |= SCROLLBARS_MASK;
2518 initializeScrollbars(a);
2519 }
2520 break;
2521 case R.styleable.View_fadingEdge:
2522 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2523 if (fadingEdge != FADING_EDGE_NONE) {
2524 viewFlagValues |= fadingEdge;
2525 viewFlagMasks |= FADING_EDGE_MASK;
2526 initializeFadingEdge(a);
2527 }
2528 break;
2529 case R.styleable.View_scrollbarStyle:
2530 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2531 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2532 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2533 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2534 }
2535 break;
2536 case R.styleable.View_isScrollContainer:
2537 setScrollContainer = true;
2538 if (a.getBoolean(attr, false)) {
2539 setScrollContainer(true);
2540 }
2541 break;
2542 case com.android.internal.R.styleable.View_keepScreenOn:
2543 if (a.getBoolean(attr, false)) {
2544 viewFlagValues |= KEEP_SCREEN_ON;
2545 viewFlagMasks |= KEEP_SCREEN_ON;
2546 }
2547 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002548 case R.styleable.View_filterTouchesWhenObscured:
2549 if (a.getBoolean(attr, false)) {
2550 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2551 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2552 }
2553 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 case R.styleable.View_nextFocusLeft:
2555 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2556 break;
2557 case R.styleable.View_nextFocusRight:
2558 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2559 break;
2560 case R.styleable.View_nextFocusUp:
2561 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2562 break;
2563 case R.styleable.View_nextFocusDown:
2564 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2565 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002566 case R.styleable.View_nextFocusForward:
2567 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2568 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 case R.styleable.View_minWidth:
2570 mMinWidth = a.getDimensionPixelSize(attr, 0);
2571 break;
2572 case R.styleable.View_minHeight:
2573 mMinHeight = a.getDimensionPixelSize(attr, 0);
2574 break;
Romain Guy9a817362009-05-01 10:57:14 -07002575 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002576 if (context.isRestricted()) {
2577 throw new IllegalStateException("The android:onClick attribute cannot "
2578 + "be used within a restricted context");
2579 }
2580
Romain Guy9a817362009-05-01 10:57:14 -07002581 final String handlerName = a.getString(attr);
2582 if (handlerName != null) {
2583 setOnClickListener(new OnClickListener() {
2584 private Method mHandler;
2585
2586 public void onClick(View v) {
2587 if (mHandler == null) {
2588 try {
2589 mHandler = getContext().getClass().getMethod(handlerName,
2590 View.class);
2591 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002592 int id = getId();
2593 String idText = id == NO_ID ? "" : " with id '"
2594 + getContext().getResources().getResourceEntryName(
2595 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002596 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002597 handlerName + "(View) in the activity "
2598 + getContext().getClass() + " for onClick handler"
2599 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002600 }
2601 }
2602
2603 try {
2604 mHandler.invoke(getContext(), View.this);
2605 } catch (IllegalAccessException e) {
2606 throw new IllegalStateException("Could not execute non "
2607 + "public method of the activity", e);
2608 } catch (InvocationTargetException e) {
2609 throw new IllegalStateException("Could not execute "
2610 + "method of the activity", e);
2611 }
2612 }
2613 });
2614 }
2615 break;
Adam Powell637d3372010-08-25 14:37:03 -07002616 case R.styleable.View_overScrollMode:
2617 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2618 break;
Adam Powell20232d02010-12-08 21:08:53 -08002619 case R.styleable.View_verticalScrollbarPosition:
2620 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2621 break;
Romain Guy171c5922011-01-06 10:04:23 -08002622 case R.styleable.View_layerType:
2623 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
2624 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 }
2626 }
2627
Adam Powell637d3372010-08-25 14:37:03 -07002628 setOverScrollMode(overScrollMode);
2629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 if (background != null) {
2631 setBackgroundDrawable(background);
2632 }
2633
2634 if (padding >= 0) {
2635 leftPadding = padding;
2636 topPadding = padding;
2637 rightPadding = padding;
2638 bottomPadding = padding;
2639 }
2640
2641 // If the user specified the padding (either with android:padding or
2642 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2643 // use the default padding or the padding from the background drawable
2644 // (stored at this point in mPadding*)
2645 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2646 topPadding >= 0 ? topPadding : mPaddingTop,
2647 rightPadding >= 0 ? rightPadding : mPaddingRight,
2648 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2649
2650 if (viewFlagMasks != 0) {
2651 setFlags(viewFlagValues, viewFlagMasks);
2652 }
2653
2654 // Needs to be called after mViewFlags is set
2655 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2656 recomputePadding();
2657 }
2658
2659 if (x != 0 || y != 0) {
2660 scrollTo(x, y);
2661 }
2662
Chet Haase73066682010-11-29 15:55:32 -08002663 if (transformSet) {
2664 setTranslationX(tx);
2665 setTranslationY(ty);
2666 setRotation(rotation);
2667 setRotationX(rotationX);
2668 setRotationY(rotationY);
2669 setScaleX(sx);
2670 setScaleY(sy);
2671 }
2672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2674 setScrollContainer(true);
2675 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002676
2677 computeOpaqueFlags();
2678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 a.recycle();
2680 }
2681
2682 /**
2683 * Non-public constructor for use in testing
2684 */
2685 View() {
2686 }
2687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 /**
2689 * <p>
2690 * Initializes the fading edges from a given set of styled attributes. This
2691 * method should be called by subclasses that need fading edges and when an
2692 * instance of these subclasses is created programmatically rather than
2693 * being inflated from XML. This method is automatically called when the XML
2694 * is inflated.
2695 * </p>
2696 *
2697 * @param a the styled attributes set to initialize the fading edges from
2698 */
2699 protected void initializeFadingEdge(TypedArray a) {
2700 initScrollCache();
2701
2702 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2703 R.styleable.View_fadingEdgeLength,
2704 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2705 }
2706
2707 /**
2708 * Returns the size of the vertical faded edges used to indicate that more
2709 * content in this view is visible.
2710 *
2711 * @return The size in pixels of the vertical faded edge or 0 if vertical
2712 * faded edges are not enabled for this view.
2713 * @attr ref android.R.styleable#View_fadingEdgeLength
2714 */
2715 public int getVerticalFadingEdgeLength() {
2716 if (isVerticalFadingEdgeEnabled()) {
2717 ScrollabilityCache cache = mScrollCache;
2718 if (cache != null) {
2719 return cache.fadingEdgeLength;
2720 }
2721 }
2722 return 0;
2723 }
2724
2725 /**
2726 * Set the size of the faded edge used to indicate that more content in this
2727 * view is available. Will not change whether the fading edge is enabled; use
2728 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2729 * to enable the fading edge for the vertical or horizontal fading edges.
2730 *
2731 * @param length The size in pixels of the faded edge used to indicate that more
2732 * content in this view is visible.
2733 */
2734 public void setFadingEdgeLength(int length) {
2735 initScrollCache();
2736 mScrollCache.fadingEdgeLength = length;
2737 }
2738
2739 /**
2740 * Returns the size of the horizontal faded edges used to indicate that more
2741 * content in this view is visible.
2742 *
2743 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2744 * faded edges are not enabled for this view.
2745 * @attr ref android.R.styleable#View_fadingEdgeLength
2746 */
2747 public int getHorizontalFadingEdgeLength() {
2748 if (isHorizontalFadingEdgeEnabled()) {
2749 ScrollabilityCache cache = mScrollCache;
2750 if (cache != null) {
2751 return cache.fadingEdgeLength;
2752 }
2753 }
2754 return 0;
2755 }
2756
2757 /**
2758 * Returns the width of the vertical scrollbar.
2759 *
2760 * @return The width in pixels of the vertical scrollbar or 0 if there
2761 * is no vertical scrollbar.
2762 */
2763 public int getVerticalScrollbarWidth() {
2764 ScrollabilityCache cache = mScrollCache;
2765 if (cache != null) {
2766 ScrollBarDrawable scrollBar = cache.scrollBar;
2767 if (scrollBar != null) {
2768 int size = scrollBar.getSize(true);
2769 if (size <= 0) {
2770 size = cache.scrollBarSize;
2771 }
2772 return size;
2773 }
2774 return 0;
2775 }
2776 return 0;
2777 }
2778
2779 /**
2780 * Returns the height of the horizontal scrollbar.
2781 *
2782 * @return The height in pixels of the horizontal scrollbar or 0 if
2783 * there is no horizontal scrollbar.
2784 */
2785 protected int getHorizontalScrollbarHeight() {
2786 ScrollabilityCache cache = mScrollCache;
2787 if (cache != null) {
2788 ScrollBarDrawable scrollBar = cache.scrollBar;
2789 if (scrollBar != null) {
2790 int size = scrollBar.getSize(false);
2791 if (size <= 0) {
2792 size = cache.scrollBarSize;
2793 }
2794 return size;
2795 }
2796 return 0;
2797 }
2798 return 0;
2799 }
2800
2801 /**
2802 * <p>
2803 * Initializes the scrollbars from a given set of styled attributes. This
2804 * method should be called by subclasses that need scrollbars and when an
2805 * instance of these subclasses is created programmatically rather than
2806 * being inflated from XML. This method is automatically called when the XML
2807 * is inflated.
2808 * </p>
2809 *
2810 * @param a the styled attributes set to initialize the scrollbars from
2811 */
2812 protected void initializeScrollbars(TypedArray a) {
2813 initScrollCache();
2814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002816
2817 if (scrollabilityCache.scrollBar == null) {
2818 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2819 }
2820
Romain Guy8bda2482010-03-02 11:42:11 -08002821 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822
Mike Cleronf116bf82009-09-27 19:14:12 -07002823 if (!fadeScrollbars) {
2824 scrollabilityCache.state = ScrollabilityCache.ON;
2825 }
2826 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2827
2828
2829 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2830 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2831 .getScrollBarFadeDuration());
2832 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2833 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2834 ViewConfiguration.getScrollDefaultDelay());
2835
2836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2838 com.android.internal.R.styleable.View_scrollbarSize,
2839 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2840
2841 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2842 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2843
2844 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2845 if (thumb != null) {
2846 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2847 }
2848
2849 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2850 false);
2851 if (alwaysDraw) {
2852 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2853 }
2854
2855 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2856 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2857
2858 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2859 if (thumb != null) {
2860 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2861 }
2862
2863 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2864 false);
2865 if (alwaysDraw) {
2866 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2867 }
2868
2869 // Re-apply user/background padding so that scrollbar(s) get added
2870 recomputePadding();
2871 }
2872
2873 /**
2874 * <p>
2875 * Initalizes the scrollability cache if necessary.
2876 * </p>
2877 */
2878 private void initScrollCache() {
2879 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002880 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 }
2882 }
2883
2884 /**
Adam Powell20232d02010-12-08 21:08:53 -08002885 * Set the position of the vertical scroll bar. Should be one of
2886 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
2887 * {@link #SCROLLBAR_POSITION_RIGHT}.
2888 *
2889 * @param position Where the vertical scroll bar should be positioned.
2890 */
2891 public void setVerticalScrollbarPosition(int position) {
2892 if (mVerticalScrollbarPosition != position) {
2893 mVerticalScrollbarPosition = position;
2894 computeOpaqueFlags();
2895 recomputePadding();
2896 }
2897 }
2898
2899 /**
2900 * @return The position where the vertical scroll bar will show, if applicable.
2901 * @see #setVerticalScrollbarPosition(int)
2902 */
2903 public int getVerticalScrollbarPosition() {
2904 return mVerticalScrollbarPosition;
2905 }
2906
2907 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 * Register a callback to be invoked when focus of this view changed.
2909 *
2910 * @param l The callback that will run.
2911 */
2912 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2913 mOnFocusChangeListener = l;
2914 }
2915
2916 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002917 * Add a listener that will be called when the bounds of the view change due to
2918 * layout processing.
2919 *
2920 * @param listener The listener that will be called when layout bounds change.
2921 */
2922 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2923 if (mOnLayoutChangeListeners == null) {
2924 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2925 }
2926 mOnLayoutChangeListeners.add(listener);
2927 }
2928
2929 /**
2930 * Remove a listener for layout changes.
2931 *
2932 * @param listener The listener for layout bounds change.
2933 */
2934 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2935 if (mOnLayoutChangeListeners == null) {
2936 return;
2937 }
2938 mOnLayoutChangeListeners.remove(listener);
2939 }
2940
2941 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 * Returns the focus-change callback registered for this view.
2943 *
2944 * @return The callback, or null if one is not registered.
2945 */
2946 public OnFocusChangeListener getOnFocusChangeListener() {
2947 return mOnFocusChangeListener;
2948 }
2949
2950 /**
2951 * Register a callback to be invoked when this view is clicked. If this view is not
2952 * clickable, it becomes clickable.
2953 *
2954 * @param l The callback that will run
2955 *
2956 * @see #setClickable(boolean)
2957 */
2958 public void setOnClickListener(OnClickListener l) {
2959 if (!isClickable()) {
2960 setClickable(true);
2961 }
2962 mOnClickListener = l;
2963 }
2964
2965 /**
2966 * Register a callback to be invoked when this view is clicked and held. If this view is not
2967 * long clickable, it becomes long clickable.
2968 *
2969 * @param l The callback that will run
2970 *
2971 * @see #setLongClickable(boolean)
2972 */
2973 public void setOnLongClickListener(OnLongClickListener l) {
2974 if (!isLongClickable()) {
2975 setLongClickable(true);
2976 }
2977 mOnLongClickListener = l;
2978 }
2979
2980 /**
2981 * Register a callback to be invoked when the context menu for this view is
2982 * being built. If this view is not long clickable, it becomes long clickable.
2983 *
2984 * @param l The callback that will run
2985 *
2986 */
2987 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2988 if (!isLongClickable()) {
2989 setLongClickable(true);
2990 }
2991 mOnCreateContextMenuListener = l;
2992 }
2993
2994 /**
2995 * Call this view's OnClickListener, if it is defined.
2996 *
2997 * @return True there was an assigned OnClickListener that was called, false
2998 * otherwise is returned.
2999 */
3000 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07003001 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 if (mOnClickListener != null) {
3004 playSoundEffect(SoundEffectConstants.CLICK);
3005 mOnClickListener.onClick(this);
3006 return true;
3007 }
3008
3009 return false;
3010 }
3011
3012 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07003013 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3014 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07003016 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 */
3018 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07003019 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 boolean handled = false;
3022 if (mOnLongClickListener != null) {
3023 handled = mOnLongClickListener.onLongClick(View.this);
3024 }
3025 if (!handled) {
3026 handled = showContextMenu();
3027 }
3028 if (handled) {
3029 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3030 }
3031 return handled;
3032 }
3033
3034 /**
3035 * Bring up the context menu for this view.
3036 *
3037 * @return Whether a context menu was displayed.
3038 */
3039 public boolean showContextMenu() {
3040 return getParent().showContextMenuForChild(this);
3041 }
3042
3043 /**
Adam Powell6e346362010-07-23 10:18:23 -07003044 * Start an action mode.
3045 *
3046 * @param callback Callback that will control the lifecycle of the action mode
3047 * @return The new action mode if it is started, null otherwise
3048 *
3049 * @see ActionMode
3050 */
3051 public ActionMode startActionMode(ActionMode.Callback callback) {
3052 return getParent().startActionModeForChild(this, callback);
3053 }
3054
3055 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 * Register a callback to be invoked when a key is pressed in this view.
3057 * @param l the key listener to attach to this view
3058 */
3059 public void setOnKeyListener(OnKeyListener l) {
3060 mOnKeyListener = l;
3061 }
3062
3063 /**
3064 * Register a callback to be invoked when a touch event is sent to this view.
3065 * @param l the touch listener to attach to this view
3066 */
3067 public void setOnTouchListener(OnTouchListener l) {
3068 mOnTouchListener = l;
3069 }
3070
3071 /**
Chris Tate32affef2010-10-18 15:29:21 -07003072 * Register a callback to be invoked when a drag event is sent to this view.
3073 * @param l The drag listener to attach to this view
3074 */
3075 public void setOnDragListener(OnDragListener l) {
3076 mOnDragListener = l;
3077 }
3078
3079 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
3081 *
3082 * Note: this does not check whether this {@link View} should get focus, it just
3083 * gives it focus no matter what. It should only be called internally by framework
3084 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3085 *
3086 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
3087 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
3088 * focus moved when requestFocus() is called. It may not always
3089 * apply, in which case use the default View.FOCUS_DOWN.
3090 * @param previouslyFocusedRect The rectangle of the view that had focus
3091 * prior in this View's coordinate system.
3092 */
3093 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3094 if (DBG) {
3095 System.out.println(this + " requestFocus()");
3096 }
3097
3098 if ((mPrivateFlags & FOCUSED) == 0) {
3099 mPrivateFlags |= FOCUSED;
3100
3101 if (mParent != null) {
3102 mParent.requestChildFocus(this, this);
3103 }
3104
3105 onFocusChanged(true, direction, previouslyFocusedRect);
3106 refreshDrawableState();
3107 }
3108 }
3109
3110 /**
3111 * Request that a rectangle of this view be visible on the screen,
3112 * scrolling if necessary just enough.
3113 *
3114 * <p>A View should call this if it maintains some notion of which part
3115 * of its content is interesting. For example, a text editing view
3116 * should call this when its cursor moves.
3117 *
3118 * @param rectangle The rectangle.
3119 * @return Whether any parent scrolled.
3120 */
3121 public boolean requestRectangleOnScreen(Rect rectangle) {
3122 return requestRectangleOnScreen(rectangle, false);
3123 }
3124
3125 /**
3126 * Request that a rectangle of this view be visible on the screen,
3127 * scrolling if necessary just enough.
3128 *
3129 * <p>A View should call this if it maintains some notion of which part
3130 * of its content is interesting. For example, a text editing view
3131 * should call this when its cursor moves.
3132 *
3133 * <p>When <code>immediate</code> is set to true, scrolling will not be
3134 * animated.
3135 *
3136 * @param rectangle The rectangle.
3137 * @param immediate True to forbid animated scrolling, false otherwise
3138 * @return Whether any parent scrolled.
3139 */
3140 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3141 View child = this;
3142 ViewParent parent = mParent;
3143 boolean scrolled = false;
3144 while (parent != null) {
3145 scrolled |= parent.requestChildRectangleOnScreen(child,
3146 rectangle, immediate);
3147
3148 // offset rect so next call has the rectangle in the
3149 // coordinate system of its direct child.
3150 rectangle.offset(child.getLeft(), child.getTop());
3151 rectangle.offset(-child.getScrollX(), -child.getScrollY());
3152
3153 if (!(parent instanceof View)) {
3154 break;
3155 }
Romain Guy8506ab42009-06-11 17:35:47 -07003156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 child = (View) parent;
3158 parent = child.getParent();
3159 }
3160 return scrolled;
3161 }
3162
3163 /**
3164 * Called when this view wants to give up focus. This will cause
3165 * {@link #onFocusChanged} to be called.
3166 */
3167 public void clearFocus() {
3168 if (DBG) {
3169 System.out.println(this + " clearFocus()");
3170 }
3171
3172 if ((mPrivateFlags & FOCUSED) != 0) {
3173 mPrivateFlags &= ~FOCUSED;
3174
3175 if (mParent != null) {
3176 mParent.clearChildFocus(this);
3177 }
3178
3179 onFocusChanged(false, 0, null);
3180 refreshDrawableState();
3181 }
3182 }
3183
3184 /**
3185 * Called to clear the focus of a view that is about to be removed.
3186 * Doesn't call clearChildFocus, which prevents this view from taking
3187 * focus again before it has been removed from the parent
3188 */
3189 void clearFocusForRemoval() {
3190 if ((mPrivateFlags & FOCUSED) != 0) {
3191 mPrivateFlags &= ~FOCUSED;
3192
3193 onFocusChanged(false, 0, null);
3194 refreshDrawableState();
3195 }
3196 }
3197
3198 /**
3199 * Called internally by the view system when a new view is getting focus.
3200 * This is what clears the old focus.
3201 */
3202 void unFocus() {
3203 if (DBG) {
3204 System.out.println(this + " unFocus()");
3205 }
3206
3207 if ((mPrivateFlags & FOCUSED) != 0) {
3208 mPrivateFlags &= ~FOCUSED;
3209
3210 onFocusChanged(false, 0, null);
3211 refreshDrawableState();
3212 }
3213 }
3214
3215 /**
3216 * Returns true if this view has focus iteself, or is the ancestor of the
3217 * view that has focus.
3218 *
3219 * @return True if this view has or contains focus, false otherwise.
3220 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003221 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 public boolean hasFocus() {
3223 return (mPrivateFlags & FOCUSED) != 0;
3224 }
3225
3226 /**
3227 * Returns true if this view is focusable or if it contains a reachable View
3228 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3229 * is a View whose parents do not block descendants focus.
3230 *
3231 * Only {@link #VISIBLE} views are considered focusable.
3232 *
3233 * @return True if the view is focusable or if the view contains a focusable
3234 * View, false otherwise.
3235 *
3236 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3237 */
3238 public boolean hasFocusable() {
3239 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3240 }
3241
3242 /**
3243 * Called by the view system when the focus state of this view changes.
3244 * When the focus change event is caused by directional navigation, direction
3245 * and previouslyFocusedRect provide insight into where the focus is coming from.
3246 * When overriding, be sure to call up through to the super class so that
3247 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07003248 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 * @param gainFocus True if the View has focus; false otherwise.
3250 * @param direction The direction focus has moved when requestFocus()
3251 * is called to give this view focus. Values are
Jeff Brown4e6319b2010-12-13 10:36:51 -08003252 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3253 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3254 * It may not always apply, in which case use the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 * @param previouslyFocusedRect The rectangle, in this view's coordinate
3256 * system, of the previously focused view. If applicable, this will be
3257 * passed in as finer grained information about where the focus is coming
3258 * from (in addition to direction). Will be <code>null</code> otherwise.
3259 */
3260 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003261 if (gainFocus) {
3262 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3263 }
3264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 InputMethodManager imm = InputMethodManager.peekInstance();
3266 if (!gainFocus) {
3267 if (isPressed()) {
3268 setPressed(false);
3269 }
3270 if (imm != null && mAttachInfo != null
3271 && mAttachInfo.mHasWindowFocus) {
3272 imm.focusOut(this);
3273 }
Romain Guya2431d02009-04-30 16:30:00 -07003274 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 } else if (imm != null && mAttachInfo != null
3276 && mAttachInfo.mHasWindowFocus) {
3277 imm.focusIn(this);
3278 }
Romain Guy8506ab42009-06-11 17:35:47 -07003279
Romain Guy0fd89bf2011-01-26 15:41:30 -08003280 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 if (mOnFocusChangeListener != null) {
3282 mOnFocusChangeListener.onFocusChange(this, gainFocus);
3283 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003284
3285 if (mAttachInfo != null) {
3286 mAttachInfo.mKeyDispatchState.reset(this);
3287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 }
3289
3290 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07003291 * {@inheritDoc}
3292 */
3293 public void sendAccessibilityEvent(int eventType) {
3294 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3295 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3296 }
3297 }
3298
3299 /**
3300 * {@inheritDoc}
3301 */
3302 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
Svetoslav Ganov9cd1eca2011-01-13 14:24:02 -08003303 if (!isShown()) {
3304 return;
3305 }
svetoslavganov75986cf2009-05-14 22:28:01 -07003306 event.setClassName(getClass().getName());
3307 event.setPackageName(getContext().getPackageName());
3308 event.setEnabled(isEnabled());
3309 event.setContentDescription(mContentDescription);
3310
3311 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3312 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3313 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3314 event.setItemCount(focusablesTempList.size());
3315 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3316 focusablesTempList.clear();
3317 }
3318
3319 dispatchPopulateAccessibilityEvent(event);
3320
3321 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3322 }
3323
3324 /**
3325 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3326 * to be populated.
3327 *
3328 * @param event The event.
3329 *
3330 * @return True if the event population was completed.
3331 */
3332 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3333 return false;
3334 }
3335
3336 /**
3337 * Gets the {@link View} description. It briefly describes the view and is
3338 * primarily used for accessibility support. Set this property to enable
3339 * better accessibility support for your application. This is especially
3340 * true for views that do not have textual representation (For example,
3341 * ImageButton).
3342 *
3343 * @return The content descriptiopn.
3344 *
3345 * @attr ref android.R.styleable#View_contentDescription
3346 */
3347 public CharSequence getContentDescription() {
3348 return mContentDescription;
3349 }
3350
3351 /**
3352 * Sets the {@link View} description. It briefly describes the view and is
3353 * primarily used for accessibility support. Set this property to enable
3354 * better accessibility support for your application. This is especially
3355 * true for views that do not have textual representation (For example,
3356 * ImageButton).
3357 *
3358 * @param contentDescription The content description.
3359 *
3360 * @attr ref android.R.styleable#View_contentDescription
3361 */
3362 public void setContentDescription(CharSequence contentDescription) {
3363 mContentDescription = contentDescription;
3364 }
3365
3366 /**
Romain Guya2431d02009-04-30 16:30:00 -07003367 * Invoked whenever this view loses focus, either by losing window focus or by losing
3368 * focus within its window. This method can be used to clear any state tied to the
3369 * focus. For instance, if a button is held pressed with the trackball and the window
3370 * loses focus, this method can be used to cancel the press.
3371 *
3372 * Subclasses of View overriding this method should always call super.onFocusLost().
3373 *
3374 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003375 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003376 *
3377 * @hide pending API council approval
3378 */
3379 protected void onFocusLost() {
3380 resetPressedState();
3381 }
3382
3383 private void resetPressedState() {
3384 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3385 return;
3386 }
3387
3388 if (isPressed()) {
3389 setPressed(false);
3390
3391 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003392 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003393 }
3394 }
3395 }
3396
3397 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 * Returns true if this view has focus
3399 *
3400 * @return True if this view has focus, false otherwise.
3401 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003402 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 public boolean isFocused() {
3404 return (mPrivateFlags & FOCUSED) != 0;
3405 }
3406
3407 /**
3408 * Find the view in the hierarchy rooted at this view that currently has
3409 * focus.
3410 *
3411 * @return The view that currently has focus, or null if no focused view can
3412 * be found.
3413 */
3414 public View findFocus() {
3415 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3416 }
3417
3418 /**
3419 * Change whether this view is one of the set of scrollable containers in
3420 * its window. This will be used to determine whether the window can
3421 * resize or must pan when a soft input area is open -- scrollable
3422 * containers allow the window to use resize mode since the container
3423 * will appropriately shrink.
3424 */
3425 public void setScrollContainer(boolean isScrollContainer) {
3426 if (isScrollContainer) {
3427 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3428 mAttachInfo.mScrollContainers.add(this);
3429 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3430 }
3431 mPrivateFlags |= SCROLL_CONTAINER;
3432 } else {
3433 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3434 mAttachInfo.mScrollContainers.remove(this);
3435 }
3436 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3437 }
3438 }
3439
3440 /**
3441 * Returns the quality of the drawing cache.
3442 *
3443 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3444 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3445 *
3446 * @see #setDrawingCacheQuality(int)
3447 * @see #setDrawingCacheEnabled(boolean)
3448 * @see #isDrawingCacheEnabled()
3449 *
3450 * @attr ref android.R.styleable#View_drawingCacheQuality
3451 */
3452 public int getDrawingCacheQuality() {
3453 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3454 }
3455
3456 /**
3457 * Set the drawing cache quality of this view. This value is used only when the
3458 * drawing cache is enabled
3459 *
3460 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3461 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3462 *
3463 * @see #getDrawingCacheQuality()
3464 * @see #setDrawingCacheEnabled(boolean)
3465 * @see #isDrawingCacheEnabled()
3466 *
3467 * @attr ref android.R.styleable#View_drawingCacheQuality
3468 */
3469 public void setDrawingCacheQuality(int quality) {
3470 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3471 }
3472
3473 /**
3474 * Returns whether the screen should remain on, corresponding to the current
3475 * value of {@link #KEEP_SCREEN_ON}.
3476 *
3477 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3478 *
3479 * @see #setKeepScreenOn(boolean)
3480 *
3481 * @attr ref android.R.styleable#View_keepScreenOn
3482 */
3483 public boolean getKeepScreenOn() {
3484 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3485 }
3486
3487 /**
3488 * Controls whether the screen should remain on, modifying the
3489 * value of {@link #KEEP_SCREEN_ON}.
3490 *
3491 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3492 *
3493 * @see #getKeepScreenOn()
3494 *
3495 * @attr ref android.R.styleable#View_keepScreenOn
3496 */
3497 public void setKeepScreenOn(boolean keepScreenOn) {
3498 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
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_LEFT}.
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_nextFocusLeft
3506 */
3507 public int getNextFocusLeftId() {
3508 return mNextFocusLeftId;
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_LEFT}.
3513 * @param nextFocusLeftId 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_nextFocusLeft
3517 */
3518 public void setNextFocusLeftId(int nextFocusLeftId) {
3519 mNextFocusLeftId = nextFocusLeftId;
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_RIGHT}.
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_nextFocusRight
3527 */
3528 public int getNextFocusRightId() {
3529 return mNextFocusRightId;
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_RIGHT}.
3534 * @param nextFocusRightId 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_nextFocusRight
3538 */
3539 public void setNextFocusRightId(int nextFocusRightId) {
3540 mNextFocusRightId = nextFocusRightId;
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_UP}.
3545 * @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 -08003546 *
3547 * @attr ref android.R.styleable#View_nextFocusUp
3548 */
3549 public int getNextFocusUpId() {
3550 return mNextFocusUpId;
3551 }
3552
3553 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003554 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3555 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
3556 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 *
3558 * @attr ref android.R.styleable#View_nextFocusUp
3559 */
3560 public void setNextFocusUpId(int nextFocusUpId) {
3561 mNextFocusUpId = nextFocusUpId;
3562 }
3563
3564 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003565 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3566 * @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 -08003567 *
3568 * @attr ref android.R.styleable#View_nextFocusDown
3569 */
3570 public int getNextFocusDownId() {
3571 return mNextFocusDownId;
3572 }
3573
3574 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003575 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3576 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
3577 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578 *
3579 * @attr ref android.R.styleable#View_nextFocusDown
3580 */
3581 public void setNextFocusDownId(int nextFocusDownId) {
3582 mNextFocusDownId = nextFocusDownId;
3583 }
3584
3585 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003586 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3587 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3588 *
3589 * @attr ref android.R.styleable#View_nextFocusForward
3590 */
3591 public int getNextFocusForwardId() {
3592 return mNextFocusForwardId;
3593 }
3594
3595 /**
3596 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3597 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
3598 * decide automatically.
3599 *
3600 * @attr ref android.R.styleable#View_nextFocusForward
3601 */
3602 public void setNextFocusForwardId(int nextFocusForwardId) {
3603 mNextFocusForwardId = nextFocusForwardId;
3604 }
3605
3606 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 * Returns the visibility of this view and all of its ancestors
3608 *
3609 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3610 */
3611 public boolean isShown() {
3612 View current = this;
3613 //noinspection ConstantConditions
3614 do {
3615 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3616 return false;
3617 }
3618 ViewParent parent = current.mParent;
3619 if (parent == null) {
3620 return false; // We are not attached to the view root
3621 }
3622 if (!(parent instanceof View)) {
3623 return true;
3624 }
3625 current = (View) parent;
3626 } while (current != null);
3627
3628 return false;
3629 }
3630
3631 /**
3632 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3633 * is set
3634 *
3635 * @param insets Insets for system windows
3636 *
3637 * @return True if this view applied the insets, false otherwise
3638 */
3639 protected boolean fitSystemWindows(Rect insets) {
3640 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3641 mPaddingLeft = insets.left;
3642 mPaddingTop = insets.top;
3643 mPaddingRight = insets.right;
3644 mPaddingBottom = insets.bottom;
3645 requestLayout();
3646 return true;
3647 }
3648 return false;
3649 }
3650
3651 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003652 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3653 * @return True if window has FITS_SYSTEM_WINDOWS set
3654 *
3655 * @hide
3656 */
3657 public boolean isFitsSystemWindowsFlagSet() {
3658 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3659 }
3660
3661 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 * Returns the visibility status for this view.
3663 *
3664 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3665 * @attr ref android.R.styleable#View_visibility
3666 */
3667 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003668 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3669 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3670 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 })
3672 public int getVisibility() {
3673 return mViewFlags & VISIBILITY_MASK;
3674 }
3675
3676 /**
3677 * Set the enabled state of this view.
3678 *
3679 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3680 * @attr ref android.R.styleable#View_visibility
3681 */
3682 @RemotableViewMethod
3683 public void setVisibility(int visibility) {
3684 setFlags(visibility, VISIBILITY_MASK);
3685 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3686 }
3687
3688 /**
3689 * Returns the enabled status for this view. The interpretation of the
3690 * enabled state varies by subclass.
3691 *
3692 * @return True if this view is enabled, false otherwise.
3693 */
3694 @ViewDebug.ExportedProperty
3695 public boolean isEnabled() {
3696 return (mViewFlags & ENABLED_MASK) == ENABLED;
3697 }
3698
3699 /**
3700 * Set the enabled state of this view. The interpretation of the enabled
3701 * state varies by subclass.
3702 *
3703 * @param enabled True if this view is enabled, false otherwise.
3704 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003705 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003706 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003707 if (enabled == isEnabled()) return;
3708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3710
3711 /*
3712 * The View most likely has to change its appearance, so refresh
3713 * the drawable state.
3714 */
3715 refreshDrawableState();
3716
3717 // Invalidate too, since the default behavior for views is to be
3718 // be drawn at 50% alpha rather than to change the drawable.
Romain Guy0fd89bf2011-01-26 15:41:30 -08003719 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 }
3721
3722 /**
3723 * Set whether this view can receive the focus.
3724 *
3725 * Setting this to false will also ensure that this view is not focusable
3726 * in touch mode.
3727 *
3728 * @param focusable If true, this view can receive the focus.
3729 *
3730 * @see #setFocusableInTouchMode(boolean)
3731 * @attr ref android.R.styleable#View_focusable
3732 */
3733 public void setFocusable(boolean focusable) {
3734 if (!focusable) {
3735 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3736 }
3737 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3738 }
3739
3740 /**
3741 * Set whether this view can receive focus while in touch mode.
3742 *
3743 * Setting this to true will also ensure that this view is focusable.
3744 *
3745 * @param focusableInTouchMode If true, this view can receive the focus while
3746 * in touch mode.
3747 *
3748 * @see #setFocusable(boolean)
3749 * @attr ref android.R.styleable#View_focusableInTouchMode
3750 */
3751 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3752 // Focusable in touch mode should always be set before the focusable flag
3753 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3754 // which, in touch mode, will not successfully request focus on this view
3755 // because the focusable in touch mode flag is not set
3756 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3757 if (focusableInTouchMode) {
3758 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3759 }
3760 }
3761
3762 /**
3763 * Set whether this view should have sound effects enabled for events such as
3764 * clicking and touching.
3765 *
3766 * <p>You may wish to disable sound effects for a view if you already play sounds,
3767 * for instance, a dial key that plays dtmf tones.
3768 *
3769 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3770 * @see #isSoundEffectsEnabled()
3771 * @see #playSoundEffect(int)
3772 * @attr ref android.R.styleable#View_soundEffectsEnabled
3773 */
3774 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3775 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3776 }
3777
3778 /**
3779 * @return whether this view should have sound effects enabled for events such as
3780 * clicking and touching.
3781 *
3782 * @see #setSoundEffectsEnabled(boolean)
3783 * @see #playSoundEffect(int)
3784 * @attr ref android.R.styleable#View_soundEffectsEnabled
3785 */
3786 @ViewDebug.ExportedProperty
3787 public boolean isSoundEffectsEnabled() {
3788 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3789 }
3790
3791 /**
3792 * Set whether this view should have haptic feedback for events such as
3793 * long presses.
3794 *
3795 * <p>You may wish to disable haptic feedback if your view already controls
3796 * its own haptic feedback.
3797 *
3798 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3799 * @see #isHapticFeedbackEnabled()
3800 * @see #performHapticFeedback(int)
3801 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3802 */
3803 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3804 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3805 }
3806
3807 /**
3808 * @return whether this view should have haptic feedback enabled for events
3809 * long presses.
3810 *
3811 * @see #setHapticFeedbackEnabled(boolean)
3812 * @see #performHapticFeedback(int)
3813 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3814 */
3815 @ViewDebug.ExportedProperty
3816 public boolean isHapticFeedbackEnabled() {
3817 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3818 }
3819
3820 /**
3821 * If this view doesn't do any drawing on its own, set this flag to
3822 * allow further optimizations. By default, this flag is not set on
3823 * View, but could be set on some View subclasses such as ViewGroup.
3824 *
3825 * Typically, if you override {@link #onDraw} you should clear this flag.
3826 *
3827 * @param willNotDraw whether or not this View draw on its own
3828 */
3829 public void setWillNotDraw(boolean willNotDraw) {
3830 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3831 }
3832
3833 /**
3834 * Returns whether or not this View draws on its own.
3835 *
3836 * @return true if this view has nothing to draw, false otherwise
3837 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003838 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 public boolean willNotDraw() {
3840 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3841 }
3842
3843 /**
3844 * When a View's drawing cache is enabled, drawing is redirected to an
3845 * offscreen bitmap. Some views, like an ImageView, must be able to
3846 * bypass this mechanism if they already draw a single bitmap, to avoid
3847 * unnecessary usage of the memory.
3848 *
3849 * @param willNotCacheDrawing true if this view does not cache its
3850 * drawing, false otherwise
3851 */
3852 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3853 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3854 }
3855
3856 /**
3857 * Returns whether or not this View can cache its drawing or not.
3858 *
3859 * @return true if this view does not cache its drawing, false otherwise
3860 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003861 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 public boolean willNotCacheDrawing() {
3863 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3864 }
3865
3866 /**
3867 * Indicates whether this view reacts to click events or not.
3868 *
3869 * @return true if the view is clickable, false otherwise
3870 *
3871 * @see #setClickable(boolean)
3872 * @attr ref android.R.styleable#View_clickable
3873 */
3874 @ViewDebug.ExportedProperty
3875 public boolean isClickable() {
3876 return (mViewFlags & CLICKABLE) == CLICKABLE;
3877 }
3878
3879 /**
3880 * Enables or disables click events for this view. When a view
3881 * is clickable it will change its state to "pressed" on every click.
3882 * Subclasses should set the view clickable to visually react to
3883 * user's clicks.
3884 *
3885 * @param clickable true to make the view clickable, false otherwise
3886 *
3887 * @see #isClickable()
3888 * @attr ref android.R.styleable#View_clickable
3889 */
3890 public void setClickable(boolean clickable) {
3891 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3892 }
3893
3894 /**
3895 * Indicates whether this view reacts to long click events or not.
3896 *
3897 * @return true if the view is long clickable, false otherwise
3898 *
3899 * @see #setLongClickable(boolean)
3900 * @attr ref android.R.styleable#View_longClickable
3901 */
3902 public boolean isLongClickable() {
3903 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3904 }
3905
3906 /**
3907 * Enables or disables long click events for this view. When a view is long
3908 * clickable it reacts to the user holding down the button for a longer
3909 * duration than a tap. This event can either launch the listener or a
3910 * context menu.
3911 *
3912 * @param longClickable true to make the view long clickable, false otherwise
3913 * @see #isLongClickable()
3914 * @attr ref android.R.styleable#View_longClickable
3915 */
3916 public void setLongClickable(boolean longClickable) {
3917 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3918 }
3919
3920 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003921 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 *
3923 * @see #isClickable()
3924 * @see #setClickable(boolean)
3925 *
3926 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3927 * the View's internal state from a previously set "pressed" state.
3928 */
3929 public void setPressed(boolean pressed) {
3930 if (pressed) {
3931 mPrivateFlags |= PRESSED;
3932 } else {
3933 mPrivateFlags &= ~PRESSED;
3934 }
3935 refreshDrawableState();
3936 dispatchSetPressed(pressed);
3937 }
3938
3939 /**
3940 * Dispatch setPressed to all of this View's children.
3941 *
3942 * @see #setPressed(boolean)
3943 *
3944 * @param pressed The new pressed state
3945 */
3946 protected void dispatchSetPressed(boolean pressed) {
3947 }
3948
3949 /**
3950 * Indicates whether the view is currently in pressed state. Unless
3951 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3952 * the pressed state.
3953 *
3954 * @see #setPressed
3955 * @see #isClickable()
3956 * @see #setClickable(boolean)
3957 *
3958 * @return true if the view is currently pressed, false otherwise
3959 */
3960 public boolean isPressed() {
3961 return (mPrivateFlags & PRESSED) == PRESSED;
3962 }
3963
3964 /**
3965 * Indicates whether this view will save its state (that is,
3966 * whether its {@link #onSaveInstanceState} method will be called).
3967 *
3968 * @return Returns true if the view state saving is enabled, else false.
3969 *
3970 * @see #setSaveEnabled(boolean)
3971 * @attr ref android.R.styleable#View_saveEnabled
3972 */
3973 public boolean isSaveEnabled() {
3974 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3975 }
3976
3977 /**
3978 * Controls whether the saving of this view's state is
3979 * enabled (that is, whether its {@link #onSaveInstanceState} method
3980 * will be called). Note that even if freezing is enabled, the
3981 * view still must have an id assigned to it (via {@link #setId setId()})
3982 * for its state to be saved. This flag can only disable the
3983 * saving of this view; any child views may still have their state saved.
3984 *
3985 * @param enabled Set to false to <em>disable</em> state saving, or true
3986 * (the default) to allow it.
3987 *
3988 * @see #isSaveEnabled()
3989 * @see #setId(int)
3990 * @see #onSaveInstanceState()
3991 * @attr ref android.R.styleable#View_saveEnabled
3992 */
3993 public void setSaveEnabled(boolean enabled) {
3994 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3995 }
3996
Jeff Brown85a31762010-09-01 17:01:00 -07003997 /**
3998 * Gets whether the framework should discard touches when the view's
3999 * window is obscured by another visible window.
4000 * Refer to the {@link View} security documentation for more details.
4001 *
4002 * @return True if touch filtering is enabled.
4003 *
4004 * @see #setFilterTouchesWhenObscured(boolean)
4005 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4006 */
4007 @ViewDebug.ExportedProperty
4008 public boolean getFilterTouchesWhenObscured() {
4009 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
4010 }
4011
4012 /**
4013 * Sets whether the framework should discard touches when the view's
4014 * window is obscured by another visible window.
4015 * Refer to the {@link View} security documentation for more details.
4016 *
4017 * @param enabled True if touch filtering should be enabled.
4018 *
4019 * @see #getFilterTouchesWhenObscured
4020 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4021 */
4022 public void setFilterTouchesWhenObscured(boolean enabled) {
4023 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
4024 FILTER_TOUCHES_WHEN_OBSCURED);
4025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026
4027 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004028 * Indicates whether the entire hierarchy under this view will save its
4029 * state when a state saving traversal occurs from its parent. The default
4030 * is true; if false, these views will not be saved unless
4031 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4032 *
4033 * @return Returns true if the view state saving from parent is enabled, else false.
4034 *
4035 * @see #setSaveFromParentEnabled(boolean)
4036 */
4037 public boolean isSaveFromParentEnabled() {
4038 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4039 }
4040
4041 /**
4042 * Controls whether the entire hierarchy under this view will save its
4043 * state when a state saving traversal occurs from its parent. The default
4044 * is true; if false, these views will not be saved unless
4045 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4046 *
4047 * @param enabled Set to false to <em>disable</em> state saving, or true
4048 * (the default) to allow it.
4049 *
4050 * @see #isSaveFromParentEnabled()
4051 * @see #setId(int)
4052 * @see #onSaveInstanceState()
4053 */
4054 public void setSaveFromParentEnabled(boolean enabled) {
4055 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4056 }
4057
4058
4059 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 * Returns whether this View is able to take focus.
4061 *
4062 * @return True if this view can take focus, or false otherwise.
4063 * @attr ref android.R.styleable#View_focusable
4064 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004065 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 public final boolean isFocusable() {
4067 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4068 }
4069
4070 /**
4071 * When a view is focusable, it may not want to take focus when in touch mode.
4072 * For example, a button would like focus when the user is navigating via a D-pad
4073 * so that the user can click on it, but once the user starts touching the screen,
4074 * the button shouldn't take focus
4075 * @return Whether the view is focusable in touch mode.
4076 * @attr ref android.R.styleable#View_focusableInTouchMode
4077 */
4078 @ViewDebug.ExportedProperty
4079 public final boolean isFocusableInTouchMode() {
4080 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4081 }
4082
4083 /**
4084 * Find the nearest view in the specified direction that can take focus.
4085 * This does not actually give focus to that view.
4086 *
4087 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4088 *
4089 * @return The nearest focusable in the specified direction, or null if none
4090 * can be found.
4091 */
4092 public View focusSearch(int direction) {
4093 if (mParent != null) {
4094 return mParent.focusSearch(this, direction);
4095 } else {
4096 return null;
4097 }
4098 }
4099
4100 /**
4101 * This method is the last chance for the focused view and its ancestors to
4102 * respond to an arrow key. This is called when the focused view did not
4103 * consume the key internally, nor could the view system find a new view in
4104 * the requested direction to give focus to.
4105 *
4106 * @param focused The currently focused view.
4107 * @param direction The direction focus wants to move. One of FOCUS_UP,
4108 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4109 * @return True if the this view consumed this unhandled move.
4110 */
4111 public boolean dispatchUnhandledMove(View focused, int direction) {
4112 return false;
4113 }
4114
4115 /**
4116 * If a user manually specified the next view id for a particular direction,
Jeff Brown4e6319b2010-12-13 10:36:51 -08004117 * use the root to look up the view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 * @param root The root view of the hierarchy containing this view.
Jeff Brown4e6319b2010-12-13 10:36:51 -08004119 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4120 * or FOCUS_BACKWARD.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 * @return The user specified next view, or null if there is none.
4122 */
4123 View findUserSetNextFocus(View root, int direction) {
4124 switch (direction) {
4125 case FOCUS_LEFT:
4126 if (mNextFocusLeftId == View.NO_ID) return null;
4127 return findViewShouldExist(root, mNextFocusLeftId);
4128 case FOCUS_RIGHT:
4129 if (mNextFocusRightId == View.NO_ID) return null;
4130 return findViewShouldExist(root, mNextFocusRightId);
4131 case FOCUS_UP:
4132 if (mNextFocusUpId == View.NO_ID) return null;
4133 return findViewShouldExist(root, mNextFocusUpId);
4134 case FOCUS_DOWN:
4135 if (mNextFocusDownId == View.NO_ID) return null;
4136 return findViewShouldExist(root, mNextFocusDownId);
Jeff Brown4e6319b2010-12-13 10:36:51 -08004137 case FOCUS_FORWARD:
4138 if (mNextFocusForwardId == View.NO_ID) return null;
4139 return findViewShouldExist(root, mNextFocusForwardId);
4140 case FOCUS_BACKWARD: {
4141 final int id = mID;
4142 return root.findViewByPredicate(new Predicate<View>() {
4143 @Override
4144 public boolean apply(View t) {
4145 return t.mNextFocusForwardId == id;
4146 }
4147 });
4148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004149 }
4150 return null;
4151 }
4152
4153 private static View findViewShouldExist(View root, int childViewId) {
4154 View result = root.findViewById(childViewId);
4155 if (result == null) {
4156 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4157 + "by user for id " + childViewId);
4158 }
4159 return result;
4160 }
4161
4162 /**
4163 * Find and return all focusable views that are descendants of this view,
4164 * possibly including this view if it is focusable itself.
4165 *
4166 * @param direction The direction of the focus
4167 * @return A list of focusable views
4168 */
4169 public ArrayList<View> getFocusables(int direction) {
4170 ArrayList<View> result = new ArrayList<View>(24);
4171 addFocusables(result, direction);
4172 return result;
4173 }
4174
4175 /**
4176 * Add any focusable views that are descendants of this view (possibly
4177 * including this view if it is focusable itself) to views. If we are in touch mode,
4178 * only add views that are also focusable in touch mode.
4179 *
4180 * @param views Focusable views found so far
4181 * @param direction The direction of the focus
4182 */
4183 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07004184 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186
svetoslavganov75986cf2009-05-14 22:28:01 -07004187 /**
4188 * Adds any focusable views that are descendants of this view (possibly
4189 * including this view if it is focusable itself) to views. This method
4190 * adds all focusable views regardless if we are in touch mode or
4191 * only views focusable in touch mode if we are in touch mode depending on
4192 * the focusable mode paramater.
4193 *
4194 * @param views Focusable views found so far or null if all we are interested is
4195 * the number of focusables.
4196 * @param direction The direction of the focus.
4197 * @param focusableMode The type of focusables to be added.
4198 *
4199 * @see #FOCUSABLES_ALL
4200 * @see #FOCUSABLES_TOUCH_MODE
4201 */
4202 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4203 if (!isFocusable()) {
4204 return;
4205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206
svetoslavganov75986cf2009-05-14 22:28:01 -07004207 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4208 isInTouchMode() && !isFocusableInTouchMode()) {
4209 return;
4210 }
4211
4212 if (views != null) {
4213 views.add(this);
4214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 }
4216
4217 /**
4218 * Find and return all touchable views that are descendants of this view,
4219 * possibly including this view if it is touchable itself.
4220 *
4221 * @return A list of touchable views
4222 */
4223 public ArrayList<View> getTouchables() {
4224 ArrayList<View> result = new ArrayList<View>();
4225 addTouchables(result);
4226 return result;
4227 }
4228
4229 /**
4230 * Add any touchable views that are descendants of this view (possibly
4231 * including this view if it is touchable itself) to views.
4232 *
4233 * @param views Touchable views found so far
4234 */
4235 public void addTouchables(ArrayList<View> views) {
4236 final int viewFlags = mViewFlags;
4237
4238 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4239 && (viewFlags & ENABLED_MASK) == ENABLED) {
4240 views.add(this);
4241 }
4242 }
4243
4244 /**
4245 * Call this to try to give focus to a specific view or to one of its
4246 * descendants.
4247 *
4248 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4249 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4250 * while the device is in touch mode.
4251 *
4252 * See also {@link #focusSearch}, which is what you call to say that you
4253 * have focus, and you want your parent to look for the next one.
4254 *
4255 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4256 * {@link #FOCUS_DOWN} and <code>null</code>.
4257 *
4258 * @return Whether this view or one of its descendants actually took focus.
4259 */
4260 public final boolean requestFocus() {
4261 return requestFocus(View.FOCUS_DOWN);
4262 }
4263
4264
4265 /**
4266 * Call this to try to give focus to a specific view or to one of its
4267 * descendants and give it a hint about what direction focus is heading.
4268 *
4269 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4270 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4271 * while the device is in touch mode.
4272 *
4273 * See also {@link #focusSearch}, which is what you call to say that you
4274 * have focus, and you want your parent to look for the next one.
4275 *
4276 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4277 * <code>null</code> set for the previously focused rectangle.
4278 *
4279 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4280 * @return Whether this view or one of its descendants actually took focus.
4281 */
4282 public final boolean requestFocus(int direction) {
4283 return requestFocus(direction, null);
4284 }
4285
4286 /**
4287 * Call this to try to give focus to a specific view or to one of its descendants
4288 * and give it hints about the direction and a specific rectangle that the focus
4289 * is coming from. The rectangle can help give larger views a finer grained hint
4290 * about where focus is coming from, and therefore, where to show selection, or
4291 * forward focus change internally.
4292 *
4293 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4294 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4295 * while the device is in touch mode.
4296 *
4297 * A View will not take focus if it is not visible.
4298 *
4299 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4300 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4301 *
4302 * See also {@link #focusSearch}, which is what you call to say that you
4303 * have focus, and you want your parent to look for the next one.
4304 *
4305 * You may wish to override this method if your custom {@link View} has an internal
4306 * {@link View} that it wishes to forward the request to.
4307 *
4308 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4309 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4310 * to give a finer grained hint about where focus is coming from. May be null
4311 * if there is no hint.
4312 * @return Whether this view or one of its descendants actually took focus.
4313 */
4314 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4315 // need to be focusable
4316 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4317 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4318 return false;
4319 }
4320
4321 // need to be focusable in touch mode if in touch mode
4322 if (isInTouchMode() &&
4323 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4324 return false;
4325 }
4326
4327 // need to not have any parents blocking us
4328 if (hasAncestorThatBlocksDescendantFocus()) {
4329 return false;
4330 }
4331
4332 handleFocusGainInternal(direction, previouslyFocusedRect);
4333 return true;
4334 }
4335
Christopher Tate2c095f32010-10-04 14:13:40 -07004336 /** Gets the ViewRoot, or null if not attached. */
4337 /*package*/ ViewRoot getViewRoot() {
4338 View root = getRootView();
4339 return root != null ? (ViewRoot)root.getParent() : null;
4340 }
4341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 /**
4343 * Call this to try to give focus to a specific view or to one of its descendants. This is a
4344 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4345 * touch mode to request focus when they are touched.
4346 *
4347 * @return Whether this view or one of its descendants actually took focus.
4348 *
4349 * @see #isInTouchMode()
4350 *
4351 */
4352 public final boolean requestFocusFromTouch() {
4353 // Leave touch mode if we need to
4354 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07004355 ViewRoot viewRoot = getViewRoot();
4356 if (viewRoot != null) {
4357 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 }
4359 }
4360 return requestFocus(View.FOCUS_DOWN);
4361 }
4362
4363 /**
4364 * @return Whether any ancestor of this view blocks descendant focus.
4365 */
4366 private boolean hasAncestorThatBlocksDescendantFocus() {
4367 ViewParent ancestor = mParent;
4368 while (ancestor instanceof ViewGroup) {
4369 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4370 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4371 return true;
4372 } else {
4373 ancestor = vgAncestor.getParent();
4374 }
4375 }
4376 return false;
4377 }
4378
4379 /**
Romain Guya440b002010-02-24 15:57:54 -08004380 * @hide
4381 */
4382 public void dispatchStartTemporaryDetach() {
4383 onStartTemporaryDetach();
4384 }
4385
4386 /**
4387 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4389 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004390 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 */
4392 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004393 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004394 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004395 }
4396
4397 /**
4398 * @hide
4399 */
4400 public void dispatchFinishTemporaryDetach() {
4401 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 }
Romain Guy8506ab42009-06-11 17:35:47 -07004403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004404 /**
4405 * Called after {@link #onStartTemporaryDetach} when the container is done
4406 * changing the view.
4407 */
4408 public void onFinishTemporaryDetach() {
4409 }
Romain Guy8506ab42009-06-11 17:35:47 -07004410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411 /**
4412 * capture information of this view for later analysis: developement only
4413 * check dynamic switch to make sure we only dump view
4414 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4415 */
4416 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004417 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 return;
4419 }
4420 ViewDebug.dumpCapturedView(subTag, v);
4421 }
4422
4423 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004424 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4425 * for this view's window. Returns null if the view is not currently attached
4426 * to the window. Normally you will not need to use this directly, but
4427 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4428 */
4429 public KeyEvent.DispatcherState getKeyDispatcherState() {
4430 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4431 }
4432
4433 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004434 * Dispatch a key event before it is processed by any input method
4435 * associated with the view hierarchy. This can be used to intercept
4436 * key events in special situations before the IME consumes them; a
4437 * typical example would be handling the BACK key to update the application's
4438 * UI instead of allowing the IME to see it and close itself.
4439 *
4440 * @param event The key event to be dispatched.
4441 * @return True if the event was handled, false otherwise.
4442 */
4443 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4444 return onKeyPreIme(event.getKeyCode(), event);
4445 }
4446
4447 /**
4448 * Dispatch a key event to the next view on the focus path. This path runs
4449 * from the top of the view tree down to the currently focused view. If this
4450 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4451 * the next node down the focus path. This method also fires any key
4452 * listeners.
4453 *
4454 * @param event The key event to be dispatched.
4455 * @return True if the event was handled, false otherwise.
4456 */
4457 public boolean dispatchKeyEvent(KeyEvent event) {
4458 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004459
Romain Guyf607bdc2010-09-10 19:20:06 -07004460 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 if (android.util.Config.LOGV) {
4462 captureViewInfo("captureViewKeyEvent", this);
4463 }
4464
Romain Guyf607bdc2010-09-10 19:20:06 -07004465 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4467 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4468 return true;
4469 }
4470
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004471 return event.dispatch(this, mAttachInfo != null
4472 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004473 }
4474
4475 /**
4476 * Dispatches a key shortcut event.
4477 *
4478 * @param event The key event to be dispatched.
4479 * @return True if the event was handled by the view, false otherwise.
4480 */
4481 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4482 return onKeyShortcut(event.getKeyCode(), event);
4483 }
4484
4485 /**
4486 * Pass the touch screen motion event down to the target view, or this
4487 * view if it is the target.
4488 *
4489 * @param event The motion event to be dispatched.
4490 * @return True if the event was handled by the view, false otherwise.
4491 */
4492 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004493 if (!onFilterTouchEventForSecurity(event)) {
4494 return false;
4495 }
4496
Romain Guyf607bdc2010-09-10 19:20:06 -07004497 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4499 mOnTouchListener.onTouch(this, event)) {
4500 return true;
4501 }
4502 return onTouchEvent(event);
4503 }
4504
4505 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004506 * Filter the touch event to apply security policies.
4507 *
4508 * @param event The motion event to be filtered.
4509 * @return True if the event should be dispatched, false if the event should be dropped.
4510 *
4511 * @see #getFilterTouchesWhenObscured
4512 */
4513 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004514 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004515 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4516 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4517 // Window is obscured, drop this touch.
4518 return false;
4519 }
4520 return true;
4521 }
4522
4523 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004524 * Pass a trackball motion event down to the focused view.
4525 *
4526 * @param event The motion event to be dispatched.
4527 * @return True if the event was handled by the view, false otherwise.
4528 */
4529 public boolean dispatchTrackballEvent(MotionEvent event) {
4530 //Log.i("view", "view=" + this + ", " + event.toString());
4531 return onTrackballEvent(event);
4532 }
4533
4534 /**
Jeff Browncb1404e2011-01-15 18:14:15 -08004535 * Pass a generic motion event down to the focused view.
4536 *
4537 * @param event The motion event to be dispatched.
4538 * @return True if the event was handled by the view, false otherwise.
4539 */
4540 public boolean dispatchGenericMotionEvent(MotionEvent event) {
4541 return onGenericMotionEvent(event);
4542 }
4543
4544 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 * Called when the window containing this view gains or loses window focus.
4546 * ViewGroups should override to route to their children.
4547 *
4548 * @param hasFocus True if the window containing this view now has focus,
4549 * false otherwise.
4550 */
4551 public void dispatchWindowFocusChanged(boolean hasFocus) {
4552 onWindowFocusChanged(hasFocus);
4553 }
4554
4555 /**
4556 * Called when the window containing this view gains or loses focus. Note
4557 * that this is separate from view focus: to receive key events, both
4558 * your view and its window must have focus. If a window is displayed
4559 * on top of yours that takes input focus, then your own window will lose
4560 * focus but the view focus will remain unchanged.
4561 *
4562 * @param hasWindowFocus True if the window containing this view now has
4563 * focus, false otherwise.
4564 */
4565 public void onWindowFocusChanged(boolean hasWindowFocus) {
4566 InputMethodManager imm = InputMethodManager.peekInstance();
4567 if (!hasWindowFocus) {
4568 if (isPressed()) {
4569 setPressed(false);
4570 }
4571 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4572 imm.focusOut(this);
4573 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004574 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004575 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004576 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4578 imm.focusIn(this);
4579 }
4580 refreshDrawableState();
4581 }
4582
4583 /**
4584 * Returns true if this view is in a window that currently has window focus.
4585 * Note that this is not the same as the view itself having focus.
4586 *
4587 * @return True if this view is in a window that currently has window focus.
4588 */
4589 public boolean hasWindowFocus() {
4590 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4591 }
4592
4593 /**
Adam Powell326d8082009-12-09 15:10:07 -08004594 * Dispatch a view visibility change down the view hierarchy.
4595 * ViewGroups should override to route to their children.
4596 * @param changedView The view whose visibility changed. Could be 'this' or
4597 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004598 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4599 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004600 */
4601 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4602 onVisibilityChanged(changedView, visibility);
4603 }
4604
4605 /**
4606 * Called when the visibility of the view or an ancestor of the view is changed.
4607 * @param changedView The view whose visibility changed. Could be 'this' or
4608 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004609 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4610 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004611 */
4612 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004613 if (visibility == VISIBLE) {
4614 if (mAttachInfo != null) {
4615 initialAwakenScrollBars();
4616 } else {
4617 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4618 }
4619 }
Adam Powell326d8082009-12-09 15:10:07 -08004620 }
4621
4622 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004623 * Dispatch a hint about whether this view is displayed. For instance, when
4624 * a View moves out of the screen, it might receives a display hint indicating
4625 * the view is not displayed. Applications should not <em>rely</em> on this hint
4626 * as there is no guarantee that they will receive one.
4627 *
4628 * @param hint A hint about whether or not this view is displayed:
4629 * {@link #VISIBLE} or {@link #INVISIBLE}.
4630 */
4631 public void dispatchDisplayHint(int hint) {
4632 onDisplayHint(hint);
4633 }
4634
4635 /**
4636 * Gives this view a hint about whether is displayed or not. For instance, when
4637 * a View moves out of the screen, it might receives a display hint indicating
4638 * the view is not displayed. Applications should not <em>rely</em> on this hint
4639 * as there is no guarantee that they will receive one.
4640 *
4641 * @param hint A hint about whether or not this view is displayed:
4642 * {@link #VISIBLE} or {@link #INVISIBLE}.
4643 */
4644 protected void onDisplayHint(int hint) {
4645 }
4646
4647 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004648 * Dispatch a window visibility change down the view hierarchy.
4649 * ViewGroups should override to route to their children.
4650 *
4651 * @param visibility The new visibility of the window.
4652 *
4653 * @see #onWindowVisibilityChanged
4654 */
4655 public void dispatchWindowVisibilityChanged(int visibility) {
4656 onWindowVisibilityChanged(visibility);
4657 }
4658
4659 /**
4660 * Called when the window containing has change its visibility
4661 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4662 * that this tells you whether or not your window is being made visible
4663 * to the window manager; this does <em>not</em> tell you whether or not
4664 * your window is obscured by other windows on the screen, even if it
4665 * is itself visible.
4666 *
4667 * @param visibility The new visibility of the window.
4668 */
4669 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004670 if (visibility == VISIBLE) {
4671 initialAwakenScrollBars();
4672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004673 }
4674
4675 /**
4676 * Returns the current visibility of the window this view is attached to
4677 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4678 *
4679 * @return Returns the current visibility of the view's window.
4680 */
4681 public int getWindowVisibility() {
4682 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4683 }
4684
4685 /**
4686 * Retrieve the overall visible display size in which the window this view is
4687 * attached to has been positioned in. This takes into account screen
4688 * decorations above the window, for both cases where the window itself
4689 * is being position inside of them or the window is being placed under
4690 * then and covered insets are used for the window to position its content
4691 * inside. In effect, this tells you the available area where content can
4692 * be placed and remain visible to users.
4693 *
4694 * <p>This function requires an IPC back to the window manager to retrieve
4695 * the requested information, so should not be used in performance critical
4696 * code like drawing.
4697 *
4698 * @param outRect Filled in with the visible display frame. If the view
4699 * is not attached to a window, this is simply the raw display size.
4700 */
4701 public void getWindowVisibleDisplayFrame(Rect outRect) {
4702 if (mAttachInfo != null) {
4703 try {
4704 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4705 } catch (RemoteException e) {
4706 return;
4707 }
4708 // XXX This is really broken, and probably all needs to be done
4709 // in the window manager, and we need to know more about whether
4710 // we want the area behind or in front of the IME.
4711 final Rect insets = mAttachInfo.mVisibleInsets;
4712 outRect.left += insets.left;
4713 outRect.top += insets.top;
4714 outRect.right -= insets.right;
4715 outRect.bottom -= insets.bottom;
4716 return;
4717 }
4718 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4719 outRect.set(0, 0, d.getWidth(), d.getHeight());
4720 }
4721
4722 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004723 * Dispatch a notification about a resource configuration change down
4724 * the view hierarchy.
4725 * ViewGroups should override to route to their children.
4726 *
4727 * @param newConfig The new resource configuration.
4728 *
4729 * @see #onConfigurationChanged
4730 */
4731 public void dispatchConfigurationChanged(Configuration newConfig) {
4732 onConfigurationChanged(newConfig);
4733 }
4734
4735 /**
4736 * Called when the current configuration of the resources being used
4737 * by the application have changed. You can use this to decide when
4738 * to reload resources that can changed based on orientation and other
4739 * configuration characterstics. You only need to use this if you are
4740 * not relying on the normal {@link android.app.Activity} mechanism of
4741 * recreating the activity instance upon a configuration change.
4742 *
4743 * @param newConfig The new resource configuration.
4744 */
4745 protected void onConfigurationChanged(Configuration newConfig) {
4746 }
4747
4748 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004749 * Private function to aggregate all per-view attributes in to the view
4750 * root.
4751 */
4752 void dispatchCollectViewAttributes(int visibility) {
4753 performCollectViewAttributes(visibility);
4754 }
4755
4756 void performCollectViewAttributes(int visibility) {
Romain Guyd30b36d2011-01-26 10:54:43 -08004757 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
Joe Onorato664644d2011-01-23 17:53:23 -08004758 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
4759 mAttachInfo.mKeepScreenOn = true;
4760 }
4761 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
4762 if (mOnSystemUiVisibilityChangeListener != null) {
4763 mAttachInfo.mHasSystemUiListeners = true;
4764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004765 }
4766 }
4767
4768 void needGlobalAttributesUpdate(boolean force) {
Joe Onorato664644d2011-01-23 17:53:23 -08004769 final AttachInfo ai = mAttachInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004770 if (ai != null) {
Joe Onorato664644d2011-01-23 17:53:23 -08004771 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
4772 || ai.mHasSystemUiListeners) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004773 ai.mRecomputeGlobalAttributes = true;
4774 }
4775 }
4776 }
4777
4778 /**
4779 * Returns whether the device is currently in touch mode. Touch mode is entered
4780 * once the user begins interacting with the device by touch, and affects various
4781 * things like whether focus is always visible to the user.
4782 *
4783 * @return Whether the device is in touch mode.
4784 */
4785 @ViewDebug.ExportedProperty
4786 public boolean isInTouchMode() {
4787 if (mAttachInfo != null) {
4788 return mAttachInfo.mInTouchMode;
4789 } else {
4790 return ViewRoot.isInTouchMode();
4791 }
4792 }
4793
4794 /**
4795 * Returns the context the view is running in, through which it can
4796 * access the current theme, resources, etc.
4797 *
4798 * @return The view's Context.
4799 */
4800 @ViewDebug.CapturedViewProperty
4801 public final Context getContext() {
4802 return mContext;
4803 }
4804
4805 /**
4806 * Handle a key event before it is processed by any input method
4807 * associated with the view hierarchy. This can be used to intercept
4808 * key events in special situations before the IME consumes them; a
4809 * typical example would be handling the BACK key to update the application's
4810 * UI instead of allowing the IME to see it and close itself.
4811 *
4812 * @param keyCode The value in event.getKeyCode().
4813 * @param event Description of the key event.
4814 * @return If you handled the event, return true. If you want to allow the
4815 * event to be handled by the next receiver, return false.
4816 */
4817 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4818 return false;
4819 }
4820
4821 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004822 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
4823 * KeyEvent.Callback.onKeyDown()}: perform press of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004824 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4825 * is released, if the view is enabled and clickable.
4826 *
4827 * @param keyCode A key code that represents the button pressed, from
4828 * {@link android.view.KeyEvent}.
4829 * @param event The KeyEvent object that defines the button action.
4830 */
4831 public boolean onKeyDown(int keyCode, KeyEvent event) {
4832 boolean result = false;
4833
4834 switch (keyCode) {
4835 case KeyEvent.KEYCODE_DPAD_CENTER:
4836 case KeyEvent.KEYCODE_ENTER: {
4837 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4838 return true;
4839 }
4840 // Long clickable items don't necessarily have to be clickable
4841 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4842 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4843 (event.getRepeatCount() == 0)) {
4844 setPressed(true);
4845 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004846 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004847 }
4848 return true;
4849 }
4850 break;
4851 }
4852 }
4853 return result;
4854 }
4855
4856 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004857 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4858 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4859 * the event).
4860 */
4861 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4862 return false;
4863 }
4864
4865 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004866 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
4867 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004868 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4869 * {@link KeyEvent#KEYCODE_ENTER} is released.
4870 *
4871 * @param keyCode A key code that represents the button pressed, from
4872 * {@link android.view.KeyEvent}.
4873 * @param event The KeyEvent object that defines the button action.
4874 */
4875 public boolean onKeyUp(int keyCode, KeyEvent event) {
4876 boolean result = false;
4877
4878 switch (keyCode) {
4879 case KeyEvent.KEYCODE_DPAD_CENTER:
4880 case KeyEvent.KEYCODE_ENTER: {
4881 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4882 return true;
4883 }
4884 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4885 setPressed(false);
4886
4887 if (!mHasPerformedLongPress) {
4888 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004889 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890
4891 result = performClick();
4892 }
4893 }
4894 break;
4895 }
4896 }
4897 return result;
4898 }
4899
4900 /**
4901 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4902 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4903 * the event).
4904 *
4905 * @param keyCode A key code that represents the button pressed, from
4906 * {@link android.view.KeyEvent}.
4907 * @param repeatCount The number of times the action was made.
4908 * @param event The KeyEvent object that defines the button action.
4909 */
4910 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4911 return false;
4912 }
4913
4914 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08004915 * Called on the focused view when a key shortcut event is not handled.
4916 * Override this method to implement local key shortcuts for the View.
4917 * Key shortcuts can also be implemented by setting the
4918 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004919 *
4920 * @param keyCode The value in event.getKeyCode().
4921 * @param event Description of the key event.
4922 * @return If you handled the event, return true. If you want to allow the
4923 * event to be handled by the next receiver, return false.
4924 */
4925 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4926 return false;
4927 }
4928
4929 /**
4930 * Check whether the called view is a text editor, in which case it
4931 * would make sense to automatically display a soft input window for
4932 * it. Subclasses should override this if they implement
4933 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004934 * a call on that method would return a non-null InputConnection, and
4935 * they are really a first-class editor that the user would normally
4936 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004937 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004938 * <p>The default implementation always returns false. This does
4939 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4940 * will not be called or the user can not otherwise perform edits on your
4941 * view; it is just a hint to the system that this is not the primary
4942 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004943 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944 * @return Returns true if this view is a text editor, else false.
4945 */
4946 public boolean onCheckIsTextEditor() {
4947 return false;
4948 }
Romain Guy8506ab42009-06-11 17:35:47 -07004949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004950 /**
4951 * Create a new InputConnection for an InputMethod to interact
4952 * with the view. The default implementation returns null, since it doesn't
4953 * support input methods. You can override this to implement such support.
4954 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004955 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004956 * <p>When implementing this, you probably also want to implement
4957 * {@link #onCheckIsTextEditor()} to indicate you will return a
4958 * non-null InputConnection.
4959 *
4960 * @param outAttrs Fill in with attribute information about the connection.
4961 */
4962 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4963 return null;
4964 }
4965
4966 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004967 * Called by the {@link android.view.inputmethod.InputMethodManager}
4968 * when a view who is not the current
4969 * input connection target is trying to make a call on the manager. The
4970 * default implementation returns false; you can override this to return
4971 * true for certain views if you are performing InputConnection proxying
4972 * to them.
4973 * @param view The View that is making the InputMethodManager call.
4974 * @return Return true to allow the call, false to reject.
4975 */
4976 public boolean checkInputConnectionProxy(View view) {
4977 return false;
4978 }
Romain Guy8506ab42009-06-11 17:35:47 -07004979
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004980 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004981 * Show the context menu for this view. It is not safe to hold on to the
4982 * menu after returning from this method.
4983 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004984 * You should normally not overload this method. Overload
4985 * {@link #onCreateContextMenu(ContextMenu)} or define an
4986 * {@link OnCreateContextMenuListener} to add items to the context menu.
4987 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004988 * @param menu The context menu to populate
4989 */
4990 public void createContextMenu(ContextMenu menu) {
4991 ContextMenuInfo menuInfo = getContextMenuInfo();
4992
4993 // Sets the current menu info so all items added to menu will have
4994 // my extra info set.
4995 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4996
4997 onCreateContextMenu(menu);
4998 if (mOnCreateContextMenuListener != null) {
4999 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
5000 }
5001
5002 // Clear the extra information so subsequent items that aren't mine don't
5003 // have my extra info.
5004 ((MenuBuilder)menu).setCurrentMenuInfo(null);
5005
5006 if (mParent != null) {
5007 mParent.createContextMenu(menu);
5008 }
5009 }
5010
5011 /**
5012 * Views should implement this if they have extra information to associate
5013 * with the context menu. The return result is supplied as a parameter to
5014 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
5015 * callback.
5016 *
5017 * @return Extra information about the item for which the context menu
5018 * should be shown. This information will vary across different
5019 * subclasses of View.
5020 */
5021 protected ContextMenuInfo getContextMenuInfo() {
5022 return null;
5023 }
5024
5025 /**
5026 * Views should implement this if the view itself is going to add items to
5027 * the context menu.
5028 *
5029 * @param menu the context menu to populate
5030 */
5031 protected void onCreateContextMenu(ContextMenu menu) {
5032 }
5033
5034 /**
5035 * Implement this method to handle trackball motion events. The
5036 * <em>relative</em> movement of the trackball since the last event
5037 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
5038 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
5039 * that a movement of 1 corresponds to the user pressing one DPAD key (so
5040 * they will often be fractional values, representing the more fine-grained
5041 * movement information available from a trackball).
5042 *
5043 * @param event The motion event.
5044 * @return True if the event was handled, false otherwise.
5045 */
5046 public boolean onTrackballEvent(MotionEvent event) {
5047 return false;
5048 }
5049
5050 /**
Jeff Browncb1404e2011-01-15 18:14:15 -08005051 * Implement this method to handle generic motion events.
5052 * <p>
5053 * Generic motion events are dispatched to the focused view to describe
5054 * the motions of input devices such as joysticks. The
5055 * {@link MotionEvent#getSource() source} of the motion event specifies
5056 * the class of input that was received. Implementations of this method
5057 * must examine the bits in the source before processing the event.
5058 * The following code example shows how this is done.
5059 * </p>
5060 * <code>
5061 * public boolean onGenericMotionEvent(MotionEvent event) {
5062 * if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
5063 * float x = event.getX();
5064 * float y = event.getY();
5065 * // process the joystick motion
5066 * return true;
5067 * }
5068 * return super.onGenericMotionEvent(event);
5069 * }
5070 * </code>
5071 *
5072 * @param event The generic motion event being processed.
5073 *
5074 * @return Return true if you have consumed the event, false if you haven't.
5075 * The default implementation always returns false.
5076 */
5077 public boolean onGenericMotionEvent(MotionEvent event) {
5078 return false;
5079 }
5080
5081 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005082 * Implement this method to handle touch screen motion events.
5083 *
5084 * @param event The motion event.
5085 * @return True if the event was handled, false otherwise.
5086 */
5087 public boolean onTouchEvent(MotionEvent event) {
5088 final int viewFlags = mViewFlags;
5089
5090 if ((viewFlags & ENABLED_MASK) == DISABLED) {
5091 // A disabled view that is clickable still consumes the touch
5092 // events, it just doesn't respond to them.
5093 return (((viewFlags & CLICKABLE) == CLICKABLE ||
5094 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
5095 }
5096
5097 if (mTouchDelegate != null) {
5098 if (mTouchDelegate.onTouchEvent(event)) {
5099 return true;
5100 }
5101 }
5102
5103 if (((viewFlags & CLICKABLE) == CLICKABLE ||
5104 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
5105 switch (event.getAction()) {
5106 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08005107 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
5108 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 // take focus if we don't have it already and we should in
5110 // touch mode.
5111 boolean focusTaken = false;
5112 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
5113 focusTaken = requestFocus();
5114 }
5115
Dianne Hackbornbe1f6222011-01-20 15:24:28 -08005116 if (prepressed) {
5117 // The button is being released before we actually
5118 // showed it as pressed. Make it show the pressed
5119 // state now (before scheduling the click) to ensure
5120 // the user sees it.
5121 mPrivateFlags |= PRESSED;
5122 refreshDrawableState();
5123 }
5124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 if (!mHasPerformedLongPress) {
5126 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05005127 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128
5129 // Only perform take click actions if we were in the pressed state
5130 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08005131 // Use a Runnable and post this rather than calling
5132 // performClick directly. This lets other visual state
5133 // of the view update before click actions start.
5134 if (mPerformClick == null) {
5135 mPerformClick = new PerformClick();
5136 }
5137 if (!post(mPerformClick)) {
5138 performClick();
5139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005140 }
5141 }
5142
5143 if (mUnsetPressedState == null) {
5144 mUnsetPressedState = new UnsetPressedState();
5145 }
5146
Adam Powelle14579b2009-12-16 18:39:52 -08005147 if (prepressed) {
Adam Powelle14579b2009-12-16 18:39:52 -08005148 postDelayed(mUnsetPressedState,
5149 ViewConfiguration.getPressedStateDuration());
5150 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005151 // If the post failed, unpress right now
5152 mUnsetPressedState.run();
5153 }
Adam Powelle14579b2009-12-16 18:39:52 -08005154 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005155 }
5156 break;
5157
5158 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08005159 if (mPendingCheckForTap == null) {
5160 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005161 }
Adam Powelle14579b2009-12-16 18:39:52 -08005162 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08005163 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08005164 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005165 break;
5166
5167 case MotionEvent.ACTION_CANCEL:
5168 mPrivateFlags &= ~PRESSED;
5169 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08005170 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005171 break;
5172
5173 case MotionEvent.ACTION_MOVE:
5174 final int x = (int) event.getX();
5175 final int y = (int) event.getY();
5176
5177 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07005178 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08005180 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005181 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08005182 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05005183 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005184
5185 // Need to switch from pressed to not pressed
5186 mPrivateFlags &= ~PRESSED;
5187 refreshDrawableState();
5188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005189 }
5190 break;
5191 }
5192 return true;
5193 }
5194
5195 return false;
5196 }
5197
5198 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05005199 * Remove the longpress detection timer.
5200 */
5201 private void removeLongPressCallback() {
5202 if (mPendingCheckForLongPress != null) {
5203 removeCallbacks(mPendingCheckForLongPress);
5204 }
5205 }
Adam Powell3cb8b632011-01-21 15:34:14 -08005206
5207 /**
5208 * Remove the pending click action
5209 */
5210 private void removePerformClickCallback() {
5211 if (mPerformClick != null) {
5212 removeCallbacks(mPerformClick);
5213 }
5214 }
5215
Adam Powelle14579b2009-12-16 18:39:52 -08005216 /**
Romain Guya440b002010-02-24 15:57:54 -08005217 * Remove the prepress detection timer.
5218 */
5219 private void removeUnsetPressCallback() {
5220 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
5221 setPressed(false);
5222 removeCallbacks(mUnsetPressedState);
5223 }
5224 }
5225
5226 /**
Adam Powelle14579b2009-12-16 18:39:52 -08005227 * Remove the tap detection timer.
5228 */
5229 private void removeTapCallback() {
5230 if (mPendingCheckForTap != null) {
5231 mPrivateFlags &= ~PREPRESSED;
5232 removeCallbacks(mPendingCheckForTap);
5233 }
5234 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05005235
5236 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005237 * Cancels a pending long press. Your subclass can use this if you
5238 * want the context menu to come up if the user presses and holds
5239 * at the same place, but you don't want it to come up if they press
5240 * and then move around enough to cause scrolling.
5241 */
5242 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05005243 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08005244
5245 /*
5246 * The prepressed state handled by the tap callback is a display
5247 * construct, but the tap callback will post a long press callback
5248 * less its own timeout. Remove it here.
5249 */
5250 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005251 }
5252
5253 /**
5254 * Sets the TouchDelegate for this View.
5255 */
5256 public void setTouchDelegate(TouchDelegate delegate) {
5257 mTouchDelegate = delegate;
5258 }
5259
5260 /**
5261 * Gets the TouchDelegate for this View.
5262 */
5263 public TouchDelegate getTouchDelegate() {
5264 return mTouchDelegate;
5265 }
5266
5267 /**
5268 * Set flags controlling behavior of this view.
5269 *
5270 * @param flags Constant indicating the value which should be set
5271 * @param mask Constant indicating the bit range that should be changed
5272 */
5273 void setFlags(int flags, int mask) {
5274 int old = mViewFlags;
5275 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
5276
5277 int changed = mViewFlags ^ old;
5278 if (changed == 0) {
5279 return;
5280 }
5281 int privateFlags = mPrivateFlags;
5282
5283 /* Check if the FOCUSABLE bit has changed */
5284 if (((changed & FOCUSABLE_MASK) != 0) &&
5285 ((privateFlags & HAS_BOUNDS) !=0)) {
5286 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
5287 && ((privateFlags & FOCUSED) != 0)) {
5288 /* Give up focus if we are no longer focusable */
5289 clearFocus();
5290 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
5291 && ((privateFlags & FOCUSED) == 0)) {
5292 /*
5293 * Tell the view system that we are now available to take focus
5294 * if no one else already has it.
5295 */
5296 if (mParent != null) mParent.focusableViewAvailable(this);
5297 }
5298 }
5299
5300 if ((flags & VISIBILITY_MASK) == VISIBLE) {
5301 if ((changed & VISIBILITY_MASK) != 0) {
5302 /*
5303 * If this view is becoming visible, set the DRAWN flag so that
5304 * the next invalidate() will not be skipped.
5305 */
5306 mPrivateFlags |= DRAWN;
5307
5308 needGlobalAttributesUpdate(true);
5309
5310 // a view becoming visible is worth notifying the parent
5311 // about in case nothing has focus. even if this specific view
5312 // isn't focusable, it may contain something that is, so let
5313 // the root view try to give this focus if nothing else does.
5314 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
5315 mParent.focusableViewAvailable(this);
5316 }
5317 }
5318 }
5319
5320 /* Check if the GONE bit has changed */
5321 if ((changed & GONE) != 0) {
5322 needGlobalAttributesUpdate(false);
5323 requestLayout();
Romain Guy0fd89bf2011-01-26 15:41:30 -08005324 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005325
Romain Guyecd80ee2009-12-03 17:13:02 -08005326 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5327 if (hasFocus()) clearFocus();
5328 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005329 }
5330 if (mAttachInfo != null) {
5331 mAttachInfo.mViewVisibilityChanged = true;
5332 }
5333 }
5334
5335 /* Check if the VISIBLE bit has changed */
5336 if ((changed & INVISIBLE) != 0) {
5337 needGlobalAttributesUpdate(false);
Romain Guy0fd89bf2011-01-26 15:41:30 -08005338 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005339
5340 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5341 // root view becoming invisible shouldn't clear focus
5342 if (getRootView() != this) {
5343 clearFocus();
5344 }
5345 }
5346 if (mAttachInfo != null) {
5347 mAttachInfo.mViewVisibilityChanged = true;
5348 }
5349 }
5350
Adam Powell326d8082009-12-09 15:10:07 -08005351 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07005352 if (mParent instanceof ViewGroup) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005353 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
5354 ((View) mParent).invalidate(true);
Chet Haase5e25c2c2010-09-16 11:15:56 -07005355 }
Adam Powell326d8082009-12-09 15:10:07 -08005356 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5357 }
5358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005359 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5360 destroyDrawingCache();
5361 }
5362
5363 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5364 destroyDrawingCache();
5365 mPrivateFlags &= ~DRAWING_CACHE_VALID;
Romain Guy0fd89bf2011-01-26 15:41:30 -08005366 invalidateParentCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367 }
5368
5369 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5370 destroyDrawingCache();
5371 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5372 }
5373
5374 if ((changed & DRAW_MASK) != 0) {
5375 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5376 if (mBGDrawable != null) {
5377 mPrivateFlags &= ~SKIP_DRAW;
5378 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5379 } else {
5380 mPrivateFlags |= SKIP_DRAW;
5381 }
5382 } else {
5383 mPrivateFlags &= ~SKIP_DRAW;
5384 }
5385 requestLayout();
Romain Guy0fd89bf2011-01-26 15:41:30 -08005386 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 }
5388
5389 if ((changed & KEEP_SCREEN_ON) != 0) {
Joe Onorato664644d2011-01-23 17:53:23 -08005390 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005391 mParent.recomputeViewAttributes(this);
5392 }
5393 }
5394 }
5395
5396 /**
5397 * Change the view's z order in the tree, so it's on top of other sibling
5398 * views
5399 */
5400 public void bringToFront() {
5401 if (mParent != null) {
5402 mParent.bringChildToFront(this);
5403 }
5404 }
5405
5406 /**
5407 * This is called in response to an internal scroll in this view (i.e., the
5408 * view scrolled its own contents). This is typically as a result of
5409 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5410 * called.
5411 *
5412 * @param l Current horizontal scroll origin.
5413 * @param t Current vertical scroll origin.
5414 * @param oldl Previous horizontal scroll origin.
5415 * @param oldt Previous vertical scroll origin.
5416 */
5417 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5418 mBackgroundSizeChanged = true;
5419
5420 final AttachInfo ai = mAttachInfo;
5421 if (ai != null) {
5422 ai.mViewScrollChanged = true;
5423 }
5424 }
5425
5426 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005427 * Interface definition for a callback to be invoked when the layout bounds of a view
5428 * changes due to layout processing.
5429 */
5430 public interface OnLayoutChangeListener {
5431 /**
5432 * Called when the focus state of a view has changed.
5433 *
5434 * @param v The view whose state has changed.
5435 * @param left The new value of the view's left property.
5436 * @param top The new value of the view's top property.
5437 * @param right The new value of the view's right property.
5438 * @param bottom The new value of the view's bottom property.
5439 * @param oldLeft The previous value of the view's left property.
5440 * @param oldTop The previous value of the view's top property.
5441 * @param oldRight The previous value of the view's right property.
5442 * @param oldBottom The previous value of the view's bottom property.
5443 */
5444 void onLayoutChange(View v, int left, int top, int right, int bottom,
5445 int oldLeft, int oldTop, int oldRight, int oldBottom);
5446 }
5447
5448 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005449 * This is called during layout when the size of this view has changed. If
5450 * you were just added to the view hierarchy, you're called with the old
5451 * values of 0.
5452 *
5453 * @param w Current width of this view.
5454 * @param h Current height of this view.
5455 * @param oldw Old width of this view.
5456 * @param oldh Old height of this view.
5457 */
5458 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5459 }
5460
5461 /**
5462 * Called by draw to draw the child views. This may be overridden
5463 * by derived classes to gain control just before its children are drawn
5464 * (but after its own view has been drawn).
5465 * @param canvas the canvas on which to draw the view
5466 */
5467 protected void dispatchDraw(Canvas canvas) {
5468 }
5469
5470 /**
5471 * Gets the parent of this view. Note that the parent is a
5472 * ViewParent and not necessarily a View.
5473 *
5474 * @return Parent of this view.
5475 */
5476 public final ViewParent getParent() {
5477 return mParent;
5478 }
5479
5480 /**
5481 * Return the scrolled left position of this view. This is the left edge of
5482 * the displayed part of your view. You do not need to draw any pixels
5483 * farther left, since those are outside of the frame of your view on
5484 * screen.
5485 *
5486 * @return The left edge of the displayed part of your view, in pixels.
5487 */
5488 public final int getScrollX() {
5489 return mScrollX;
5490 }
5491
5492 /**
5493 * Return the scrolled top position of this view. This is the top edge of
5494 * the displayed part of your view. You do not need to draw any pixels above
5495 * it, since those are outside of the frame of your view on screen.
5496 *
5497 * @return The top edge of the displayed part of your view, in pixels.
5498 */
5499 public final int getScrollY() {
5500 return mScrollY;
5501 }
5502
5503 /**
5504 * Return the width of the your view.
5505 *
5506 * @return The width of your view, in pixels.
5507 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005508 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 public final int getWidth() {
5510 return mRight - mLeft;
5511 }
5512
5513 /**
5514 * Return the height of your view.
5515 *
5516 * @return The height of your view, in pixels.
5517 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005518 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 public final int getHeight() {
5520 return mBottom - mTop;
5521 }
5522
5523 /**
5524 * Return the visible drawing bounds of your view. Fills in the output
5525 * rectangle with the values from getScrollX(), getScrollY(),
5526 * getWidth(), and getHeight().
5527 *
5528 * @param outRect The (scrolled) drawing bounds of the view.
5529 */
5530 public void getDrawingRect(Rect outRect) {
5531 outRect.left = mScrollX;
5532 outRect.top = mScrollY;
5533 outRect.right = mScrollX + (mRight - mLeft);
5534 outRect.bottom = mScrollY + (mBottom - mTop);
5535 }
5536
5537 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005538 * Like {@link #getMeasuredWidthAndState()}, but only returns the
5539 * raw width component (that is the result is masked by
5540 * {@link #MEASURED_SIZE_MASK}).
5541 *
5542 * @return The raw measured width of this view.
5543 */
5544 public final int getMeasuredWidth() {
5545 return mMeasuredWidth & MEASURED_SIZE_MASK;
5546 }
5547
5548 /**
5549 * Return the full width measurement information for this view as computed
5550 * by the most recent call to {@link #measure}. This result is a bit mask
5551 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005552 * This should be used during measurement and layout calculations only. Use
5553 * {@link #getWidth()} to see how wide a view is after layout.
5554 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005555 * @return The measured width of this view as a bit mask.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08005557 public final int getMeasuredWidthAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 return mMeasuredWidth;
5559 }
5560
5561 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005562 * Like {@link #getMeasuredHeightAndState()}, but only returns the
5563 * raw width component (that is the result is masked by
5564 * {@link #MEASURED_SIZE_MASK}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005566 * @return The raw measured height of this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 */
5568 public final int getMeasuredHeight() {
Dianne Hackborn189ee182010-12-02 21:48:53 -08005569 return mMeasuredHeight & MEASURED_SIZE_MASK;
5570 }
5571
5572 /**
5573 * Return the full height measurement information for this view as computed
5574 * by the most recent call to {@link #measure}. This result is a bit mask
5575 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5576 * This should be used during measurement and layout calculations only. Use
5577 * {@link #getHeight()} to see how wide a view is after layout.
5578 *
5579 * @return The measured width of this view as a bit mask.
5580 */
5581 public final int getMeasuredHeightAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 return mMeasuredHeight;
5583 }
5584
5585 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005586 * Return only the state bits of {@link #getMeasuredWidthAndState()}
5587 * and {@link #getMeasuredHeightAndState()}, combined into one integer.
5588 * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
5589 * and the height component is at the shifted bits
5590 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
5591 */
5592 public final int getMeasuredState() {
5593 return (mMeasuredWidth&MEASURED_STATE_MASK)
5594 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
5595 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
5596 }
5597
5598 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005599 * The transform matrix of this view, which is calculated based on the current
5600 * roation, scale, and pivot properties.
5601 *
5602 * @see #getRotation()
5603 * @see #getScaleX()
5604 * @see #getScaleY()
5605 * @see #getPivotX()
5606 * @see #getPivotY()
5607 * @return The current transform matrix for the view
5608 */
5609 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005610 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005611 return mMatrix;
5612 }
5613
5614 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005615 * Utility function to determine if the value is far enough away from zero to be
5616 * considered non-zero.
5617 * @param value A floating point value to check for zero-ness
5618 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5619 */
5620 private static boolean nonzero(float value) {
5621 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5622 }
5623
5624 /**
Jeff Brown86671742010-09-30 20:00:15 -07005625 * Returns true if the transform matrix is the identity matrix.
5626 * Recomputes the matrix if necessary.
Romain Guy33e72ae2010-07-17 12:40:29 -07005627 *
5628 * @return True if the transform matrix is the identity matrix, false otherwise.
5629 */
Jeff Brown86671742010-09-30 20:00:15 -07005630 final boolean hasIdentityMatrix() {
5631 updateMatrix();
5632 return mMatrixIsIdentity;
5633 }
5634
5635 /**
5636 * Recomputes the transform matrix if necessary.
5637 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005638 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005639 if (mMatrixDirty) {
5640 // transform-related properties have changed since the last time someone
5641 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005642
5643 // Figure out if we need to update the pivot point
5644 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005645 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005646 mPrevWidth = mRight - mLeft;
5647 mPrevHeight = mBottom - mTop;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -08005648 mPivotX = mPrevWidth / 2f;
5649 mPivotY = mPrevHeight / 2f;
Chet Haasefd2b0022010-08-06 13:08:56 -07005650 }
5651 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005652 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005653 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5654 mMatrix.setTranslate(mTranslationX, mTranslationY);
5655 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5656 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5657 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005658 if (mCamera == null) {
5659 mCamera = new Camera();
5660 matrix3D = new Matrix();
5661 }
5662 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005663 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005664 mCamera.rotateX(mRotationX);
5665 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005666 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005667 mCamera.getMatrix(matrix3D);
5668 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005669 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005670 mMatrix.postConcat(matrix3D);
5671 mCamera.restore();
5672 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005673 mMatrixDirty = false;
5674 mMatrixIsIdentity = mMatrix.isIdentity();
5675 mInverseMatrixDirty = true;
5676 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005677 }
5678
5679 /**
5680 * Utility method to retrieve the inverse of the current mMatrix property.
5681 * We cache the matrix to avoid recalculating it when transform properties
5682 * have not changed.
5683 *
5684 * @return The inverse of the current matrix of this view.
5685 */
Jeff Brown86671742010-09-30 20:00:15 -07005686 final Matrix getInverseMatrix() {
5687 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005688 if (mInverseMatrixDirty) {
5689 if (mInverseMatrix == null) {
5690 mInverseMatrix = new Matrix();
5691 }
5692 mMatrix.invert(mInverseMatrix);
5693 mInverseMatrixDirty = false;
5694 }
5695 return mInverseMatrix;
5696 }
5697
5698 /**
5699 * The degrees that the view is rotated around the pivot point.
5700 *
5701 * @see #getPivotX()
5702 * @see #getPivotY()
5703 * @return The degrees of rotation.
5704 */
5705 public float getRotation() {
5706 return mRotation;
5707 }
5708
5709 /**
Chet Haase897247b2010-09-09 14:54:47 -07005710 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5711 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005712 *
5713 * @param rotation The degrees of rotation.
5714 * @see #getPivotX()
5715 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005716 *
5717 * @attr ref android.R.styleable#View_rotation
Chet Haasec3aa3612010-06-17 08:50:37 -07005718 */
5719 public void setRotation(float rotation) {
5720 if (mRotation != rotation) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005721 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005722 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005723 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005724 mRotation = rotation;
5725 mMatrixDirty = true;
5726 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005727 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005728 }
5729 }
5730
5731 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005732 * The degrees that the view is rotated around the vertical axis through the pivot point.
5733 *
5734 * @see #getPivotX()
5735 * @see #getPivotY()
5736 * @return The degrees of Y rotation.
5737 */
5738 public float getRotationY() {
5739 return mRotationY;
5740 }
5741
5742 /**
Chet Haase897247b2010-09-09 14:54:47 -07005743 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5744 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5745 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005746 *
5747 * @param rotationY The degrees of Y rotation.
5748 * @see #getPivotX()
5749 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005750 *
5751 * @attr ref android.R.styleable#View_rotationY
Chet Haasefd2b0022010-08-06 13:08:56 -07005752 */
5753 public void setRotationY(float rotationY) {
5754 if (mRotationY != rotationY) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005755 invalidateParentCaches();
Chet Haasefd2b0022010-08-06 13:08:56 -07005756 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005757 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005758 mRotationY = rotationY;
5759 mMatrixDirty = true;
5760 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005761 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005762 }
5763 }
5764
5765 /**
5766 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5767 *
5768 * @see #getPivotX()
5769 * @see #getPivotY()
5770 * @return The degrees of X rotation.
5771 */
5772 public float getRotationX() {
5773 return mRotationX;
5774 }
5775
5776 /**
Chet Haase897247b2010-09-09 14:54:47 -07005777 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5778 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5779 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005780 *
5781 * @param rotationX The degrees of X rotation.
5782 * @see #getPivotX()
5783 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005784 *
5785 * @attr ref android.R.styleable#View_rotationX
Chet Haasefd2b0022010-08-06 13:08:56 -07005786 */
5787 public void setRotationX(float rotationX) {
5788 if (mRotationX != rotationX) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005789 invalidateParentCaches();
Chet Haasefd2b0022010-08-06 13:08:56 -07005790 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005791 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005792 mRotationX = rotationX;
5793 mMatrixDirty = true;
5794 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005795 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005796 }
5797 }
5798
5799 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005800 * The amount that the view is scaled in x around the pivot point, as a proportion of
5801 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5802 *
Joe Onorato93162322010-09-16 15:42:01 -04005803 * <p>By default, this is 1.0f.
5804 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005805 * @see #getPivotX()
5806 * @see #getPivotY()
5807 * @return The scaling factor.
5808 */
5809 public float getScaleX() {
5810 return mScaleX;
5811 }
5812
5813 /**
5814 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5815 * the view's unscaled width. A value of 1 means that no scaling is applied.
5816 *
5817 * @param scaleX The scaling factor.
5818 * @see #getPivotX()
5819 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005820 *
5821 * @attr ref android.R.styleable#View_scaleX
Chet Haasec3aa3612010-06-17 08:50:37 -07005822 */
5823 public void setScaleX(float scaleX) {
5824 if (mScaleX != scaleX) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005825 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005826 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005827 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005828 mScaleX = scaleX;
5829 mMatrixDirty = true;
5830 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005831 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005832 }
5833 }
5834
5835 /**
5836 * The amount that the view is scaled in y around the pivot point, as a proportion of
5837 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5838 *
Joe Onorato93162322010-09-16 15:42:01 -04005839 * <p>By default, this is 1.0f.
5840 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005841 * @see #getPivotX()
5842 * @see #getPivotY()
5843 * @return The scaling factor.
5844 */
5845 public float getScaleY() {
5846 return mScaleY;
5847 }
5848
5849 /**
5850 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5851 * the view's unscaled width. A value of 1 means that no scaling is applied.
5852 *
5853 * @param scaleY The scaling factor.
5854 * @see #getPivotX()
5855 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005856 *
5857 * @attr ref android.R.styleable#View_scaleY
Chet Haasec3aa3612010-06-17 08:50:37 -07005858 */
5859 public void setScaleY(float scaleY) {
5860 if (mScaleY != scaleY) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005861 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005862 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005863 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005864 mScaleY = scaleY;
5865 mMatrixDirty = true;
5866 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005867 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005868 }
5869 }
5870
5871 /**
5872 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5873 * and {@link #setScaleX(float) scaled}.
5874 *
5875 * @see #getRotation()
5876 * @see #getScaleX()
5877 * @see #getScaleY()
5878 * @see #getPivotY()
5879 * @return The x location of the pivot point.
5880 */
5881 public float getPivotX() {
5882 return mPivotX;
5883 }
5884
5885 /**
5886 * Sets the x location of the point around which the view is
5887 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005888 * By default, the pivot point is centered on the object.
5889 * Setting this property disables this behavior and causes the view to use only the
5890 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005891 *
5892 * @param pivotX The x location of the pivot point.
5893 * @see #getRotation()
5894 * @see #getScaleX()
5895 * @see #getScaleY()
5896 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005897 *
5898 * @attr ref android.R.styleable#View_transformPivotX
Chet Haasec3aa3612010-06-17 08:50:37 -07005899 */
5900 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005901 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005902 if (mPivotX != pivotX) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005903 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005904 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005905 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005906 mPivotX = pivotX;
5907 mMatrixDirty = true;
5908 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005909 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005910 }
5911 }
5912
5913 /**
5914 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5915 * and {@link #setScaleY(float) scaled}.
5916 *
5917 * @see #getRotation()
5918 * @see #getScaleX()
5919 * @see #getScaleY()
5920 * @see #getPivotY()
5921 * @return The y location of the pivot point.
5922 */
5923 public float getPivotY() {
5924 return mPivotY;
5925 }
5926
5927 /**
5928 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005929 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5930 * Setting this property disables this behavior and causes the view to use only the
5931 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005932 *
5933 * @param pivotY The y location of the pivot point.
5934 * @see #getRotation()
5935 * @see #getScaleX()
5936 * @see #getScaleY()
5937 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005938 *
5939 * @attr ref android.R.styleable#View_transformPivotY
Chet Haasec3aa3612010-06-17 08:50:37 -07005940 */
5941 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005942 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005943 if (mPivotY != pivotY) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005944 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005945 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005946 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005947 mPivotY = pivotY;
5948 mMatrixDirty = true;
5949 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005950 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005951 }
5952 }
5953
5954 /**
5955 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5956 * completely transparent and 1 means the view is completely opaque.
5957 *
Joe Onorato93162322010-09-16 15:42:01 -04005958 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005959 * @return The opacity of the view.
5960 */
5961 public float getAlpha() {
5962 return mAlpha;
5963 }
5964
5965 /**
Romain Guy171c5922011-01-06 10:04:23 -08005966 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5967 * completely transparent and 1 means the view is completely opaque.</p>
5968 *
5969 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
5970 * responsible for applying the opacity itself. Otherwise, calling this method is
5971 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
5972 * setting a hardware layer.</p>
Chet Haasec3aa3612010-06-17 08:50:37 -07005973 *
5974 * @param alpha The opacity of the view.
Chet Haase73066682010-11-29 15:55:32 -08005975 *
Romain Guy171c5922011-01-06 10:04:23 -08005976 * @see #setLayerType(int, android.graphics.Paint)
5977 *
Chet Haase73066682010-11-29 15:55:32 -08005978 * @attr ref android.R.styleable#View_alpha
Chet Haasec3aa3612010-06-17 08:50:37 -07005979 */
5980 public void setAlpha(float alpha) {
5981 mAlpha = alpha;
Romain Guy0fd89bf2011-01-26 15:41:30 -08005982 invalidateParentCaches();
Chet Haaseed032702010-10-01 14:05:54 -07005983 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07005984 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005985 // subclass is handling alpha - don't optimize rendering cache invalidation
Romain Guy0fd89bf2011-01-26 15:41:30 -08005986 invalidate(true);
Chet Haaseed032702010-10-01 14:05:54 -07005987 } else {
Romain Guya3496a92010-10-12 11:53:24 -07005988 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005989 invalidate(false);
5990 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005991 }
5992
5993 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 * Top position of this view relative to its parent.
5995 *
5996 * @return The top of this view, in pixels.
5997 */
5998 @ViewDebug.CapturedViewProperty
5999 public final int getTop() {
6000 return mTop;
6001 }
6002
6003 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006004 * Sets the top position of this view relative to its parent. This method is meant to be called
6005 * by the layout system and should not generally be called otherwise, because the property
6006 * may be changed at any time by the layout.
6007 *
6008 * @param top The top of this view, in pixels.
6009 */
6010 public final void setTop(int top) {
6011 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07006012 updateMatrix();
6013 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006014 final ViewParent p = mParent;
6015 if (p != null && mAttachInfo != null) {
6016 final Rect r = mAttachInfo.mTmpInvalRect;
6017 int minTop;
6018 int yLoc;
6019 if (top < mTop) {
6020 minTop = top;
6021 yLoc = top - mTop;
6022 } else {
6023 minTop = mTop;
6024 yLoc = 0;
6025 }
6026 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
6027 p.invalidateChild(this, r);
6028 }
6029 } else {
6030 // Double-invalidation is necessary to capture view's old and new areas
Romain Guy0fd89bf2011-01-26 15:41:30 -08006031 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006032 }
6033
Chet Haaseed032702010-10-01 14:05:54 -07006034 int width = mRight - mLeft;
6035 int oldHeight = mBottom - mTop;
6036
Chet Haase21cd1382010-09-01 17:42:29 -07006037 mTop = top;
6038
Chet Haaseed032702010-10-01 14:05:54 -07006039 onSizeChanged(width, mBottom - mTop, width, oldHeight);
6040
Chet Haase21cd1382010-09-01 17:42:29 -07006041 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006042 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6043 // A change in dimension means an auto-centered pivot point changes, too
6044 mMatrixDirty = true;
6045 }
Chet Haase21cd1382010-09-01 17:42:29 -07006046 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006047 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006048 }
Chet Haase55dbb652010-12-21 20:15:08 -08006049 mBackgroundSizeChanged = true;
Chet Haase678e0ad2011-01-25 09:37:18 -08006050 invalidateParentIfNeeded();
Chet Haase21cd1382010-09-01 17:42:29 -07006051 }
6052 }
6053
6054 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 * Bottom position of this view relative to its parent.
6056 *
6057 * @return The bottom of this view, in pixels.
6058 */
6059 @ViewDebug.CapturedViewProperty
6060 public final int getBottom() {
6061 return mBottom;
6062 }
6063
6064 /**
Michael Jurkadab559a2011-01-04 20:31:51 -08006065 * True if this view has changed since the last time being drawn.
6066 *
6067 * @return The dirty state of this view.
6068 */
6069 public boolean isDirty() {
6070 return (mPrivateFlags & DIRTY_MASK) != 0;
6071 }
6072
6073 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006074 * Sets the bottom position of this view relative to its parent. This method is meant to be
6075 * called by the layout system and should not generally be called otherwise, because the
6076 * property may be changed at any time by the layout.
6077 *
6078 * @param bottom The bottom of this view, in pixels.
6079 */
6080 public final void setBottom(int bottom) {
6081 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07006082 updateMatrix();
6083 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006084 final ViewParent p = mParent;
6085 if (p != null && mAttachInfo != null) {
6086 final Rect r = mAttachInfo.mTmpInvalRect;
6087 int maxBottom;
6088 if (bottom < mBottom) {
6089 maxBottom = mBottom;
6090 } else {
6091 maxBottom = bottom;
6092 }
6093 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
6094 p.invalidateChild(this, r);
6095 }
6096 } else {
6097 // Double-invalidation is necessary to capture view's old and new areas
Romain Guy0fd89bf2011-01-26 15:41:30 -08006098 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006099 }
6100
Chet Haaseed032702010-10-01 14:05:54 -07006101 int width = mRight - mLeft;
6102 int oldHeight = mBottom - mTop;
6103
Chet Haase21cd1382010-09-01 17:42:29 -07006104 mBottom = bottom;
6105
Chet Haaseed032702010-10-01 14:05:54 -07006106 onSizeChanged(width, mBottom - mTop, width, oldHeight);
6107
Chet Haase21cd1382010-09-01 17:42:29 -07006108 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006109 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6110 // A change in dimension means an auto-centered pivot point changes, too
6111 mMatrixDirty = true;
6112 }
Chet Haase21cd1382010-09-01 17:42:29 -07006113 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006114 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006115 }
Chet Haase55dbb652010-12-21 20:15:08 -08006116 mBackgroundSizeChanged = true;
Chet Haase678e0ad2011-01-25 09:37:18 -08006117 invalidateParentIfNeeded();
Chet Haase21cd1382010-09-01 17:42:29 -07006118 }
6119 }
6120
6121 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 * Left position of this view relative to its parent.
6123 *
6124 * @return The left edge of this view, in pixels.
6125 */
6126 @ViewDebug.CapturedViewProperty
6127 public final int getLeft() {
6128 return mLeft;
6129 }
6130
6131 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006132 * Sets the left position of this view relative to its parent. This method is meant to be called
6133 * by the layout system and should not generally be called otherwise, because the property
6134 * may be changed at any time by the layout.
6135 *
6136 * @param left The bottom of this view, in pixels.
6137 */
6138 public final void setLeft(int left) {
6139 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07006140 updateMatrix();
6141 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006142 final ViewParent p = mParent;
6143 if (p != null && mAttachInfo != null) {
6144 final Rect r = mAttachInfo.mTmpInvalRect;
6145 int minLeft;
6146 int xLoc;
6147 if (left < mLeft) {
6148 minLeft = left;
6149 xLoc = left - mLeft;
6150 } else {
6151 minLeft = mLeft;
6152 xLoc = 0;
6153 }
6154 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
6155 p.invalidateChild(this, r);
6156 }
6157 } else {
6158 // Double-invalidation is necessary to capture view's old and new areas
Romain Guy0fd89bf2011-01-26 15:41:30 -08006159 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006160 }
6161
Chet Haaseed032702010-10-01 14:05:54 -07006162 int oldWidth = mRight - mLeft;
6163 int height = mBottom - mTop;
6164
Chet Haase21cd1382010-09-01 17:42:29 -07006165 mLeft = left;
6166
Chet Haaseed032702010-10-01 14:05:54 -07006167 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6168
Chet Haase21cd1382010-09-01 17:42:29 -07006169 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006170 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6171 // A change in dimension means an auto-centered pivot point changes, too
6172 mMatrixDirty = true;
6173 }
Chet Haase21cd1382010-09-01 17:42:29 -07006174 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006175 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006176 }
Chet Haase55dbb652010-12-21 20:15:08 -08006177 mBackgroundSizeChanged = true;
Chet Haase678e0ad2011-01-25 09:37:18 -08006178 invalidateParentIfNeeded();
Chet Haase21cd1382010-09-01 17:42:29 -07006179 }
6180 }
6181
6182 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183 * Right position of this view relative to its parent.
6184 *
6185 * @return The right edge of this view, in pixels.
6186 */
6187 @ViewDebug.CapturedViewProperty
6188 public final int getRight() {
6189 return mRight;
6190 }
6191
6192 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006193 * Sets the right position of this view relative to its parent. This method is meant to be called
6194 * by the layout system and should not generally be called otherwise, because the property
6195 * may be changed at any time by the layout.
6196 *
6197 * @param right The bottom of this view, in pixels.
6198 */
6199 public final void setRight(int right) {
6200 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07006201 updateMatrix();
6202 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006203 final ViewParent p = mParent;
6204 if (p != null && mAttachInfo != null) {
6205 final Rect r = mAttachInfo.mTmpInvalRect;
6206 int maxRight;
6207 if (right < mRight) {
6208 maxRight = mRight;
6209 } else {
6210 maxRight = right;
6211 }
6212 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
6213 p.invalidateChild(this, r);
6214 }
6215 } else {
6216 // Double-invalidation is necessary to capture view's old and new areas
Romain Guy0fd89bf2011-01-26 15:41:30 -08006217 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006218 }
6219
Chet Haaseed032702010-10-01 14:05:54 -07006220 int oldWidth = mRight - mLeft;
6221 int height = mBottom - mTop;
6222
Chet Haase21cd1382010-09-01 17:42:29 -07006223 mRight = right;
6224
Chet Haaseed032702010-10-01 14:05:54 -07006225 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6226
Chet Haase21cd1382010-09-01 17:42:29 -07006227 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006228 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6229 // A change in dimension means an auto-centered pivot point changes, too
6230 mMatrixDirty = true;
6231 }
Chet Haase21cd1382010-09-01 17:42:29 -07006232 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006233 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006234 }
Chet Haase55dbb652010-12-21 20:15:08 -08006235 mBackgroundSizeChanged = true;
Chet Haase678e0ad2011-01-25 09:37:18 -08006236 invalidateParentIfNeeded();
Chet Haase21cd1382010-09-01 17:42:29 -07006237 }
6238 }
6239
6240 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006241 * The visual x position of this view, in pixels. This is equivalent to the
6242 * {@link #setTranslationX(float) translationX} property plus the current
6243 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07006244 *
Chet Haasedf030d22010-07-30 17:22:38 -07006245 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006246 */
Chet Haasedf030d22010-07-30 17:22:38 -07006247 public float getX() {
6248 return mLeft + mTranslationX;
6249 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006250
Chet Haasedf030d22010-07-30 17:22:38 -07006251 /**
6252 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
6253 * {@link #setTranslationX(float) translationX} property to be the difference between
6254 * the x value passed in and the current {@link #getLeft() left} property.
6255 *
6256 * @param x The visual x position of this view, in pixels.
6257 */
6258 public void setX(float x) {
6259 setTranslationX(x - mLeft);
6260 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006261
Chet Haasedf030d22010-07-30 17:22:38 -07006262 /**
6263 * The visual y position of this view, in pixels. This is equivalent to the
6264 * {@link #setTranslationY(float) translationY} property plus the current
6265 * {@link #getTop() top} property.
6266 *
6267 * @return The visual y position of this view, in pixels.
6268 */
6269 public float getY() {
6270 return mTop + mTranslationY;
6271 }
6272
6273 /**
6274 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
6275 * {@link #setTranslationY(float) translationY} property to be the difference between
6276 * the y value passed in and the current {@link #getTop() top} property.
6277 *
6278 * @param y The visual y position of this view, in pixels.
6279 */
6280 public void setY(float y) {
6281 setTranslationY(y - mTop);
6282 }
6283
6284
6285 /**
6286 * The horizontal location of this view relative to its {@link #getLeft() left} position.
6287 * This position is post-layout, in addition to wherever the object's
6288 * layout placed it.
6289 *
6290 * @return The horizontal position of this view relative to its left position, in pixels.
6291 */
6292 public float getTranslationX() {
6293 return mTranslationX;
6294 }
6295
6296 /**
6297 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
6298 * This effectively positions the object post-layout, in addition to wherever the object's
6299 * layout placed it.
6300 *
6301 * @param translationX The horizontal position of this view relative to its left position,
6302 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006303 *
6304 * @attr ref android.R.styleable#View_translationX
Chet Haasedf030d22010-07-30 17:22:38 -07006305 */
6306 public void setTranslationX(float translationX) {
6307 if (mTranslationX != translationX) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006308 invalidateParentCaches();
Chet Haasedf030d22010-07-30 17:22:38 -07006309 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006310 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006311 mTranslationX = translationX;
6312 mMatrixDirty = true;
6313 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006314 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006315 }
6316 }
6317
6318 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006319 * The horizontal location of this view relative to its {@link #getTop() top} position.
6320 * This position is post-layout, in addition to wherever the object's
6321 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006322 *
Chet Haasedf030d22010-07-30 17:22:38 -07006323 * @return The vertical position of this view relative to its top position,
6324 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006325 */
Chet Haasedf030d22010-07-30 17:22:38 -07006326 public float getTranslationY() {
6327 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07006328 }
6329
6330 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006331 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
6332 * This effectively positions the object post-layout, in addition to wherever the object's
6333 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006334 *
Chet Haasedf030d22010-07-30 17:22:38 -07006335 * @param translationY The vertical position of this view relative to its top position,
6336 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006337 *
6338 * @attr ref android.R.styleable#View_translationY
Chet Haasec3aa3612010-06-17 08:50:37 -07006339 */
Chet Haasedf030d22010-07-30 17:22:38 -07006340 public void setTranslationY(float translationY) {
6341 if (mTranslationY != translationY) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006342 invalidateParentCaches();
Chet Haasedf030d22010-07-30 17:22:38 -07006343 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006344 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006345 mTranslationY = translationY;
6346 mMatrixDirty = true;
6347 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006348 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006349 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006350 }
6351
6352 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 * Hit rectangle in parent's coordinates
6354 *
6355 * @param outRect The hit rectangle of the view.
6356 */
6357 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07006358 updateMatrix();
6359 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006360 outRect.set(mLeft, mTop, mRight, mBottom);
6361 } else {
6362 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07006363 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07006364 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07006365 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
6366 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07006367 }
6368 }
6369
6370 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07006371 * Determines whether the given point, in local coordinates is inside the view.
6372 */
6373 /*package*/ final boolean pointInView(float localX, float localY) {
6374 return localX >= 0 && localX < (mRight - mLeft)
6375 && localY >= 0 && localY < (mBottom - mTop);
6376 }
6377
6378 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07006379 * Utility method to determine whether the given point, in local coordinates,
6380 * is inside the view, where the area of the view is expanded by the slop factor.
6381 * This method is called while processing touch-move events to determine if the event
6382 * is still within the view.
6383 */
6384 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07006385 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07006386 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 }
6388
6389 /**
6390 * When a view has focus and the user navigates away from it, the next view is searched for
6391 * starting from the rectangle filled in by this method.
6392 *
6393 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
6394 * view maintains some idea of internal selection, such as a cursor, or a selected row
6395 * or column, you should override this method and fill in a more specific rectangle.
6396 *
6397 * @param r The rectangle to fill in, in this view's coordinates.
6398 */
6399 public void getFocusedRect(Rect r) {
6400 getDrawingRect(r);
6401 }
6402
6403 /**
6404 * If some part of this view is not clipped by any of its parents, then
6405 * return that area in r in global (root) coordinates. To convert r to local
6406 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
6407 * -globalOffset.y)) If the view is completely clipped or translated out,
6408 * return false.
6409 *
6410 * @param r If true is returned, r holds the global coordinates of the
6411 * visible portion of this view.
6412 * @param globalOffset If true is returned, globalOffset holds the dx,dy
6413 * between this view and its root. globalOffet may be null.
6414 * @return true if r is non-empty (i.e. part of the view is visible at the
6415 * root level.
6416 */
6417 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6418 int width = mRight - mLeft;
6419 int height = mBottom - mTop;
6420 if (width > 0 && height > 0) {
6421 r.set(0, 0, width, height);
6422 if (globalOffset != null) {
6423 globalOffset.set(-mScrollX, -mScrollY);
6424 }
6425 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6426 }
6427 return false;
6428 }
6429
6430 public final boolean getGlobalVisibleRect(Rect r) {
6431 return getGlobalVisibleRect(r, null);
6432 }
6433
6434 public final boolean getLocalVisibleRect(Rect r) {
6435 Point offset = new Point();
6436 if (getGlobalVisibleRect(r, offset)) {
6437 r.offset(-offset.x, -offset.y); // make r local
6438 return true;
6439 }
6440 return false;
6441 }
6442
6443 /**
6444 * Offset this view's vertical location by the specified number of pixels.
6445 *
6446 * @param offset the number of pixels to offset the view by
6447 */
6448 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006449 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006450 updateMatrix();
6451 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006452 final ViewParent p = mParent;
6453 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006454 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006455 int minTop;
6456 int maxBottom;
6457 int yLoc;
6458 if (offset < 0) {
6459 minTop = mTop + offset;
6460 maxBottom = mBottom;
6461 yLoc = offset;
6462 } else {
6463 minTop = mTop;
6464 maxBottom = mBottom + offset;
6465 yLoc = 0;
6466 }
6467 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6468 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006469 }
6470 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006471 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006472 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006473
Chet Haasec3aa3612010-06-17 08:50:37 -07006474 mTop += offset;
6475 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006476
Chet Haasec3aa3612010-06-17 08:50:37 -07006477 if (!mMatrixIsIdentity) {
6478 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006479 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006480 }
Chet Haase678e0ad2011-01-25 09:37:18 -08006481 invalidateParentIfNeeded();
Chet Haasec3aa3612010-06-17 08:50:37 -07006482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 }
6484
6485 /**
6486 * Offset this view's horizontal location by the specified amount of pixels.
6487 *
6488 * @param offset the numer of pixels to offset the view by
6489 */
6490 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006491 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006492 updateMatrix();
6493 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006494 final ViewParent p = mParent;
6495 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006496 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006497 int minLeft;
6498 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006499 if (offset < 0) {
6500 minLeft = mLeft + offset;
6501 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006502 } else {
6503 minLeft = mLeft;
6504 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006505 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006506 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07006507 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006508 }
6509 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006510 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006511 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006512
Chet Haasec3aa3612010-06-17 08:50:37 -07006513 mLeft += offset;
6514 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006515
Chet Haasec3aa3612010-06-17 08:50:37 -07006516 if (!mMatrixIsIdentity) {
6517 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006518 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006519 }
Chet Haase678e0ad2011-01-25 09:37:18 -08006520 invalidateParentIfNeeded();
Chet Haasec3aa3612010-06-17 08:50:37 -07006521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 }
6523
6524 /**
6525 * Get the LayoutParams associated with this view. All views should have
6526 * layout parameters. These supply parameters to the <i>parent</i> of this
6527 * view specifying how it should be arranged. There are many subclasses of
6528 * ViewGroup.LayoutParams, and these correspond to the different subclasses
6529 * of ViewGroup that are responsible for arranging their children.
6530 * @return The LayoutParams associated with this view
6531 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07006532 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 public ViewGroup.LayoutParams getLayoutParams() {
6534 return mLayoutParams;
6535 }
6536
6537 /**
6538 * Set the layout parameters associated with this view. These supply
6539 * parameters to the <i>parent</i> of this view specifying how it should be
6540 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6541 * correspond to the different subclasses of ViewGroup that are responsible
6542 * for arranging their children.
6543 *
6544 * @param params the layout parameters for this view
6545 */
6546 public void setLayoutParams(ViewGroup.LayoutParams params) {
6547 if (params == null) {
6548 throw new NullPointerException("params == null");
6549 }
6550 mLayoutParams = params;
6551 requestLayout();
6552 }
6553
6554 /**
6555 * Set the scrolled position of your view. This will cause a call to
6556 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6557 * invalidated.
6558 * @param x the x position to scroll to
6559 * @param y the y position to scroll to
6560 */
6561 public void scrollTo(int x, int y) {
6562 if (mScrollX != x || mScrollY != y) {
6563 int oldX = mScrollX;
6564 int oldY = mScrollY;
6565 mScrollX = x;
6566 mScrollY = y;
Romain Guy0fd89bf2011-01-26 15:41:30 -08006567 invalidateParentCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006569 if (!awakenScrollBars()) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006570 invalidate(true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 }
6573 }
6574
6575 /**
6576 * Move the scrolled position of your view. This will cause a call to
6577 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6578 * invalidated.
6579 * @param x the amount of pixels to scroll by horizontally
6580 * @param y the amount of pixels to scroll by vertically
6581 */
6582 public void scrollBy(int x, int y) {
6583 scrollTo(mScrollX + x, mScrollY + y);
6584 }
6585
6586 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006587 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6588 * animation to fade the scrollbars out after a default delay. If a subclass
6589 * provides animated scrolling, the start delay should equal the duration
6590 * of the scrolling animation.</p>
6591 *
6592 * <p>The animation starts only if at least one of the scrollbars is
6593 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6594 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6595 * this method returns true, and false otherwise. If the animation is
6596 * started, this method calls {@link #invalidate()}; in that case the
6597 * caller should not call {@link #invalidate()}.</p>
6598 *
6599 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006600 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006601 *
6602 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6603 * and {@link #scrollTo(int, int)}.</p>
6604 *
6605 * @return true if the animation is played, false otherwise
6606 *
6607 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006608 * @see #scrollBy(int, int)
6609 * @see #scrollTo(int, int)
6610 * @see #isHorizontalScrollBarEnabled()
6611 * @see #isVerticalScrollBarEnabled()
6612 * @see #setHorizontalScrollBarEnabled(boolean)
6613 * @see #setVerticalScrollBarEnabled(boolean)
6614 */
6615 protected boolean awakenScrollBars() {
6616 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006617 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006618 }
6619
6620 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006621 * Trigger the scrollbars to draw.
6622 * This method differs from awakenScrollBars() only in its default duration.
6623 * initialAwakenScrollBars() will show the scroll bars for longer than
6624 * usual to give the user more of a chance to notice them.
6625 *
6626 * @return true if the animation is played, false otherwise.
6627 */
6628 private boolean initialAwakenScrollBars() {
6629 return mScrollCache != null &&
6630 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6631 }
6632
6633 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006634 * <p>
6635 * Trigger the scrollbars to draw. When invoked this method starts an
6636 * animation to fade the scrollbars out after a fixed delay. If a subclass
6637 * provides animated scrolling, the start delay should equal the duration of
6638 * the scrolling animation.
6639 * </p>
6640 *
6641 * <p>
6642 * The animation starts only if at least one of the scrollbars is enabled,
6643 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6644 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6645 * this method returns true, and false otherwise. If the animation is
6646 * started, this method calls {@link #invalidate()}; in that case the caller
6647 * should not call {@link #invalidate()}.
6648 * </p>
6649 *
6650 * <p>
6651 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006652 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006653 * </p>
6654 *
6655 * @param startDelay the delay, in milliseconds, after which the animation
6656 * should start; when the delay is 0, the animation starts
6657 * immediately
6658 * @return true if the animation is played, false otherwise
6659 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006660 * @see #scrollBy(int, int)
6661 * @see #scrollTo(int, int)
6662 * @see #isHorizontalScrollBarEnabled()
6663 * @see #isVerticalScrollBarEnabled()
6664 * @see #setHorizontalScrollBarEnabled(boolean)
6665 * @see #setVerticalScrollBarEnabled(boolean)
6666 */
6667 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006668 return awakenScrollBars(startDelay, true);
6669 }
6670
6671 /**
6672 * <p>
6673 * Trigger the scrollbars to draw. When invoked this method starts an
6674 * animation to fade the scrollbars out after a fixed delay. If a subclass
6675 * provides animated scrolling, the start delay should equal the duration of
6676 * the scrolling animation.
6677 * </p>
6678 *
6679 * <p>
6680 * The animation starts only if at least one of the scrollbars is enabled,
6681 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6682 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6683 * this method returns true, and false otherwise. If the animation is
6684 * started, this method calls {@link #invalidate()} if the invalidate parameter
6685 * is set to true; in that case the caller
6686 * should not call {@link #invalidate()}.
6687 * </p>
6688 *
6689 * <p>
6690 * This method should be invoked everytime a subclass directly updates the
6691 * scroll parameters.
6692 * </p>
6693 *
6694 * @param startDelay the delay, in milliseconds, after which the animation
6695 * should start; when the delay is 0, the animation starts
6696 * immediately
6697 *
6698 * @param invalidate Wheter this method should call invalidate
6699 *
6700 * @return true if the animation is played, false otherwise
6701 *
6702 * @see #scrollBy(int, int)
6703 * @see #scrollTo(int, int)
6704 * @see #isHorizontalScrollBarEnabled()
6705 * @see #isVerticalScrollBarEnabled()
6706 * @see #setHorizontalScrollBarEnabled(boolean)
6707 * @see #setVerticalScrollBarEnabled(boolean)
6708 */
6709 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006710 final ScrollabilityCache scrollCache = mScrollCache;
6711
6712 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6713 return false;
6714 }
6715
6716 if (scrollCache.scrollBar == null) {
6717 scrollCache.scrollBar = new ScrollBarDrawable();
6718 }
6719
6720 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6721
Mike Cleron290947b2009-09-29 18:34:32 -07006722 if (invalidate) {
6723 // Invalidate to show the scrollbars
Romain Guy0fd89bf2011-01-26 15:41:30 -08006724 invalidate(true);
Mike Cleron290947b2009-09-29 18:34:32 -07006725 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006726
6727 if (scrollCache.state == ScrollabilityCache.OFF) {
6728 // FIXME: this is copied from WindowManagerService.
6729 // We should get this value from the system when it
6730 // is possible to do so.
6731 final int KEY_REPEAT_FIRST_DELAY = 750;
6732 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6733 }
6734
6735 // Tell mScrollCache when we should start fading. This may
6736 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006737 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006738 scrollCache.fadeStartTime = fadeStartTime;
6739 scrollCache.state = ScrollabilityCache.ON;
6740
6741 // Schedule our fader to run, unscheduling any old ones first
6742 if (mAttachInfo != null) {
6743 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6744 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6745 }
6746
6747 return true;
6748 }
6749
6750 return false;
6751 }
6752
6753 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 * Mark the the area defined by dirty as needing to be drawn. If the view is
6755 * visible, {@link #onDraw} will be called at some point in the future.
6756 * This must be called from a UI thread. To call from a non-UI thread, call
6757 * {@link #postInvalidate()}.
6758 *
6759 * WARNING: This method is destructive to dirty.
6760 * @param dirty the rectangle representing the bounds of the dirty region
6761 */
6762 public void invalidate(Rect dirty) {
6763 if (ViewDebug.TRACE_HIERARCHY) {
6764 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6765 }
6766
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006767 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
Chet Haasedaf98e92011-01-10 14:10:36 -08006768 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
6769 (mPrivateFlags & INVALIDATED) != INVALIDATED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 mPrivateFlags &= ~DRAWING_CACHE_VALID;
Chet Haasedaf98e92011-01-10 14:10:36 -08006771 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 final ViewParent p = mParent;
6773 final AttachInfo ai = mAttachInfo;
Romain Guy7d7b5492011-01-24 16:33:45 -08006774 //noinspection PointlessBooleanExpression,ConstantConditions
6775 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
6776 if (p != null && ai != null && ai.mHardwareAccelerated) {
6777 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6778 // with a null dirty rect, which tells the ViewRoot to redraw everything
6779 p.invalidateChild(this, null);
6780 return;
6781 }
Romain Guyaf636eb2010-12-09 17:47:21 -08006782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 if (p != null && ai != null) {
6784 final int scrollX = mScrollX;
6785 final int scrollY = mScrollY;
6786 final Rect r = ai.mTmpInvalRect;
6787 r.set(dirty.left - scrollX, dirty.top - scrollY,
6788 dirty.right - scrollX, dirty.bottom - scrollY);
6789 mParent.invalidateChild(this, r);
6790 }
6791 }
6792 }
6793
6794 /**
6795 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6796 * The coordinates of the dirty rect are relative to the view.
6797 * If the view is visible, {@link #onDraw} will be called at some point
6798 * in the future. This must be called from a UI thread. To call
6799 * from a non-UI thread, call {@link #postInvalidate()}.
6800 * @param l the left position of the dirty region
6801 * @param t the top position of the dirty region
6802 * @param r the right position of the dirty region
6803 * @param b the bottom position of the dirty region
6804 */
6805 public void invalidate(int l, int t, int r, int b) {
6806 if (ViewDebug.TRACE_HIERARCHY) {
6807 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6808 }
6809
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006810 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
Chet Haasedaf98e92011-01-10 14:10:36 -08006811 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
6812 (mPrivateFlags & INVALIDATED) != INVALIDATED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 mPrivateFlags &= ~DRAWING_CACHE_VALID;
Chet Haasedaf98e92011-01-10 14:10:36 -08006814 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 final ViewParent p = mParent;
6816 final AttachInfo ai = mAttachInfo;
Romain Guy7d7b5492011-01-24 16:33:45 -08006817 //noinspection PointlessBooleanExpression,ConstantConditions
6818 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
6819 if (p != null && ai != null && ai.mHardwareAccelerated) {
6820 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6821 // with a null dirty rect, which tells the ViewRoot to redraw everything
6822 p.invalidateChild(this, null);
6823 return;
6824 }
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006826 if (p != null && ai != null && l < r && t < b) {
6827 final int scrollX = mScrollX;
6828 final int scrollY = mScrollY;
6829 final Rect tmpr = ai.mTmpInvalRect;
6830 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6831 p.invalidateChild(this, tmpr);
6832 }
6833 }
6834 }
6835
6836 /**
6837 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6838 * be called at some point in the future. This must be called from a
6839 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6840 */
6841 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006842 invalidate(true);
6843 }
Romain Guyc5d55862011-01-21 19:01:46 -08006844
Chet Haaseed032702010-10-01 14:05:54 -07006845 /**
6846 * This is where the invalidate() work actually happens. A full invalidate()
6847 * causes the drawing cache to be invalidated, but this function can be called with
6848 * invalidateCache set to false to skip that invalidation step for cases that do not
6849 * need it (for example, a component that remains at the same dimensions with the same
6850 * content).
6851 *
6852 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6853 * well. This is usually true for a full invalidate, but may be set to false if the
6854 * View's contents or dimensions have not changed.
6855 */
6856 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 if (ViewDebug.TRACE_HIERARCHY) {
6858 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6859 }
6860
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006861 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
Romain Guyc5d55862011-01-21 19:01:46 -08006862 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
Romain Guy0fd89bf2011-01-26 15:41:30 -08006863 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
6864 mLastIsOpaque = isOpaque();
Chet Haaseed032702010-10-01 14:05:54 -07006865 mPrivateFlags &= ~DRAWN;
6866 if (invalidateCache) {
Chet Haasedaf98e92011-01-10 14:10:36 -08006867 mPrivateFlags |= INVALIDATED;
Chet Haaseed032702010-10-01 14:05:54 -07006868 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006870 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006871 final ViewParent p = mParent;
Romain Guy7d7b5492011-01-24 16:33:45 -08006872 //noinspection PointlessBooleanExpression,ConstantConditions
6873 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
6874 if (p != null && ai != null && ai.mHardwareAccelerated) {
6875 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6876 // with a null dirty rect, which tells the ViewRoot to redraw everything
6877 p.invalidateChild(this, null);
6878 return;
6879 }
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006880 }
Michael Jurkaebefea42010-11-15 16:04:01 -08006881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006882 if (p != null && ai != null) {
6883 final Rect r = ai.mTmpInvalRect;
6884 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6885 // Don't call invalidate -- we don't want to internally scroll
6886 // our own bounds
6887 p.invalidateChild(this, r);
6888 }
6889 }
6890 }
6891
6892 /**
Romain Guy0fd89bf2011-01-26 15:41:30 -08006893 * Used to indicate that the parent of this view should clear its caches. This functionality
Chet Haasedaf98e92011-01-10 14:10:36 -08006894 * is used to force the parent to rebuild its display list (when hardware-accelerated),
6895 * which is necessary when various parent-managed properties of the view change, such as
Romain Guy0fd89bf2011-01-26 15:41:30 -08006896 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
6897 * clears the parent caches and does not causes an invalidate event.
Chet Haasedaf98e92011-01-10 14:10:36 -08006898 *
6899 * @hide
6900 */
Romain Guy0fd89bf2011-01-26 15:41:30 -08006901 protected void invalidateParentCaches() {
6902 if (mParent instanceof View) {
6903 ((View) mParent).mPrivateFlags |= INVALIDATED;
6904 }
6905 }
6906
6907 /**
6908 * Used to indicate that the parent of this view should be invalidated. This functionality
6909 * is used to force the parent to rebuild its display list (when hardware-accelerated),
6910 * which is necessary when various parent-managed properties of the view change, such as
6911 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
6912 * an invalidation event to the parent.
6913 *
6914 * @hide
6915 */
6916 protected void invalidateParentIfNeeded() {
Chet Haasedaf98e92011-01-10 14:10:36 -08006917 if (isHardwareAccelerated() && mParent instanceof View) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006918 ((View) mParent).invalidate(true);
Chet Haasedaf98e92011-01-10 14:10:36 -08006919 }
6920 }
6921
6922 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006923 * Indicates whether this View is opaque. An opaque View guarantees that it will
6924 * draw all the pixels overlapping its bounds using a fully opaque color.
6925 *
6926 * Subclasses of View should override this method whenever possible to indicate
6927 * whether an instance is opaque. Opaque Views are treated in a special way by
6928 * the View hierarchy, possibly allowing it to perform optimizations during
6929 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006930 *
Romain Guy24443ea2009-05-11 11:56:30 -07006931 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006932 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006933 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006934 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006935 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6936 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006937 }
6938
Adam Powell20232d02010-12-08 21:08:53 -08006939 /**
6940 * @hide
6941 */
6942 protected void computeOpaqueFlags() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006943 // Opaque if:
6944 // - Has a background
6945 // - Background is opaque
6946 // - Doesn't have scrollbars or scrollbars are inside overlay
6947
6948 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6949 mPrivateFlags |= OPAQUE_BACKGROUND;
6950 } else {
6951 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6952 }
6953
6954 final int flags = mViewFlags;
6955 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6956 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6957 mPrivateFlags |= OPAQUE_SCROLLBARS;
6958 } else {
6959 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6960 }
6961 }
6962
6963 /**
6964 * @hide
6965 */
6966 protected boolean hasOpaqueScrollbars() {
6967 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006968 }
6969
6970 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006971 * @return A handler associated with the thread running the View. This
6972 * handler can be used to pump events in the UI events queue.
6973 */
6974 public Handler getHandler() {
6975 if (mAttachInfo != null) {
6976 return mAttachInfo.mHandler;
6977 }
6978 return null;
6979 }
6980
6981 /**
6982 * Causes the Runnable to be added to the message queue.
6983 * The runnable will be run on the user interface thread.
6984 *
6985 * @param action The Runnable that will be executed.
6986 *
6987 * @return Returns true if the Runnable was successfully placed in to the
6988 * message queue. Returns false on failure, usually because the
6989 * looper processing the message queue is exiting.
6990 */
6991 public boolean post(Runnable action) {
6992 Handler handler;
6993 if (mAttachInfo != null) {
6994 handler = mAttachInfo.mHandler;
6995 } else {
6996 // Assume that post will succeed later
6997 ViewRoot.getRunQueue().post(action);
6998 return true;
6999 }
7000
7001 return handler.post(action);
7002 }
7003
7004 /**
7005 * Causes the Runnable to be added to the message queue, to be run
7006 * after the specified amount of time elapses.
7007 * The runnable will be run on the user interface thread.
7008 *
7009 * @param action The Runnable that will be executed.
7010 * @param delayMillis The delay (in milliseconds) until the Runnable
7011 * will be executed.
7012 *
7013 * @return true if the Runnable was successfully placed in to the
7014 * message queue. Returns false on failure, usually because the
7015 * looper processing the message queue is exiting. Note that a
7016 * result of true does not mean the Runnable will be processed --
7017 * if the looper is quit before the delivery time of the message
7018 * occurs then the message will be dropped.
7019 */
7020 public boolean postDelayed(Runnable action, long delayMillis) {
7021 Handler handler;
7022 if (mAttachInfo != null) {
7023 handler = mAttachInfo.mHandler;
7024 } else {
7025 // Assume that post will succeed later
7026 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
7027 return true;
7028 }
7029
7030 return handler.postDelayed(action, delayMillis);
7031 }
7032
7033 /**
7034 * Removes the specified Runnable from the message queue.
7035 *
7036 * @param action The Runnable to remove from the message handling queue
7037 *
7038 * @return true if this view could ask the Handler to remove the Runnable,
7039 * false otherwise. When the returned value is true, the Runnable
7040 * may or may not have been actually removed from the message queue
7041 * (for instance, if the Runnable was not in the queue already.)
7042 */
7043 public boolean removeCallbacks(Runnable action) {
7044 Handler handler;
7045 if (mAttachInfo != null) {
7046 handler = mAttachInfo.mHandler;
7047 } else {
7048 // Assume that post will succeed later
7049 ViewRoot.getRunQueue().removeCallbacks(action);
7050 return true;
7051 }
7052
7053 handler.removeCallbacks(action);
7054 return true;
7055 }
7056
7057 /**
7058 * Cause an invalidate to happen on a subsequent cycle through the event loop.
7059 * Use this to invalidate the View from a non-UI thread.
7060 *
7061 * @see #invalidate()
7062 */
7063 public void postInvalidate() {
7064 postInvalidateDelayed(0);
7065 }
7066
7067 /**
7068 * Cause an invalidate of the specified area to happen on a subsequent cycle
7069 * through the event loop. Use this to invalidate the View from a non-UI thread.
7070 *
7071 * @param left The left coordinate of the rectangle to invalidate.
7072 * @param top The top coordinate of the rectangle to invalidate.
7073 * @param right The right coordinate of the rectangle to invalidate.
7074 * @param bottom The bottom coordinate of the rectangle to invalidate.
7075 *
7076 * @see #invalidate(int, int, int, int)
7077 * @see #invalidate(Rect)
7078 */
7079 public void postInvalidate(int left, int top, int right, int bottom) {
7080 postInvalidateDelayed(0, left, top, right, bottom);
7081 }
7082
7083 /**
7084 * Cause an invalidate to happen on a subsequent cycle through the event
7085 * loop. Waits for the specified amount of time.
7086 *
7087 * @param delayMilliseconds the duration in milliseconds to delay the
7088 * invalidation by
7089 */
7090 public void postInvalidateDelayed(long delayMilliseconds) {
7091 // We try only with the AttachInfo because there's no point in invalidating
7092 // if we are not attached to our window
7093 if (mAttachInfo != null) {
7094 Message msg = Message.obtain();
7095 msg.what = AttachInfo.INVALIDATE_MSG;
7096 msg.obj = this;
7097 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
7098 }
7099 }
7100
7101 /**
7102 * Cause an invalidate of the specified area to happen on a subsequent cycle
7103 * through the event loop. Waits for the specified amount of time.
7104 *
7105 * @param delayMilliseconds the duration in milliseconds to delay the
7106 * invalidation by
7107 * @param left The left coordinate of the rectangle to invalidate.
7108 * @param top The top coordinate of the rectangle to invalidate.
7109 * @param right The right coordinate of the rectangle to invalidate.
7110 * @param bottom The bottom coordinate of the rectangle to invalidate.
7111 */
7112 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
7113 int right, int bottom) {
7114
7115 // We try only with the AttachInfo because there's no point in invalidating
7116 // if we are not attached to our window
7117 if (mAttachInfo != null) {
7118 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
7119 info.target = this;
7120 info.left = left;
7121 info.top = top;
7122 info.right = right;
7123 info.bottom = bottom;
7124
7125 final Message msg = Message.obtain();
7126 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
7127 msg.obj = info;
7128 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
7129 }
7130 }
7131
7132 /**
7133 * Called by a parent to request that a child update its values for mScrollX
7134 * and mScrollY if necessary. This will typically be done if the child is
7135 * animating a scroll using a {@link android.widget.Scroller Scroller}
7136 * object.
7137 */
7138 public void computeScroll() {
7139 }
7140
7141 /**
7142 * <p>Indicate whether the horizontal edges are faded when the view is
7143 * scrolled horizontally.</p>
7144 *
7145 * @return true if the horizontal edges should are faded on scroll, false
7146 * otherwise
7147 *
7148 * @see #setHorizontalFadingEdgeEnabled(boolean)
7149 * @attr ref android.R.styleable#View_fadingEdge
7150 */
7151 public boolean isHorizontalFadingEdgeEnabled() {
7152 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
7153 }
7154
7155 /**
7156 * <p>Define whether the horizontal edges should be faded when this view
7157 * is scrolled horizontally.</p>
7158 *
7159 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
7160 * be faded when the view is scrolled
7161 * horizontally
7162 *
7163 * @see #isHorizontalFadingEdgeEnabled()
7164 * @attr ref android.R.styleable#View_fadingEdge
7165 */
7166 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
7167 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
7168 if (horizontalFadingEdgeEnabled) {
7169 initScrollCache();
7170 }
7171
7172 mViewFlags ^= FADING_EDGE_HORIZONTAL;
7173 }
7174 }
7175
7176 /**
7177 * <p>Indicate whether the vertical edges are faded when the view is
7178 * scrolled horizontally.</p>
7179 *
7180 * @return true if the vertical edges should are faded on scroll, false
7181 * otherwise
7182 *
7183 * @see #setVerticalFadingEdgeEnabled(boolean)
7184 * @attr ref android.R.styleable#View_fadingEdge
7185 */
7186 public boolean isVerticalFadingEdgeEnabled() {
7187 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
7188 }
7189
7190 /**
7191 * <p>Define whether the vertical edges should be faded when this view
7192 * is scrolled vertically.</p>
7193 *
7194 * @param verticalFadingEdgeEnabled true if the vertical edges should
7195 * be faded when the view is scrolled
7196 * vertically
7197 *
7198 * @see #isVerticalFadingEdgeEnabled()
7199 * @attr ref android.R.styleable#View_fadingEdge
7200 */
7201 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
7202 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
7203 if (verticalFadingEdgeEnabled) {
7204 initScrollCache();
7205 }
7206
7207 mViewFlags ^= FADING_EDGE_VERTICAL;
7208 }
7209 }
7210
7211 /**
7212 * Returns the strength, or intensity, of the top faded edge. The strength is
7213 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7214 * returns 0.0 or 1.0 but no value in between.
7215 *
7216 * Subclasses should override this method to provide a smoother fade transition
7217 * when scrolling occurs.
7218 *
7219 * @return the intensity of the top fade as a float between 0.0f and 1.0f
7220 */
7221 protected float getTopFadingEdgeStrength() {
7222 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
7223 }
7224
7225 /**
7226 * Returns the strength, or intensity, of the bottom faded edge. The strength is
7227 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7228 * returns 0.0 or 1.0 but no value in between.
7229 *
7230 * Subclasses should override this method to provide a smoother fade transition
7231 * when scrolling occurs.
7232 *
7233 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
7234 */
7235 protected float getBottomFadingEdgeStrength() {
7236 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
7237 computeVerticalScrollRange() ? 1.0f : 0.0f;
7238 }
7239
7240 /**
7241 * Returns the strength, or intensity, of the left faded edge. The strength is
7242 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7243 * returns 0.0 or 1.0 but no value in between.
7244 *
7245 * Subclasses should override this method to provide a smoother fade transition
7246 * when scrolling occurs.
7247 *
7248 * @return the intensity of the left fade as a float between 0.0f and 1.0f
7249 */
7250 protected float getLeftFadingEdgeStrength() {
7251 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
7252 }
7253
7254 /**
7255 * Returns the strength, or intensity, of the right faded edge. The strength is
7256 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7257 * returns 0.0 or 1.0 but no value in between.
7258 *
7259 * Subclasses should override this method to provide a smoother fade transition
7260 * when scrolling occurs.
7261 *
7262 * @return the intensity of the right fade as a float between 0.0f and 1.0f
7263 */
7264 protected float getRightFadingEdgeStrength() {
7265 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
7266 computeHorizontalScrollRange() ? 1.0f : 0.0f;
7267 }
7268
7269 /**
7270 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
7271 * scrollbar is not drawn by default.</p>
7272 *
7273 * @return true if the horizontal scrollbar should be painted, false
7274 * otherwise
7275 *
7276 * @see #setHorizontalScrollBarEnabled(boolean)
7277 */
7278 public boolean isHorizontalScrollBarEnabled() {
7279 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7280 }
7281
7282 /**
7283 * <p>Define whether the horizontal scrollbar should be drawn or not. The
7284 * scrollbar is not drawn by default.</p>
7285 *
7286 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
7287 * be painted
7288 *
7289 * @see #isHorizontalScrollBarEnabled()
7290 */
7291 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
7292 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
7293 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007294 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 recomputePadding();
7296 }
7297 }
7298
7299 /**
7300 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
7301 * scrollbar is not drawn by default.</p>
7302 *
7303 * @return true if the vertical scrollbar should be painted, false
7304 * otherwise
7305 *
7306 * @see #setVerticalScrollBarEnabled(boolean)
7307 */
7308 public boolean isVerticalScrollBarEnabled() {
7309 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
7310 }
7311
7312 /**
7313 * <p>Define whether the vertical scrollbar should be drawn or not. The
7314 * scrollbar is not drawn by default.</p>
7315 *
7316 * @param verticalScrollBarEnabled true if the vertical scrollbar should
7317 * be painted
7318 *
7319 * @see #isVerticalScrollBarEnabled()
7320 */
7321 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
7322 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
7323 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007324 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007325 recomputePadding();
7326 }
7327 }
7328
Adam Powell20232d02010-12-08 21:08:53 -08007329 /**
7330 * @hide
7331 */
7332 protected void recomputePadding() {
7333 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 }
Mike Cleronfe81d382009-09-28 14:22:16 -07007335
7336 /**
7337 * Define whether scrollbars will fade when the view is not scrolling.
7338 *
7339 * @param fadeScrollbars wheter to enable fading
7340 *
7341 */
7342 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
7343 initScrollCache();
7344 final ScrollabilityCache scrollabilityCache = mScrollCache;
7345 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07007346 if (fadeScrollbars) {
7347 scrollabilityCache.state = ScrollabilityCache.OFF;
7348 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07007349 scrollabilityCache.state = ScrollabilityCache.ON;
7350 }
7351 }
7352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007353 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07007354 *
7355 * Returns true if scrollbars will fade when this view is not scrolling
7356 *
7357 * @return true if scrollbar fading is enabled
7358 */
7359 public boolean isScrollbarFadingEnabled() {
7360 return mScrollCache != null && mScrollCache.fadeScrollBars;
7361 }
7362
7363 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007364 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
7365 * inset. When inset, they add to the padding of the view. And the scrollbars
7366 * can be drawn inside the padding area or on the edge of the view. For example,
7367 * if a view has a background drawable and you want to draw the scrollbars
7368 * inside the padding specified by the drawable, you can use
7369 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
7370 * appear at the edge of the view, ignoring the padding, then you can use
7371 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
7372 * @param style the style of the scrollbars. Should be one of
7373 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
7374 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
7375 * @see #SCROLLBARS_INSIDE_OVERLAY
7376 * @see #SCROLLBARS_INSIDE_INSET
7377 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7378 * @see #SCROLLBARS_OUTSIDE_INSET
7379 */
7380 public void setScrollBarStyle(int style) {
7381 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
7382 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07007383 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007384 recomputePadding();
7385 }
7386 }
7387
7388 /**
7389 * <p>Returns the current scrollbar style.</p>
7390 * @return the current scrollbar style
7391 * @see #SCROLLBARS_INSIDE_OVERLAY
7392 * @see #SCROLLBARS_INSIDE_INSET
7393 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7394 * @see #SCROLLBARS_OUTSIDE_INSET
7395 */
7396 public int getScrollBarStyle() {
7397 return mViewFlags & SCROLLBARS_STYLE_MASK;
7398 }
7399
7400 /**
7401 * <p>Compute the horizontal range that the horizontal scrollbar
7402 * represents.</p>
7403 *
7404 * <p>The range is expressed in arbitrary units that must be the same as the
7405 * units used by {@link #computeHorizontalScrollExtent()} and
7406 * {@link #computeHorizontalScrollOffset()}.</p>
7407 *
7408 * <p>The default range is the drawing width of this view.</p>
7409 *
7410 * @return the total horizontal range represented by the horizontal
7411 * scrollbar
7412 *
7413 * @see #computeHorizontalScrollExtent()
7414 * @see #computeHorizontalScrollOffset()
7415 * @see android.widget.ScrollBarDrawable
7416 */
7417 protected int computeHorizontalScrollRange() {
7418 return getWidth();
7419 }
7420
7421 /**
7422 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7423 * within the horizontal range. This value is used to compute the position
7424 * of the thumb within the scrollbar's track.</p>
7425 *
7426 * <p>The range is expressed in arbitrary units that must be the same as the
7427 * units used by {@link #computeHorizontalScrollRange()} and
7428 * {@link #computeHorizontalScrollExtent()}.</p>
7429 *
7430 * <p>The default offset is the scroll offset of this view.</p>
7431 *
7432 * @return the horizontal offset of the scrollbar's thumb
7433 *
7434 * @see #computeHorizontalScrollRange()
7435 * @see #computeHorizontalScrollExtent()
7436 * @see android.widget.ScrollBarDrawable
7437 */
7438 protected int computeHorizontalScrollOffset() {
7439 return mScrollX;
7440 }
7441
7442 /**
7443 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7444 * within the horizontal range. This value is used to compute the length
7445 * of the thumb within the scrollbar's track.</p>
7446 *
7447 * <p>The range is expressed in arbitrary units that must be the same as the
7448 * units used by {@link #computeHorizontalScrollRange()} and
7449 * {@link #computeHorizontalScrollOffset()}.</p>
7450 *
7451 * <p>The default extent is the drawing width of this view.</p>
7452 *
7453 * @return the horizontal extent of the scrollbar's thumb
7454 *
7455 * @see #computeHorizontalScrollRange()
7456 * @see #computeHorizontalScrollOffset()
7457 * @see android.widget.ScrollBarDrawable
7458 */
7459 protected int computeHorizontalScrollExtent() {
7460 return getWidth();
7461 }
7462
7463 /**
7464 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7465 *
7466 * <p>The range is expressed in arbitrary units that must be the same as the
7467 * units used by {@link #computeVerticalScrollExtent()} and
7468 * {@link #computeVerticalScrollOffset()}.</p>
7469 *
7470 * @return the total vertical range represented by the vertical scrollbar
7471 *
7472 * <p>The default range is the drawing height of this view.</p>
7473 *
7474 * @see #computeVerticalScrollExtent()
7475 * @see #computeVerticalScrollOffset()
7476 * @see android.widget.ScrollBarDrawable
7477 */
7478 protected int computeVerticalScrollRange() {
7479 return getHeight();
7480 }
7481
7482 /**
7483 * <p>Compute the vertical offset of the vertical scrollbar's thumb
7484 * within the horizontal range. This value is used to compute the position
7485 * of the thumb within the scrollbar's track.</p>
7486 *
7487 * <p>The range is expressed in arbitrary units that must be the same as the
7488 * units used by {@link #computeVerticalScrollRange()} and
7489 * {@link #computeVerticalScrollExtent()}.</p>
7490 *
7491 * <p>The default offset is the scroll offset of this view.</p>
7492 *
7493 * @return the vertical offset of the scrollbar's thumb
7494 *
7495 * @see #computeVerticalScrollRange()
7496 * @see #computeVerticalScrollExtent()
7497 * @see android.widget.ScrollBarDrawable
7498 */
7499 protected int computeVerticalScrollOffset() {
7500 return mScrollY;
7501 }
7502
7503 /**
7504 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7505 * within the vertical range. This value is used to compute the length
7506 * of the thumb within the scrollbar's track.</p>
7507 *
7508 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08007509 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007510 * {@link #computeVerticalScrollOffset()}.</p>
7511 *
7512 * <p>The default extent is the drawing height of this view.</p>
7513 *
7514 * @return the vertical extent of the scrollbar's thumb
7515 *
7516 * @see #computeVerticalScrollRange()
7517 * @see #computeVerticalScrollOffset()
7518 * @see android.widget.ScrollBarDrawable
7519 */
7520 protected int computeVerticalScrollExtent() {
7521 return getHeight();
7522 }
7523
7524 /**
7525 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7526 * scrollbars are painted only if they have been awakened first.</p>
7527 *
7528 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07007529 *
7530 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007531 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08007532 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 // scrollbars are drawn only when the animation is running
7534 final ScrollabilityCache cache = mScrollCache;
7535 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007536
7537 int state = cache.state;
7538
7539 if (state == ScrollabilityCache.OFF) {
7540 return;
7541 }
7542
7543 boolean invalidate = false;
7544
7545 if (state == ScrollabilityCache.FADING) {
7546 // We're fading -- get our fade interpolation
7547 if (cache.interpolatorValues == null) {
7548 cache.interpolatorValues = new float[1];
7549 }
7550
7551 float[] values = cache.interpolatorValues;
7552
7553 // Stops the animation if we're done
7554 if (cache.scrollBarInterpolator.timeToValues(values) ==
7555 Interpolator.Result.FREEZE_END) {
7556 cache.state = ScrollabilityCache.OFF;
7557 } else {
7558 cache.scrollBar.setAlpha(Math.round(values[0]));
7559 }
7560
7561 // This will make the scroll bars inval themselves after
7562 // drawing. We only want this when we're fading so that
7563 // we prevent excessive redraws
7564 invalidate = true;
7565 } else {
7566 // We're just on -- but we may have been fading before so
7567 // reset alpha
7568 cache.scrollBar.setAlpha(255);
7569 }
7570
7571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007572 final int viewFlags = mViewFlags;
7573
7574 final boolean drawHorizontalScrollBar =
7575 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7576 final boolean drawVerticalScrollBar =
7577 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7578 && !isVerticalScrollBarHidden();
7579
7580 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7581 final int width = mRight - mLeft;
7582 final int height = mBottom - mTop;
7583
7584 final ScrollBarDrawable scrollBar = cache.scrollBar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585
Mike Reede8853fc2009-09-04 14:01:48 -04007586 final int scrollX = mScrollX;
7587 final int scrollY = mScrollY;
7588 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7589
Mike Cleronf116bf82009-09-27 19:14:12 -07007590 int left, top, right, bottom;
7591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 if (drawHorizontalScrollBar) {
Adam Powell3ba67742011-01-27 14:16:55 -08007593 int size = scrollBar.getSize(false);
7594 if (size <= 0) {
7595 size = cache.scrollBarSize;
7596 }
7597
Mike Cleronf116bf82009-09-27 19:14:12 -07007598 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04007599 computeHorizontalScrollOffset(),
7600 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04007601 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07007602 getVerticalScrollbarWidth() : 0;
7603 top = scrollY + height - size - (mUserPaddingBottom & inside);
7604 left = scrollX + (mPaddingLeft & inside);
7605 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7606 bottom = top + size;
7607 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7608 if (invalidate) {
7609 invalidate(left, top, right, bottom);
7610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 }
7612
7613 if (drawVerticalScrollBar) {
Adam Powell3ba67742011-01-27 14:16:55 -08007614 int size = scrollBar.getSize(true);
7615 if (size <= 0) {
7616 size = cache.scrollBarSize;
7617 }
7618
Mike Reede8853fc2009-09-04 14:01:48 -04007619 scrollBar.setParameters(computeVerticalScrollRange(),
7620 computeVerticalScrollOffset(),
7621 computeVerticalScrollExtent(), true);
Adam Powell20232d02010-12-08 21:08:53 -08007622 switch (mVerticalScrollbarPosition) {
7623 default:
7624 case SCROLLBAR_POSITION_DEFAULT:
7625 case SCROLLBAR_POSITION_RIGHT:
7626 left = scrollX + width - size - (mUserPaddingRight & inside);
7627 break;
7628 case SCROLLBAR_POSITION_LEFT:
7629 left = scrollX + (mUserPaddingLeft & inside);
7630 break;
7631 }
Mike Cleronf116bf82009-09-27 19:14:12 -07007632 top = scrollY + (mPaddingTop & inside);
7633 right = left + size;
7634 bottom = scrollY + height - (mUserPaddingBottom & inside);
7635 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7636 if (invalidate) {
7637 invalidate(left, top, right, bottom);
7638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007639 }
7640 }
7641 }
7642 }
Romain Guy8506ab42009-06-11 17:35:47 -07007643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007644 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007645 * 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 -08007646 * FastScroller is visible.
7647 * @return whether to temporarily hide the vertical scrollbar
7648 * @hide
7649 */
7650 protected boolean isVerticalScrollBarHidden() {
7651 return false;
7652 }
7653
7654 /**
7655 * <p>Draw the horizontal scrollbar if
7656 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7657 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007658 * @param canvas the canvas on which to draw the scrollbar
7659 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 *
7661 * @see #isHorizontalScrollBarEnabled()
7662 * @see #computeHorizontalScrollRange()
7663 * @see #computeHorizontalScrollExtent()
7664 * @see #computeHorizontalScrollOffset()
7665 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007666 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007667 */
Romain Guy8fb95422010-08-17 18:38:51 -07007668 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7669 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007670 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007671 scrollBar.draw(canvas);
7672 }
Mike Reede8853fc2009-09-04 14:01:48 -04007673
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007674 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7676 * returns true.</p>
7677 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 * @param canvas the canvas on which to draw the scrollbar
7679 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007680 *
7681 * @see #isVerticalScrollBarEnabled()
7682 * @see #computeVerticalScrollRange()
7683 * @see #computeVerticalScrollExtent()
7684 * @see #computeVerticalScrollOffset()
7685 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007686 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 */
Romain Guy8fb95422010-08-17 18:38:51 -07007688 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7689 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007690 scrollBar.setBounds(l, t, r, b);
7691 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 }
7693
7694 /**
7695 * Implement this to do your drawing.
7696 *
7697 * @param canvas the canvas on which the background will be drawn
7698 */
7699 protected void onDraw(Canvas canvas) {
7700 }
7701
7702 /*
7703 * Caller is responsible for calling requestLayout if necessary.
7704 * (This allows addViewInLayout to not request a new layout.)
7705 */
7706 void assignParent(ViewParent parent) {
7707 if (mParent == null) {
7708 mParent = parent;
7709 } else if (parent == null) {
7710 mParent = null;
7711 } else {
7712 throw new RuntimeException("view " + this + " being added, but"
7713 + " it already has a parent");
7714 }
7715 }
7716
7717 /**
7718 * This is called when the view is attached to a window. At this point it
7719 * has a Surface and will start drawing. Note that this function is
7720 * guaranteed to be called before {@link #onDraw}, however it may be called
7721 * any time before the first onDraw -- including before or after
7722 * {@link #onMeasure}.
7723 *
7724 * @see #onDetachedFromWindow()
7725 */
7726 protected void onAttachedToWindow() {
7727 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7728 mParent.requestTransparentRegion(this);
7729 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007730 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7731 initialAwakenScrollBars();
7732 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7733 }
Chet Haasea9b61ac2010-12-20 07:40:25 -08007734 jumpDrawablesToCurrentState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 }
7736
7737 /**
7738 * This is called when the view is detached from a window. At this point it
7739 * no longer has a surface for drawing.
7740 *
7741 * @see #onAttachedToWindow()
7742 */
7743 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007744 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guy6c319ca2011-01-11 14:29:25 -08007745
Romain Guya440b002010-02-24 15:57:54 -08007746 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007747 removeLongPressCallback();
Adam Powell3cb8b632011-01-21 15:34:14 -08007748 removePerformClickCallback();
Romain Guy6c319ca2011-01-11 14:29:25 -08007749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007750 destroyDrawingCache();
Romain Guy6c319ca2011-01-11 14:29:25 -08007751
7752 if (mHardwareLayer != null) {
7753 mHardwareLayer.destroy();
7754 mHardwareLayer = null;
7755 }
Romain Guy8dd5b1e2011-01-14 17:28:51 -08007756
Chet Haasedaf98e92011-01-10 14:10:36 -08007757 if (mDisplayList != null) {
7758 mDisplayList.invalidate();
7759 }
7760
Romain Guy8dd5b1e2011-01-14 17:28:51 -08007761 if (mAttachInfo != null) {
7762 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
7763 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this);
7764 }
7765
Patrick Dubroyec84c3a2011-01-13 17:55:37 -08007766 mCurrentAnimation = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007767 }
7768
7769 /**
7770 * @return The number of times this view has been attached to a window
7771 */
7772 protected int getWindowAttachCount() {
7773 return mWindowAttachCount;
7774 }
7775
7776 /**
7777 * Retrieve a unique token identifying the window this view is attached to.
7778 * @return Return the window's token for use in
7779 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7780 */
7781 public IBinder getWindowToken() {
7782 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7783 }
7784
7785 /**
7786 * Retrieve a unique token identifying the top-level "real" window of
7787 * the window that this view is attached to. That is, this is like
7788 * {@link #getWindowToken}, except if the window this view in is a panel
7789 * window (attached to another containing window), then the token of
7790 * the containing window is returned instead.
7791 *
7792 * @return Returns the associated window token, either
7793 * {@link #getWindowToken()} or the containing window's token.
7794 */
7795 public IBinder getApplicationWindowToken() {
7796 AttachInfo ai = mAttachInfo;
7797 if (ai != null) {
7798 IBinder appWindowToken = ai.mPanelParentWindowToken;
7799 if (appWindowToken == null) {
7800 appWindowToken = ai.mWindowToken;
7801 }
7802 return appWindowToken;
7803 }
7804 return null;
7805 }
7806
7807 /**
7808 * Retrieve private session object this view hierarchy is using to
7809 * communicate with the window manager.
7810 * @return the session object to communicate with the window manager
7811 */
7812 /*package*/ IWindowSession getWindowSession() {
7813 return mAttachInfo != null ? mAttachInfo.mSession : null;
7814 }
7815
7816 /**
7817 * @param info the {@link android.view.View.AttachInfo} to associated with
7818 * this view
7819 */
7820 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7821 //System.out.println("Attached! " + this);
7822 mAttachInfo = info;
7823 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007824 // We will need to evaluate the drawable state at least once.
7825 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 if (mFloatingTreeObserver != null) {
7827 info.mTreeObserver.merge(mFloatingTreeObserver);
7828 mFloatingTreeObserver = null;
7829 }
7830 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7831 mAttachInfo.mScrollContainers.add(this);
7832 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7833 }
7834 performCollectViewAttributes(visibility);
7835 onAttachedToWindow();
7836 int vis = info.mWindowVisibility;
7837 if (vis != GONE) {
7838 onWindowVisibilityChanged(vis);
7839 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007840 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7841 // If nobody has evaluated the drawable state yet, then do it now.
7842 refreshDrawableState();
7843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 }
7845
7846 void dispatchDetachedFromWindow() {
7847 //System.out.println("Detached! " + this);
7848 AttachInfo info = mAttachInfo;
7849 if (info != null) {
7850 int vis = info.mWindowVisibility;
7851 if (vis != GONE) {
7852 onWindowVisibilityChanged(GONE);
7853 }
7854 }
7855
7856 onDetachedFromWindow();
7857 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7858 mAttachInfo.mScrollContainers.remove(this);
7859 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7860 }
7861 mAttachInfo = null;
7862 }
7863
7864 /**
7865 * Store this view hierarchy's frozen state into the given container.
7866 *
7867 * @param container The SparseArray in which to save the view's state.
7868 *
7869 * @see #restoreHierarchyState
7870 * @see #dispatchSaveInstanceState
7871 * @see #onSaveInstanceState
7872 */
7873 public void saveHierarchyState(SparseArray<Parcelable> container) {
7874 dispatchSaveInstanceState(container);
7875 }
7876
7877 /**
7878 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7879 * May be overridden to modify how freezing happens to a view's children; for example, some
7880 * views may want to not store state for their children.
7881 *
7882 * @param container The SparseArray in which to save the view's state.
7883 *
7884 * @see #dispatchRestoreInstanceState
7885 * @see #saveHierarchyState
7886 * @see #onSaveInstanceState
7887 */
7888 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7889 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7890 mPrivateFlags &= ~SAVE_STATE_CALLED;
7891 Parcelable state = onSaveInstanceState();
7892 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7893 throw new IllegalStateException(
7894 "Derived class did not call super.onSaveInstanceState()");
7895 }
7896 if (state != null) {
7897 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7898 // + ": " + state);
7899 container.put(mID, state);
7900 }
7901 }
7902 }
7903
7904 /**
7905 * Hook allowing a view to generate a representation of its internal state
7906 * that can later be used to create a new instance with that same state.
7907 * This state should only contain information that is not persistent or can
7908 * not be reconstructed later. For example, you will never store your
7909 * current position on screen because that will be computed again when a
7910 * new instance of the view is placed in its view hierarchy.
7911 * <p>
7912 * Some examples of things you may store here: the current cursor position
7913 * in a text view (but usually not the text itself since that is stored in a
7914 * content provider or other persistent storage), the currently selected
7915 * item in a list view.
7916 *
7917 * @return Returns a Parcelable object containing the view's current dynamic
7918 * state, or null if there is nothing interesting to save. The
7919 * default implementation returns null.
7920 * @see #onRestoreInstanceState
7921 * @see #saveHierarchyState
7922 * @see #dispatchSaveInstanceState
7923 * @see #setSaveEnabled(boolean)
7924 */
7925 protected Parcelable onSaveInstanceState() {
7926 mPrivateFlags |= SAVE_STATE_CALLED;
7927 return BaseSavedState.EMPTY_STATE;
7928 }
7929
7930 /**
7931 * Restore this view hierarchy's frozen state from the given container.
7932 *
7933 * @param container The SparseArray which holds previously frozen states.
7934 *
7935 * @see #saveHierarchyState
7936 * @see #dispatchRestoreInstanceState
7937 * @see #onRestoreInstanceState
7938 */
7939 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7940 dispatchRestoreInstanceState(container);
7941 }
7942
7943 /**
7944 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7945 * children. May be overridden to modify how restoreing happens to a view's children; for
7946 * example, some views may want to not store state for their children.
7947 *
7948 * @param container The SparseArray which holds previously saved state.
7949 *
7950 * @see #dispatchSaveInstanceState
7951 * @see #restoreHierarchyState
7952 * @see #onRestoreInstanceState
7953 */
7954 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7955 if (mID != NO_ID) {
7956 Parcelable state = container.get(mID);
7957 if (state != null) {
7958 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7959 // + ": " + state);
7960 mPrivateFlags &= ~SAVE_STATE_CALLED;
7961 onRestoreInstanceState(state);
7962 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7963 throw new IllegalStateException(
7964 "Derived class did not call super.onRestoreInstanceState()");
7965 }
7966 }
7967 }
7968 }
7969
7970 /**
7971 * Hook allowing a view to re-apply a representation of its internal state that had previously
7972 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7973 * null state.
7974 *
7975 * @param state The frozen state that had previously been returned by
7976 * {@link #onSaveInstanceState}.
7977 *
7978 * @see #onSaveInstanceState
7979 * @see #restoreHierarchyState
7980 * @see #dispatchRestoreInstanceState
7981 */
7982 protected void onRestoreInstanceState(Parcelable state) {
7983 mPrivateFlags |= SAVE_STATE_CALLED;
7984 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007985 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7986 + "received " + state.getClass().toString() + " instead. This usually happens "
7987 + "when two views of different type have the same id in the same hierarchy. "
7988 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7989 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007990 }
7991 }
7992
7993 /**
7994 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7995 *
7996 * @return the drawing start time in milliseconds
7997 */
7998 public long getDrawingTime() {
7999 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
8000 }
8001
8002 /**
8003 * <p>Enables or disables the duplication of the parent's state into this view. When
8004 * duplication is enabled, this view gets its drawable state from its parent rather
8005 * than from its own internal properties.</p>
8006 *
8007 * <p>Note: in the current implementation, setting this property to true after the
8008 * view was added to a ViewGroup might have no effect at all. This property should
8009 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
8010 *
8011 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
8012 * property is enabled, an exception will be thrown.</p>
Gilles Debunnefb817032011-01-13 13:52:49 -08008013 *
8014 * <p>Note: if the child view uses and updates additionnal states which are unknown to the
8015 * parent, these states should not be affected by this method.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008016 *
8017 * @param enabled True to enable duplication of the parent's drawable state, false
8018 * to disable it.
8019 *
8020 * @see #getDrawableState()
8021 * @see #isDuplicateParentStateEnabled()
8022 */
8023 public void setDuplicateParentStateEnabled(boolean enabled) {
8024 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
8025 }
8026
8027 /**
8028 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
8029 *
8030 * @return True if this view's drawable state is duplicated from the parent,
8031 * false otherwise
8032 *
8033 * @see #getDrawableState()
8034 * @see #setDuplicateParentStateEnabled(boolean)
8035 */
8036 public boolean isDuplicateParentStateEnabled() {
8037 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
8038 }
8039
8040 /**
Romain Guy171c5922011-01-06 10:04:23 -08008041 * <p>Specifies the type of layer backing this view. The layer can be
8042 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
8043 * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
8044 *
8045 * <p>A layer is associated with an optional {@link android.graphics.Paint}
8046 * instance that controls how the layer is composed on screen. The following
8047 * properties of the paint are taken into account when composing the layer:</p>
8048 * <ul>
8049 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
8050 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
8051 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
8052 * </ul>
8053 *
8054 * <p>If this view has an alpha value set to < 1.0 by calling
8055 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
8056 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
8057 * equivalent to setting a hardware layer on this view and providing a paint with
8058 * the desired alpha value.<p>
8059 *
8060 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
8061 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
8062 * for more information on when and how to use layers.</p>
8063 *
8064 * @param layerType The ype of layer to use with this view, must be one of
8065 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
8066 * {@link #LAYER_TYPE_HARDWARE}
8067 * @param paint The paint used to compose the layer. This argument is optional
8068 * and can be null. It is ignored when the layer type is
8069 * {@link #LAYER_TYPE_NONE}
8070 *
8071 * @see #getLayerType()
8072 * @see #LAYER_TYPE_NONE
8073 * @see #LAYER_TYPE_SOFTWARE
8074 * @see #LAYER_TYPE_HARDWARE
8075 * @see #setAlpha(float)
8076 *
8077 * @attr ref android.R.styleable#View_layerType
8078 */
8079 public void setLayerType(int layerType, Paint paint) {
8080 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
8081 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
8082 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
8083 }
Chet Haasedaf98e92011-01-10 14:10:36 -08008084
Romain Guyd6cd5722011-01-17 14:42:41 -08008085 if (layerType == mLayerType) {
8086 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
8087 mLayerPaint = paint == null ? new Paint() : paint;
Romain Guy0fd89bf2011-01-26 15:41:30 -08008088 invalidateParentCaches();
8089 invalidate(true);
Romain Guyd6cd5722011-01-17 14:42:41 -08008090 }
8091 return;
8092 }
Romain Guy171c5922011-01-06 10:04:23 -08008093
8094 // Destroy any previous software drawing cache if needed
Romain Guy6c319ca2011-01-11 14:29:25 -08008095 switch (mLayerType) {
8096 case LAYER_TYPE_SOFTWARE:
8097 if (mDrawingCache != null) {
8098 mDrawingCache.recycle();
8099 mDrawingCache = null;
8100 }
8101
8102 if (mUnscaledDrawingCache != null) {
8103 mUnscaledDrawingCache.recycle();
8104 mUnscaledDrawingCache = null;
8105 }
8106 break;
8107 case LAYER_TYPE_HARDWARE:
8108 if (mHardwareLayer != null) {
8109 mHardwareLayer.destroy();
8110 mHardwareLayer = null;
8111 }
8112 break;
8113 default:
8114 break;
Romain Guy171c5922011-01-06 10:04:23 -08008115 }
8116
8117 mLayerType = layerType;
Romain Guyd6cd5722011-01-17 14:42:41 -08008118 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : (paint == null ? new Paint() : paint);
Romain Guy171c5922011-01-06 10:04:23 -08008119
Romain Guy0fd89bf2011-01-26 15:41:30 -08008120 invalidateParentCaches();
8121 invalidate(true);
Romain Guy171c5922011-01-06 10:04:23 -08008122 }
8123
8124 /**
8125 * Indicates what type of layer is currently associated with this view. By default
8126 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
8127 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
8128 * for more information on the different types of layers.
8129 *
8130 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
8131 * {@link #LAYER_TYPE_HARDWARE}
8132 *
8133 * @see #setLayerType(int, android.graphics.Paint)
8134 * @see #LAYER_TYPE_NONE
8135 * @see #LAYER_TYPE_SOFTWARE
8136 * @see #LAYER_TYPE_HARDWARE
8137 */
8138 public int getLayerType() {
8139 return mLayerType;
8140 }
Romain Guy6c319ca2011-01-11 14:29:25 -08008141
8142 /**
8143 * <p>Returns a hardware layer that can be used to draw this view again
8144 * without executing its draw method.</p>
8145 *
8146 * @return A HardwareLayer ready to render, or null if an error occurred.
8147 */
Romain Guy5e7f7662011-01-24 22:35:56 -08008148 HardwareLayer getHardwareLayer() {
Romain Guy6c319ca2011-01-11 14:29:25 -08008149 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8150 return null;
8151 }
8152
8153 final int width = mRight - mLeft;
8154 final int height = mBottom - mTop;
8155
8156 if (width == 0 || height == 0) {
8157 return null;
8158 }
8159
8160 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
8161 if (mHardwareLayer == null) {
8162 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
8163 width, height, isOpaque());
8164 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
8165 mHardwareLayer.resize(width, height);
8166 }
8167
Romain Guy5e7f7662011-01-24 22:35:56 -08008168 Canvas currentCanvas = mAttachInfo.mHardwareCanvas;
8169 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
8170 mAttachInfo.mHardwareCanvas = canvas;
Romain Guy6c319ca2011-01-11 14:29:25 -08008171 try {
8172 canvas.setViewport(width, height);
Romain Guy7d7b5492011-01-24 16:33:45 -08008173 // TODO: We should pass the dirty rect
8174 canvas.onPreDraw(null);
Romain Guy6c319ca2011-01-11 14:29:25 -08008175
Romain Guy4f09f542011-01-26 22:41:43 -08008176 final int restoreCount = canvas.save();
8177
Romain Guy6c319ca2011-01-11 14:29:25 -08008178 computeScroll();
8179 canvas.translate(-mScrollX, -mScrollY);
8180
Romain Guy6c319ca2011-01-11 14:29:25 -08008181 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8182
8183 // Fast path for layouts with no backgrounds
8184 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8185 mPrivateFlags &= ~DIRTY_MASK;
8186 dispatchDraw(canvas);
8187 } else {
8188 draw(canvas);
8189 }
8190
8191 canvas.restoreToCount(restoreCount);
8192 } finally {
8193 canvas.onPostDraw();
Romain Guy5e7f7662011-01-24 22:35:56 -08008194 mHardwareLayer.end(currentCanvas);
8195 mAttachInfo.mHardwareCanvas = currentCanvas;
Romain Guy6c319ca2011-01-11 14:29:25 -08008196 }
8197 }
8198
8199 return mHardwareLayer;
8200 }
Romain Guy171c5922011-01-06 10:04:23 -08008201
8202 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008203 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
8204 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
8205 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
8206 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
8207 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
8208 * null.</p>
Romain Guy171c5922011-01-06 10:04:23 -08008209 *
8210 * <p>Enabling the drawing cache is similar to
8211 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
Chet Haasedaf98e92011-01-10 14:10:36 -08008212 * acceleration is turned off. When hardware acceleration is turned on, enabling the
8213 * drawing cache has no effect on rendering because the system uses a different mechanism
8214 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
8215 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
8216 * for information on how to enable software and hardware layers.</p>
8217 *
8218 * <p>This API can be used to manually generate
8219 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
8220 * {@link #getDrawingCache()}.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008221 *
8222 * @param enabled true to enable the drawing cache, false otherwise
8223 *
8224 * @see #isDrawingCacheEnabled()
8225 * @see #getDrawingCache()
8226 * @see #buildDrawingCache()
Romain Guy171c5922011-01-06 10:04:23 -08008227 * @see #setLayerType(int, android.graphics.Paint)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228 */
8229 public void setDrawingCacheEnabled(boolean enabled) {
8230 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
8231 }
8232
8233 /**
8234 * <p>Indicates whether the drawing cache is enabled for this view.</p>
8235 *
8236 * @return true if the drawing cache is enabled
8237 *
8238 * @see #setDrawingCacheEnabled(boolean)
8239 * @see #getDrawingCache()
8240 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07008241 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008242 public boolean isDrawingCacheEnabled() {
8243 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
8244 }
8245
8246 /**
Chet Haasedaf98e92011-01-10 14:10:36 -08008247 * Debugging utility which recursively outputs the dirty state of a view and its
8248 * descendants.
8249 *
8250 * @hide
8251 */
8252 public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
8253 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
8254 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
8255 (mPrivateFlags & View.DRAWING_CACHE_VALID) +
8256 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
8257 if (clear) {
8258 mPrivateFlags &= clearMask;
8259 }
8260 if (this instanceof ViewGroup) {
8261 ViewGroup parent = (ViewGroup) this;
8262 final int count = parent.getChildCount();
8263 for (int i = 0; i < count; i++) {
Romain Guy7d7b5492011-01-24 16:33:45 -08008264 final View child = parent.getChildAt(i);
Chet Haasedaf98e92011-01-10 14:10:36 -08008265 child.outputDirtyFlags(indent + " ", clear, clearMask);
8266 }
8267 }
8268 }
8269
8270 /**
8271 * This method is used by ViewGroup to cause its children to restore or recreate their
8272 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
8273 * to recreate its own display list, which would happen if it went through the normal
8274 * draw/dispatchDraw mechanisms.
8275 *
8276 * @hide
8277 */
8278 protected void dispatchGetDisplayList() {}
Chet Haasef4ac5472011-01-27 10:30:25 -08008279
8280 /**
8281 * A view that is not attached or hardware accelerated cannot create a display list.
8282 * This method checks these conditions and returns the appropriate result.
8283 *
8284 * @return true if view has the ability to create a display list, false otherwise.
8285 *
8286 * @hide
8287 */
8288 public boolean canHaveDisplayList() {
8289 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8290 return false;
8291 }
8292 return true;
8293 }
Chet Haasedaf98e92011-01-10 14:10:36 -08008294
8295 /**
Romain Guyb051e892010-09-28 19:09:36 -07008296 * <p>Returns a display list that can be used to draw this view again
8297 * without executing its draw method.</p>
8298 *
8299 * @return A DisplayList ready to replay, or null if caching is not enabled.
Chet Haasedaf98e92011-01-10 14:10:36 -08008300 *
8301 * @hide
Romain Guyb051e892010-09-28 19:09:36 -07008302 */
Chet Haasedaf98e92011-01-10 14:10:36 -08008303 public DisplayList getDisplayList() {
Chet Haasef4ac5472011-01-27 10:30:25 -08008304 if (!canHaveDisplayList()) {
Romain Guyb051e892010-09-28 19:09:36 -07008305 return null;
8306 }
8307
Chet Haasedaf98e92011-01-10 14:10:36 -08008308 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
8309 mDisplayList == null || !mDisplayList.isValid() ||
8310 mRecreateDisplayList)) {
8311 // Don't need to recreate the display list, just need to tell our
8312 // children to restore/recreate theirs
8313 if (mDisplayList != null && mDisplayList.isValid() &&
8314 !mRecreateDisplayList) {
8315 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8316 mPrivateFlags &= ~DIRTY_MASK;
8317 dispatchGetDisplayList();
8318
8319 return mDisplayList;
8320 }
8321
8322 // If we got here, we're recreating it. Mark it as such to ensure that
8323 // we copy in child display lists into ours in drawChild()
8324 mRecreateDisplayList = true;
Chet Haase9e90a992011-01-04 16:23:21 -08008325 if (mDisplayList == null) {
Chet Haasedaf98e92011-01-10 14:10:36 -08008326 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this);
8327 // If we're creating a new display list, make sure our parent gets invalidated
8328 // since they will need to recreate their display list to account for this
8329 // new child display list.
Romain Guy0fd89bf2011-01-26 15:41:30 -08008330 invalidateParentCaches();
Chet Haase9e90a992011-01-04 16:23:21 -08008331 }
Romain Guyb051e892010-09-28 19:09:36 -07008332
8333 final HardwareCanvas canvas = mDisplayList.start();
8334 try {
8335 int width = mRight - mLeft;
8336 int height = mBottom - mTop;
8337
8338 canvas.setViewport(width, height);
Romain Guy7d7b5492011-01-24 16:33:45 -08008339 // The dirty rect should always be null for a display list
8340 canvas.onPreDraw(null);
Romain Guyb051e892010-09-28 19:09:36 -07008341
8342 final int restoreCount = canvas.save();
8343
Chet Haasedaf98e92011-01-10 14:10:36 -08008344 computeScroll();
8345 canvas.translate(-mScrollX, -mScrollY);
Romain Guy2fe9a8f2010-10-04 20:17:01 -07008346 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07008347
8348 // Fast path for layouts with no backgrounds
8349 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8350 mPrivateFlags &= ~DIRTY_MASK;
8351 dispatchDraw(canvas);
8352 } else {
8353 draw(canvas);
8354 }
8355
8356 canvas.restoreToCount(restoreCount);
8357 } finally {
8358 canvas.onPostDraw();
8359
8360 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07008361 }
Chet Haase77785f92011-01-25 23:22:09 -08008362 } else {
8363 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8364 mPrivateFlags &= ~DIRTY_MASK;
Romain Guyb051e892010-09-28 19:09:36 -07008365 }
8366
8367 return mDisplayList;
8368 }
8369
8370 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008371 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
8372 *
8373 * @return A non-scaled bitmap representing this view or null if cache is disabled.
8374 *
8375 * @see #getDrawingCache(boolean)
8376 */
8377 public Bitmap getDrawingCache() {
8378 return getDrawingCache(false);
8379 }
8380
8381 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008382 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
8383 * is null when caching is disabled. If caching is enabled and the cache is not ready,
8384 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
8385 * draw from the cache when the cache is enabled. To benefit from the cache, you must
8386 * request the drawing cache by calling this method and draw it on screen if the
8387 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008388 *
8389 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8390 * this method will create a bitmap of the same size as this view. Because this bitmap
8391 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8392 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8393 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8394 * size than the view. This implies that your application must be able to handle this
8395 * size.</p>
8396 *
8397 * @param autoScale Indicates whether the generated bitmap should be scaled based on
8398 * the current density of the screen when the application is in compatibility
8399 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008400 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008401 * @return A bitmap representing this view or null if cache is disabled.
8402 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008403 * @see #setDrawingCacheEnabled(boolean)
8404 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07008405 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008406 * @see #destroyDrawingCache()
8407 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008408 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8410 return null;
8411 }
8412 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008413 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008414 }
Romain Guy02890fd2010-08-06 17:58:44 -07008415 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008416 }
8417
8418 /**
8419 * <p>Frees the resources used by the drawing cache. If you call
8420 * {@link #buildDrawingCache()} manually without calling
8421 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8422 * should cleanup the cache with this method afterwards.</p>
8423 *
8424 * @see #setDrawingCacheEnabled(boolean)
8425 * @see #buildDrawingCache()
8426 * @see #getDrawingCache()
8427 */
8428 public void destroyDrawingCache() {
8429 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008430 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008431 mDrawingCache = null;
8432 }
Romain Guyfbd8f692009-06-26 14:51:58 -07008433 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008434 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07008435 mUnscaledDrawingCache = null;
8436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008437 }
8438
8439 /**
8440 * Setting a solid background color for the drawing cache's bitmaps will improve
8441 * perfromance and memory usage. Note, though that this should only be used if this
8442 * view will always be drawn on top of a solid color.
8443 *
8444 * @param color The background color to use for the drawing cache's bitmap
8445 *
8446 * @see #setDrawingCacheEnabled(boolean)
8447 * @see #buildDrawingCache()
8448 * @see #getDrawingCache()
8449 */
8450 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08008451 if (color != mDrawingCacheBackgroundColor) {
8452 mDrawingCacheBackgroundColor = color;
8453 mPrivateFlags &= ~DRAWING_CACHE_VALID;
8454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008455 }
8456
8457 /**
8458 * @see #setDrawingCacheBackgroundColor(int)
8459 *
8460 * @return The background color to used for the drawing cache's bitmap
8461 */
8462 public int getDrawingCacheBackgroundColor() {
8463 return mDrawingCacheBackgroundColor;
8464 }
8465
8466 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008467 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
8468 *
8469 * @see #buildDrawingCache(boolean)
8470 */
8471 public void buildDrawingCache() {
8472 buildDrawingCache(false);
8473 }
8474
8475 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
8477 *
8478 * <p>If you call {@link #buildDrawingCache()} manually without calling
8479 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8480 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008481 *
8482 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8483 * this method will create a bitmap of the same size as this view. Because this bitmap
8484 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8485 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8486 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8487 * size than the view. This implies that your application must be able to handle this
8488 * size.</p>
Romain Guy0d9275e2010-10-26 14:22:30 -07008489 *
8490 * <p>You should avoid calling this method when hardware acceleration is enabled. If
8491 * you do not need the drawing cache bitmap, calling this method will increase memory
8492 * usage and cause the view to be rendered in software once, thus negatively impacting
8493 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 *
8495 * @see #getDrawingCache()
8496 * @see #destroyDrawingCache()
8497 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008498 public void buildDrawingCache(boolean autoScale) {
8499 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07008500 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008501
8502 if (ViewDebug.TRACE_HIERARCHY) {
8503 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
8504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008505
Romain Guy8506ab42009-06-11 17:35:47 -07008506 int width = mRight - mLeft;
8507 int height = mBottom - mTop;
8508
8509 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07008510 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07008511
Romain Guye1123222009-06-29 14:24:56 -07008512 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008513 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
8514 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07008515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516
8517 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07008518 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08008519 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008520
8521 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07008522 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08008523 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008524 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
8525 destroyDrawingCache();
8526 return;
8527 }
8528
8529 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07008530 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531
8532 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 Bitmap.Config quality;
8534 if (!opaque) {
8535 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
8536 case DRAWING_CACHE_QUALITY_AUTO:
8537 quality = Bitmap.Config.ARGB_8888;
8538 break;
8539 case DRAWING_CACHE_QUALITY_LOW:
8540 quality = Bitmap.Config.ARGB_4444;
8541 break;
8542 case DRAWING_CACHE_QUALITY_HIGH:
8543 quality = Bitmap.Config.ARGB_8888;
8544 break;
8545 default:
8546 quality = Bitmap.Config.ARGB_8888;
8547 break;
8548 }
8549 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07008550 // Optimization for translucent windows
8551 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08008552 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008553 }
8554
8555 // Try to cleanup memory
8556 if (bitmap != null) bitmap.recycle();
8557
8558 try {
8559 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07008560 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07008561 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07008562 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008563 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07008564 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008565 }
Adam Powell26153a32010-11-08 15:22:27 -08008566 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008567 } catch (OutOfMemoryError e) {
8568 // If there is not enough memory to create the bitmap cache, just
8569 // ignore the issue as bitmap caches are not required to draw the
8570 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07008571 if (autoScale) {
8572 mDrawingCache = null;
8573 } else {
8574 mUnscaledDrawingCache = null;
8575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008576 return;
8577 }
8578
8579 clear = drawingCacheBackgroundColor != 0;
8580 }
8581
8582 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008583 if (attachInfo != null) {
8584 canvas = attachInfo.mCanvas;
8585 if (canvas == null) {
8586 canvas = new Canvas();
8587 }
8588 canvas.setBitmap(bitmap);
8589 // Temporarily clobber the cached Canvas in case one of our children
8590 // is also using a drawing cache. Without this, the children would
8591 // steal the canvas by attaching their own bitmap to it and bad, bad
8592 // thing would happen (invisible views, corrupted drawings, etc.)
8593 attachInfo.mCanvas = null;
8594 } else {
8595 // This case should hopefully never or seldom happen
8596 canvas = new Canvas(bitmap);
8597 }
8598
8599 if (clear) {
8600 bitmap.eraseColor(drawingCacheBackgroundColor);
8601 }
8602
8603 computeScroll();
8604 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07008605
Romain Guye1123222009-06-29 14:24:56 -07008606 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008607 final float scale = attachInfo.mApplicationScale;
8608 canvas.scale(scale, scale);
8609 }
8610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 canvas.translate(-mScrollX, -mScrollY);
8612
Romain Guy5bcdff42009-05-14 21:27:18 -07008613 mPrivateFlags |= DRAWN;
Romain Guy171c5922011-01-06 10:04:23 -08008614 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
8615 mLayerType != LAYER_TYPE_NONE) {
Romain Guy0d9275e2010-10-26 14:22:30 -07008616 mPrivateFlags |= DRAWING_CACHE_VALID;
8617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008618
8619 // Fast path for layouts with no backgrounds
8620 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8621 if (ViewDebug.TRACE_HIERARCHY) {
8622 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8623 }
Romain Guy5bcdff42009-05-14 21:27:18 -07008624 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625 dispatchDraw(canvas);
8626 } else {
8627 draw(canvas);
8628 }
8629
8630 canvas.restoreToCount(restoreCount);
8631
8632 if (attachInfo != null) {
8633 // Restore the cached Canvas for our siblings
8634 attachInfo.mCanvas = canvas;
8635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008636 }
8637 }
8638
8639 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008640 * Create a snapshot of the view into a bitmap. We should probably make
8641 * some form of this public, but should think about the API.
8642 */
Romain Guy223ff5c2010-03-02 17:07:47 -08008643 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008644 int width = mRight - mLeft;
8645 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008646
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008647 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07008648 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008649 width = (int) ((width * scale) + 0.5f);
8650 height = (int) ((height * scale) + 0.5f);
8651
Romain Guy8c11e312009-09-14 15:15:30 -07008652 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008653 if (bitmap == null) {
8654 throw new OutOfMemoryError();
8655 }
8656
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008657 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8658
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008659 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008660 if (attachInfo != null) {
8661 canvas = attachInfo.mCanvas;
8662 if (canvas == null) {
8663 canvas = new Canvas();
8664 }
8665 canvas.setBitmap(bitmap);
8666 // Temporarily clobber the cached Canvas in case one of our children
8667 // is also using a drawing cache. Without this, the children would
8668 // steal the canvas by attaching their own bitmap to it and bad, bad
8669 // things would happen (invisible views, corrupted drawings, etc.)
8670 attachInfo.mCanvas = null;
8671 } else {
8672 // This case should hopefully never or seldom happen
8673 canvas = new Canvas(bitmap);
8674 }
8675
Romain Guy5bcdff42009-05-14 21:27:18 -07008676 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008677 bitmap.eraseColor(backgroundColor);
8678 }
8679
8680 computeScroll();
8681 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008682 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008683 canvas.translate(-mScrollX, -mScrollY);
8684
Romain Guy5bcdff42009-05-14 21:27:18 -07008685 // Temporarily remove the dirty mask
8686 int flags = mPrivateFlags;
8687 mPrivateFlags &= ~DIRTY_MASK;
8688
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008689 // Fast path for layouts with no backgrounds
8690 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8691 dispatchDraw(canvas);
8692 } else {
8693 draw(canvas);
8694 }
8695
Romain Guy5bcdff42009-05-14 21:27:18 -07008696 mPrivateFlags = flags;
8697
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008698 canvas.restoreToCount(restoreCount);
8699
8700 if (attachInfo != null) {
8701 // Restore the cached Canvas for our siblings
8702 attachInfo.mCanvas = canvas;
8703 }
Romain Guy8506ab42009-06-11 17:35:47 -07008704
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008705 return bitmap;
8706 }
8707
8708 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 * Indicates whether this View is currently in edit mode. A View is usually
8710 * in edit mode when displayed within a developer tool. For instance, if
8711 * this View is being drawn by a visual user interface builder, this method
8712 * should return true.
8713 *
8714 * Subclasses should check the return value of this method to provide
8715 * different behaviors if their normal behavior might interfere with the
8716 * host environment. For instance: the class spawns a thread in its
8717 * constructor, the drawing code relies on device-specific features, etc.
8718 *
8719 * This method is usually checked in the drawing code of custom widgets.
8720 *
8721 * @return True if this View is in edit mode, false otherwise.
8722 */
8723 public boolean isInEditMode() {
8724 return false;
8725 }
8726
8727 /**
8728 * If the View draws content inside its padding and enables fading edges,
8729 * it needs to support padding offsets. Padding offsets are added to the
8730 * fading edges to extend the length of the fade so that it covers pixels
8731 * drawn inside the padding.
8732 *
8733 * Subclasses of this class should override this method if they need
8734 * to draw content inside the padding.
8735 *
8736 * @return True if padding offset must be applied, false otherwise.
8737 *
8738 * @see #getLeftPaddingOffset()
8739 * @see #getRightPaddingOffset()
8740 * @see #getTopPaddingOffset()
8741 * @see #getBottomPaddingOffset()
8742 *
8743 * @since CURRENT
8744 */
8745 protected boolean isPaddingOffsetRequired() {
8746 return false;
8747 }
8748
8749 /**
8750 * Amount by which to extend the left fading region. Called only when
8751 * {@link #isPaddingOffsetRequired()} returns true.
8752 *
8753 * @return The left padding offset in pixels.
8754 *
8755 * @see #isPaddingOffsetRequired()
8756 *
8757 * @since CURRENT
8758 */
8759 protected int getLeftPaddingOffset() {
8760 return 0;
8761 }
8762
8763 /**
8764 * Amount by which to extend the right fading region. Called only when
8765 * {@link #isPaddingOffsetRequired()} returns true.
8766 *
8767 * @return The right padding offset in pixels.
8768 *
8769 * @see #isPaddingOffsetRequired()
8770 *
8771 * @since CURRENT
8772 */
8773 protected int getRightPaddingOffset() {
8774 return 0;
8775 }
8776
8777 /**
8778 * Amount by which to extend the top fading region. Called only when
8779 * {@link #isPaddingOffsetRequired()} returns true.
8780 *
8781 * @return The top padding offset in pixels.
8782 *
8783 * @see #isPaddingOffsetRequired()
8784 *
8785 * @since CURRENT
8786 */
8787 protected int getTopPaddingOffset() {
8788 return 0;
8789 }
8790
8791 /**
8792 * Amount by which to extend the bottom fading region. Called only when
8793 * {@link #isPaddingOffsetRequired()} returns true.
8794 *
8795 * @return The bottom padding offset in pixels.
8796 *
8797 * @see #isPaddingOffsetRequired()
8798 *
8799 * @since CURRENT
8800 */
8801 protected int getBottomPaddingOffset() {
8802 return 0;
8803 }
8804
8805 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008806 * <p>Indicates whether this view is attached to an hardware accelerated
8807 * window or not.</p>
8808 *
8809 * <p>Even if this method returns true, it does not mean that every call
8810 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8811 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8812 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8813 * window is hardware accelerated,
8814 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8815 * return false, and this method will return true.</p>
8816 *
8817 * @return True if the view is attached to a window and the window is
8818 * hardware accelerated; false in any other case.
8819 */
8820 public boolean isHardwareAccelerated() {
8821 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8822 }
8823
8824 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008825 * Manually render this view (and all of its children) to the given Canvas.
8826 * The view must have already done a full layout before this function is
Chet Haasec75ec332010-12-17 07:44:30 -08008827 * called. When implementing a view, implement {@link #onDraw} instead of
8828 * overriding this method. If you do need to override this method, call
8829 * the superclass version.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008830 *
8831 * @param canvas The Canvas to which the View is rendered.
8832 */
8833 public void draw(Canvas canvas) {
8834 if (ViewDebug.TRACE_HIERARCHY) {
8835 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8836 }
8837
Romain Guy5bcdff42009-05-14 21:27:18 -07008838 final int privateFlags = mPrivateFlags;
8839 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8840 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8841 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008843 /*
8844 * Draw traversal performs several drawing steps which must be executed
8845 * in the appropriate order:
8846 *
8847 * 1. Draw the background
8848 * 2. If necessary, save the canvas' layers to prepare for fading
8849 * 3. Draw view's content
8850 * 4. Draw children
8851 * 5. If necessary, draw the fading edges and restore layers
8852 * 6. Draw decorations (scrollbars for instance)
8853 */
8854
8855 // Step 1, draw the background, if needed
8856 int saveCount;
8857
Romain Guy24443ea2009-05-11 11:56:30 -07008858 if (!dirtyOpaque) {
8859 final Drawable background = mBGDrawable;
8860 if (background != null) {
8861 final int scrollX = mScrollX;
8862 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008863
Romain Guy24443ea2009-05-11 11:56:30 -07008864 if (mBackgroundSizeChanged) {
8865 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8866 mBackgroundSizeChanged = false;
8867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008868
Romain Guy24443ea2009-05-11 11:56:30 -07008869 if ((scrollX | scrollY) == 0) {
8870 background.draw(canvas);
8871 } else {
8872 canvas.translate(scrollX, scrollY);
8873 background.draw(canvas);
8874 canvas.translate(-scrollX, -scrollY);
8875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008876 }
8877 }
8878
8879 // skip step 2 & 5 if possible (common case)
8880 final int viewFlags = mViewFlags;
8881 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8882 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8883 if (!verticalEdges && !horizontalEdges) {
8884 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008885 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008886
8887 // Step 4, draw the children
8888 dispatchDraw(canvas);
8889
8890 // Step 6, draw decorations (scrollbars)
8891 onDrawScrollBars(canvas);
8892
8893 // we're done...
8894 return;
8895 }
8896
8897 /*
8898 * Here we do the full fledged routine...
8899 * (this is an uncommon case where speed matters less,
8900 * this is why we repeat some of the tests that have been
8901 * done above)
8902 */
8903
8904 boolean drawTop = false;
8905 boolean drawBottom = false;
8906 boolean drawLeft = false;
8907 boolean drawRight = false;
8908
8909 float topFadeStrength = 0.0f;
8910 float bottomFadeStrength = 0.0f;
8911 float leftFadeStrength = 0.0f;
8912 float rightFadeStrength = 0.0f;
8913
8914 // Step 2, save the canvas' layers
8915 int paddingLeft = mPaddingLeft;
8916 int paddingTop = mPaddingTop;
8917
8918 final boolean offsetRequired = isPaddingOffsetRequired();
8919 if (offsetRequired) {
8920 paddingLeft += getLeftPaddingOffset();
8921 paddingTop += getTopPaddingOffset();
8922 }
8923
8924 int left = mScrollX + paddingLeft;
8925 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8926 int top = mScrollY + paddingTop;
8927 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8928
8929 if (offsetRequired) {
8930 right += getRightPaddingOffset();
8931 bottom += getBottomPaddingOffset();
8932 }
8933
8934 final ScrollabilityCache scrollabilityCache = mScrollCache;
8935 int length = scrollabilityCache.fadingEdgeLength;
8936
8937 // clip the fade length if top and bottom fades overlap
8938 // overlapping fades produce odd-looking artifacts
8939 if (verticalEdges && (top + length > bottom - length)) {
8940 length = (bottom - top) / 2;
8941 }
8942
8943 // also clip horizontal fades if necessary
8944 if (horizontalEdges && (left + length > right - length)) {
8945 length = (right - left) / 2;
8946 }
8947
8948 if (verticalEdges) {
8949 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008950 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008951 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008952 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008953 }
8954
8955 if (horizontalEdges) {
8956 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008957 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008958 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008959 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 }
8961
8962 saveCount = canvas.getSaveCount();
8963
8964 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008965 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008966 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8967
8968 if (drawTop) {
8969 canvas.saveLayer(left, top, right, top + length, null, flags);
8970 }
8971
8972 if (drawBottom) {
8973 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8974 }
8975
8976 if (drawLeft) {
8977 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8978 }
8979
8980 if (drawRight) {
8981 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8982 }
8983 } else {
8984 scrollabilityCache.setFadeColor(solidColor);
8985 }
8986
8987 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008988 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989
8990 // Step 4, draw the children
8991 dispatchDraw(canvas);
8992
8993 // Step 5, draw the fade effect and restore layers
8994 final Paint p = scrollabilityCache.paint;
8995 final Matrix matrix = scrollabilityCache.matrix;
8996 final Shader fade = scrollabilityCache.shader;
8997 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8998
8999 if (drawTop) {
9000 matrix.setScale(1, fadeHeight * topFadeStrength);
9001 matrix.postTranslate(left, top);
9002 fade.setLocalMatrix(matrix);
9003 canvas.drawRect(left, top, right, top + length, p);
9004 }
9005
9006 if (drawBottom) {
9007 matrix.setScale(1, fadeHeight * bottomFadeStrength);
9008 matrix.postRotate(180);
9009 matrix.postTranslate(left, bottom);
9010 fade.setLocalMatrix(matrix);
9011 canvas.drawRect(left, bottom - length, right, bottom, p);
9012 }
9013
9014 if (drawLeft) {
9015 matrix.setScale(1, fadeHeight * leftFadeStrength);
9016 matrix.postRotate(-90);
9017 matrix.postTranslate(left, top);
9018 fade.setLocalMatrix(matrix);
9019 canvas.drawRect(left, top, left + length, bottom, p);
9020 }
9021
9022 if (drawRight) {
9023 matrix.setScale(1, fadeHeight * rightFadeStrength);
9024 matrix.postRotate(90);
9025 matrix.postTranslate(right, top);
9026 fade.setLocalMatrix(matrix);
9027 canvas.drawRect(right - length, top, right, bottom, p);
9028 }
9029
9030 canvas.restoreToCount(saveCount);
9031
9032 // Step 6, draw decorations (scrollbars)
9033 onDrawScrollBars(canvas);
9034 }
9035
9036 /**
9037 * Override this if your view is known to always be drawn on top of a solid color background,
9038 * and needs to draw fading edges. Returning a non-zero color enables the view system to
9039 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
9040 * should be set to 0xFF.
9041 *
9042 * @see #setVerticalFadingEdgeEnabled
9043 * @see #setHorizontalFadingEdgeEnabled
9044 *
9045 * @return The known solid color background for this view, or 0 if the color may vary
9046 */
9047 public int getSolidColor() {
9048 return 0;
9049 }
9050
9051 /**
9052 * Build a human readable string representation of the specified view flags.
9053 *
9054 * @param flags the view flags to convert to a string
9055 * @return a String representing the supplied flags
9056 */
9057 private static String printFlags(int flags) {
9058 String output = "";
9059 int numFlags = 0;
9060 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
9061 output += "TAKES_FOCUS";
9062 numFlags++;
9063 }
9064
9065 switch (flags & VISIBILITY_MASK) {
9066 case INVISIBLE:
9067 if (numFlags > 0) {
9068 output += " ";
9069 }
9070 output += "INVISIBLE";
9071 // USELESS HERE numFlags++;
9072 break;
9073 case GONE:
9074 if (numFlags > 0) {
9075 output += " ";
9076 }
9077 output += "GONE";
9078 // USELESS HERE numFlags++;
9079 break;
9080 default:
9081 break;
9082 }
9083 return output;
9084 }
9085
9086 /**
9087 * Build a human readable string representation of the specified private
9088 * view flags.
9089 *
9090 * @param privateFlags the private view flags to convert to a string
9091 * @return a String representing the supplied flags
9092 */
9093 private static String printPrivateFlags(int privateFlags) {
9094 String output = "";
9095 int numFlags = 0;
9096
9097 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
9098 output += "WANTS_FOCUS";
9099 numFlags++;
9100 }
9101
9102 if ((privateFlags & FOCUSED) == FOCUSED) {
9103 if (numFlags > 0) {
9104 output += " ";
9105 }
9106 output += "FOCUSED";
9107 numFlags++;
9108 }
9109
9110 if ((privateFlags & SELECTED) == SELECTED) {
9111 if (numFlags > 0) {
9112 output += " ";
9113 }
9114 output += "SELECTED";
9115 numFlags++;
9116 }
9117
9118 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
9119 if (numFlags > 0) {
9120 output += " ";
9121 }
9122 output += "IS_ROOT_NAMESPACE";
9123 numFlags++;
9124 }
9125
9126 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
9127 if (numFlags > 0) {
9128 output += " ";
9129 }
9130 output += "HAS_BOUNDS";
9131 numFlags++;
9132 }
9133
9134 if ((privateFlags & DRAWN) == DRAWN) {
9135 if (numFlags > 0) {
9136 output += " ";
9137 }
9138 output += "DRAWN";
9139 // USELESS HERE numFlags++;
9140 }
9141 return output;
9142 }
9143
9144 /**
9145 * <p>Indicates whether or not this view's layout will be requested during
9146 * the next hierarchy layout pass.</p>
9147 *
9148 * @return true if the layout will be forced during next layout pass
9149 */
9150 public boolean isLayoutRequested() {
9151 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
9152 }
9153
9154 /**
9155 * Assign a size and position to a view and all of its
9156 * descendants
9157 *
9158 * <p>This is the second phase of the layout mechanism.
9159 * (The first is measuring). In this phase, each parent calls
9160 * layout on all of its children to position them.
9161 * This is typically done using the child measurements
Chet Haase9c087442011-01-12 16:20:16 -08009162 * that were stored in the measure pass().</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009163 *
Chet Haase9c087442011-01-12 16:20:16 -08009164 * <p>Derived classes should not override this method.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009165 * Derived classes with children should override
9166 * onLayout. In that method, they should
Chet Haase9c087442011-01-12 16:20:16 -08009167 * call layout on each of their children.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009168 *
9169 * @param l Left position, relative to parent
9170 * @param t Top position, relative to parent
9171 * @param r Right position, relative to parent
9172 * @param b Bottom position, relative to parent
9173 */
Romain Guy5429e1d2010-09-07 12:38:00 -07009174 @SuppressWarnings({"unchecked"})
Chet Haase9c087442011-01-12 16:20:16 -08009175 public void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07009176 int oldL = mLeft;
9177 int oldT = mTop;
9178 int oldB = mBottom;
9179 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009180 boolean changed = setFrame(l, t, r, b);
9181 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
9182 if (ViewDebug.TRACE_HIERARCHY) {
9183 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
9184 }
9185
9186 onLayout(changed, l, t, r, b);
9187 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07009188
9189 if (mOnLayoutChangeListeners != null) {
9190 ArrayList<OnLayoutChangeListener> listenersCopy =
9191 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
9192 int numListeners = listenersCopy.size();
9193 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07009194 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07009195 }
9196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009197 }
9198 mPrivateFlags &= ~FORCE_LAYOUT;
9199 }
9200
9201 /**
9202 * Called from layout when this view should
9203 * assign a size and position to each of its children.
9204 *
9205 * Derived classes with children should override
9206 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07009207 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009208 * @param changed This is a new size or position for this view
9209 * @param left Left position, relative to parent
9210 * @param top Top position, relative to parent
9211 * @param right Right position, relative to parent
9212 * @param bottom Bottom position, relative to parent
9213 */
9214 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
9215 }
9216
9217 /**
9218 * Assign a size and position to this view.
9219 *
9220 * This is called from layout.
9221 *
9222 * @param left Left position, relative to parent
9223 * @param top Top position, relative to parent
9224 * @param right Right position, relative to parent
9225 * @param bottom Bottom position, relative to parent
9226 * @return true if the new size and position are different than the
9227 * previous ones
9228 * {@hide}
9229 */
9230 protected boolean setFrame(int left, int top, int right, int bottom) {
9231 boolean changed = false;
9232
9233 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07009234 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009235 + right + "," + bottom + ")");
9236 }
9237
9238 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
9239 changed = true;
9240
9241 // Remember our drawn bit
9242 int drawn = mPrivateFlags & DRAWN;
9243
9244 // Invalidate our old position
Romain Guy0fd89bf2011-01-26 15:41:30 -08009245 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009246
9247
9248 int oldWidth = mRight - mLeft;
9249 int oldHeight = mBottom - mTop;
9250
9251 mLeft = left;
9252 mTop = top;
9253 mRight = right;
9254 mBottom = bottom;
9255
9256 mPrivateFlags |= HAS_BOUNDS;
9257
9258 int newWidth = right - left;
9259 int newHeight = bottom - top;
9260
9261 if (newWidth != oldWidth || newHeight != oldHeight) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009262 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9263 // A change in dimension means an auto-centered pivot point changes, too
9264 mMatrixDirty = true;
9265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
9267 }
9268
9269 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
9270 // If we are visible, force the DRAWN bit to on so that
9271 // this invalidate will go through (at least to our parent).
9272 // This is because someone may have invalidated this view
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009273 // before this call to setFrame came in, thereby clearing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009274 // the DRAWN bit.
9275 mPrivateFlags |= DRAWN;
Romain Guy0fd89bf2011-01-26 15:41:30 -08009276 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009277 }
9278
9279 // Reset drawn bit to original value (invalidate turns it off)
9280 mPrivateFlags |= drawn;
9281
9282 mBackgroundSizeChanged = true;
9283 }
9284 return changed;
9285 }
9286
9287 /**
9288 * Finalize inflating a view from XML. This is called as the last phase
9289 * of inflation, after all child views have been added.
9290 *
9291 * <p>Even if the subclass overrides onFinishInflate, they should always be
9292 * sure to call the super method, so that we get called.
9293 */
9294 protected void onFinishInflate() {
9295 }
9296
9297 /**
9298 * Returns the resources associated with this view.
9299 *
9300 * @return Resources object.
9301 */
9302 public Resources getResources() {
9303 return mResources;
9304 }
9305
9306 /**
9307 * Invalidates the specified Drawable.
9308 *
9309 * @param drawable the drawable to invalidate
9310 */
9311 public void invalidateDrawable(Drawable drawable) {
9312 if (verifyDrawable(drawable)) {
9313 final Rect dirty = drawable.getBounds();
9314 final int scrollX = mScrollX;
9315 final int scrollY = mScrollY;
9316
9317 invalidate(dirty.left + scrollX, dirty.top + scrollY,
9318 dirty.right + scrollX, dirty.bottom + scrollY);
9319 }
9320 }
9321
9322 /**
9323 * Schedules an action on a drawable to occur at a specified time.
9324 *
9325 * @param who the recipient of the action
9326 * @param what the action to run on the drawable
9327 * @param when the time at which the action must occur. Uses the
9328 * {@link SystemClock#uptimeMillis} timebase.
9329 */
9330 public void scheduleDrawable(Drawable who, Runnable what, long when) {
9331 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9332 mAttachInfo.mHandler.postAtTime(what, who, when);
9333 }
9334 }
9335
9336 /**
9337 * Cancels a scheduled action on a drawable.
9338 *
9339 * @param who the recipient of the action
9340 * @param what the action to cancel
9341 */
9342 public void unscheduleDrawable(Drawable who, Runnable what) {
9343 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9344 mAttachInfo.mHandler.removeCallbacks(what, who);
9345 }
9346 }
9347
9348 /**
9349 * Unschedule any events associated with the given Drawable. This can be
9350 * used when selecting a new Drawable into a view, so that the previous
9351 * one is completely unscheduled.
9352 *
9353 * @param who The Drawable to unschedule.
9354 *
9355 * @see #drawableStateChanged
9356 */
9357 public void unscheduleDrawable(Drawable who) {
9358 if (mAttachInfo != null) {
9359 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
9360 }
9361 }
9362
9363 /**
9364 * If your view subclass is displaying its own Drawable objects, it should
9365 * override this function and return true for any Drawable it is
9366 * displaying. This allows animations for those drawables to be
9367 * scheduled.
9368 *
9369 * <p>Be sure to call through to the super class when overriding this
9370 * function.
9371 *
9372 * @param who The Drawable to verify. Return true if it is one you are
9373 * displaying, else return the result of calling through to the
9374 * super class.
9375 *
9376 * @return boolean If true than the Drawable is being displayed in the
9377 * view; else false and it is not allowed to animate.
9378 *
9379 * @see #unscheduleDrawable
9380 * @see #drawableStateChanged
9381 */
9382 protected boolean verifyDrawable(Drawable who) {
9383 return who == mBGDrawable;
9384 }
9385
9386 /**
9387 * This function is called whenever the state of the view changes in such
9388 * a way that it impacts the state of drawables being shown.
9389 *
9390 * <p>Be sure to call through to the superclass when overriding this
9391 * function.
9392 *
9393 * @see Drawable#setState
9394 */
9395 protected void drawableStateChanged() {
9396 Drawable d = mBGDrawable;
9397 if (d != null && d.isStateful()) {
9398 d.setState(getDrawableState());
9399 }
9400 }
9401
9402 /**
9403 * Call this to force a view to update its drawable state. This will cause
9404 * drawableStateChanged to be called on this view. Views that are interested
9405 * in the new state should call getDrawableState.
9406 *
9407 * @see #drawableStateChanged
9408 * @see #getDrawableState
9409 */
9410 public void refreshDrawableState() {
9411 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9412 drawableStateChanged();
9413
9414 ViewParent parent = mParent;
9415 if (parent != null) {
9416 parent.childDrawableStateChanged(this);
9417 }
9418 }
9419
9420 /**
9421 * Return an array of resource IDs of the drawable states representing the
9422 * current state of the view.
9423 *
9424 * @return The current drawable state
9425 *
9426 * @see Drawable#setState
9427 * @see #drawableStateChanged
9428 * @see #onCreateDrawableState
9429 */
9430 public final int[] getDrawableState() {
9431 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
9432 return mDrawableState;
9433 } else {
9434 mDrawableState = onCreateDrawableState(0);
9435 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
9436 return mDrawableState;
9437 }
9438 }
9439
9440 /**
9441 * Generate the new {@link android.graphics.drawable.Drawable} state for
9442 * this view. This is called by the view
9443 * system when the cached Drawable state is determined to be invalid. To
9444 * retrieve the current state, you should use {@link #getDrawableState}.
9445 *
9446 * @param extraSpace if non-zero, this is the number of extra entries you
9447 * would like in the returned array in which you can place your own
9448 * states.
9449 *
9450 * @return Returns an array holding the current {@link Drawable} state of
9451 * the view.
9452 *
9453 * @see #mergeDrawableStates
9454 */
9455 protected int[] onCreateDrawableState(int extraSpace) {
9456 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
9457 mParent instanceof View) {
9458 return ((View) mParent).onCreateDrawableState(extraSpace);
9459 }
9460
9461 int[] drawableState;
9462
9463 int privateFlags = mPrivateFlags;
9464
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009465 int viewStateIndex = 0;
9466 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
9467 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
9468 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07009469 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009470 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
9471 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08009472 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
9473 // This is set if HW acceleration is requested, even if the current
9474 // process doesn't allow it. This is just to allow app preview
9475 // windows to better match their app.
9476 viewStateIndex |= VIEW_STATE_ACCELERATED;
9477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009478
9479 drawableState = VIEW_STATE_SETS[viewStateIndex];
9480
9481 //noinspection ConstantIfStatement
9482 if (false) {
9483 Log.i("View", "drawableStateIndex=" + viewStateIndex);
9484 Log.i("View", toString()
9485 + " pressed=" + ((privateFlags & PRESSED) != 0)
9486 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
9487 + " fo=" + hasFocus()
9488 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009489 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009490 + ": " + Arrays.toString(drawableState));
9491 }
9492
9493 if (extraSpace == 0) {
9494 return drawableState;
9495 }
9496
9497 final int[] fullState;
9498 if (drawableState != null) {
9499 fullState = new int[drawableState.length + extraSpace];
9500 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
9501 } else {
9502 fullState = new int[extraSpace];
9503 }
9504
9505 return fullState;
9506 }
9507
9508 /**
9509 * Merge your own state values in <var>additionalState</var> into the base
9510 * state values <var>baseState</var> that were returned by
9511 * {@link #onCreateDrawableState}.
9512 *
9513 * @param baseState The base state values returned by
9514 * {@link #onCreateDrawableState}, which will be modified to also hold your
9515 * own additional state values.
9516 *
9517 * @param additionalState The additional state values you would like
9518 * added to <var>baseState</var>; this array is not modified.
9519 *
9520 * @return As a convenience, the <var>baseState</var> array you originally
9521 * passed into the function is returned.
9522 *
9523 * @see #onCreateDrawableState
9524 */
9525 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
9526 final int N = baseState.length;
9527 int i = N - 1;
9528 while (i >= 0 && baseState[i] == 0) {
9529 i--;
9530 }
9531 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
9532 return baseState;
9533 }
9534
9535 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07009536 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
9537 * on all Drawable objects associated with this view.
9538 */
9539 public void jumpDrawablesToCurrentState() {
9540 if (mBGDrawable != null) {
9541 mBGDrawable.jumpToCurrentState();
9542 }
9543 }
9544
9545 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009546 * Sets the background color for this view.
9547 * @param color the color of the background
9548 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009549 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009550 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07009551 if (mBGDrawable instanceof ColorDrawable) {
9552 ((ColorDrawable) mBGDrawable).setColor(color);
9553 } else {
9554 setBackgroundDrawable(new ColorDrawable(color));
9555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009556 }
9557
9558 /**
9559 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07009560 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009561 * @param resid The identifier of the resource.
9562 * @attr ref android.R.styleable#View_background
9563 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009564 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009565 public void setBackgroundResource(int resid) {
9566 if (resid != 0 && resid == mBackgroundResource) {
9567 return;
9568 }
9569
9570 Drawable d= null;
9571 if (resid != 0) {
9572 d = mResources.getDrawable(resid);
9573 }
9574 setBackgroundDrawable(d);
9575
9576 mBackgroundResource = resid;
9577 }
9578
9579 /**
9580 * Set the background to a given Drawable, or remove the background. If the
9581 * background has padding, this View's padding is set to the background's
9582 * padding. However, when a background is removed, this View's padding isn't
9583 * touched. If setting the padding is desired, please use
9584 * {@link #setPadding(int, int, int, int)}.
9585 *
9586 * @param d The Drawable to use as the background, or null to remove the
9587 * background
9588 */
9589 public void setBackgroundDrawable(Drawable d) {
9590 boolean requestLayout = false;
9591
9592 mBackgroundResource = 0;
9593
9594 /*
9595 * Regardless of whether we're setting a new background or not, we want
9596 * to clear the previous drawable.
9597 */
9598 if (mBGDrawable != null) {
9599 mBGDrawable.setCallback(null);
9600 unscheduleDrawable(mBGDrawable);
9601 }
9602
9603 if (d != null) {
9604 Rect padding = sThreadLocal.get();
9605 if (padding == null) {
9606 padding = new Rect();
9607 sThreadLocal.set(padding);
9608 }
9609 if (d.getPadding(padding)) {
9610 setPadding(padding.left, padding.top, padding.right, padding.bottom);
9611 }
9612
9613 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
9614 // if it has a different minimum size, we should layout again
9615 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9616 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9617 requestLayout = true;
9618 }
9619
9620 d.setCallback(this);
9621 if (d.isStateful()) {
9622 d.setState(getDrawableState());
9623 }
9624 d.setVisible(getVisibility() == VISIBLE, false);
9625 mBGDrawable = d;
9626
9627 if ((mPrivateFlags & SKIP_DRAW) != 0) {
9628 mPrivateFlags &= ~SKIP_DRAW;
9629 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9630 requestLayout = true;
9631 }
9632 } else {
9633 /* Remove the background */
9634 mBGDrawable = null;
9635
9636 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9637 /*
9638 * This view ONLY drew the background before and we're removing
9639 * the background, so now it won't draw anything
9640 * (hence we SKIP_DRAW)
9641 */
9642 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9643 mPrivateFlags |= SKIP_DRAW;
9644 }
9645
9646 /*
9647 * When the background is set, we try to apply its padding to this
9648 * View. When the background is removed, we don't touch this View's
9649 * padding. This is noted in the Javadocs. Hence, we don't need to
9650 * requestLayout(), the invalidate() below is sufficient.
9651 */
9652
9653 // The old background's minimum size could have affected this
9654 // View's layout, so let's requestLayout
9655 requestLayout = true;
9656 }
9657
Romain Guy8f1344f52009-05-15 16:03:59 -07009658 computeOpaqueFlags();
9659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009660 if (requestLayout) {
9661 requestLayout();
9662 }
9663
9664 mBackgroundSizeChanged = true;
Romain Guy0fd89bf2011-01-26 15:41:30 -08009665 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009666 }
9667
9668 /**
9669 * Gets the background drawable
9670 * @return The drawable used as the background for this view, if any.
9671 */
9672 public Drawable getBackground() {
9673 return mBGDrawable;
9674 }
9675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009676 /**
9677 * Sets the padding. The view may add on the space required to display
9678 * the scrollbars, depending on the style and visibility of the scrollbars.
9679 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9680 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9681 * from the values set in this call.
9682 *
9683 * @attr ref android.R.styleable#View_padding
9684 * @attr ref android.R.styleable#View_paddingBottom
9685 * @attr ref android.R.styleable#View_paddingLeft
9686 * @attr ref android.R.styleable#View_paddingRight
9687 * @attr ref android.R.styleable#View_paddingTop
9688 * @param left the left padding in pixels
9689 * @param top the top padding in pixels
9690 * @param right the right padding in pixels
9691 * @param bottom the bottom padding in pixels
9692 */
9693 public void setPadding(int left, int top, int right, int bottom) {
9694 boolean changed = false;
9695
Adam Powell20232d02010-12-08 21:08:53 -08009696 mUserPaddingLeft = left;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009697 mUserPaddingRight = right;
9698 mUserPaddingBottom = bottom;
9699
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009700 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07009701
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009702 // Common case is there are no scroll bars.
9703 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009704 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
Adam Powell20232d02010-12-08 21:08:53 -08009705 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9706 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009707 ? 0 : getVerticalScrollbarWidth();
Adam Powell20232d02010-12-08 21:08:53 -08009708 switch (mVerticalScrollbarPosition) {
9709 case SCROLLBAR_POSITION_DEFAULT:
9710 case SCROLLBAR_POSITION_RIGHT:
9711 right += offset;
9712 break;
9713 case SCROLLBAR_POSITION_LEFT:
9714 left += offset;
9715 break;
9716 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009717 }
Adam Powell20232d02010-12-08 21:08:53 -08009718 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009719 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9720 ? 0 : getHorizontalScrollbarHeight();
9721 }
9722 }
Romain Guy8506ab42009-06-11 17:35:47 -07009723
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009724 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009725 changed = true;
9726 mPaddingLeft = left;
9727 }
9728 if (mPaddingTop != top) {
9729 changed = true;
9730 mPaddingTop = top;
9731 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009732 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009733 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009734 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009735 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009736 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009737 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009738 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009739 }
9740
9741 if (changed) {
9742 requestLayout();
9743 }
9744 }
9745
9746 /**
9747 * Returns the top padding of this view.
9748 *
9749 * @return the top padding in pixels
9750 */
9751 public int getPaddingTop() {
9752 return mPaddingTop;
9753 }
9754
9755 /**
9756 * Returns the bottom padding of this view. If there are inset and enabled
9757 * scrollbars, this value may include the space required to display the
9758 * scrollbars as well.
9759 *
9760 * @return the bottom padding in pixels
9761 */
9762 public int getPaddingBottom() {
9763 return mPaddingBottom;
9764 }
9765
9766 /**
9767 * Returns the left padding of this view. If there are inset and enabled
9768 * scrollbars, this value may include the space required to display the
9769 * scrollbars as well.
9770 *
9771 * @return the left padding in pixels
9772 */
9773 public int getPaddingLeft() {
9774 return mPaddingLeft;
9775 }
9776
9777 /**
9778 * Returns the right padding of this view. If there are inset and enabled
9779 * scrollbars, this value may include the space required to display the
9780 * scrollbars as well.
9781 *
9782 * @return the right padding in pixels
9783 */
9784 public int getPaddingRight() {
9785 return mPaddingRight;
9786 }
9787
9788 /**
9789 * Changes the selection state of this view. A view can be selected or not.
9790 * Note that selection is not the same as focus. Views are typically
9791 * selected in the context of an AdapterView like ListView or GridView;
9792 * the selected view is the view that is highlighted.
9793 *
9794 * @param selected true if the view must be selected, false otherwise
9795 */
9796 public void setSelected(boolean selected) {
9797 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9798 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009799 if (!selected) resetPressedState();
Romain Guy0fd89bf2011-01-26 15:41:30 -08009800 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009801 refreshDrawableState();
9802 dispatchSetSelected(selected);
9803 }
9804 }
9805
9806 /**
9807 * Dispatch setSelected to all of this View's children.
9808 *
9809 * @see #setSelected(boolean)
9810 *
9811 * @param selected The new selected state
9812 */
9813 protected void dispatchSetSelected(boolean selected) {
9814 }
9815
9816 /**
9817 * Indicates the selection state of this view.
9818 *
9819 * @return true if the view is selected, false otherwise
9820 */
9821 @ViewDebug.ExportedProperty
9822 public boolean isSelected() {
9823 return (mPrivateFlags & SELECTED) != 0;
9824 }
9825
9826 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009827 * Changes the activated state of this view. A view can be activated or not.
9828 * Note that activation is not the same as selection. Selection is
9829 * a transient property, representing the view (hierarchy) the user is
9830 * currently interacting with. Activation is a longer-term state that the
9831 * user can move views in and out of. For example, in a list view with
9832 * single or multiple selection enabled, the views in the current selection
9833 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9834 * here.) The activated state is propagated down to children of the view it
9835 * is set on.
9836 *
9837 * @param activated true if the view must be activated, false otherwise
9838 */
9839 public void setActivated(boolean activated) {
9840 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9841 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
Romain Guy0fd89bf2011-01-26 15:41:30 -08009842 invalidate(true);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009843 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009844 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009845 }
9846 }
9847
9848 /**
9849 * Dispatch setActivated to all of this View's children.
9850 *
9851 * @see #setActivated(boolean)
9852 *
9853 * @param activated The new activated state
9854 */
9855 protected void dispatchSetActivated(boolean activated) {
9856 }
9857
9858 /**
9859 * Indicates the activation state of this view.
9860 *
9861 * @return true if the view is activated, false otherwise
9862 */
9863 @ViewDebug.ExportedProperty
9864 public boolean isActivated() {
9865 return (mPrivateFlags & ACTIVATED) != 0;
9866 }
9867
9868 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009869 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9870 * observer can be used to get notifications when global events, like
9871 * layout, happen.
9872 *
9873 * The returned ViewTreeObserver observer is not guaranteed to remain
9874 * valid for the lifetime of this View. If the caller of this method keeps
9875 * a long-lived reference to ViewTreeObserver, it should always check for
9876 * the return value of {@link ViewTreeObserver#isAlive()}.
9877 *
9878 * @return The ViewTreeObserver for this view's hierarchy.
9879 */
9880 public ViewTreeObserver getViewTreeObserver() {
9881 if (mAttachInfo != null) {
9882 return mAttachInfo.mTreeObserver;
9883 }
9884 if (mFloatingTreeObserver == null) {
9885 mFloatingTreeObserver = new ViewTreeObserver();
9886 }
9887 return mFloatingTreeObserver;
9888 }
9889
9890 /**
9891 * <p>Finds the topmost view in the current view hierarchy.</p>
9892 *
9893 * @return the topmost view containing this view
9894 */
9895 public View getRootView() {
9896 if (mAttachInfo != null) {
9897 final View v = mAttachInfo.mRootView;
9898 if (v != null) {
9899 return v;
9900 }
9901 }
Romain Guy8506ab42009-06-11 17:35:47 -07009902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009903 View parent = this;
9904
9905 while (parent.mParent != null && parent.mParent instanceof View) {
9906 parent = (View) parent.mParent;
9907 }
9908
9909 return parent;
9910 }
9911
9912 /**
9913 * <p>Computes the coordinates of this view on the screen. The argument
9914 * must be an array of two integers. After the method returns, the array
9915 * contains the x and y location in that order.</p>
9916 *
9917 * @param location an array of two integers in which to hold the coordinates
9918 */
9919 public void getLocationOnScreen(int[] location) {
9920 getLocationInWindow(location);
9921
9922 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009923 if (info != null) {
9924 location[0] += info.mWindowLeft;
9925 location[1] += info.mWindowTop;
9926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009927 }
9928
9929 /**
9930 * <p>Computes the coordinates of this view in its window. The argument
9931 * must be an array of two integers. After the method returns, the array
9932 * contains the x and y location in that order.</p>
9933 *
9934 * @param location an array of two integers in which to hold the coordinates
9935 */
9936 public void getLocationInWindow(int[] location) {
9937 if (location == null || location.length < 2) {
9938 throw new IllegalArgumentException("location must be an array of "
9939 + "two integers");
9940 }
9941
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009942 location[0] = mLeft + (int) (mTranslationX + 0.5f);
9943 location[1] = mTop + (int) (mTranslationY + 0.5f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009944
9945 ViewParent viewParent = mParent;
9946 while (viewParent instanceof View) {
9947 final View view = (View)viewParent;
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009948 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
9949 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009950 viewParent = view.mParent;
9951 }
Romain Guy8506ab42009-06-11 17:35:47 -07009952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009953 if (viewParent instanceof ViewRoot) {
9954 // *cough*
9955 final ViewRoot vr = (ViewRoot)viewParent;
9956 location[1] -= vr.mCurScrollY;
9957 }
9958 }
9959
9960 /**
9961 * {@hide}
9962 * @param id the id of the view to be found
9963 * @return the view of the specified id, null if cannot be found
9964 */
9965 protected View findViewTraversal(int id) {
9966 if (id == mID) {
9967 return this;
9968 }
9969 return null;
9970 }
9971
9972 /**
9973 * {@hide}
9974 * @param tag the tag of the view to be found
9975 * @return the view of specified tag, null if cannot be found
9976 */
9977 protected View findViewWithTagTraversal(Object tag) {
9978 if (tag != null && tag.equals(mTag)) {
9979 return this;
9980 }
9981 return null;
9982 }
9983
9984 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009985 * {@hide}
9986 * @param predicate The predicate to evaluate.
9987 * @return The first view that matches the predicate or null.
9988 */
9989 protected View findViewByPredicateTraversal(Predicate<View> predicate) {
9990 if (predicate.apply(this)) {
9991 return this;
9992 }
9993 return null;
9994 }
9995
9996 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009997 * Look for a child view with the given id. If this view has the given
9998 * id, return this view.
9999 *
10000 * @param id The id to search for.
10001 * @return The view that has the given id in the hierarchy or null
10002 */
10003 public final View findViewById(int id) {
10004 if (id < 0) {
10005 return null;
10006 }
10007 return findViewTraversal(id);
10008 }
10009
10010 /**
10011 * Look for a child view with the given tag. If this view has the given
10012 * tag, return this view.
10013 *
10014 * @param tag The tag to search for, using "tag.equals(getTag())".
10015 * @return The View that has the given tag in the hierarchy or null
10016 */
10017 public final View findViewWithTag(Object tag) {
10018 if (tag == null) {
10019 return null;
10020 }
10021 return findViewWithTagTraversal(tag);
10022 }
10023
10024 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -080010025 * {@hide}
10026 * Look for a child view that matches the specified predicate.
10027 * If this view matches the predicate, return this view.
10028 *
10029 * @param predicate The predicate to evaluate.
10030 * @return The first view that matches the predicate or null.
10031 */
10032 public final View findViewByPredicate(Predicate<View> predicate) {
10033 return findViewByPredicateTraversal(predicate);
10034 }
10035
10036 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010037 * Sets the identifier for this view. The identifier does not have to be
10038 * unique in this view's hierarchy. The identifier should be a positive
10039 * number.
10040 *
10041 * @see #NO_ID
10042 * @see #getId
10043 * @see #findViewById
10044 *
10045 * @param id a number used to identify the view
10046 *
10047 * @attr ref android.R.styleable#View_id
10048 */
10049 public void setId(int id) {
10050 mID = id;
10051 }
10052
10053 /**
10054 * {@hide}
10055 *
10056 * @param isRoot true if the view belongs to the root namespace, false
10057 * otherwise
10058 */
10059 public void setIsRootNamespace(boolean isRoot) {
10060 if (isRoot) {
10061 mPrivateFlags |= IS_ROOT_NAMESPACE;
10062 } else {
10063 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
10064 }
10065 }
10066
10067 /**
10068 * {@hide}
10069 *
10070 * @return true if the view belongs to the root namespace, false otherwise
10071 */
10072 public boolean isRootNamespace() {
10073 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
10074 }
10075
10076 /**
10077 * Returns this view's identifier.
10078 *
10079 * @return a positive integer used to identify the view or {@link #NO_ID}
10080 * if the view has no ID
10081 *
10082 * @see #setId
10083 * @see #findViewById
10084 * @attr ref android.R.styleable#View_id
10085 */
10086 @ViewDebug.CapturedViewProperty
10087 public int getId() {
10088 return mID;
10089 }
10090
10091 /**
10092 * Returns this view's tag.
10093 *
10094 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -070010095 *
10096 * @see #setTag(Object)
10097 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010098 */
10099 @ViewDebug.ExportedProperty
10100 public Object getTag() {
10101 return mTag;
10102 }
10103
10104 /**
10105 * Sets the tag associated with this view. A tag can be used to mark
10106 * a view in its hierarchy and does not have to be unique within the
10107 * hierarchy. Tags can also be used to store data within a view without
10108 * resorting to another data structure.
10109 *
10110 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -070010111 *
10112 * @see #getTag()
10113 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010114 */
10115 public void setTag(final Object tag) {
10116 mTag = tag;
10117 }
10118
10119 /**
Romain Guyd90a3312009-05-06 14:54:28 -070010120 * Returns the tag associated with this view and the specified key.
10121 *
10122 * @param key The key identifying the tag
10123 *
10124 * @return the Object stored in this view as a tag
10125 *
10126 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -070010127 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -070010128 */
10129 public Object getTag(int key) {
10130 SparseArray<Object> tags = null;
10131 synchronized (sTagsLock) {
10132 if (sTags != null) {
10133 tags = sTags.get(this);
10134 }
10135 }
10136
10137 if (tags != null) return tags.get(key);
10138 return null;
10139 }
10140
10141 /**
10142 * Sets a tag associated with this view and a key. A tag can be used
10143 * to mark a view in its hierarchy and does not have to be unique within
10144 * the hierarchy. Tags can also be used to store data within a view
10145 * without resorting to another data structure.
10146 *
10147 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -070010148 * application to ensure it is unique (see the <a
10149 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
10150 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -070010151 * the Android framework or not associated with any package will cause
10152 * an {@link IllegalArgumentException} to be thrown.
10153 *
10154 * @param key The key identifying the tag
10155 * @param tag An Object to tag the view with
10156 *
10157 * @throws IllegalArgumentException If they specified key is not valid
10158 *
10159 * @see #setTag(Object)
10160 * @see #getTag(int)
10161 */
10162 public void setTag(int key, final Object tag) {
10163 // If the package id is 0x00 or 0x01, it's either an undefined package
10164 // or a framework id
10165 if ((key >>> 24) < 2) {
10166 throw new IllegalArgumentException("The key must be an application-specific "
10167 + "resource id.");
10168 }
10169
10170 setTagInternal(this, key, tag);
10171 }
10172
10173 /**
10174 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
10175 * framework id.
10176 *
10177 * @hide
10178 */
10179 public void setTagInternal(int key, Object tag) {
10180 if ((key >>> 24) != 0x1) {
10181 throw new IllegalArgumentException("The key must be a framework-specific "
10182 + "resource id.");
10183 }
10184
Romain Guy8506ab42009-06-11 17:35:47 -070010185 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -070010186 }
10187
10188 private static void setTagInternal(View view, int key, Object tag) {
10189 SparseArray<Object> tags = null;
10190 synchronized (sTagsLock) {
10191 if (sTags == null) {
10192 sTags = new WeakHashMap<View, SparseArray<Object>>();
10193 } else {
10194 tags = sTags.get(view);
10195 }
10196 }
10197
10198 if (tags == null) {
10199 tags = new SparseArray<Object>(2);
10200 synchronized (sTagsLock) {
10201 sTags.put(view, tags);
10202 }
10203 }
10204
10205 tags.put(key, tag);
10206 }
10207
10208 /**
Romain Guy13922e02009-05-12 17:56:14 -070010209 * @param consistency The type of consistency. See ViewDebug for more information.
10210 *
10211 * @hide
10212 */
10213 protected boolean dispatchConsistencyCheck(int consistency) {
10214 return onConsistencyCheck(consistency);
10215 }
10216
10217 /**
10218 * Method that subclasses should implement to check their consistency. The type of
10219 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -070010220 *
Romain Guy13922e02009-05-12 17:56:14 -070010221 * @param consistency The type of consistency. See ViewDebug for more information.
10222 *
10223 * @throws IllegalStateException if the view is in an inconsistent state.
10224 *
10225 * @hide
10226 */
10227 protected boolean onConsistencyCheck(int consistency) {
10228 boolean result = true;
10229
10230 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
10231 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
10232
10233 if (checkLayout) {
10234 if (getParent() == null) {
10235 result = false;
10236 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10237 "View " + this + " does not have a parent.");
10238 }
10239
10240 if (mAttachInfo == null) {
10241 result = false;
10242 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10243 "View " + this + " is not attached to a window.");
10244 }
10245 }
10246
10247 if (checkDrawing) {
10248 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
10249 // from their draw() method
10250
10251 if ((mPrivateFlags & DRAWN) != DRAWN &&
10252 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
10253 result = false;
10254 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10255 "View " + this + " was invalidated but its drawing cache is valid.");
10256 }
10257 }
10258
10259 return result;
10260 }
10261
10262 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010263 * Prints information about this view in the log output, with the tag
10264 * {@link #VIEW_LOG_TAG}.
10265 *
10266 * @hide
10267 */
10268 public void debug() {
10269 debug(0);
10270 }
10271
10272 /**
10273 * Prints information about this view in the log output, with the tag
10274 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
10275 * indentation defined by the <code>depth</code>.
10276 *
10277 * @param depth the indentation level
10278 *
10279 * @hide
10280 */
10281 protected void debug(int depth) {
10282 String output = debugIndent(depth - 1);
10283
10284 output += "+ " + this;
10285 int id = getId();
10286 if (id != -1) {
10287 output += " (id=" + id + ")";
10288 }
10289 Object tag = getTag();
10290 if (tag != null) {
10291 output += " (tag=" + tag + ")";
10292 }
10293 Log.d(VIEW_LOG_TAG, output);
10294
10295 if ((mPrivateFlags & FOCUSED) != 0) {
10296 output = debugIndent(depth) + " FOCUSED";
10297 Log.d(VIEW_LOG_TAG, output);
10298 }
10299
10300 output = debugIndent(depth);
10301 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
10302 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
10303 + "} ";
10304 Log.d(VIEW_LOG_TAG, output);
10305
10306 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
10307 || mPaddingBottom != 0) {
10308 output = debugIndent(depth);
10309 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
10310 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
10311 Log.d(VIEW_LOG_TAG, output);
10312 }
10313
10314 output = debugIndent(depth);
10315 output += "mMeasureWidth=" + mMeasuredWidth +
10316 " mMeasureHeight=" + mMeasuredHeight;
10317 Log.d(VIEW_LOG_TAG, output);
10318
10319 output = debugIndent(depth);
10320 if (mLayoutParams == null) {
10321 output += "BAD! no layout params";
10322 } else {
10323 output = mLayoutParams.debug(output);
10324 }
10325 Log.d(VIEW_LOG_TAG, output);
10326
10327 output = debugIndent(depth);
10328 output += "flags={";
10329 output += View.printFlags(mViewFlags);
10330 output += "}";
10331 Log.d(VIEW_LOG_TAG, output);
10332
10333 output = debugIndent(depth);
10334 output += "privateFlags={";
10335 output += View.printPrivateFlags(mPrivateFlags);
10336 output += "}";
10337 Log.d(VIEW_LOG_TAG, output);
10338 }
10339
10340 /**
10341 * Creates an string of whitespaces used for indentation.
10342 *
10343 * @param depth the indentation level
10344 * @return a String containing (depth * 2 + 3) * 2 white spaces
10345 *
10346 * @hide
10347 */
10348 protected static String debugIndent(int depth) {
10349 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
10350 for (int i = 0; i < (depth * 2) + 3; i++) {
10351 spaces.append(' ').append(' ');
10352 }
10353 return spaces.toString();
10354 }
10355
10356 /**
10357 * <p>Return the offset of the widget's text baseline from the widget's top
10358 * boundary. If this widget does not support baseline alignment, this
10359 * method returns -1. </p>
10360 *
10361 * @return the offset of the baseline within the widget's bounds or -1
10362 * if baseline alignment is not supported
10363 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -070010364 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010365 public int getBaseline() {
10366 return -1;
10367 }
10368
10369 /**
10370 * Call this when something has changed which has invalidated the
10371 * layout of this view. This will schedule a layout pass of the view
10372 * tree.
10373 */
10374 public void requestLayout() {
10375 if (ViewDebug.TRACE_HIERARCHY) {
10376 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
10377 }
10378
10379 mPrivateFlags |= FORCE_LAYOUT;
Chet Haase5af048c2011-01-24 17:00:32 -080010380 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010381
10382 if (mParent != null && !mParent.isLayoutRequested()) {
10383 mParent.requestLayout();
10384 }
10385 }
10386
10387 /**
10388 * Forces this view to be laid out during the next layout pass.
10389 * This method does not call requestLayout() or forceLayout()
10390 * on the parent.
10391 */
10392 public void forceLayout() {
10393 mPrivateFlags |= FORCE_LAYOUT;
Chet Haase5af048c2011-01-24 17:00:32 -080010394 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010395 }
10396
10397 /**
10398 * <p>
10399 * This is called to find out how big a view should be. The parent
10400 * supplies constraint information in the width and height parameters.
10401 * </p>
10402 *
10403 * <p>
10404 * The actual mesurement work of a view is performed in
10405 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
10406 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
10407 * </p>
10408 *
10409 *
10410 * @param widthMeasureSpec Horizontal space requirements as imposed by the
10411 * parent
10412 * @param heightMeasureSpec Vertical space requirements as imposed by the
10413 * parent
10414 *
10415 * @see #onMeasure(int, int)
10416 */
10417 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
10418 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
10419 widthMeasureSpec != mOldWidthMeasureSpec ||
10420 heightMeasureSpec != mOldHeightMeasureSpec) {
10421
10422 // first clears the measured dimension flag
10423 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
10424
10425 if (ViewDebug.TRACE_HIERARCHY) {
10426 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
10427 }
10428
10429 // measure ourselves, this should set the measured dimension flag back
10430 onMeasure(widthMeasureSpec, heightMeasureSpec);
10431
10432 // flag not set, setMeasuredDimension() was not invoked, we raise
10433 // an exception to warn the developer
10434 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
10435 throw new IllegalStateException("onMeasure() did not set the"
10436 + " measured dimension by calling"
10437 + " setMeasuredDimension()");
10438 }
10439
10440 mPrivateFlags |= LAYOUT_REQUIRED;
10441 }
10442
10443 mOldWidthMeasureSpec = widthMeasureSpec;
10444 mOldHeightMeasureSpec = heightMeasureSpec;
10445 }
10446
10447 /**
10448 * <p>
10449 * Measure the view and its content to determine the measured width and the
10450 * measured height. This method is invoked by {@link #measure(int, int)} and
10451 * should be overriden by subclasses to provide accurate and efficient
10452 * measurement of their contents.
10453 * </p>
10454 *
10455 * <p>
10456 * <strong>CONTRACT:</strong> When overriding this method, you
10457 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
10458 * measured width and height of this view. Failure to do so will trigger an
10459 * <code>IllegalStateException</code>, thrown by
10460 * {@link #measure(int, int)}. Calling the superclass'
10461 * {@link #onMeasure(int, int)} is a valid use.
10462 * </p>
10463 *
10464 * <p>
10465 * The base class implementation of measure defaults to the background size,
10466 * unless a larger size is allowed by the MeasureSpec. Subclasses should
10467 * override {@link #onMeasure(int, int)} to provide better measurements of
10468 * their content.
10469 * </p>
10470 *
10471 * <p>
10472 * If this method is overridden, it is the subclass's responsibility to make
10473 * sure the measured height and width are at least the view's minimum height
10474 * and width ({@link #getSuggestedMinimumHeight()} and
10475 * {@link #getSuggestedMinimumWidth()}).
10476 * </p>
10477 *
10478 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
10479 * The requirements are encoded with
10480 * {@link android.view.View.MeasureSpec}.
10481 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
10482 * The requirements are encoded with
10483 * {@link android.view.View.MeasureSpec}.
10484 *
10485 * @see #getMeasuredWidth()
10486 * @see #getMeasuredHeight()
10487 * @see #setMeasuredDimension(int, int)
10488 * @see #getSuggestedMinimumHeight()
10489 * @see #getSuggestedMinimumWidth()
10490 * @see android.view.View.MeasureSpec#getMode(int)
10491 * @see android.view.View.MeasureSpec#getSize(int)
10492 */
10493 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10494 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
10495 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
10496 }
10497
10498 /**
10499 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
10500 * measured width and measured height. Failing to do so will trigger an
10501 * exception at measurement time.</p>
10502 *
Dianne Hackborn189ee182010-12-02 21:48:53 -080010503 * @param measuredWidth The measured width of this view. May be a complex
10504 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10505 * {@link #MEASURED_STATE_TOO_SMALL}.
10506 * @param measuredHeight The measured height of this view. May be a complex
10507 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10508 * {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010509 */
10510 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
10511 mMeasuredWidth = measuredWidth;
10512 mMeasuredHeight = measuredHeight;
10513
10514 mPrivateFlags |= MEASURED_DIMENSION_SET;
10515 }
10516
10517 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -080010518 * Merge two states as returned by {@link #getMeasuredState()}.
10519 * @param curState The current state as returned from a view or the result
10520 * of combining multiple views.
10521 * @param newState The new view state to combine.
10522 * @return Returns a new integer reflecting the combination of the two
10523 * states.
10524 */
10525 public static int combineMeasuredStates(int curState, int newState) {
10526 return curState | newState;
10527 }
10528
10529 /**
10530 * Version of {@link #resolveSizeAndState(int, int, int)}
10531 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
10532 */
10533 public static int resolveSize(int size, int measureSpec) {
10534 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
10535 }
10536
10537 /**
10538 * Utility to reconcile a desired size and state, with constraints imposed
10539 * by a MeasureSpec. Will take the desired size, unless a different size
10540 * is imposed by the constraints. The returned value is a compound integer,
10541 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
10542 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
10543 * size is smaller than the size the view wants to be.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010544 *
10545 * @param size How big the view wants to be
10546 * @param measureSpec Constraints imposed by the parent
Dianne Hackborn189ee182010-12-02 21:48:53 -080010547 * @return Size information bit mask as defined by
10548 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010549 */
Dianne Hackborn189ee182010-12-02 21:48:53 -080010550 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010551 int result = size;
10552 int specMode = MeasureSpec.getMode(measureSpec);
10553 int specSize = MeasureSpec.getSize(measureSpec);
10554 switch (specMode) {
10555 case MeasureSpec.UNSPECIFIED:
10556 result = size;
10557 break;
10558 case MeasureSpec.AT_MOST:
Dianne Hackborn189ee182010-12-02 21:48:53 -080010559 if (specSize < size) {
10560 result = specSize | MEASURED_STATE_TOO_SMALL;
10561 } else {
10562 result = size;
10563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010564 break;
10565 case MeasureSpec.EXACTLY:
10566 result = specSize;
10567 break;
10568 }
Dianne Hackborn189ee182010-12-02 21:48:53 -080010569 return result | (childMeasuredState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010570 }
10571
10572 /**
10573 * Utility to return a default size. Uses the supplied size if the
10574 * MeasureSpec imposed no contraints. Will get larger if allowed
10575 * by the MeasureSpec.
10576 *
10577 * @param size Default size for this view
10578 * @param measureSpec Constraints imposed by the parent
10579 * @return The size this view should be.
10580 */
10581 public static int getDefaultSize(int size, int measureSpec) {
10582 int result = size;
10583 int specMode = MeasureSpec.getMode(measureSpec);
10584 int specSize = MeasureSpec.getSize(measureSpec);
10585
10586 switch (specMode) {
10587 case MeasureSpec.UNSPECIFIED:
10588 result = size;
10589 break;
10590 case MeasureSpec.AT_MOST:
10591 case MeasureSpec.EXACTLY:
10592 result = specSize;
10593 break;
10594 }
10595 return result;
10596 }
10597
10598 /**
10599 * Returns the suggested minimum height that the view should use. This
10600 * returns the maximum of the view's minimum height
10601 * and the background's minimum height
10602 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10603 * <p>
10604 * When being used in {@link #onMeasure(int, int)}, the caller should still
10605 * ensure the returned height is within the requirements of the parent.
10606 *
10607 * @return The suggested minimum height of the view.
10608 */
10609 protected int getSuggestedMinimumHeight() {
10610 int suggestedMinHeight = mMinHeight;
10611
10612 if (mBGDrawable != null) {
10613 final int bgMinHeight = mBGDrawable.getMinimumHeight();
10614 if (suggestedMinHeight < bgMinHeight) {
10615 suggestedMinHeight = bgMinHeight;
10616 }
10617 }
10618
10619 return suggestedMinHeight;
10620 }
10621
10622 /**
10623 * Returns the suggested minimum width that the view should use. This
10624 * returns the maximum of the view's minimum width)
10625 * and the background's minimum width
10626 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10627 * <p>
10628 * When being used in {@link #onMeasure(int, int)}, the caller should still
10629 * ensure the returned width is within the requirements of the parent.
10630 *
10631 * @return The suggested minimum width of the view.
10632 */
10633 protected int getSuggestedMinimumWidth() {
10634 int suggestedMinWidth = mMinWidth;
10635
10636 if (mBGDrawable != null) {
10637 final int bgMinWidth = mBGDrawable.getMinimumWidth();
10638 if (suggestedMinWidth < bgMinWidth) {
10639 suggestedMinWidth = bgMinWidth;
10640 }
10641 }
10642
10643 return suggestedMinWidth;
10644 }
10645
10646 /**
10647 * Sets the minimum height of the view. It is not guaranteed the view will
10648 * be able to achieve this minimum height (for example, if its parent layout
10649 * constrains it with less available height).
10650 *
10651 * @param minHeight The minimum height the view will try to be.
10652 */
10653 public void setMinimumHeight(int minHeight) {
10654 mMinHeight = minHeight;
10655 }
10656
10657 /**
10658 * Sets the minimum width of the view. It is not guaranteed the view will
10659 * be able to achieve this minimum width (for example, if its parent layout
10660 * constrains it with less available width).
10661 *
10662 * @param minWidth The minimum width the view will try to be.
10663 */
10664 public void setMinimumWidth(int minWidth) {
10665 mMinWidth = minWidth;
10666 }
10667
10668 /**
10669 * Get the animation currently associated with this view.
10670 *
10671 * @return The animation that is currently playing or
10672 * scheduled to play for this view.
10673 */
10674 public Animation getAnimation() {
10675 return mCurrentAnimation;
10676 }
10677
10678 /**
10679 * Start the specified animation now.
10680 *
10681 * @param animation the animation to start now
10682 */
10683 public void startAnimation(Animation animation) {
10684 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10685 setAnimation(animation);
Romain Guy0fd89bf2011-01-26 15:41:30 -080010686 invalidateParentCaches();
10687 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 }
10689
10690 /**
10691 * Cancels any animations for this view.
10692 */
10693 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -080010694 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -080010695 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -080010696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010697 mCurrentAnimation = null;
Romain Guy0fd89bf2011-01-26 15:41:30 -080010698 invalidateParentIfNeeded();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010699 }
10700
10701 /**
10702 * Sets the next animation to play for this view.
10703 * If you want the animation to play immediately, use
10704 * startAnimation. This method provides allows fine-grained
10705 * control over the start time and invalidation, but you
10706 * must make sure that 1) the animation has a start time set, and
10707 * 2) the view will be invalidated when the animation is supposed to
10708 * start.
10709 *
10710 * @param animation The next animation, or null.
10711 */
10712 public void setAnimation(Animation animation) {
10713 mCurrentAnimation = animation;
10714 if (animation != null) {
10715 animation.reset();
10716 }
10717 }
10718
10719 /**
10720 * Invoked by a parent ViewGroup to notify the start of the animation
10721 * currently associated with this view. If you override this method,
10722 * always call super.onAnimationStart();
10723 *
10724 * @see #setAnimation(android.view.animation.Animation)
10725 * @see #getAnimation()
10726 */
10727 protected void onAnimationStart() {
10728 mPrivateFlags |= ANIMATION_STARTED;
10729 }
10730
10731 /**
10732 * Invoked by a parent ViewGroup to notify the end of the animation
10733 * currently associated with this view. If you override this method,
10734 * always call super.onAnimationEnd();
10735 *
10736 * @see #setAnimation(android.view.animation.Animation)
10737 * @see #getAnimation()
10738 */
10739 protected void onAnimationEnd() {
10740 mPrivateFlags &= ~ANIMATION_STARTED;
10741 }
10742
10743 /**
10744 * Invoked if there is a Transform that involves alpha. Subclass that can
10745 * draw themselves with the specified alpha should return true, and then
10746 * respect that alpha when their onDraw() is called. If this returns false
10747 * then the view may be redirected to draw into an offscreen buffer to
10748 * fulfill the request, which will look fine, but may be slower than if the
10749 * subclass handles it internally. The default implementation returns false.
10750 *
10751 * @param alpha The alpha (0..255) to apply to the view's drawing
10752 * @return true if the view can draw with the specified alpha.
10753 */
10754 protected boolean onSetAlpha(int alpha) {
10755 return false;
10756 }
10757
10758 /**
10759 * This is used by the RootView to perform an optimization when
10760 * the view hierarchy contains one or several SurfaceView.
10761 * SurfaceView is always considered transparent, but its children are not,
10762 * therefore all View objects remove themselves from the global transparent
10763 * region (passed as a parameter to this function).
10764 *
10765 * @param region The transparent region for this ViewRoot (window).
10766 *
10767 * @return Returns true if the effective visibility of the view at this
10768 * point is opaque, regardless of the transparent region; returns false
10769 * if it is possible for underlying windows to be seen behind the view.
10770 *
10771 * {@hide}
10772 */
10773 public boolean gatherTransparentRegion(Region region) {
10774 final AttachInfo attachInfo = mAttachInfo;
10775 if (region != null && attachInfo != null) {
10776 final int pflags = mPrivateFlags;
10777 if ((pflags & SKIP_DRAW) == 0) {
10778 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10779 // remove it from the transparent region.
10780 final int[] location = attachInfo.mTransparentLocation;
10781 getLocationInWindow(location);
10782 region.op(location[0], location[1], location[0] + mRight - mLeft,
10783 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10784 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10785 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10786 // exists, so we remove the background drawable's non-transparent
10787 // parts from this transparent region.
10788 applyDrawableToTransparentRegion(mBGDrawable, region);
10789 }
10790 }
10791 return true;
10792 }
10793
10794 /**
10795 * Play a sound effect for this view.
10796 *
10797 * <p>The framework will play sound effects for some built in actions, such as
10798 * clicking, but you may wish to play these effects in your widget,
10799 * for instance, for internal navigation.
10800 *
10801 * <p>The sound effect will only be played if sound effects are enabled by the user, and
10802 * {@link #isSoundEffectsEnabled()} is true.
10803 *
10804 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10805 */
10806 public void playSoundEffect(int soundConstant) {
10807 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10808 return;
10809 }
10810 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10811 }
10812
10813 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010814 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010815 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010816 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010817 *
10818 * <p>The framework will provide haptic feedback for some built in actions,
10819 * such as long presses, but you may wish to provide feedback for your
10820 * own widget.
10821 *
10822 * <p>The feedback will only be performed if
10823 * {@link #isHapticFeedbackEnabled()} is true.
10824 *
10825 * @param feedbackConstant One of the constants defined in
10826 * {@link HapticFeedbackConstants}
10827 */
10828 public boolean performHapticFeedback(int feedbackConstant) {
10829 return performHapticFeedback(feedbackConstant, 0);
10830 }
10831
10832 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010833 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010834 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010835 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010836 *
10837 * @param feedbackConstant One of the constants defined in
10838 * {@link HapticFeedbackConstants}
10839 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10840 */
10841 public boolean performHapticFeedback(int feedbackConstant, int flags) {
10842 if (mAttachInfo == null) {
10843 return false;
10844 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010845 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010846 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010847 && !isHapticFeedbackEnabled()) {
10848 return false;
10849 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010850 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10851 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010852 }
10853
10854 /**
Joe Onorato664644d2011-01-23 17:53:23 -080010855 * Request that the visibility of the status bar be changed.
10856 */
10857 public void setSystemUiVisibility(int visibility) {
10858 if (visibility != mSystemUiVisibility) {
10859 mSystemUiVisibility = visibility;
10860 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10861 mParent.recomputeViewAttributes(this);
10862 }
10863 }
10864 }
10865
10866 /**
10867 * Returns the status bar visibility that this view has requested.
10868 */
Joe Onoratoe595cad2011-01-24 09:22:12 -080010869 public int getSystemUiVisibility() {
Joe Onorato664644d2011-01-23 17:53:23 -080010870 return mSystemUiVisibility;
10871 }
10872
10873 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
10874 mOnSystemUiVisibilityChangeListener = l;
10875 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10876 mParent.recomputeViewAttributes(this);
10877 }
10878 }
10879
10880 /**
10881 */
10882 public void dispatchSystemUiVisibilityChanged(int visibility) {
Joe Onorato14782f72011-01-25 19:53:17 -080010883 mSystemUiVisibility = visibility;
Joe Onorato664644d2011-01-23 17:53:23 -080010884 if (mOnSystemUiVisibilityChangeListener != null) {
10885 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(visibility);
10886 }
10887 }
10888
10889 /**
Christopher Tate2c095f32010-10-04 14:13:40 -070010890 * !!! TODO: real docs
10891 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010892 * The base class implementation makes the shadow the same size and appearance
Christopher Tate2c095f32010-10-04 14:13:40 -070010893 * as the view itself, and positions it with its center at the touch point.
10894 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010895 public static class DragShadowBuilder {
Christopher Tatea0374192010-10-05 13:06:41 -070010896 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010897
10898 /**
Christopher Tate17ed60c2011-01-18 12:50:26 -080010899 * Construct a shadow builder object for use with the given View object. The
10900 * default implementation will construct a drag shadow the same size and
10901 * appearance as the supplied View.
10902 *
10903 * @param view A view within the application's layout whose appearance
10904 * should be replicated as the drag shadow.
Christopher Tate2c095f32010-10-04 14:13:40 -070010905 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010906 public DragShadowBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010907 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010908 }
10909
Christopher Tate17ed60c2011-01-18 12:50:26 -080010910 /**
10911 * Construct a shadow builder object with no associated View. This
10912 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
10913 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
10914 * to supply the drag shadow's dimensions and appearance without
10915 * reference to any View object.
10916 */
10917 public DragShadowBuilder() {
10918 mView = new WeakReference<View>(null);
10919 }
10920
10921 /**
10922 * Returns the View object that had been passed to the
10923 * {@link #View.DragShadowBuilder(View)}
10924 * constructor. If that View parameter was {@code null} or if the
10925 * {@link #View.DragShadowBuilder()}
10926 * constructor was used to instantiate the builder object, this method will return
10927 * null.
10928 *
10929 * @return The View object associate with this builder object.
10930 */
Chris Tate6b391282010-10-14 15:48:59 -070010931 final public View getView() {
10932 return mView.get();
10933 }
10934
Christopher Tate2c095f32010-10-04 14:13:40 -070010935 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010936 * Provide the draggable-shadow metrics for the operation: the dimensions of
10937 * the shadow image itself, and the point within that shadow that should
Christopher Tate2c095f32010-10-04 14:13:40 -070010938 * be centered under the touch location while dragging.
10939 * <p>
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010940 * The default implementation sets the dimensions of the shadow to be the
Christopher Tate17ed60c2011-01-18 12:50:26 -080010941 * same as the dimensions of the View object that had been supplied to the
10942 * {@link #View.DragShadowBuilder(View)} constructor
10943 * when the builder object was instantiated, and centers the shadow under the touch
10944 * point.
Christopher Tate2c095f32010-10-04 14:13:40 -070010945 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010946 * @param shadowSize The application should set the {@code x} member of this
10947 * parameter to the desired shadow width, and the {@code y} member to
Christopher Tate2c095f32010-10-04 14:13:40 -070010948 * the desired height.
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010949 * @param shadowTouchPoint The application should set this point to be the
10950 * location within the shadow that should track directly underneath
Christopher Tate2c095f32010-10-04 14:13:40 -070010951 * the touch point on the screen during a drag.
10952 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010953 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070010954 final View view = mView.get();
10955 if (view != null) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010956 shadowSize.set(view.getWidth(), view.getHeight());
10957 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
Christopher Tatea0374192010-10-05 13:06:41 -070010958 } else {
10959 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10960 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010961 }
10962
10963 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010964 * Draw the shadow image for the upcoming drag. The shadow canvas was
10965 * created with the dimensions supplied by the
10966 * {@link #onProvideShadowMetrics(Point, Point)} callback.
Christopher Tate17ed60c2011-01-18 12:50:26 -080010967 * <p>
10968 * The default implementation replicates the appearance of the View object
10969 * that had been supplied to the
10970 * {@link #View.DragShadowBuilder(View)}
10971 * constructor when the builder object was instantiated.
Christopher Tate2c095f32010-10-04 14:13:40 -070010972 *
10973 * @param canvas
10974 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010975 public void onDrawShadow(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070010976 final View view = mView.get();
10977 if (view != null) {
10978 view.draw(canvas);
10979 } else {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010980 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
Christopher Tatea0374192010-10-05 13:06:41 -070010981 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010982 }
10983 }
10984
10985 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010986 * Drag and drop. App calls startDrag(), then callbacks to the shadow builder's
10987 * {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} and
10988 * {@link DragShadowBuilder#onDrawShadow(Canvas)} methods happen, then the drag
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010989 * operation is handed over to the OS.
Christopher Tatea53146c2010-09-07 11:57:52 -070010990 * !!! TODO: real docs
Christopher Tate407b4e92010-11-30 17:14:08 -080010991 *
10992 * @param data !!! TODO
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010993 * @param shadowBuilder !!! TODO
Christopher Tate407b4e92010-11-30 17:14:08 -080010994 * @param myLocalState An arbitrary object that will be passed as part of every DragEvent
10995 * delivered to the calling application during the course of the current drag operation.
10996 * This object is private to the application that called startDrag(), and is not
10997 * visible to other applications. It provides a lightweight way for the application to
10998 * propagate information from the initiator to the recipient of a drag within its own
10999 * application; for example, to help disambiguate between 'copy' and 'move' semantics.
Christopher Tate02d2b3b2011-01-10 20:43:53 -080011000 * @param flags Flags affecting the drag operation. At present no flags are defined;
11001 * pass 0 for this parameter.
Christopher Tate407b4e92010-11-30 17:14:08 -080011002 * @return {@code true} if the drag operation was initiated successfully; {@code false} if
11003 * an error prevented the drag from taking place.
Christopher Tatea53146c2010-09-07 11:57:52 -070011004 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011005 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080011006 Object myLocalState, int flags) {
Christopher Tate2c095f32010-10-04 14:13:40 -070011007 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate02d2b3b2011-01-10 20:43:53 -080011008 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
Christopher Tatea53146c2010-09-07 11:57:52 -070011009 }
11010 boolean okay = false;
11011
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011012 Point shadowSize = new Point();
11013 Point shadowTouchPoint = new Point();
11014 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
Christopher Tate2c095f32010-10-04 14:13:40 -070011015
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011016 if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
11017 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
11018 throw new IllegalStateException("Drag shadow dimensions must not be negative");
Christopher Tate2c095f32010-10-04 14:13:40 -070011019 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011020
Chris Tatea32dcf72010-10-14 12:13:50 -070011021 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011022 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
11023 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
Chris Tatea32dcf72010-10-14 12:13:50 -070011024 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011025 Surface surface = new Surface();
11026 try {
11027 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080011028 flags, shadowSize.x, shadowSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070011029 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070011030 + " surface=" + surface);
11031 if (token != null) {
11032 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070011033 try {
Chris Tate6b391282010-10-14 15:48:59 -070011034 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011035 shadowBuilder.onDrawShadow(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070011036 } finally {
11037 surface.unlockCanvasAndPost(canvas);
11038 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011039
Christopher Tate407b4e92010-11-30 17:14:08 -080011040 final ViewRoot root = getViewRoot();
11041
11042 // Cache the local state object for delivery with DragEvents
11043 root.setLocalDragState(myLocalState);
11044
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011045 // repurpose 'shadowSize' for the last touch point
11046 root.getLastTouchPoint(shadowSize);
Christopher Tate2c095f32010-10-04 14:13:40 -070011047
Christopher Tatea53146c2010-09-07 11:57:52 -070011048 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011049 shadowSize.x, shadowSize.y,
11050 shadowTouchPoint.x, shadowTouchPoint.y, data);
Christopher Tate2c095f32010-10-04 14:13:40 -070011051 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070011052 }
11053 } catch (Exception e) {
11054 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
11055 surface.destroy();
11056 }
11057
11058 return okay;
11059 }
11060
Christopher Tatea53146c2010-09-07 11:57:52 -070011061 /**
11062 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
11063 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
11064 *
11065 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
11066 * being dragged. onDragEvent() should return 'true' if the view can handle
11067 * a drop of that content. A view that returns 'false' here will receive no
11068 * further calls to onDragEvent() about the drag/drop operation.
11069 *
11070 * For DRAG_ENTERED, event.getClipDescription() describes the content being
11071 * dragged. This will be the same content description passed in the
11072 * DRAG_STARTED_EVENT invocation.
11073 *
11074 * For DRAG_EXITED, event.getClipDescription() describes the content being
11075 * dragged. This will be the same content description passed in the
11076 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
11077 * drag-acceptance visual state.
11078 *
11079 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
11080 * coordinates of the current drag point. The view must return 'true' if it
11081 * can accept a drop of the current drag content, false otherwise.
11082 *
11083 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
11084 * within the view; also, event.getClipData() returns the full data payload
11085 * being dropped. The view should return 'true' if it consumed the dropped
11086 * content, 'false' if it did not.
11087 *
11088 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
11089 * to its normal visual state.
11090 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070011091 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070011092 return false;
11093 }
11094
11095 /**
11096 * Views typically don't need to override dispatchDragEvent(); it just calls
Chris Tate32affef2010-10-18 15:29:21 -070011097 * onDragEvent(event) and passes the result up appropriately.
Christopher Tatea53146c2010-09-07 11:57:52 -070011098 */
11099 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070011100 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
11101 && mOnDragListener.onDrag(this, event)) {
11102 return true;
11103 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011104 return onDragEvent(event);
11105 }
11106
11107 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070011108 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
11109 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070011110 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070011111 */
11112 public void onCloseSystemDialogs(String reason) {
11113 }
11114
11115 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011116 * Given a Drawable whose bounds have been set to draw into this view,
11117 * update a Region being computed for {@link #gatherTransparentRegion} so
11118 * that any non-transparent parts of the Drawable are removed from the
11119 * given transparent region.
11120 *
11121 * @param dr The Drawable whose transparency is to be applied to the region.
11122 * @param region A Region holding the current transparency information,
11123 * where any parts of the region that are set are considered to be
11124 * transparent. On return, this region will be modified to have the
11125 * transparency information reduced by the corresponding parts of the
11126 * Drawable that are not transparent.
11127 * {@hide}
11128 */
11129 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
11130 if (DBG) {
11131 Log.i("View", "Getting transparent region for: " + this);
11132 }
11133 final Region r = dr.getTransparentRegion();
11134 final Rect db = dr.getBounds();
11135 final AttachInfo attachInfo = mAttachInfo;
11136 if (r != null && attachInfo != null) {
11137 final int w = getRight()-getLeft();
11138 final int h = getBottom()-getTop();
11139 if (db.left > 0) {
11140 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
11141 r.op(0, 0, db.left, h, Region.Op.UNION);
11142 }
11143 if (db.right < w) {
11144 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
11145 r.op(db.right, 0, w, h, Region.Op.UNION);
11146 }
11147 if (db.top > 0) {
11148 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
11149 r.op(0, 0, w, db.top, Region.Op.UNION);
11150 }
11151 if (db.bottom < h) {
11152 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
11153 r.op(0, db.bottom, w, h, Region.Op.UNION);
11154 }
11155 final int[] location = attachInfo.mTransparentLocation;
11156 getLocationInWindow(location);
11157 r.translate(location[0], location[1]);
11158 region.op(r, Region.Op.INTERSECT);
11159 } else {
11160 region.op(db, Region.Op.DIFFERENCE);
11161 }
11162 }
11163
Adam Powelle14579b2009-12-16 18:39:52 -080011164 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 mHasPerformedLongPress = false;
11166
11167 if (mPendingCheckForLongPress == null) {
11168 mPendingCheckForLongPress = new CheckForLongPress();
11169 }
11170 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080011171 postDelayed(mPendingCheckForLongPress,
11172 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011173 }
11174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011175 /**
11176 * Inflate a view from an XML resource. This convenience method wraps the {@link
11177 * LayoutInflater} class, which provides a full range of options for view inflation.
11178 *
11179 * @param context The Context object for your activity or application.
11180 * @param resource The resource ID to inflate
11181 * @param root A view group that will be the parent. Used to properly inflate the
11182 * layout_* parameters.
11183 * @see LayoutInflater
11184 */
11185 public static View inflate(Context context, int resource, ViewGroup root) {
11186 LayoutInflater factory = LayoutInflater.from(context);
11187 return factory.inflate(resource, root);
11188 }
Romain Guy33e72ae2010-07-17 12:40:29 -070011189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011190 /**
Adam Powell637d3372010-08-25 14:37:03 -070011191 * Scroll the view with standard behavior for scrolling beyond the normal
11192 * content boundaries. Views that call this method should override
11193 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
11194 * results of an over-scroll operation.
11195 *
11196 * Views can use this method to handle any touch or fling-based scrolling.
11197 *
11198 * @param deltaX Change in X in pixels
11199 * @param deltaY Change in Y in pixels
11200 * @param scrollX Current X scroll value in pixels before applying deltaX
11201 * @param scrollY Current Y scroll value in pixels before applying deltaY
11202 * @param scrollRangeX Maximum content scroll range along the X axis
11203 * @param scrollRangeY Maximum content scroll range along the Y axis
11204 * @param maxOverScrollX Number of pixels to overscroll by in either direction
11205 * along the X axis.
11206 * @param maxOverScrollY Number of pixels to overscroll by in either direction
11207 * along the Y axis.
11208 * @param isTouchEvent true if this scroll operation is the result of a touch event.
11209 * @return true if scrolling was clamped to an over-scroll boundary along either
11210 * axis, false otherwise.
11211 */
11212 protected boolean overScrollBy(int deltaX, int deltaY,
11213 int scrollX, int scrollY,
11214 int scrollRangeX, int scrollRangeY,
11215 int maxOverScrollX, int maxOverScrollY,
11216 boolean isTouchEvent) {
11217 final int overScrollMode = mOverScrollMode;
11218 final boolean canScrollHorizontal =
11219 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
11220 final boolean canScrollVertical =
11221 computeVerticalScrollRange() > computeVerticalScrollExtent();
11222 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
11223 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
11224 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
11225 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
11226
11227 int newScrollX = scrollX + deltaX;
11228 if (!overScrollHorizontal) {
11229 maxOverScrollX = 0;
11230 }
11231
11232 int newScrollY = scrollY + deltaY;
11233 if (!overScrollVertical) {
11234 maxOverScrollY = 0;
11235 }
11236
11237 // Clamp values if at the limits and record
11238 final int left = -maxOverScrollX;
11239 final int right = maxOverScrollX + scrollRangeX;
11240 final int top = -maxOverScrollY;
11241 final int bottom = maxOverScrollY + scrollRangeY;
11242
11243 boolean clampedX = false;
11244 if (newScrollX > right) {
11245 newScrollX = right;
11246 clampedX = true;
11247 } else if (newScrollX < left) {
11248 newScrollX = left;
11249 clampedX = true;
11250 }
11251
11252 boolean clampedY = false;
11253 if (newScrollY > bottom) {
11254 newScrollY = bottom;
11255 clampedY = true;
11256 } else if (newScrollY < top) {
11257 newScrollY = top;
11258 clampedY = true;
11259 }
11260
11261 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
11262
11263 return clampedX || clampedY;
11264 }
11265
11266 /**
11267 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
11268 * respond to the results of an over-scroll operation.
11269 *
11270 * @param scrollX New X scroll value in pixels
11271 * @param scrollY New Y scroll value in pixels
11272 * @param clampedX True if scrollX was clamped to an over-scroll boundary
11273 * @param clampedY True if scrollY was clamped to an over-scroll boundary
11274 */
11275 protected void onOverScrolled(int scrollX, int scrollY,
11276 boolean clampedX, boolean clampedY) {
11277 // Intentionally empty.
11278 }
11279
11280 /**
11281 * Returns the over-scroll mode for this view. The result will be
11282 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11283 * (allow over-scrolling only if the view content is larger than the container),
11284 * or {@link #OVER_SCROLL_NEVER}.
11285 *
11286 * @return This view's over-scroll mode.
11287 */
11288 public int getOverScrollMode() {
11289 return mOverScrollMode;
11290 }
11291
11292 /**
11293 * Set the over-scroll mode for this view. Valid over-scroll modes are
11294 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11295 * (allow over-scrolling only if the view content is larger than the container),
11296 * or {@link #OVER_SCROLL_NEVER}.
11297 *
11298 * Setting the over-scroll mode of a view will have an effect only if the
11299 * view is capable of scrolling.
11300 *
11301 * @param overScrollMode The new over-scroll mode for this view.
11302 */
11303 public void setOverScrollMode(int overScrollMode) {
11304 if (overScrollMode != OVER_SCROLL_ALWAYS &&
11305 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
11306 overScrollMode != OVER_SCROLL_NEVER) {
11307 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
11308 }
11309 mOverScrollMode = overScrollMode;
11310 }
11311
11312 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
11314 * Each MeasureSpec represents a requirement for either the width or the height.
11315 * A MeasureSpec is comprised of a size and a mode. There are three possible
11316 * modes:
11317 * <dl>
11318 * <dt>UNSPECIFIED</dt>
11319 * <dd>
11320 * The parent has not imposed any constraint on the child. It can be whatever size
11321 * it wants.
11322 * </dd>
11323 *
11324 * <dt>EXACTLY</dt>
11325 * <dd>
11326 * The parent has determined an exact size for the child. The child is going to be
11327 * given those bounds regardless of how big it wants to be.
11328 * </dd>
11329 *
11330 * <dt>AT_MOST</dt>
11331 * <dd>
11332 * The child can be as large as it wants up to the specified size.
11333 * </dd>
11334 * </dl>
11335 *
11336 * MeasureSpecs are implemented as ints to reduce object allocation. This class
11337 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
11338 */
11339 public static class MeasureSpec {
11340 private static final int MODE_SHIFT = 30;
11341 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
11342
11343 /**
11344 * Measure specification mode: The parent has not imposed any constraint
11345 * on the child. It can be whatever size it wants.
11346 */
11347 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
11348
11349 /**
11350 * Measure specification mode: The parent has determined an exact size
11351 * for the child. The child is going to be given those bounds regardless
11352 * of how big it wants to be.
11353 */
11354 public static final int EXACTLY = 1 << MODE_SHIFT;
11355
11356 /**
11357 * Measure specification mode: The child can be as large as it wants up
11358 * to the specified size.
11359 */
11360 public static final int AT_MOST = 2 << MODE_SHIFT;
11361
11362 /**
11363 * Creates a measure specification based on the supplied size and mode.
11364 *
11365 * The mode must always be one of the following:
11366 * <ul>
11367 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
11368 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
11369 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
11370 * </ul>
11371 *
11372 * @param size the size of the measure specification
11373 * @param mode the mode of the measure specification
11374 * @return the measure specification based on size and mode
11375 */
11376 public static int makeMeasureSpec(int size, int mode) {
11377 return size + mode;
11378 }
11379
11380 /**
11381 * Extracts the mode from the supplied measure specification.
11382 *
11383 * @param measureSpec the measure specification to extract the mode from
11384 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
11385 * {@link android.view.View.MeasureSpec#AT_MOST} or
11386 * {@link android.view.View.MeasureSpec#EXACTLY}
11387 */
11388 public static int getMode(int measureSpec) {
11389 return (measureSpec & MODE_MASK);
11390 }
11391
11392 /**
11393 * Extracts the size from the supplied measure specification.
11394 *
11395 * @param measureSpec the measure specification to extract the size from
11396 * @return the size in pixels defined in the supplied measure specification
11397 */
11398 public static int getSize(int measureSpec) {
11399 return (measureSpec & ~MODE_MASK);
11400 }
11401
11402 /**
11403 * Returns a String representation of the specified measure
11404 * specification.
11405 *
11406 * @param measureSpec the measure specification to convert to a String
11407 * @return a String with the following format: "MeasureSpec: MODE SIZE"
11408 */
11409 public static String toString(int measureSpec) {
11410 int mode = getMode(measureSpec);
11411 int size = getSize(measureSpec);
11412
11413 StringBuilder sb = new StringBuilder("MeasureSpec: ");
11414
11415 if (mode == UNSPECIFIED)
11416 sb.append("UNSPECIFIED ");
11417 else if (mode == EXACTLY)
11418 sb.append("EXACTLY ");
11419 else if (mode == AT_MOST)
11420 sb.append("AT_MOST ");
11421 else
11422 sb.append(mode).append(" ");
11423
11424 sb.append(size);
11425 return sb.toString();
11426 }
11427 }
11428
11429 class CheckForLongPress implements Runnable {
11430
11431 private int mOriginalWindowAttachCount;
11432
11433 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011434 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011435 && mOriginalWindowAttachCount == mWindowAttachCount) {
11436 if (performLongClick()) {
11437 mHasPerformedLongPress = true;
11438 }
11439 }
11440 }
11441
11442 public void rememberWindowAttachCount() {
11443 mOriginalWindowAttachCount = mWindowAttachCount;
11444 }
11445 }
Adam Powelle14579b2009-12-16 18:39:52 -080011446
11447 private final class CheckForTap implements Runnable {
11448 public void run() {
11449 mPrivateFlags &= ~PREPRESSED;
11450 mPrivateFlags |= PRESSED;
11451 refreshDrawableState();
11452 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
11453 postCheckForLongClick(ViewConfiguration.getTapTimeout());
11454 }
11455 }
11456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011457
Adam Powella35d7682010-03-12 14:48:13 -080011458 private final class PerformClick implements Runnable {
11459 public void run() {
11460 performClick();
11461 }
11462 }
11463
Dianne Hackborn63042d62011-01-26 18:56:29 -080011464 /** @hide */
11465 public void hackTurnOffWindowResizeAnim(boolean off) {
11466 mAttachInfo.mTurnOffWindowResizeAnim = off;
11467 }
11468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011469 /**
11470 * Interface definition for a callback to be invoked when a key event is
11471 * dispatched to this view. The callback will be invoked before the key
11472 * event is given to the view.
11473 */
11474 public interface OnKeyListener {
11475 /**
11476 * Called when a key is dispatched to a view. This allows listeners to
11477 * get a chance to respond before the target view.
11478 *
11479 * @param v The view the key has been dispatched to.
11480 * @param keyCode The code for the physical key that was pressed
11481 * @param event The KeyEvent object containing full information about
11482 * the event.
11483 * @return True if the listener has consumed the event, false otherwise.
11484 */
11485 boolean onKey(View v, int keyCode, KeyEvent event);
11486 }
11487
11488 /**
11489 * Interface definition for a callback to be invoked when a touch event is
11490 * dispatched to this view. The callback will be invoked before the touch
11491 * event is given to the view.
11492 */
11493 public interface OnTouchListener {
11494 /**
11495 * Called when a touch event is dispatched to a view. This allows listeners to
11496 * get a chance to respond before the target view.
11497 *
11498 * @param v The view the touch event has been dispatched to.
11499 * @param event The MotionEvent object containing full information about
11500 * the event.
11501 * @return True if the listener has consumed the event, false otherwise.
11502 */
11503 boolean onTouch(View v, MotionEvent event);
11504 }
11505
11506 /**
11507 * Interface definition for a callback to be invoked when a view has been clicked and held.
11508 */
11509 public interface OnLongClickListener {
11510 /**
11511 * Called when a view has been clicked and held.
11512 *
11513 * @param v The view that was clicked and held.
11514 *
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -080011515 * @return true if the callback consumed the long click, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011516 */
11517 boolean onLongClick(View v);
11518 }
11519
11520 /**
Chris Tate32affef2010-10-18 15:29:21 -070011521 * Interface definition for a callback to be invoked when a drag is being dispatched
11522 * to this view. The callback will be invoked before the hosting view's own
11523 * onDrag(event) method. If the listener wants to fall back to the hosting view's
11524 * onDrag(event) behavior, it should return 'false' from this callback.
11525 */
11526 public interface OnDragListener {
11527 /**
11528 * Called when a drag event is dispatched to a view. This allows listeners
11529 * to get a chance to override base View behavior.
11530 *
11531 * @param v The view the drag has been dispatched to.
11532 * @param event The DragEvent object containing full information
11533 * about the event.
11534 * @return true if the listener consumed the DragEvent, false in order to fall
11535 * back to the view's default handling.
11536 */
11537 boolean onDrag(View v, DragEvent event);
11538 }
11539
11540 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011541 * Interface definition for a callback to be invoked when the focus state of
11542 * a view changed.
11543 */
11544 public interface OnFocusChangeListener {
11545 /**
11546 * Called when the focus state of a view has changed.
11547 *
11548 * @param v The view whose state has changed.
11549 * @param hasFocus The new focus state of v.
11550 */
11551 void onFocusChange(View v, boolean hasFocus);
11552 }
11553
11554 /**
11555 * Interface definition for a callback to be invoked when a view is clicked.
11556 */
11557 public interface OnClickListener {
11558 /**
11559 * Called when a view has been clicked.
11560 *
11561 * @param v The view that was clicked.
11562 */
11563 void onClick(View v);
11564 }
11565
11566 /**
11567 * Interface definition for a callback to be invoked when the context menu
11568 * for this view is being built.
11569 */
11570 public interface OnCreateContextMenuListener {
11571 /**
11572 * Called when the context menu for this view is being built. It is not
11573 * safe to hold onto the menu after this method returns.
11574 *
11575 * @param menu The context menu that is being built
11576 * @param v The view for which the context menu is being built
11577 * @param menuInfo Extra information about the item for which the
11578 * context menu should be shown. This information will vary
11579 * depending on the class of v.
11580 */
11581 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
11582 }
11583
Joe Onorato664644d2011-01-23 17:53:23 -080011584 /**
11585 * Interface definition for a callback to be invoked when the status bar changes
11586 * visibility.
11587 *
11588 * @see #setOnSystemUiVisibilityChangeListener
11589 */
11590 public interface OnSystemUiVisibilityChangeListener {
11591 /**
11592 * Called when the status bar changes visibility because of a call to
11593 * {@link #setSystemUiVisibility}.
11594 *
11595 * @param visibility {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}.
11596 */
11597 public void onSystemUiVisibilityChange(int visibility);
11598 }
11599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011600 private final class UnsetPressedState implements Runnable {
11601 public void run() {
11602 setPressed(false);
11603 }
11604 }
11605
11606 /**
11607 * Base class for derived classes that want to save and restore their own
11608 * state in {@link android.view.View#onSaveInstanceState()}.
11609 */
11610 public static class BaseSavedState extends AbsSavedState {
11611 /**
11612 * Constructor used when reading from a parcel. Reads the state of the superclass.
11613 *
11614 * @param source
11615 */
11616 public BaseSavedState(Parcel source) {
11617 super(source);
11618 }
11619
11620 /**
11621 * Constructor called by derived classes when creating their SavedState objects
11622 *
11623 * @param superState The state of the superclass of this view
11624 */
11625 public BaseSavedState(Parcelable superState) {
11626 super(superState);
11627 }
11628
11629 public static final Parcelable.Creator<BaseSavedState> CREATOR =
11630 new Parcelable.Creator<BaseSavedState>() {
11631 public BaseSavedState createFromParcel(Parcel in) {
11632 return new BaseSavedState(in);
11633 }
11634
11635 public BaseSavedState[] newArray(int size) {
11636 return new BaseSavedState[size];
11637 }
11638 };
11639 }
11640
11641 /**
11642 * A set of information given to a view when it is attached to its parent
11643 * window.
11644 */
11645 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011646 interface Callbacks {
11647 void playSoundEffect(int effectId);
11648 boolean performHapticFeedback(int effectId, boolean always);
11649 }
11650
11651 /**
11652 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11653 * to a Handler. This class contains the target (View) to invalidate and
11654 * the coordinates of the dirty rectangle.
11655 *
11656 * For performance purposes, this class also implements a pool of up to
11657 * POOL_LIMIT objects that get reused. This reduces memory allocations
11658 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011659 */
Romain Guyd928d682009-03-31 17:52:16 -070011660 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011661 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070011662 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11663 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070011664 public InvalidateInfo newInstance() {
11665 return new InvalidateInfo();
11666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011667
Romain Guyd928d682009-03-31 17:52:16 -070011668 public void onAcquired(InvalidateInfo element) {
11669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011670
Romain Guyd928d682009-03-31 17:52:16 -070011671 public void onReleased(InvalidateInfo element) {
11672 }
11673 }, POOL_LIMIT)
11674 );
11675
11676 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011677
11678 View target;
11679
11680 int left;
11681 int top;
11682 int right;
11683 int bottom;
11684
Romain Guyd928d682009-03-31 17:52:16 -070011685 public void setNextPoolable(InvalidateInfo element) {
11686 mNext = element;
11687 }
11688
11689 public InvalidateInfo getNextPoolable() {
11690 return mNext;
11691 }
11692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011693 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070011694 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011695 }
11696
11697 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070011698 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011699 }
11700 }
11701
11702 final IWindowSession mSession;
11703
11704 final IWindow mWindow;
11705
11706 final IBinder mWindowToken;
11707
11708 final Callbacks mRootCallbacks;
11709
Chet Haasedaf98e92011-01-10 14:10:36 -080011710 Canvas mHardwareCanvas;
11711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011712 /**
11713 * The top view of the hierarchy.
11714 */
11715 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070011716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011717 IBinder mPanelParentWindowToken;
11718 Surface mSurface;
11719
Romain Guyb051e892010-09-28 19:09:36 -070011720 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080011721 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070011722 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070011723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011724 /**
Romain Guy8506ab42009-06-11 17:35:47 -070011725 * Scale factor used by the compatibility mode
11726 */
11727 float mApplicationScale;
11728
11729 /**
11730 * Indicates whether the application is in compatibility mode
11731 */
11732 boolean mScalingRequired;
11733
11734 /**
Dianne Hackborn63042d62011-01-26 18:56:29 -080011735 * If set, ViewRoot doesn't use its lame animation for when the window resizes.
11736 */
11737 boolean mTurnOffWindowResizeAnim;
11738
11739 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011740 * Left position of this view's window
11741 */
11742 int mWindowLeft;
11743
11744 /**
11745 * Top position of this view's window
11746 */
11747 int mWindowTop;
11748
11749 /**
Adam Powell26153a32010-11-08 15:22:27 -080011750 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070011751 */
Adam Powell26153a32010-11-08 15:22:27 -080011752 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070011753
11754 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011755 * For windows that are full-screen but using insets to layout inside
11756 * of the screen decorations, these are the current insets for the
11757 * content of the window.
11758 */
11759 final Rect mContentInsets = new Rect();
11760
11761 /**
11762 * For windows that are full-screen but using insets to layout inside
11763 * of the screen decorations, these are the current insets for the
11764 * actual visible parts of the window.
11765 */
11766 final Rect mVisibleInsets = new Rect();
11767
11768 /**
11769 * The internal insets given by this window. This value is
11770 * supplied by the client (through
11771 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11772 * be given to the window manager when changed to be used in laying
11773 * out windows behind it.
11774 */
11775 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11776 = new ViewTreeObserver.InternalInsetsInfo();
11777
11778 /**
11779 * All views in the window's hierarchy that serve as scroll containers,
11780 * used to determine if the window can be resized or must be panned
11781 * to adjust for a soft input area.
11782 */
11783 final ArrayList<View> mScrollContainers = new ArrayList<View>();
11784
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070011785 final KeyEvent.DispatcherState mKeyDispatchState
11786 = new KeyEvent.DispatcherState();
11787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011788 /**
11789 * Indicates whether the view's window currently has the focus.
11790 */
11791 boolean mHasWindowFocus;
11792
11793 /**
11794 * The current visibility of the window.
11795 */
11796 int mWindowVisibility;
11797
11798 /**
11799 * Indicates the time at which drawing started to occur.
11800 */
11801 long mDrawingTime;
11802
11803 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070011804 * Indicates whether or not ignoring the DIRTY_MASK flags.
11805 */
11806 boolean mIgnoreDirtyState;
11807
11808 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011809 * Indicates whether the view's window is currently in touch mode.
11810 */
11811 boolean mInTouchMode;
11812
11813 /**
11814 * Indicates that ViewRoot should trigger a global layout change
11815 * the next time it performs a traversal
11816 */
11817 boolean mRecomputeGlobalAttributes;
11818
11819 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011820 * Set during a traveral if any views want to keep the screen on.
11821 */
11822 boolean mKeepScreenOn;
11823
11824 /**
Joe Onorato664644d2011-01-23 17:53:23 -080011825 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
11826 */
11827 int mSystemUiVisibility;
11828
11829 /**
11830 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
11831 * attached.
11832 */
11833 boolean mHasSystemUiListeners;
11834
11835 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011836 * Set if the visibility of any views has changed.
11837 */
11838 boolean mViewVisibilityChanged;
11839
11840 /**
11841 * Set to true if a view has been scrolled.
11842 */
11843 boolean mViewScrollChanged;
11844
11845 /**
11846 * Global to the view hierarchy used as a temporary for dealing with
11847 * x/y points in the transparent region computations.
11848 */
11849 final int[] mTransparentLocation = new int[2];
11850
11851 /**
11852 * Global to the view hierarchy used as a temporary for dealing with
11853 * x/y points in the ViewGroup.invalidateChild implementation.
11854 */
11855 final int[] mInvalidateChildLocation = new int[2];
11856
Chet Haasec3aa3612010-06-17 08:50:37 -070011857
11858 /**
11859 * Global to the view hierarchy used as a temporary for dealing with
11860 * x/y location when view is transformed.
11861 */
11862 final float[] mTmpTransformLocation = new float[2];
11863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011864 /**
11865 * The view tree observer used to dispatch global events like
11866 * layout, pre-draw, touch mode change, etc.
11867 */
11868 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11869
11870 /**
11871 * A Canvas used by the view hierarchy to perform bitmap caching.
11872 */
11873 Canvas mCanvas;
11874
11875 /**
11876 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11877 * handler can be used to pump events in the UI events queue.
11878 */
11879 final Handler mHandler;
11880
11881 /**
11882 * Identifier for messages requesting the view to be invalidated.
11883 * Such messages should be sent to {@link #mHandler}.
11884 */
11885 static final int INVALIDATE_MSG = 0x1;
11886
11887 /**
11888 * Identifier for messages requesting the view to invalidate a region.
11889 * Such messages should be sent to {@link #mHandler}.
11890 */
11891 static final int INVALIDATE_RECT_MSG = 0x2;
11892
11893 /**
11894 * Temporary for use in computing invalidate rectangles while
11895 * calling up the hierarchy.
11896 */
11897 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070011898
11899 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070011900 * Temporary for use in computing hit areas with transformed views
11901 */
11902 final RectF mTmpTransformRect = new RectF();
11903
11904 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070011905 * Temporary list for use in collecting focusable descendents of a view.
11906 */
11907 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011909 /**
11910 * Creates a new set of attachment information with the specified
11911 * events handler and thread.
11912 *
11913 * @param handler the events handler the view must use
11914 */
11915 AttachInfo(IWindowSession session, IWindow window,
11916 Handler handler, Callbacks effectPlayer) {
11917 mSession = session;
11918 mWindow = window;
11919 mWindowToken = window.asBinder();
11920 mHandler = handler;
11921 mRootCallbacks = effectPlayer;
11922 }
11923 }
11924
11925 /**
11926 * <p>ScrollabilityCache holds various fields used by a View when scrolling
11927 * is supported. This avoids keeping too many unused fields in most
11928 * instances of View.</p>
11929 */
Mike Cleronf116bf82009-09-27 19:14:12 -070011930 private static class ScrollabilityCache implements Runnable {
11931
11932 /**
11933 * Scrollbars are not visible
11934 */
11935 public static final int OFF = 0;
11936
11937 /**
11938 * Scrollbars are visible
11939 */
11940 public static final int ON = 1;
11941
11942 /**
11943 * Scrollbars are fading away
11944 */
11945 public static final int FADING = 2;
11946
11947 public boolean fadeScrollBars;
11948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011949 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070011950 public int scrollBarDefaultDelayBeforeFade;
11951 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011952
11953 public int scrollBarSize;
11954 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070011955 public float[] interpolatorValues;
11956 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011957
11958 public final Paint paint;
11959 public final Matrix matrix;
11960 public Shader shader;
11961
Mike Cleronf116bf82009-09-27 19:14:12 -070011962 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11963
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011964 private static final float[] OPAQUE = { 255 };
11965 private static final float[] TRANSPARENT = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070011966
11967 /**
11968 * When fading should start. This time moves into the future every time
11969 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11970 */
11971 public long fadeStartTime;
11972
11973
11974 /**
11975 * The current state of the scrollbars: ON, OFF, or FADING
11976 */
11977 public int state = OFF;
11978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011979 private int mLastColor;
11980
Mike Cleronf116bf82009-09-27 19:14:12 -070011981 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011982 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11983 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070011984 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11985 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011986
11987 paint = new Paint();
11988 matrix = new Matrix();
11989 // use use a height of 1, and then wack the matrix each time we
11990 // actually use it.
11991 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011993 paint.setShader(shader);
11994 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070011995 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011996 }
Romain Guy8506ab42009-06-11 17:35:47 -070011997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011998 public void setFadeColor(int color) {
11999 if (color != 0 && color != mLastColor) {
12000 mLastColor = color;
12001 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070012002
Romain Guye55e1a72009-08-27 10:42:26 -070012003 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
12004 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070012005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012006 paint.setShader(shader);
12007 // Restore the default transfer mode (src_over)
12008 paint.setXfermode(null);
12009 }
12010 }
Mike Cleronf116bf82009-09-27 19:14:12 -070012011
12012 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070012013 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070012014 if (now >= fadeStartTime) {
12015
12016 // the animation fades the scrollbars out by changing
12017 // the opacity (alpha) from fully opaque to fully
12018 // transparent
12019 int nextFrame = (int) now;
12020 int framesCount = 0;
12021
12022 Interpolator interpolator = scrollBarInterpolator;
12023
12024 // Start opaque
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080012025 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
Mike Cleronf116bf82009-09-27 19:14:12 -070012026
12027 // End transparent
12028 nextFrame += scrollBarFadeDuration;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080012029 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
Mike Cleronf116bf82009-09-27 19:14:12 -070012030
12031 state = FADING;
12032
12033 // Kick off the fade animation
Romain Guy0fd89bf2011-01-26 15:41:30 -080012034 host.invalidate(true);
Mike Cleronf116bf82009-09-27 19:14:12 -070012035 }
12036 }
12037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012038 }
12039}