blob: f9629bd9975e5f8e1b07a24c0608c509145d46b1 [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
Joe Malin32736f02011-01-19 16:14:20 -0800524 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
Mike Cleronf116bf82009-09-27 19:14:12 -0700525 * {@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;
Joe Malin32736f02011-01-19 16:14:20 -08001648
Adam Powelle14579b2009-12-16 18:39:52 -08001649 /**
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().
Joe Malin32736f02011-01-19 16:14:20 -08001654 *
Adam Powelle14579b2009-12-16 18:39:52 -08001655 * @hide
1656 */
1657 private static final int PREPRESSED = 0x02000000;
Joe Malin32736f02011-01-19 16:14:20 -08001658
Adam Powellc9fbaab2010-02-16 17:16:19 -08001659 /**
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;
Joe Malin32736f02011-01-19 16:14:20 -08001665
Adam Powell8568c3a2010-04-19 14:26:11 -07001666 /**
1667 * Indicates that we should awaken scroll bars once attached
Joe Malin32736f02011-01-19 16:14:20 -08001668 *
Adam Powell8568c3a2010-04-19 14:26:11 -07001669 * @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 *
Joe Malin32736f02011-01-19 16:14:20 -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 *
Joe Malin32736f02011-01-19 16:14:20 -08001730 * @see #setSystemUiVisibility(int)
Joe Onorato664644d2011-01-23 17:53:23 -08001731 */
1732 public static final int STATUS_BAR_HIDDEN = 0x00000001;
1733
1734 /**
Joe Onorato7bb8eeb2011-01-27 16:00:58 -08001735 * @hide
1736 *
1737 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1738 * out of the public fields to keep the undefined bits out of the developer's way.
1739 *
1740 * Flag to make the status bar not expandable. Unless you also
1741 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1742 */
1743 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1744
1745 /**
1746 * @hide
1747 *
1748 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1749 * out of the public fields to keep the undefined bits out of the developer's way.
1750 *
1751 * Flag to hide notification icons and scrolling ticker text.
1752 */
1753 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1754
1755 /**
1756 * @hide
1757 *
1758 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1759 * out of the public fields to keep the undefined bits out of the developer's way.
1760 *
1761 * Flag to disable incoming notification alerts. This will not block
1762 * icons, but it will block sound, vibrating and other visual or aural notifications.
1763 */
1764 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1765
1766 /**
1767 * @hide
1768 *
1769 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1770 * out of the public fields to keep the undefined bits out of the developer's way.
1771 *
1772 * Flag to hide only the scrolling ticker. Note that
1773 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1774 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1775 */
1776 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1777
1778 /**
1779 * @hide
1780 *
1781 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1782 * out of the public fields to keep the undefined bits out of the developer's way.
1783 *
1784 * Flag to hide the center system info area.
1785 */
1786 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1787
1788 /**
1789 * @hide
1790 *
1791 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1792 * out of the public fields to keep the undefined bits out of the developer's way.
1793 *
1794 * Flag to hide only the navigation buttons. Don't use this
1795 * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
Joe Onorato6478adc2011-01-27 21:15:01 -08001796 *
1797 * THIS DOES NOT DISABLE THE BACK BUTTON
Joe Onorato7bb8eeb2011-01-27 16:00:58 -08001798 */
1799 public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000;
1800
1801 /**
1802 * @hide
1803 *
1804 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1805 * out of the public fields to keep the undefined bits out of the developer's way.
1806 *
Joe Onorato6478adc2011-01-27 21:15:01 -08001807 * Flag to hide only the back button. Don't use this
1808 * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1809 */
1810 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1811
1812 /**
1813 * @hide
1814 *
1815 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1816 * out of the public fields to keep the undefined bits out of the developer's way.
1817 *
Joe Onorato7bb8eeb2011-01-27 16:00:58 -08001818 * Flag to hide only the clock. You might use this if your activity has
1819 * its own clock making the status bar's clock redundant.
1820 */
Joe Onorato6478adc2011-01-27 21:15:01 -08001821 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1822
Joe Onorato7bb8eeb2011-01-27 16:00:58 -08001823
1824 /**
1825 * @hide
1826 */
1827 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = STATUS_BAR_HIDDEN;
1828
1829
1830 /**
Adam Powell637d3372010-08-25 14:37:03 -07001831 * Controls the over-scroll mode for this view.
1832 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1833 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1834 * and {@link #OVER_SCROLL_NEVER}.
1835 */
1836 private int mOverScrollMode;
1837
1838 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 * The parent this view is attached to.
1840 * {@hide}
1841 *
1842 * @see #getParent()
1843 */
1844 protected ViewParent mParent;
1845
1846 /**
1847 * {@hide}
1848 */
1849 AttachInfo mAttachInfo;
1850
1851 /**
1852 * {@hide}
1853 */
Romain Guy809a7f62009-05-14 15:44:42 -07001854 @ViewDebug.ExportedProperty(flagMapping = {
1855 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1856 name = "FORCE_LAYOUT"),
1857 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1858 name = "LAYOUT_REQUIRED"),
1859 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001860 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001861 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1862 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1863 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1864 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1865 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 int mPrivateFlags;
1867
1868 /**
Joe Onorato664644d2011-01-23 17:53:23 -08001869 * This view's request for the visibility of the status bar.
1870 * @hide
1871 */
Joe Onoratoac0ee892011-01-30 15:38:30 -08001872 @ViewDebug.ExportedProperty()
Joe Onorato664644d2011-01-23 17:53:23 -08001873 int mSystemUiVisibility;
1874
1875 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 * Count of how many windows this view has been attached to.
1877 */
1878 int mWindowAttachCount;
1879
1880 /**
1881 * The layout parameters associated with this view and used by the parent
1882 * {@link android.view.ViewGroup} to determine how this view should be
1883 * laid out.
1884 * {@hide}
1885 */
1886 protected ViewGroup.LayoutParams mLayoutParams;
1887
1888 /**
1889 * The view flags hold various views states.
1890 * {@hide}
1891 */
1892 @ViewDebug.ExportedProperty
1893 int mViewFlags;
1894
1895 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001896 * The transform matrix for the View. This transform is calculated internally
1897 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1898 * is used by default. Do *not* use this variable directly; instead call
1899 * getMatrix(), which will automatically recalculate the matrix if necessary
1900 * to get the correct matrix based on the latest rotation and scale properties.
1901 */
1902 private final Matrix mMatrix = new Matrix();
1903
1904 /**
1905 * The transform matrix for the View. This transform is calculated internally
1906 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1907 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001908 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001909 * to get the correct matrix based on the latest rotation and scale properties.
1910 */
1911 private Matrix mInverseMatrix;
1912
1913 /**
1914 * An internal variable that tracks whether we need to recalculate the
1915 * transform matrix, based on whether the rotation or scaleX/Y properties
1916 * have changed since the matrix was last calculated.
1917 */
1918 private boolean mMatrixDirty = false;
1919
1920 /**
1921 * An internal variable that tracks whether we need to recalculate the
1922 * transform matrix, based on whether the rotation or scaleX/Y properties
1923 * have changed since the matrix was last calculated.
1924 */
1925 private boolean mInverseMatrixDirty = true;
1926
1927 /**
1928 * A variable that tracks whether we need to recalculate the
1929 * transform matrix, based on whether the rotation or scaleX/Y properties
1930 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001931 * is only valid after a call to updateMatrix() or to a function that
1932 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001933 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001934 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001935
1936 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001937 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1938 */
1939 private Camera mCamera = null;
1940
1941 /**
1942 * This matrix is used when computing the matrix for 3D rotations.
1943 */
1944 private Matrix matrix3D = null;
1945
1946 /**
1947 * These prev values are used to recalculate a centered pivot point when necessary. The
1948 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1949 * set), so thes values are only used then as well.
1950 */
1951 private int mPrevWidth = -1;
1952 private int mPrevHeight = -1;
1953
Joe Malin32736f02011-01-19 16:14:20 -08001954 private boolean mLastIsOpaque;
1955
Chet Haasefd2b0022010-08-06 13:08:56 -07001956 /**
1957 * Convenience value to check for float values that are close enough to zero to be considered
1958 * zero.
1959 */
Romain Guy2542d192010-08-18 11:47:12 -07001960 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001961
1962 /**
1963 * The degrees rotation around the vertical axis through the pivot point.
1964 */
1965 @ViewDebug.ExportedProperty
1966 private float mRotationY = 0f;
1967
1968 /**
1969 * The degrees rotation around the horizontal axis through the pivot point.
1970 */
1971 @ViewDebug.ExportedProperty
1972 private float mRotationX = 0f;
1973
1974 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001975 * The degrees rotation around the pivot point.
1976 */
1977 @ViewDebug.ExportedProperty
1978 private float mRotation = 0f;
1979
1980 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001981 * The amount of translation of the object away from its left property (post-layout).
1982 */
1983 @ViewDebug.ExportedProperty
1984 private float mTranslationX = 0f;
1985
1986 /**
1987 * The amount of translation of the object away from its top property (post-layout).
1988 */
1989 @ViewDebug.ExportedProperty
1990 private float mTranslationY = 0f;
1991
1992 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001993 * The amount of scale in the x direction around the pivot point. A
1994 * value of 1 means no scaling is applied.
1995 */
1996 @ViewDebug.ExportedProperty
1997 private float mScaleX = 1f;
1998
1999 /**
2000 * The amount of scale in the y direction around the pivot point. A
2001 * value of 1 means no scaling is applied.
2002 */
2003 @ViewDebug.ExportedProperty
2004 private float mScaleY = 1f;
2005
2006 /**
2007 * The amount of scale in the x direction around the pivot point. A
2008 * value of 1 means no scaling is applied.
2009 */
2010 @ViewDebug.ExportedProperty
2011 private float mPivotX = 0f;
2012
2013 /**
2014 * The amount of scale in the y direction around the pivot point. A
2015 * value of 1 means no scaling is applied.
2016 */
2017 @ViewDebug.ExportedProperty
2018 private float mPivotY = 0f;
2019
2020 /**
2021 * The opacity of the View. This is a value from 0 to 1, where 0 means
2022 * completely transparent and 1 means completely opaque.
2023 */
2024 @ViewDebug.ExportedProperty
2025 private float mAlpha = 1f;
2026
2027 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 * The distance in pixels from the left edge of this view's parent
2029 * to the left edge of this view.
2030 * {@hide}
2031 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002032 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 protected int mLeft;
2034 /**
2035 * The distance in pixels from the left edge of this view's parent
2036 * to the right edge of this view.
2037 * {@hide}
2038 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002039 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 protected int mRight;
2041 /**
2042 * The distance in pixels from the top edge of this view's parent
2043 * to the top edge of this view.
2044 * {@hide}
2045 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002046 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 protected int mTop;
2048 /**
2049 * The distance in pixels from the top edge of this view's parent
2050 * to the bottom edge of this view.
2051 * {@hide}
2052 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002053 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 protected int mBottom;
2055
2056 /**
2057 * The offset, in pixels, by which the content of this view is scrolled
2058 * horizontally.
2059 * {@hide}
2060 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002061 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 protected int mScrollX;
2063 /**
2064 * The offset, in pixels, by which the content of this view is scrolled
2065 * vertically.
2066 * {@hide}
2067 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002068 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 protected int mScrollY;
2070
2071 /**
2072 * The left padding in pixels, that is the distance in pixels between the
2073 * left edge of this view and the left edge of its content.
2074 * {@hide}
2075 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002076 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 protected int mPaddingLeft;
2078 /**
2079 * The right padding in pixels, that is the distance in pixels between the
2080 * right edge of this view and the right edge of its content.
2081 * {@hide}
2082 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002083 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 protected int mPaddingRight;
2085 /**
2086 * The top padding in pixels, that is the distance in pixels between the
2087 * top edge of this view and the top edge of its content.
2088 * {@hide}
2089 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002090 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 protected int mPaddingTop;
2092 /**
2093 * The bottom padding in pixels, that is the distance in pixels between the
2094 * bottom edge of this view and the bottom edge of its content.
2095 * {@hide}
2096 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002097 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 protected int mPaddingBottom;
2099
2100 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002101 * Briefly describes the view and is primarily used for accessibility support.
2102 */
2103 private CharSequence mContentDescription;
2104
2105 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 * Cache the paddingRight set by the user to append to the scrollbar's size.
2107 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002108 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 int mUserPaddingRight;
2110
2111 /**
2112 * Cache the paddingBottom set by the user to append to the scrollbar's size.
2113 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002114 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 int mUserPaddingBottom;
2116
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002117 /**
Adam Powell20232d02010-12-08 21:08:53 -08002118 * Cache the paddingLeft set by the user to append to the scrollbar's size.
2119 */
2120 @ViewDebug.ExportedProperty(category = "padding")
2121 int mUserPaddingLeft;
2122
2123 /**
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002124 * @hide
2125 */
2126 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2127 /**
2128 * @hide
2129 */
2130 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131
2132 private Resources mResources = null;
2133
2134 private Drawable mBGDrawable;
2135
2136 private int mBackgroundResource;
2137 private boolean mBackgroundSizeChanged;
2138
2139 /**
2140 * Listener used to dispatch focus change events.
2141 * This field should be made private, so it is hidden from the SDK.
2142 * {@hide}
2143 */
2144 protected OnFocusChangeListener mOnFocusChangeListener;
2145
2146 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002147 * Listeners for layout change events.
2148 */
2149 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2150
2151 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 * Listener used to dispatch click events.
2153 * This field should be made private, so it is hidden from the SDK.
2154 * {@hide}
2155 */
2156 protected OnClickListener mOnClickListener;
2157
2158 /**
2159 * Listener used to dispatch long click events.
2160 * This field should be made private, so it is hidden from the SDK.
2161 * {@hide}
2162 */
2163 protected OnLongClickListener mOnLongClickListener;
2164
2165 /**
2166 * Listener used to build the context menu.
2167 * This field should be made private, so it is hidden from the SDK.
2168 * {@hide}
2169 */
2170 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2171
2172 private OnKeyListener mOnKeyListener;
2173
2174 private OnTouchListener mOnTouchListener;
2175
Chris Tate32affef2010-10-18 15:29:21 -07002176 private OnDragListener mOnDragListener;
2177
Joe Onorato664644d2011-01-23 17:53:23 -08002178 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 /**
2181 * The application environment this view lives in.
2182 * This field should be made private, so it is hidden from the SDK.
2183 * {@hide}
2184 */
2185 protected Context mContext;
2186
2187 private ScrollabilityCache mScrollCache;
2188
2189 private int[] mDrawableState = null;
2190
Romain Guy02890fd2010-08-06 17:58:44 -07002191 private Bitmap mDrawingCache;
2192 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07002193 private DisplayList mDisplayList;
Romain Guy6c319ca2011-01-11 14:29:25 -08002194 private HardwareLayer mHardwareLayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195
2196 /**
2197 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2198 * the user may specify which view to go to next.
2199 */
2200 private int mNextFocusLeftId = View.NO_ID;
2201
2202 /**
2203 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2204 * the user may specify which view to go to next.
2205 */
2206 private int mNextFocusRightId = View.NO_ID;
2207
2208 /**
2209 * When this view has focus and the next focus is {@link #FOCUS_UP},
2210 * the user may specify which view to go to next.
2211 */
2212 private int mNextFocusUpId = View.NO_ID;
2213
2214 /**
2215 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2216 * the user may specify which view to go to next.
2217 */
2218 private int mNextFocusDownId = View.NO_ID;
2219
Jeff Brown4e6319b2010-12-13 10:36:51 -08002220 /**
2221 * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2222 * the user may specify which view to go to next.
2223 */
2224 int mNextFocusForwardId = View.NO_ID;
2225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08002227 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08002228 private PerformClick mPerformClick;
Joe Malin32736f02011-01-19 16:14:20 -08002229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 private UnsetPressedState mUnsetPressedState;
2231
2232 /**
2233 * Whether the long press's action has been invoked. The tap's action is invoked on the
2234 * up event while a long press is invoked as soon as the long press duration is reached, so
2235 * a long press could be performed before the tap is checked, in which case the tap's action
2236 * should not be invoked.
2237 */
2238 private boolean mHasPerformedLongPress;
2239
2240 /**
2241 * The minimum height of the view. We'll try our best to have the height
2242 * of this view to at least this amount.
2243 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002244 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 private int mMinHeight;
2246
2247 /**
2248 * The minimum width of the view. We'll try our best to have the width
2249 * of this view to at least this amount.
2250 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002251 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 private int mMinWidth;
2253
2254 /**
2255 * The delegate to handle touch events that are physically in this view
2256 * but should be handled by another view.
2257 */
2258 private TouchDelegate mTouchDelegate = null;
2259
2260 /**
2261 * Solid color to use as a background when creating the drawing cache. Enables
2262 * the cache to use 16 bit bitmaps instead of 32 bit.
2263 */
2264 private int mDrawingCacheBackgroundColor = 0;
2265
2266 /**
2267 * Special tree observer used when mAttachInfo is null.
2268 */
2269 private ViewTreeObserver mFloatingTreeObserver;
Joe Malin32736f02011-01-19 16:14:20 -08002270
Adam Powelle14579b2009-12-16 18:39:52 -08002271 /**
2272 * Cache the touch slop from the context that created the view.
2273 */
2274 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002277 * Cache drag/drop state
2278 *
2279 */
2280 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002281
2282 /**
Christopher Tate02d2b3b2011-01-10 20:43:53 -08002283 * Flag indicating that a drag can cross window boundaries
2284 * @hide
2285 */
2286 public static final int DRAG_FLAG_GLOBAL = 1;
2287
2288 /**
Adam Powell20232d02010-12-08 21:08:53 -08002289 * Position of the vertical scroll bar.
2290 */
2291 private int mVerticalScrollbarPosition;
2292
2293 /**
2294 * Position the scroll bar at the default position as determined by the system.
2295 */
2296 public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2297
2298 /**
2299 * Position the scroll bar along the left edge.
2300 */
2301 public static final int SCROLLBAR_POSITION_LEFT = 1;
2302
2303 /**
2304 * Position the scroll bar along the right edge.
2305 */
2306 public static final int SCROLLBAR_POSITION_RIGHT = 2;
2307
2308 /**
Romain Guy171c5922011-01-06 10:04:23 -08002309 * Indicates that the view does not have a layer.
Joe Malin32736f02011-01-19 16:14:20 -08002310 *
2311 * @see #getLayerType()
2312 * @see #setLayerType(int, android.graphics.Paint)
Romain Guy171c5922011-01-06 10:04:23 -08002313 * @see #LAYER_TYPE_SOFTWARE
Joe Malin32736f02011-01-19 16:14:20 -08002314 * @see #LAYER_TYPE_HARDWARE
Romain Guy171c5922011-01-06 10:04:23 -08002315 */
2316 public static final int LAYER_TYPE_NONE = 0;
2317
2318 /**
2319 * <p>Indicates that the view has a software layer. A software layer is backed
2320 * by a bitmap and causes the view to be rendered using Android's software
2321 * rendering pipeline, even if hardware acceleration is enabled.</p>
Joe Malin32736f02011-01-19 16:14:20 -08002322 *
Romain Guy171c5922011-01-06 10:04:23 -08002323 * <p>Software layers have various usages:</p>
2324 * <p>When the application is not using hardware acceleration, a software layer
2325 * is useful to apply a specific color filter and/or blending mode and/or
2326 * translucency to a view and all its children.</p>
2327 * <p>When the application is using hardware acceleration, a software layer
2328 * is useful to render drawing primitives not supported by the hardware
2329 * accelerated pipeline. It can also be used to cache a complex view tree
2330 * into a texture and reduce the complexity of drawing operations. For instance,
2331 * when animating a complex view tree with a translation, a software layer can
2332 * be used to render the view tree only once.</p>
2333 * <p>Software layers should be avoided when the affected view tree updates
2334 * often. Every update will require to re-render the software layer, which can
2335 * potentially be slow (particularly when hardware acceleration is turned on
2336 * since the layer will have to be uploaded into a hardware texture after every
2337 * update.)</p>
Joe Malin32736f02011-01-19 16:14:20 -08002338 *
2339 * @see #getLayerType()
2340 * @see #setLayerType(int, android.graphics.Paint)
Romain Guy171c5922011-01-06 10:04:23 -08002341 * @see #LAYER_TYPE_NONE
Joe Malin32736f02011-01-19 16:14:20 -08002342 * @see #LAYER_TYPE_HARDWARE
Romain Guy171c5922011-01-06 10:04:23 -08002343 */
2344 public static final int LAYER_TYPE_SOFTWARE = 1;
2345
2346 /**
2347 * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2348 * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2349 * OpenGL hardware) and causes the view to be rendered using Android's hardware
2350 * rendering pipeline, but only if hardware acceleration is turned on for the
2351 * view hierarchy. When hardware acceleration is turned off, hardware layers
2352 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
Joe Malin32736f02011-01-19 16:14:20 -08002353 *
Romain Guy171c5922011-01-06 10:04:23 -08002354 * <p>A hardware layer is useful to apply a specific color filter and/or
2355 * blending mode and/or translucency to a view and all its children.</p>
Romain Guy6c319ca2011-01-11 14:29:25 -08002356 * <p>A hardware layer can be used to cache a complex view tree into a
2357 * texture and reduce the complexity of drawing operations. For instance,
2358 * when animating a complex view tree with a translation, a hardware layer can
2359 * be used to render the view tree only once.</p>
Romain Guy171c5922011-01-06 10:04:23 -08002360 * <p>A hardware layer can also be used to increase the rendering quality when
2361 * rotation transformations are applied on a view. It can also be used to
2362 * prevent potential clipping issues when applying 3D transforms on a view.</p>
Joe Malin32736f02011-01-19 16:14:20 -08002363 *
2364 * @see #getLayerType()
Romain Guy171c5922011-01-06 10:04:23 -08002365 * @see #setLayerType(int, android.graphics.Paint)
2366 * @see #LAYER_TYPE_NONE
2367 * @see #LAYER_TYPE_SOFTWARE
2368 */
2369 public static final int LAYER_TYPE_HARDWARE = 2;
Joe Malin32736f02011-01-19 16:14:20 -08002370
Romain Guy3aaff3a2011-01-12 14:18:47 -08002371 @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2372 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2373 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2374 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2375 })
Romain Guy171c5922011-01-06 10:04:23 -08002376 int mLayerType = LAYER_TYPE_NONE;
2377 Paint mLayerPaint;
2378
2379 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 * Simple constructor to use when creating a view from code.
2381 *
2382 * @param context The Context the view is running in, through which it can
2383 * access the current theme, resources, etc.
2384 */
2385 public View(Context context) {
2386 mContext = context;
2387 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002388 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002389 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Adam Powell637d3372010-08-25 14:37:03 -07002390 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 }
2392
2393 /**
2394 * Constructor that is called when inflating a view from XML. This is called
2395 * when a view is being constructed from an XML file, supplying attributes
2396 * that were specified in the XML file. This version uses a default style of
2397 * 0, so the only attribute values applied are those in the Context's Theme
2398 * and the given AttributeSet.
2399 *
2400 * <p>
2401 * The method onFinishInflate() will be called after all children have been
2402 * added.
2403 *
2404 * @param context The Context the view is running in, through which it can
2405 * access the current theme, resources, etc.
2406 * @param attrs The attributes of the XML tag that is inflating the view.
2407 * @see #View(Context, AttributeSet, int)
2408 */
2409 public View(Context context, AttributeSet attrs) {
2410 this(context, attrs, 0);
2411 }
2412
2413 /**
2414 * Perform inflation from XML and apply a class-specific base style. This
2415 * constructor of View allows subclasses to use their own base style when
2416 * they are inflating. For example, a Button class's constructor would call
2417 * this version of the super class constructor and supply
2418 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2419 * the theme's button style to modify all of the base view attributes (in
2420 * particular its background) as well as the Button class's attributes.
2421 *
2422 * @param context The Context the view is running in, through which it can
2423 * access the current theme, resources, etc.
2424 * @param attrs The attributes of the XML tag that is inflating the view.
2425 * @param defStyle The default style to apply to this view. If 0, no style
2426 * will be applied (beyond what is included in the theme). This may
2427 * either be an attribute resource, whose value will be retrieved
2428 * from the current theme, or an explicit style resource.
2429 * @see #View(Context, AttributeSet)
2430 */
2431 public View(Context context, AttributeSet attrs, int defStyle) {
2432 this(context);
2433
2434 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2435 defStyle, 0);
2436
2437 Drawable background = null;
2438
2439 int leftPadding = -1;
2440 int topPadding = -1;
2441 int rightPadding = -1;
2442 int bottomPadding = -1;
2443
2444 int padding = -1;
2445
2446 int viewFlagValues = 0;
2447 int viewFlagMasks = 0;
2448
2449 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 int x = 0;
2452 int y = 0;
2453
Chet Haase73066682010-11-29 15:55:32 -08002454 float tx = 0;
2455 float ty = 0;
2456 float rotation = 0;
2457 float rotationX = 0;
2458 float rotationY = 0;
2459 float sx = 1f;
2460 float sy = 1f;
2461 boolean transformSet = false;
2462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2464
Adam Powell637d3372010-08-25 14:37:03 -07002465 int overScrollMode = mOverScrollMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 final int N = a.getIndexCount();
2467 for (int i = 0; i < N; i++) {
2468 int attr = a.getIndex(i);
2469 switch (attr) {
2470 case com.android.internal.R.styleable.View_background:
2471 background = a.getDrawable(attr);
2472 break;
2473 case com.android.internal.R.styleable.View_padding:
2474 padding = a.getDimensionPixelSize(attr, -1);
2475 break;
2476 case com.android.internal.R.styleable.View_paddingLeft:
2477 leftPadding = a.getDimensionPixelSize(attr, -1);
2478 break;
2479 case com.android.internal.R.styleable.View_paddingTop:
2480 topPadding = a.getDimensionPixelSize(attr, -1);
2481 break;
2482 case com.android.internal.R.styleable.View_paddingRight:
2483 rightPadding = a.getDimensionPixelSize(attr, -1);
2484 break;
2485 case com.android.internal.R.styleable.View_paddingBottom:
2486 bottomPadding = a.getDimensionPixelSize(attr, -1);
2487 break;
2488 case com.android.internal.R.styleable.View_scrollX:
2489 x = a.getDimensionPixelOffset(attr, 0);
2490 break;
2491 case com.android.internal.R.styleable.View_scrollY:
2492 y = a.getDimensionPixelOffset(attr, 0);
2493 break;
Chet Haase73066682010-11-29 15:55:32 -08002494 case com.android.internal.R.styleable.View_alpha:
2495 setAlpha(a.getFloat(attr, 1f));
2496 break;
2497 case com.android.internal.R.styleable.View_transformPivotX:
2498 setPivotX(a.getDimensionPixelOffset(attr, 0));
2499 break;
2500 case com.android.internal.R.styleable.View_transformPivotY:
2501 setPivotY(a.getDimensionPixelOffset(attr, 0));
2502 break;
2503 case com.android.internal.R.styleable.View_translationX:
2504 tx = a.getDimensionPixelOffset(attr, 0);
2505 transformSet = true;
2506 break;
2507 case com.android.internal.R.styleable.View_translationY:
2508 ty = a.getDimensionPixelOffset(attr, 0);
2509 transformSet = true;
2510 break;
2511 case com.android.internal.R.styleable.View_rotation:
2512 rotation = a.getFloat(attr, 0);
2513 transformSet = true;
2514 break;
2515 case com.android.internal.R.styleable.View_rotationX:
2516 rotationX = a.getFloat(attr, 0);
2517 transformSet = true;
2518 break;
2519 case com.android.internal.R.styleable.View_rotationY:
2520 rotationY = a.getFloat(attr, 0);
2521 transformSet = true;
2522 break;
2523 case com.android.internal.R.styleable.View_scaleX:
2524 sx = a.getFloat(attr, 1f);
2525 transformSet = true;
2526 break;
2527 case com.android.internal.R.styleable.View_scaleY:
2528 sy = a.getFloat(attr, 1f);
2529 transformSet = true;
2530 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 case com.android.internal.R.styleable.View_id:
2532 mID = a.getResourceId(attr, NO_ID);
2533 break;
2534 case com.android.internal.R.styleable.View_tag:
2535 mTag = a.getText(attr);
2536 break;
2537 case com.android.internal.R.styleable.View_fitsSystemWindows:
2538 if (a.getBoolean(attr, false)) {
2539 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2540 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2541 }
2542 break;
2543 case com.android.internal.R.styleable.View_focusable:
2544 if (a.getBoolean(attr, false)) {
2545 viewFlagValues |= FOCUSABLE;
2546 viewFlagMasks |= FOCUSABLE_MASK;
2547 }
2548 break;
2549 case com.android.internal.R.styleable.View_focusableInTouchMode:
2550 if (a.getBoolean(attr, false)) {
2551 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2552 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2553 }
2554 break;
2555 case com.android.internal.R.styleable.View_clickable:
2556 if (a.getBoolean(attr, false)) {
2557 viewFlagValues |= CLICKABLE;
2558 viewFlagMasks |= CLICKABLE;
2559 }
2560 break;
2561 case com.android.internal.R.styleable.View_longClickable:
2562 if (a.getBoolean(attr, false)) {
2563 viewFlagValues |= LONG_CLICKABLE;
2564 viewFlagMasks |= LONG_CLICKABLE;
2565 }
2566 break;
2567 case com.android.internal.R.styleable.View_saveEnabled:
2568 if (!a.getBoolean(attr, true)) {
2569 viewFlagValues |= SAVE_DISABLED;
2570 viewFlagMasks |= SAVE_DISABLED_MASK;
2571 }
2572 break;
2573 case com.android.internal.R.styleable.View_duplicateParentState:
2574 if (a.getBoolean(attr, false)) {
2575 viewFlagValues |= DUPLICATE_PARENT_STATE;
2576 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2577 }
2578 break;
2579 case com.android.internal.R.styleable.View_visibility:
2580 final int visibility = a.getInt(attr, 0);
2581 if (visibility != 0) {
2582 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2583 viewFlagMasks |= VISIBILITY_MASK;
2584 }
2585 break;
2586 case com.android.internal.R.styleable.View_drawingCacheQuality:
2587 final int cacheQuality = a.getInt(attr, 0);
2588 if (cacheQuality != 0) {
2589 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2590 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2591 }
2592 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002593 case com.android.internal.R.styleable.View_contentDescription:
2594 mContentDescription = a.getString(attr);
2595 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2597 if (!a.getBoolean(attr, true)) {
2598 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2599 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2600 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002601 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2603 if (!a.getBoolean(attr, true)) {
2604 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2605 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2606 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002607 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 case R.styleable.View_scrollbars:
2609 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2610 if (scrollbars != SCROLLBARS_NONE) {
2611 viewFlagValues |= scrollbars;
2612 viewFlagMasks |= SCROLLBARS_MASK;
2613 initializeScrollbars(a);
2614 }
2615 break;
2616 case R.styleable.View_fadingEdge:
2617 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2618 if (fadingEdge != FADING_EDGE_NONE) {
2619 viewFlagValues |= fadingEdge;
2620 viewFlagMasks |= FADING_EDGE_MASK;
2621 initializeFadingEdge(a);
2622 }
2623 break;
2624 case R.styleable.View_scrollbarStyle:
2625 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2626 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2627 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2628 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2629 }
2630 break;
2631 case R.styleable.View_isScrollContainer:
2632 setScrollContainer = true;
2633 if (a.getBoolean(attr, false)) {
2634 setScrollContainer(true);
2635 }
2636 break;
2637 case com.android.internal.R.styleable.View_keepScreenOn:
2638 if (a.getBoolean(attr, false)) {
2639 viewFlagValues |= KEEP_SCREEN_ON;
2640 viewFlagMasks |= KEEP_SCREEN_ON;
2641 }
2642 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002643 case R.styleable.View_filterTouchesWhenObscured:
2644 if (a.getBoolean(attr, false)) {
2645 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2646 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2647 }
2648 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 case R.styleable.View_nextFocusLeft:
2650 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2651 break;
2652 case R.styleable.View_nextFocusRight:
2653 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2654 break;
2655 case R.styleable.View_nextFocusUp:
2656 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2657 break;
2658 case R.styleable.View_nextFocusDown:
2659 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2660 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002661 case R.styleable.View_nextFocusForward:
2662 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2663 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 case R.styleable.View_minWidth:
2665 mMinWidth = a.getDimensionPixelSize(attr, 0);
2666 break;
2667 case R.styleable.View_minHeight:
2668 mMinHeight = a.getDimensionPixelSize(attr, 0);
2669 break;
Romain Guy9a817362009-05-01 10:57:14 -07002670 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002671 if (context.isRestricted()) {
Joe Malin32736f02011-01-19 16:14:20 -08002672 throw new IllegalStateException("The android:onClick attribute cannot "
Romain Guy870e09f2009-07-06 16:35:25 -07002673 + "be used within a restricted context");
2674 }
2675
Romain Guy9a817362009-05-01 10:57:14 -07002676 final String handlerName = a.getString(attr);
2677 if (handlerName != null) {
2678 setOnClickListener(new OnClickListener() {
2679 private Method mHandler;
2680
2681 public void onClick(View v) {
2682 if (mHandler == null) {
2683 try {
2684 mHandler = getContext().getClass().getMethod(handlerName,
2685 View.class);
2686 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002687 int id = getId();
2688 String idText = id == NO_ID ? "" : " with id '"
2689 + getContext().getResources().getResourceEntryName(
2690 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002691 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002692 handlerName + "(View) in the activity "
2693 + getContext().getClass() + " for onClick handler"
2694 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002695 }
2696 }
2697
2698 try {
2699 mHandler.invoke(getContext(), View.this);
2700 } catch (IllegalAccessException e) {
2701 throw new IllegalStateException("Could not execute non "
2702 + "public method of the activity", e);
2703 } catch (InvocationTargetException e) {
2704 throw new IllegalStateException("Could not execute "
2705 + "method of the activity", e);
2706 }
2707 }
2708 });
2709 }
2710 break;
Adam Powell637d3372010-08-25 14:37:03 -07002711 case R.styleable.View_overScrollMode:
2712 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2713 break;
Adam Powell20232d02010-12-08 21:08:53 -08002714 case R.styleable.View_verticalScrollbarPosition:
2715 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2716 break;
Romain Guy171c5922011-01-06 10:04:23 -08002717 case R.styleable.View_layerType:
2718 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
2719 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 }
2721 }
2722
Adam Powell637d3372010-08-25 14:37:03 -07002723 setOverScrollMode(overScrollMode);
2724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 if (background != null) {
2726 setBackgroundDrawable(background);
2727 }
2728
2729 if (padding >= 0) {
2730 leftPadding = padding;
2731 topPadding = padding;
2732 rightPadding = padding;
2733 bottomPadding = padding;
2734 }
2735
2736 // If the user specified the padding (either with android:padding or
2737 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2738 // use the default padding or the padding from the background drawable
2739 // (stored at this point in mPadding*)
2740 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2741 topPadding >= 0 ? topPadding : mPaddingTop,
2742 rightPadding >= 0 ? rightPadding : mPaddingRight,
2743 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2744
2745 if (viewFlagMasks != 0) {
2746 setFlags(viewFlagValues, viewFlagMasks);
2747 }
2748
2749 // Needs to be called after mViewFlags is set
2750 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2751 recomputePadding();
2752 }
2753
2754 if (x != 0 || y != 0) {
2755 scrollTo(x, y);
2756 }
2757
Chet Haase73066682010-11-29 15:55:32 -08002758 if (transformSet) {
2759 setTranslationX(tx);
2760 setTranslationY(ty);
2761 setRotation(rotation);
2762 setRotationX(rotationX);
2763 setRotationY(rotationY);
2764 setScaleX(sx);
2765 setScaleY(sy);
2766 }
2767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2769 setScrollContainer(true);
2770 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002771
2772 computeOpaqueFlags();
2773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 a.recycle();
2775 }
2776
2777 /**
2778 * Non-public constructor for use in testing
2779 */
2780 View() {
2781 }
2782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 /**
2784 * <p>
2785 * Initializes the fading edges from a given set of styled attributes. This
2786 * method should be called by subclasses that need fading edges and when an
2787 * instance of these subclasses is created programmatically rather than
2788 * being inflated from XML. This method is automatically called when the XML
2789 * is inflated.
2790 * </p>
2791 *
2792 * @param a the styled attributes set to initialize the fading edges from
2793 */
2794 protected void initializeFadingEdge(TypedArray a) {
2795 initScrollCache();
2796
2797 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2798 R.styleable.View_fadingEdgeLength,
2799 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2800 }
2801
2802 /**
2803 * Returns the size of the vertical faded edges used to indicate that more
2804 * content in this view is visible.
2805 *
2806 * @return The size in pixels of the vertical faded edge or 0 if vertical
2807 * faded edges are not enabled for this view.
2808 * @attr ref android.R.styleable#View_fadingEdgeLength
2809 */
2810 public int getVerticalFadingEdgeLength() {
2811 if (isVerticalFadingEdgeEnabled()) {
2812 ScrollabilityCache cache = mScrollCache;
2813 if (cache != null) {
2814 return cache.fadingEdgeLength;
2815 }
2816 }
2817 return 0;
2818 }
2819
2820 /**
2821 * Set the size of the faded edge used to indicate that more content in this
2822 * view is available. Will not change whether the fading edge is enabled; use
2823 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2824 * to enable the fading edge for the vertical or horizontal fading edges.
2825 *
2826 * @param length The size in pixels of the faded edge used to indicate that more
2827 * content in this view is visible.
2828 */
2829 public void setFadingEdgeLength(int length) {
2830 initScrollCache();
2831 mScrollCache.fadingEdgeLength = length;
2832 }
2833
2834 /**
2835 * Returns the size of the horizontal faded edges used to indicate that more
2836 * content in this view is visible.
2837 *
2838 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2839 * faded edges are not enabled for this view.
2840 * @attr ref android.R.styleable#View_fadingEdgeLength
2841 */
2842 public int getHorizontalFadingEdgeLength() {
2843 if (isHorizontalFadingEdgeEnabled()) {
2844 ScrollabilityCache cache = mScrollCache;
2845 if (cache != null) {
2846 return cache.fadingEdgeLength;
2847 }
2848 }
2849 return 0;
2850 }
2851
2852 /**
2853 * Returns the width of the vertical scrollbar.
2854 *
2855 * @return The width in pixels of the vertical scrollbar or 0 if there
2856 * is no vertical scrollbar.
2857 */
2858 public int getVerticalScrollbarWidth() {
2859 ScrollabilityCache cache = mScrollCache;
2860 if (cache != null) {
2861 ScrollBarDrawable scrollBar = cache.scrollBar;
2862 if (scrollBar != null) {
2863 int size = scrollBar.getSize(true);
2864 if (size <= 0) {
2865 size = cache.scrollBarSize;
2866 }
2867 return size;
2868 }
2869 return 0;
2870 }
2871 return 0;
2872 }
2873
2874 /**
2875 * Returns the height of the horizontal scrollbar.
2876 *
2877 * @return The height in pixels of the horizontal scrollbar or 0 if
2878 * there is no horizontal scrollbar.
2879 */
2880 protected int getHorizontalScrollbarHeight() {
2881 ScrollabilityCache cache = mScrollCache;
2882 if (cache != null) {
2883 ScrollBarDrawable scrollBar = cache.scrollBar;
2884 if (scrollBar != null) {
2885 int size = scrollBar.getSize(false);
2886 if (size <= 0) {
2887 size = cache.scrollBarSize;
2888 }
2889 return size;
2890 }
2891 return 0;
2892 }
2893 return 0;
2894 }
2895
2896 /**
2897 * <p>
2898 * Initializes the scrollbars from a given set of styled attributes. This
2899 * method should be called by subclasses that need scrollbars and when an
2900 * instance of these subclasses is created programmatically rather than
2901 * being inflated from XML. This method is automatically called when the XML
2902 * is inflated.
2903 * </p>
2904 *
2905 * @param a the styled attributes set to initialize the scrollbars from
2906 */
2907 protected void initializeScrollbars(TypedArray a) {
2908 initScrollCache();
2909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 final ScrollabilityCache scrollabilityCache = mScrollCache;
Joe Malin32736f02011-01-19 16:14:20 -08002911
Mike Cleronf116bf82009-09-27 19:14:12 -07002912 if (scrollabilityCache.scrollBar == null) {
2913 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2914 }
Joe Malin32736f02011-01-19 16:14:20 -08002915
Romain Guy8bda2482010-03-02 11:42:11 -08002916 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917
Mike Cleronf116bf82009-09-27 19:14:12 -07002918 if (!fadeScrollbars) {
2919 scrollabilityCache.state = ScrollabilityCache.ON;
2920 }
2921 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Joe Malin32736f02011-01-19 16:14:20 -08002922
2923
Mike Cleronf116bf82009-09-27 19:14:12 -07002924 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2925 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2926 .getScrollBarFadeDuration());
2927 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2928 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2929 ViewConfiguration.getScrollDefaultDelay());
2930
Joe Malin32736f02011-01-19 16:14:20 -08002931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2933 com.android.internal.R.styleable.View_scrollbarSize,
2934 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2935
2936 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2937 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2938
2939 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2940 if (thumb != null) {
2941 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2942 }
2943
2944 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2945 false);
2946 if (alwaysDraw) {
2947 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2948 }
2949
2950 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2951 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2952
2953 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2954 if (thumb != null) {
2955 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2956 }
2957
2958 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2959 false);
2960 if (alwaysDraw) {
2961 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2962 }
2963
2964 // Re-apply user/background padding so that scrollbar(s) get added
2965 recomputePadding();
2966 }
2967
2968 /**
2969 * <p>
2970 * Initalizes the scrollability cache if necessary.
2971 * </p>
2972 */
2973 private void initScrollCache() {
2974 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002975 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 }
2977 }
2978
2979 /**
Adam Powell20232d02010-12-08 21:08:53 -08002980 * Set the position of the vertical scroll bar. Should be one of
2981 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
2982 * {@link #SCROLLBAR_POSITION_RIGHT}.
2983 *
2984 * @param position Where the vertical scroll bar should be positioned.
2985 */
2986 public void setVerticalScrollbarPosition(int position) {
2987 if (mVerticalScrollbarPosition != position) {
2988 mVerticalScrollbarPosition = position;
2989 computeOpaqueFlags();
2990 recomputePadding();
2991 }
2992 }
2993
2994 /**
2995 * @return The position where the vertical scroll bar will show, if applicable.
2996 * @see #setVerticalScrollbarPosition(int)
2997 */
2998 public int getVerticalScrollbarPosition() {
2999 return mVerticalScrollbarPosition;
3000 }
3001
3002 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 * Register a callback to be invoked when focus of this view changed.
3004 *
3005 * @param l The callback that will run.
3006 */
3007 public void setOnFocusChangeListener(OnFocusChangeListener l) {
3008 mOnFocusChangeListener = l;
3009 }
3010
3011 /**
Chet Haase21cd1382010-09-01 17:42:29 -07003012 * Add a listener that will be called when the bounds of the view change due to
3013 * layout processing.
3014 *
3015 * @param listener The listener that will be called when layout bounds change.
3016 */
3017 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3018 if (mOnLayoutChangeListeners == null) {
3019 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3020 }
3021 mOnLayoutChangeListeners.add(listener);
3022 }
3023
3024 /**
3025 * Remove a listener for layout changes.
3026 *
3027 * @param listener The listener for layout bounds change.
3028 */
3029 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3030 if (mOnLayoutChangeListeners == null) {
3031 return;
3032 }
3033 mOnLayoutChangeListeners.remove(listener);
3034 }
3035
3036 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 * Returns the focus-change callback registered for this view.
3038 *
3039 * @return The callback, or null if one is not registered.
3040 */
3041 public OnFocusChangeListener getOnFocusChangeListener() {
3042 return mOnFocusChangeListener;
3043 }
3044
3045 /**
3046 * Register a callback to be invoked when this view is clicked. If this view is not
3047 * clickable, it becomes clickable.
3048 *
3049 * @param l The callback that will run
3050 *
3051 * @see #setClickable(boolean)
3052 */
3053 public void setOnClickListener(OnClickListener l) {
3054 if (!isClickable()) {
3055 setClickable(true);
3056 }
3057 mOnClickListener = l;
3058 }
3059
3060 /**
3061 * Register a callback to be invoked when this view is clicked and held. If this view is not
3062 * long clickable, it becomes long clickable.
3063 *
3064 * @param l The callback that will run
3065 *
3066 * @see #setLongClickable(boolean)
3067 */
3068 public void setOnLongClickListener(OnLongClickListener l) {
3069 if (!isLongClickable()) {
3070 setLongClickable(true);
3071 }
3072 mOnLongClickListener = l;
3073 }
3074
3075 /**
3076 * Register a callback to be invoked when the context menu for this view is
3077 * being built. If this view is not long clickable, it becomes long clickable.
3078 *
3079 * @param l The callback that will run
3080 *
3081 */
3082 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3083 if (!isLongClickable()) {
3084 setLongClickable(true);
3085 }
3086 mOnCreateContextMenuListener = l;
3087 }
3088
3089 /**
3090 * Call this view's OnClickListener, if it is defined.
3091 *
3092 * @return True there was an assigned OnClickListener that was called, false
3093 * otherwise is returned.
3094 */
3095 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07003096 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 if (mOnClickListener != null) {
3099 playSoundEffect(SoundEffectConstants.CLICK);
3100 mOnClickListener.onClick(this);
3101 return true;
3102 }
3103
3104 return false;
3105 }
3106
3107 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07003108 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3109 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07003111 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 */
3113 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07003114 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 boolean handled = false;
3117 if (mOnLongClickListener != null) {
3118 handled = mOnLongClickListener.onLongClick(View.this);
3119 }
3120 if (!handled) {
3121 handled = showContextMenu();
3122 }
3123 if (handled) {
3124 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3125 }
3126 return handled;
3127 }
3128
3129 /**
3130 * Bring up the context menu for this view.
3131 *
3132 * @return Whether a context menu was displayed.
3133 */
3134 public boolean showContextMenu() {
3135 return getParent().showContextMenuForChild(this);
3136 }
3137
3138 /**
Adam Powell6e346362010-07-23 10:18:23 -07003139 * Start an action mode.
3140 *
3141 * @param callback Callback that will control the lifecycle of the action mode
3142 * @return The new action mode if it is started, null otherwise
3143 *
3144 * @see ActionMode
3145 */
3146 public ActionMode startActionMode(ActionMode.Callback callback) {
3147 return getParent().startActionModeForChild(this, callback);
3148 }
3149
3150 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 * Register a callback to be invoked when a key is pressed in this view.
3152 * @param l the key listener to attach to this view
3153 */
3154 public void setOnKeyListener(OnKeyListener l) {
3155 mOnKeyListener = l;
3156 }
3157
3158 /**
3159 * Register a callback to be invoked when a touch event is sent to this view.
3160 * @param l the touch listener to attach to this view
3161 */
3162 public void setOnTouchListener(OnTouchListener l) {
3163 mOnTouchListener = l;
3164 }
3165
3166 /**
Joe Malin32736f02011-01-19 16:14:20 -08003167 * Register a drag event listener callback object for this View. The parameter is
3168 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3169 * View, the system calls the
3170 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3171 * @param l An implementation of {@link android.view.View.OnDragListener}.
Chris Tate32affef2010-10-18 15:29:21 -07003172 */
3173 public void setOnDragListener(OnDragListener l) {
3174 mOnDragListener = l;
3175 }
3176
3177 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
3179 *
3180 * Note: this does not check whether this {@link View} should get focus, it just
3181 * gives it focus no matter what. It should only be called internally by framework
3182 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3183 *
3184 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
3185 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
3186 * focus moved when requestFocus() is called. It may not always
3187 * apply, in which case use the default View.FOCUS_DOWN.
3188 * @param previouslyFocusedRect The rectangle of the view that had focus
3189 * prior in this View's coordinate system.
3190 */
3191 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3192 if (DBG) {
3193 System.out.println(this + " requestFocus()");
3194 }
3195
3196 if ((mPrivateFlags & FOCUSED) == 0) {
3197 mPrivateFlags |= FOCUSED;
3198
3199 if (mParent != null) {
3200 mParent.requestChildFocus(this, this);
3201 }
3202
3203 onFocusChanged(true, direction, previouslyFocusedRect);
3204 refreshDrawableState();
3205 }
3206 }
3207
3208 /**
3209 * Request that a rectangle of this view be visible on the screen,
3210 * scrolling if necessary just enough.
3211 *
3212 * <p>A View should call this if it maintains some notion of which part
3213 * of its content is interesting. For example, a text editing view
3214 * should call this when its cursor moves.
3215 *
3216 * @param rectangle The rectangle.
3217 * @return Whether any parent scrolled.
3218 */
3219 public boolean requestRectangleOnScreen(Rect rectangle) {
3220 return requestRectangleOnScreen(rectangle, false);
3221 }
3222
3223 /**
3224 * Request that a rectangle of this view be visible on the screen,
3225 * scrolling if necessary just enough.
3226 *
3227 * <p>A View should call this if it maintains some notion of which part
3228 * of its content is interesting. For example, a text editing view
3229 * should call this when its cursor moves.
3230 *
3231 * <p>When <code>immediate</code> is set to true, scrolling will not be
3232 * animated.
3233 *
3234 * @param rectangle The rectangle.
3235 * @param immediate True to forbid animated scrolling, false otherwise
3236 * @return Whether any parent scrolled.
3237 */
3238 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3239 View child = this;
3240 ViewParent parent = mParent;
3241 boolean scrolled = false;
3242 while (parent != null) {
3243 scrolled |= parent.requestChildRectangleOnScreen(child,
3244 rectangle, immediate);
3245
3246 // offset rect so next call has the rectangle in the
3247 // coordinate system of its direct child.
3248 rectangle.offset(child.getLeft(), child.getTop());
3249 rectangle.offset(-child.getScrollX(), -child.getScrollY());
3250
3251 if (!(parent instanceof View)) {
3252 break;
3253 }
Romain Guy8506ab42009-06-11 17:35:47 -07003254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 child = (View) parent;
3256 parent = child.getParent();
3257 }
3258 return scrolled;
3259 }
3260
3261 /**
3262 * Called when this view wants to give up focus. This will cause
3263 * {@link #onFocusChanged} to be called.
3264 */
3265 public void clearFocus() {
3266 if (DBG) {
3267 System.out.println(this + " clearFocus()");
3268 }
3269
3270 if ((mPrivateFlags & FOCUSED) != 0) {
3271 mPrivateFlags &= ~FOCUSED;
3272
3273 if (mParent != null) {
3274 mParent.clearChildFocus(this);
3275 }
3276
3277 onFocusChanged(false, 0, null);
3278 refreshDrawableState();
3279 }
3280 }
3281
3282 /**
3283 * Called to clear the focus of a view that is about to be removed.
3284 * Doesn't call clearChildFocus, which prevents this view from taking
3285 * focus again before it has been removed from the parent
3286 */
3287 void clearFocusForRemoval() {
3288 if ((mPrivateFlags & FOCUSED) != 0) {
3289 mPrivateFlags &= ~FOCUSED;
3290
3291 onFocusChanged(false, 0, null);
3292 refreshDrawableState();
3293 }
3294 }
3295
3296 /**
3297 * Called internally by the view system when a new view is getting focus.
3298 * This is what clears the old focus.
3299 */
3300 void unFocus() {
3301 if (DBG) {
3302 System.out.println(this + " unFocus()");
3303 }
3304
3305 if ((mPrivateFlags & FOCUSED) != 0) {
3306 mPrivateFlags &= ~FOCUSED;
3307
3308 onFocusChanged(false, 0, null);
3309 refreshDrawableState();
3310 }
3311 }
3312
3313 /**
3314 * Returns true if this view has focus iteself, or is the ancestor of the
3315 * view that has focus.
3316 *
3317 * @return True if this view has or contains focus, false otherwise.
3318 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003319 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 public boolean hasFocus() {
3321 return (mPrivateFlags & FOCUSED) != 0;
3322 }
3323
3324 /**
3325 * Returns true if this view is focusable or if it contains a reachable View
3326 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3327 * is a View whose parents do not block descendants focus.
3328 *
3329 * Only {@link #VISIBLE} views are considered focusable.
3330 *
3331 * @return True if the view is focusable or if the view contains a focusable
3332 * View, false otherwise.
3333 *
3334 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3335 */
3336 public boolean hasFocusable() {
3337 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3338 }
3339
3340 /**
3341 * Called by the view system when the focus state of this view changes.
3342 * When the focus change event is caused by directional navigation, direction
3343 * and previouslyFocusedRect provide insight into where the focus is coming from.
3344 * When overriding, be sure to call up through to the super class so that
3345 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07003346 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 * @param gainFocus True if the View has focus; false otherwise.
3348 * @param direction The direction focus has moved when requestFocus()
3349 * is called to give this view focus. Values are
Jeff Brown4e6319b2010-12-13 10:36:51 -08003350 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3351 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3352 * It may not always apply, in which case use the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 * @param previouslyFocusedRect The rectangle, in this view's coordinate
3354 * system, of the previously focused view. If applicable, this will be
3355 * passed in as finer grained information about where the focus is coming
3356 * from (in addition to direction). Will be <code>null</code> otherwise.
3357 */
3358 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003359 if (gainFocus) {
3360 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3361 }
3362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 InputMethodManager imm = InputMethodManager.peekInstance();
3364 if (!gainFocus) {
3365 if (isPressed()) {
3366 setPressed(false);
3367 }
3368 if (imm != null && mAttachInfo != null
3369 && mAttachInfo.mHasWindowFocus) {
3370 imm.focusOut(this);
3371 }
Romain Guya2431d02009-04-30 16:30:00 -07003372 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 } else if (imm != null && mAttachInfo != null
3374 && mAttachInfo.mHasWindowFocus) {
3375 imm.focusIn(this);
3376 }
Romain Guy8506ab42009-06-11 17:35:47 -07003377
Romain Guy0fd89bf2011-01-26 15:41:30 -08003378 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 if (mOnFocusChangeListener != null) {
3380 mOnFocusChangeListener.onFocusChange(this, gainFocus);
3381 }
Joe Malin32736f02011-01-19 16:14:20 -08003382
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003383 if (mAttachInfo != null) {
3384 mAttachInfo.mKeyDispatchState.reset(this);
3385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 }
3387
3388 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07003389 * {@inheritDoc}
3390 */
3391 public void sendAccessibilityEvent(int eventType) {
3392 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3393 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3394 }
3395 }
3396
3397 /**
3398 * {@inheritDoc}
3399 */
3400 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
Svetoslav Ganov9cd1eca2011-01-13 14:24:02 -08003401 if (!isShown()) {
3402 return;
3403 }
svetoslavganov75986cf2009-05-14 22:28:01 -07003404 event.setClassName(getClass().getName());
3405 event.setPackageName(getContext().getPackageName());
3406 event.setEnabled(isEnabled());
3407 event.setContentDescription(mContentDescription);
3408
3409 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3410 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3411 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3412 event.setItemCount(focusablesTempList.size());
3413 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3414 focusablesTempList.clear();
3415 }
3416
3417 dispatchPopulateAccessibilityEvent(event);
3418
3419 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3420 }
3421
3422 /**
3423 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3424 * to be populated.
3425 *
3426 * @param event The event.
3427 *
3428 * @return True if the event population was completed.
3429 */
3430 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3431 return false;
3432 }
3433
3434 /**
3435 * Gets the {@link View} description. It briefly describes the view and is
3436 * primarily used for accessibility support. Set this property to enable
3437 * better accessibility support for your application. This is especially
3438 * true for views that do not have textual representation (For example,
3439 * ImageButton).
3440 *
3441 * @return The content descriptiopn.
3442 *
3443 * @attr ref android.R.styleable#View_contentDescription
3444 */
3445 public CharSequence getContentDescription() {
3446 return mContentDescription;
3447 }
3448
3449 /**
3450 * Sets the {@link View} description. It briefly describes the view and is
3451 * primarily used for accessibility support. Set this property to enable
3452 * better accessibility support for your application. This is especially
3453 * true for views that do not have textual representation (For example,
3454 * ImageButton).
3455 *
3456 * @param contentDescription The content description.
3457 *
3458 * @attr ref android.R.styleable#View_contentDescription
3459 */
3460 public void setContentDescription(CharSequence contentDescription) {
3461 mContentDescription = contentDescription;
3462 }
3463
3464 /**
Romain Guya2431d02009-04-30 16:30:00 -07003465 * Invoked whenever this view loses focus, either by losing window focus or by losing
3466 * focus within its window. This method can be used to clear any state tied to the
3467 * focus. For instance, if a button is held pressed with the trackball and the window
3468 * loses focus, this method can be used to cancel the press.
3469 *
3470 * Subclasses of View overriding this method should always call super.onFocusLost().
3471 *
3472 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003473 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003474 *
3475 * @hide pending API council approval
3476 */
3477 protected void onFocusLost() {
3478 resetPressedState();
3479 }
3480
3481 private void resetPressedState() {
3482 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3483 return;
3484 }
3485
3486 if (isPressed()) {
3487 setPressed(false);
3488
3489 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003490 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003491 }
3492 }
3493 }
3494
3495 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 * Returns true if this view has focus
3497 *
3498 * @return True if this view has focus, false otherwise.
3499 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003500 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 public boolean isFocused() {
3502 return (mPrivateFlags & FOCUSED) != 0;
3503 }
3504
3505 /**
3506 * Find the view in the hierarchy rooted at this view that currently has
3507 * focus.
3508 *
3509 * @return The view that currently has focus, or null if no focused view can
3510 * be found.
3511 */
3512 public View findFocus() {
3513 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3514 }
3515
3516 /**
3517 * Change whether this view is one of the set of scrollable containers in
3518 * its window. This will be used to determine whether the window can
3519 * resize or must pan when a soft input area is open -- scrollable
3520 * containers allow the window to use resize mode since the container
3521 * will appropriately shrink.
3522 */
3523 public void setScrollContainer(boolean isScrollContainer) {
3524 if (isScrollContainer) {
3525 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3526 mAttachInfo.mScrollContainers.add(this);
3527 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3528 }
3529 mPrivateFlags |= SCROLL_CONTAINER;
3530 } else {
3531 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3532 mAttachInfo.mScrollContainers.remove(this);
3533 }
3534 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3535 }
3536 }
3537
3538 /**
3539 * Returns the quality of the drawing cache.
3540 *
3541 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3542 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3543 *
3544 * @see #setDrawingCacheQuality(int)
3545 * @see #setDrawingCacheEnabled(boolean)
3546 * @see #isDrawingCacheEnabled()
3547 *
3548 * @attr ref android.R.styleable#View_drawingCacheQuality
3549 */
3550 public int getDrawingCacheQuality() {
3551 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3552 }
3553
3554 /**
3555 * Set the drawing cache quality of this view. This value is used only when the
3556 * drawing cache is enabled
3557 *
3558 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3559 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3560 *
3561 * @see #getDrawingCacheQuality()
3562 * @see #setDrawingCacheEnabled(boolean)
3563 * @see #isDrawingCacheEnabled()
3564 *
3565 * @attr ref android.R.styleable#View_drawingCacheQuality
3566 */
3567 public void setDrawingCacheQuality(int quality) {
3568 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3569 }
3570
3571 /**
3572 * Returns whether the screen should remain on, corresponding to the current
3573 * value of {@link #KEEP_SCREEN_ON}.
3574 *
3575 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3576 *
3577 * @see #setKeepScreenOn(boolean)
3578 *
3579 * @attr ref android.R.styleable#View_keepScreenOn
3580 */
3581 public boolean getKeepScreenOn() {
3582 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3583 }
3584
3585 /**
3586 * Controls whether the screen should remain on, modifying the
3587 * value of {@link #KEEP_SCREEN_ON}.
3588 *
3589 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3590 *
3591 * @see #getKeepScreenOn()
3592 *
3593 * @attr ref android.R.styleable#View_keepScreenOn
3594 */
3595 public void setKeepScreenOn(boolean keepScreenOn) {
3596 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3597 }
3598
3599 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003600 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3601 * @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 -08003602 *
3603 * @attr ref android.R.styleable#View_nextFocusLeft
3604 */
3605 public int getNextFocusLeftId() {
3606 return mNextFocusLeftId;
3607 }
3608
3609 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003610 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3611 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
3612 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 *
3614 * @attr ref android.R.styleable#View_nextFocusLeft
3615 */
3616 public void setNextFocusLeftId(int nextFocusLeftId) {
3617 mNextFocusLeftId = nextFocusLeftId;
3618 }
3619
3620 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003621 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3622 * @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 -08003623 *
3624 * @attr ref android.R.styleable#View_nextFocusRight
3625 */
3626 public int getNextFocusRightId() {
3627 return mNextFocusRightId;
3628 }
3629
3630 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003631 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3632 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
3633 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 *
3635 * @attr ref android.R.styleable#View_nextFocusRight
3636 */
3637 public void setNextFocusRightId(int nextFocusRightId) {
3638 mNextFocusRightId = nextFocusRightId;
3639 }
3640
3641 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003642 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3643 * @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 -08003644 *
3645 * @attr ref android.R.styleable#View_nextFocusUp
3646 */
3647 public int getNextFocusUpId() {
3648 return mNextFocusUpId;
3649 }
3650
3651 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003652 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3653 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
3654 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 *
3656 * @attr ref android.R.styleable#View_nextFocusUp
3657 */
3658 public void setNextFocusUpId(int nextFocusUpId) {
3659 mNextFocusUpId = nextFocusUpId;
3660 }
3661
3662 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003663 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3664 * @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 -08003665 *
3666 * @attr ref android.R.styleable#View_nextFocusDown
3667 */
3668 public int getNextFocusDownId() {
3669 return mNextFocusDownId;
3670 }
3671
3672 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003673 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3674 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
3675 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 *
3677 * @attr ref android.R.styleable#View_nextFocusDown
3678 */
3679 public void setNextFocusDownId(int nextFocusDownId) {
3680 mNextFocusDownId = nextFocusDownId;
3681 }
3682
3683 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003684 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3685 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3686 *
3687 * @attr ref android.R.styleable#View_nextFocusForward
3688 */
3689 public int getNextFocusForwardId() {
3690 return mNextFocusForwardId;
3691 }
3692
3693 /**
3694 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3695 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
3696 * decide automatically.
3697 *
3698 * @attr ref android.R.styleable#View_nextFocusForward
3699 */
3700 public void setNextFocusForwardId(int nextFocusForwardId) {
3701 mNextFocusForwardId = nextFocusForwardId;
3702 }
3703
3704 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 * Returns the visibility of this view and all of its ancestors
3706 *
3707 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3708 */
3709 public boolean isShown() {
3710 View current = this;
3711 //noinspection ConstantConditions
3712 do {
3713 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3714 return false;
3715 }
3716 ViewParent parent = current.mParent;
3717 if (parent == null) {
3718 return false; // We are not attached to the view root
3719 }
3720 if (!(parent instanceof View)) {
3721 return true;
3722 }
3723 current = (View) parent;
3724 } while (current != null);
3725
3726 return false;
3727 }
3728
3729 /**
3730 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3731 * is set
3732 *
3733 * @param insets Insets for system windows
3734 *
3735 * @return True if this view applied the insets, false otherwise
3736 */
3737 protected boolean fitSystemWindows(Rect insets) {
3738 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3739 mPaddingLeft = insets.left;
3740 mPaddingTop = insets.top;
3741 mPaddingRight = insets.right;
3742 mPaddingBottom = insets.bottom;
3743 requestLayout();
3744 return true;
3745 }
3746 return false;
3747 }
3748
3749 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003750 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3751 * @return True if window has FITS_SYSTEM_WINDOWS set
3752 *
3753 * @hide
3754 */
3755 public boolean isFitsSystemWindowsFlagSet() {
3756 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3757 }
3758
3759 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 * Returns the visibility status for this view.
3761 *
3762 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3763 * @attr ref android.R.styleable#View_visibility
3764 */
3765 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003766 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3767 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3768 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 })
3770 public int getVisibility() {
3771 return mViewFlags & VISIBILITY_MASK;
3772 }
3773
3774 /**
3775 * Set the enabled state of this view.
3776 *
3777 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3778 * @attr ref android.R.styleable#View_visibility
3779 */
3780 @RemotableViewMethod
3781 public void setVisibility(int visibility) {
3782 setFlags(visibility, VISIBILITY_MASK);
3783 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3784 }
3785
3786 /**
3787 * Returns the enabled status for this view. The interpretation of the
3788 * enabled state varies by subclass.
3789 *
3790 * @return True if this view is enabled, false otherwise.
3791 */
3792 @ViewDebug.ExportedProperty
3793 public boolean isEnabled() {
3794 return (mViewFlags & ENABLED_MASK) == ENABLED;
3795 }
3796
3797 /**
3798 * Set the enabled state of this view. The interpretation of the enabled
3799 * state varies by subclass.
3800 *
3801 * @param enabled True if this view is enabled, false otherwise.
3802 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003803 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003805 if (enabled == isEnabled()) return;
3806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3808
3809 /*
3810 * The View most likely has to change its appearance, so refresh
3811 * the drawable state.
3812 */
3813 refreshDrawableState();
3814
3815 // Invalidate too, since the default behavior for views is to be
3816 // be drawn at 50% alpha rather than to change the drawable.
Romain Guy0fd89bf2011-01-26 15:41:30 -08003817 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003818 }
3819
3820 /**
3821 * Set whether this view can receive the focus.
3822 *
3823 * Setting this to false will also ensure that this view is not focusable
3824 * in touch mode.
3825 *
3826 * @param focusable If true, this view can receive the focus.
3827 *
3828 * @see #setFocusableInTouchMode(boolean)
3829 * @attr ref android.R.styleable#View_focusable
3830 */
3831 public void setFocusable(boolean focusable) {
3832 if (!focusable) {
3833 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3834 }
3835 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3836 }
3837
3838 /**
3839 * Set whether this view can receive focus while in touch mode.
3840 *
3841 * Setting this to true will also ensure that this view is focusable.
3842 *
3843 * @param focusableInTouchMode If true, this view can receive the focus while
3844 * in touch mode.
3845 *
3846 * @see #setFocusable(boolean)
3847 * @attr ref android.R.styleable#View_focusableInTouchMode
3848 */
3849 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3850 // Focusable in touch mode should always be set before the focusable flag
3851 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3852 // which, in touch mode, will not successfully request focus on this view
3853 // because the focusable in touch mode flag is not set
3854 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3855 if (focusableInTouchMode) {
3856 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3857 }
3858 }
3859
3860 /**
3861 * Set whether this view should have sound effects enabled for events such as
3862 * clicking and touching.
3863 *
3864 * <p>You may wish to disable sound effects for a view if you already play sounds,
3865 * for instance, a dial key that plays dtmf tones.
3866 *
3867 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3868 * @see #isSoundEffectsEnabled()
3869 * @see #playSoundEffect(int)
3870 * @attr ref android.R.styleable#View_soundEffectsEnabled
3871 */
3872 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3873 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3874 }
3875
3876 /**
3877 * @return whether this view should have sound effects enabled for events such as
3878 * clicking and touching.
3879 *
3880 * @see #setSoundEffectsEnabled(boolean)
3881 * @see #playSoundEffect(int)
3882 * @attr ref android.R.styleable#View_soundEffectsEnabled
3883 */
3884 @ViewDebug.ExportedProperty
3885 public boolean isSoundEffectsEnabled() {
3886 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3887 }
3888
3889 /**
3890 * Set whether this view should have haptic feedback for events such as
3891 * long presses.
3892 *
3893 * <p>You may wish to disable haptic feedback if your view already controls
3894 * its own haptic feedback.
3895 *
3896 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3897 * @see #isHapticFeedbackEnabled()
3898 * @see #performHapticFeedback(int)
3899 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3900 */
3901 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3902 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3903 }
3904
3905 /**
3906 * @return whether this view should have haptic feedback enabled for events
3907 * long presses.
3908 *
3909 * @see #setHapticFeedbackEnabled(boolean)
3910 * @see #performHapticFeedback(int)
3911 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3912 */
3913 @ViewDebug.ExportedProperty
3914 public boolean isHapticFeedbackEnabled() {
3915 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3916 }
3917
3918 /**
3919 * If this view doesn't do any drawing on its own, set this flag to
3920 * allow further optimizations. By default, this flag is not set on
3921 * View, but could be set on some View subclasses such as ViewGroup.
3922 *
3923 * Typically, if you override {@link #onDraw} you should clear this flag.
3924 *
3925 * @param willNotDraw whether or not this View draw on its own
3926 */
3927 public void setWillNotDraw(boolean willNotDraw) {
3928 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3929 }
3930
3931 /**
3932 * Returns whether or not this View draws on its own.
3933 *
3934 * @return true if this view has nothing to draw, false otherwise
3935 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003936 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 public boolean willNotDraw() {
3938 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3939 }
3940
3941 /**
3942 * When a View's drawing cache is enabled, drawing is redirected to an
3943 * offscreen bitmap. Some views, like an ImageView, must be able to
3944 * bypass this mechanism if they already draw a single bitmap, to avoid
3945 * unnecessary usage of the memory.
3946 *
3947 * @param willNotCacheDrawing true if this view does not cache its
3948 * drawing, false otherwise
3949 */
3950 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3951 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3952 }
3953
3954 /**
3955 * Returns whether or not this View can cache its drawing or not.
3956 *
3957 * @return true if this view does not cache its drawing, false otherwise
3958 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003959 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 public boolean willNotCacheDrawing() {
3961 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3962 }
3963
3964 /**
3965 * Indicates whether this view reacts to click events or not.
3966 *
3967 * @return true if the view is clickable, false otherwise
3968 *
3969 * @see #setClickable(boolean)
3970 * @attr ref android.R.styleable#View_clickable
3971 */
3972 @ViewDebug.ExportedProperty
3973 public boolean isClickable() {
3974 return (mViewFlags & CLICKABLE) == CLICKABLE;
3975 }
3976
3977 /**
3978 * Enables or disables click events for this view. When a view
3979 * is clickable it will change its state to "pressed" on every click.
3980 * Subclasses should set the view clickable to visually react to
3981 * user's clicks.
3982 *
3983 * @param clickable true to make the view clickable, false otherwise
3984 *
3985 * @see #isClickable()
3986 * @attr ref android.R.styleable#View_clickable
3987 */
3988 public void setClickable(boolean clickable) {
3989 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3990 }
3991
3992 /**
3993 * Indicates whether this view reacts to long click events or not.
3994 *
3995 * @return true if the view is long clickable, false otherwise
3996 *
3997 * @see #setLongClickable(boolean)
3998 * @attr ref android.R.styleable#View_longClickable
3999 */
4000 public boolean isLongClickable() {
4001 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
4002 }
4003
4004 /**
4005 * Enables or disables long click events for this view. When a view is long
4006 * clickable it reacts to the user holding down the button for a longer
4007 * duration than a tap. This event can either launch the listener or a
4008 * context menu.
4009 *
4010 * @param longClickable true to make the view long clickable, false otherwise
4011 * @see #isLongClickable()
4012 * @attr ref android.R.styleable#View_longClickable
4013 */
4014 public void setLongClickable(boolean longClickable) {
4015 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
4016 }
4017
4018 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07004019 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 *
4021 * @see #isClickable()
4022 * @see #setClickable(boolean)
4023 *
4024 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
4025 * the View's internal state from a previously set "pressed" state.
4026 */
4027 public void setPressed(boolean pressed) {
4028 if (pressed) {
4029 mPrivateFlags |= PRESSED;
4030 } else {
4031 mPrivateFlags &= ~PRESSED;
4032 }
4033 refreshDrawableState();
4034 dispatchSetPressed(pressed);
4035 }
4036
4037 /**
4038 * Dispatch setPressed to all of this View's children.
4039 *
4040 * @see #setPressed(boolean)
4041 *
4042 * @param pressed The new pressed state
4043 */
4044 protected void dispatchSetPressed(boolean pressed) {
4045 }
4046
4047 /**
4048 * Indicates whether the view is currently in pressed state. Unless
4049 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
4050 * the pressed state.
4051 *
4052 * @see #setPressed
4053 * @see #isClickable()
4054 * @see #setClickable(boolean)
4055 *
4056 * @return true if the view is currently pressed, false otherwise
4057 */
4058 public boolean isPressed() {
4059 return (mPrivateFlags & PRESSED) == PRESSED;
4060 }
4061
4062 /**
4063 * Indicates whether this view will save its state (that is,
4064 * whether its {@link #onSaveInstanceState} method will be called).
4065 *
4066 * @return Returns true if the view state saving is enabled, else false.
4067 *
4068 * @see #setSaveEnabled(boolean)
4069 * @attr ref android.R.styleable#View_saveEnabled
4070 */
4071 public boolean isSaveEnabled() {
4072 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
4073 }
4074
4075 /**
4076 * Controls whether the saving of this view's state is
4077 * enabled (that is, whether its {@link #onSaveInstanceState} method
4078 * will be called). Note that even if freezing is enabled, the
4079 * view still must have an id assigned to it (via {@link #setId setId()})
4080 * for its state to be saved. This flag can only disable the
4081 * saving of this view; any child views may still have their state saved.
4082 *
4083 * @param enabled Set to false to <em>disable</em> state saving, or true
4084 * (the default) to allow it.
4085 *
4086 * @see #isSaveEnabled()
4087 * @see #setId(int)
4088 * @see #onSaveInstanceState()
4089 * @attr ref android.R.styleable#View_saveEnabled
4090 */
4091 public void setSaveEnabled(boolean enabled) {
4092 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
4093 }
4094
Jeff Brown85a31762010-09-01 17:01:00 -07004095 /**
4096 * Gets whether the framework should discard touches when the view's
4097 * window is obscured by another visible window.
4098 * Refer to the {@link View} security documentation for more details.
4099 *
4100 * @return True if touch filtering is enabled.
4101 *
4102 * @see #setFilterTouchesWhenObscured(boolean)
4103 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4104 */
4105 @ViewDebug.ExportedProperty
4106 public boolean getFilterTouchesWhenObscured() {
4107 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
4108 }
4109
4110 /**
4111 * Sets whether the framework should discard touches when the view's
4112 * window is obscured by another visible window.
4113 * Refer to the {@link View} security documentation for more details.
4114 *
4115 * @param enabled True if touch filtering should be enabled.
4116 *
4117 * @see #getFilterTouchesWhenObscured
4118 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4119 */
4120 public void setFilterTouchesWhenObscured(boolean enabled) {
4121 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
4122 FILTER_TOUCHES_WHEN_OBSCURED);
4123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124
4125 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004126 * Indicates whether the entire hierarchy under this view will save its
4127 * state when a state saving traversal occurs from its parent. The default
4128 * is true; if false, these views will not be saved unless
4129 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4130 *
4131 * @return Returns true if the view state saving from parent is enabled, else false.
4132 *
4133 * @see #setSaveFromParentEnabled(boolean)
4134 */
4135 public boolean isSaveFromParentEnabled() {
4136 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4137 }
4138
4139 /**
4140 * Controls whether the entire hierarchy under this view will save its
4141 * state when a state saving traversal occurs from its parent. The default
4142 * is true; if false, these views will not be saved unless
4143 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4144 *
4145 * @param enabled Set to false to <em>disable</em> state saving, or true
4146 * (the default) to allow it.
4147 *
4148 * @see #isSaveFromParentEnabled()
4149 * @see #setId(int)
4150 * @see #onSaveInstanceState()
4151 */
4152 public void setSaveFromParentEnabled(boolean enabled) {
4153 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4154 }
4155
4156
4157 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004158 * Returns whether this View is able to take focus.
4159 *
4160 * @return True if this view can take focus, or false otherwise.
4161 * @attr ref android.R.styleable#View_focusable
4162 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004163 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 public final boolean isFocusable() {
4165 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4166 }
4167
4168 /**
4169 * When a view is focusable, it may not want to take focus when in touch mode.
4170 * For example, a button would like focus when the user is navigating via a D-pad
4171 * so that the user can click on it, but once the user starts touching the screen,
4172 * the button shouldn't take focus
4173 * @return Whether the view is focusable in touch mode.
4174 * @attr ref android.R.styleable#View_focusableInTouchMode
4175 */
4176 @ViewDebug.ExportedProperty
4177 public final boolean isFocusableInTouchMode() {
4178 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4179 }
4180
4181 /**
4182 * Find the nearest view in the specified direction that can take focus.
4183 * This does not actually give focus to that view.
4184 *
4185 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4186 *
4187 * @return The nearest focusable in the specified direction, or null if none
4188 * can be found.
4189 */
4190 public View focusSearch(int direction) {
4191 if (mParent != null) {
4192 return mParent.focusSearch(this, direction);
4193 } else {
4194 return null;
4195 }
4196 }
4197
4198 /**
4199 * This method is the last chance for the focused view and its ancestors to
4200 * respond to an arrow key. This is called when the focused view did not
4201 * consume the key internally, nor could the view system find a new view in
4202 * the requested direction to give focus to.
4203 *
4204 * @param focused The currently focused view.
4205 * @param direction The direction focus wants to move. One of FOCUS_UP,
4206 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4207 * @return True if the this view consumed this unhandled move.
4208 */
4209 public boolean dispatchUnhandledMove(View focused, int direction) {
4210 return false;
4211 }
4212
4213 /**
4214 * If a user manually specified the next view id for a particular direction,
Jeff Brown4e6319b2010-12-13 10:36:51 -08004215 * use the root to look up the view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 * @param root The root view of the hierarchy containing this view.
Jeff Brown4e6319b2010-12-13 10:36:51 -08004217 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4218 * or FOCUS_BACKWARD.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004219 * @return The user specified next view, or null if there is none.
4220 */
4221 View findUserSetNextFocus(View root, int direction) {
4222 switch (direction) {
4223 case FOCUS_LEFT:
4224 if (mNextFocusLeftId == View.NO_ID) return null;
4225 return findViewShouldExist(root, mNextFocusLeftId);
4226 case FOCUS_RIGHT:
4227 if (mNextFocusRightId == View.NO_ID) return null;
4228 return findViewShouldExist(root, mNextFocusRightId);
4229 case FOCUS_UP:
4230 if (mNextFocusUpId == View.NO_ID) return null;
4231 return findViewShouldExist(root, mNextFocusUpId);
4232 case FOCUS_DOWN:
4233 if (mNextFocusDownId == View.NO_ID) return null;
4234 return findViewShouldExist(root, mNextFocusDownId);
Jeff Brown4e6319b2010-12-13 10:36:51 -08004235 case FOCUS_FORWARD:
4236 if (mNextFocusForwardId == View.NO_ID) return null;
4237 return findViewShouldExist(root, mNextFocusForwardId);
4238 case FOCUS_BACKWARD: {
4239 final int id = mID;
4240 return root.findViewByPredicate(new Predicate<View>() {
4241 @Override
4242 public boolean apply(View t) {
4243 return t.mNextFocusForwardId == id;
4244 }
4245 });
4246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 }
4248 return null;
4249 }
4250
4251 private static View findViewShouldExist(View root, int childViewId) {
4252 View result = root.findViewById(childViewId);
4253 if (result == null) {
4254 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4255 + "by user for id " + childViewId);
4256 }
4257 return result;
4258 }
4259
4260 /**
4261 * Find and return all focusable views that are descendants of this view,
4262 * possibly including this view if it is focusable itself.
4263 *
4264 * @param direction The direction of the focus
4265 * @return A list of focusable views
4266 */
4267 public ArrayList<View> getFocusables(int direction) {
4268 ArrayList<View> result = new ArrayList<View>(24);
4269 addFocusables(result, direction);
4270 return result;
4271 }
4272
4273 /**
4274 * Add any focusable views that are descendants of this view (possibly
4275 * including this view if it is focusable itself) to views. If we are in touch mode,
4276 * only add views that are also focusable in touch mode.
4277 *
4278 * @param views Focusable views found so far
4279 * @param direction The direction of the focus
4280 */
4281 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07004282 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284
svetoslavganov75986cf2009-05-14 22:28:01 -07004285 /**
4286 * Adds any focusable views that are descendants of this view (possibly
4287 * including this view if it is focusable itself) to views. This method
4288 * adds all focusable views regardless if we are in touch mode or
4289 * only views focusable in touch mode if we are in touch mode depending on
4290 * the focusable mode paramater.
4291 *
4292 * @param views Focusable views found so far or null if all we are interested is
4293 * the number of focusables.
4294 * @param direction The direction of the focus.
4295 * @param focusableMode The type of focusables to be added.
4296 *
4297 * @see #FOCUSABLES_ALL
4298 * @see #FOCUSABLES_TOUCH_MODE
4299 */
4300 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4301 if (!isFocusable()) {
4302 return;
4303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304
svetoslavganov75986cf2009-05-14 22:28:01 -07004305 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4306 isInTouchMode() && !isFocusableInTouchMode()) {
4307 return;
4308 }
4309
4310 if (views != null) {
4311 views.add(this);
4312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 }
4314
4315 /**
4316 * Find and return all touchable views that are descendants of this view,
4317 * possibly including this view if it is touchable itself.
4318 *
4319 * @return A list of touchable views
4320 */
4321 public ArrayList<View> getTouchables() {
4322 ArrayList<View> result = new ArrayList<View>();
4323 addTouchables(result);
4324 return result;
4325 }
4326
4327 /**
4328 * Add any touchable views that are descendants of this view (possibly
4329 * including this view if it is touchable itself) to views.
4330 *
4331 * @param views Touchable views found so far
4332 */
4333 public void addTouchables(ArrayList<View> views) {
4334 final int viewFlags = mViewFlags;
4335
4336 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4337 && (viewFlags & ENABLED_MASK) == ENABLED) {
4338 views.add(this);
4339 }
4340 }
4341
4342 /**
4343 * Call this to try to give focus to a specific view or to one of its
4344 * descendants.
4345 *
4346 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4347 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4348 * while the device is in touch mode.
4349 *
4350 * See also {@link #focusSearch}, which is what you call to say that you
4351 * have focus, and you want your parent to look for the next one.
4352 *
4353 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4354 * {@link #FOCUS_DOWN} and <code>null</code>.
4355 *
4356 * @return Whether this view or one of its descendants actually took focus.
4357 */
4358 public final boolean requestFocus() {
4359 return requestFocus(View.FOCUS_DOWN);
4360 }
4361
4362
4363 /**
4364 * Call this to try to give focus to a specific view or to one of its
4365 * descendants and give it a hint about what direction focus is heading.
4366 *
4367 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4368 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4369 * while the device is in touch mode.
4370 *
4371 * See also {@link #focusSearch}, which is what you call to say that you
4372 * have focus, and you want your parent to look for the next one.
4373 *
4374 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4375 * <code>null</code> set for the previously focused rectangle.
4376 *
4377 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4378 * @return Whether this view or one of its descendants actually took focus.
4379 */
4380 public final boolean requestFocus(int direction) {
4381 return requestFocus(direction, null);
4382 }
4383
4384 /**
4385 * Call this to try to give focus to a specific view or to one of its descendants
4386 * and give it hints about the direction and a specific rectangle that the focus
4387 * is coming from. The rectangle can help give larger views a finer grained hint
4388 * about where focus is coming from, and therefore, where to show selection, or
4389 * forward focus change internally.
4390 *
4391 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4392 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4393 * while the device is in touch mode.
4394 *
4395 * A View will not take focus if it is not visible.
4396 *
4397 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4398 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4399 *
4400 * See also {@link #focusSearch}, which is what you call to say that you
4401 * have focus, and you want your parent to look for the next one.
4402 *
4403 * You may wish to override this method if your custom {@link View} has an internal
4404 * {@link View} that it wishes to forward the request to.
4405 *
4406 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4407 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4408 * to give a finer grained hint about where focus is coming from. May be null
4409 * if there is no hint.
4410 * @return Whether this view or one of its descendants actually took focus.
4411 */
4412 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4413 // need to be focusable
4414 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4415 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4416 return false;
4417 }
4418
4419 // need to be focusable in touch mode if in touch mode
4420 if (isInTouchMode() &&
4421 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4422 return false;
4423 }
4424
4425 // need to not have any parents blocking us
4426 if (hasAncestorThatBlocksDescendantFocus()) {
4427 return false;
4428 }
4429
4430 handleFocusGainInternal(direction, previouslyFocusedRect);
4431 return true;
4432 }
4433
Christopher Tate2c095f32010-10-04 14:13:40 -07004434 /** Gets the ViewRoot, or null if not attached. */
4435 /*package*/ ViewRoot getViewRoot() {
4436 View root = getRootView();
4437 return root != null ? (ViewRoot)root.getParent() : null;
4438 }
4439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440 /**
4441 * Call this to try to give focus to a specific view or to one of its descendants. This is a
4442 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4443 * touch mode to request focus when they are touched.
4444 *
4445 * @return Whether this view or one of its descendants actually took focus.
4446 *
4447 * @see #isInTouchMode()
4448 *
4449 */
4450 public final boolean requestFocusFromTouch() {
4451 // Leave touch mode if we need to
4452 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07004453 ViewRoot viewRoot = getViewRoot();
4454 if (viewRoot != null) {
4455 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456 }
4457 }
4458 return requestFocus(View.FOCUS_DOWN);
4459 }
4460
4461 /**
4462 * @return Whether any ancestor of this view blocks descendant focus.
4463 */
4464 private boolean hasAncestorThatBlocksDescendantFocus() {
4465 ViewParent ancestor = mParent;
4466 while (ancestor instanceof ViewGroup) {
4467 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4468 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4469 return true;
4470 } else {
4471 ancestor = vgAncestor.getParent();
4472 }
4473 }
4474 return false;
4475 }
4476
4477 /**
Romain Guya440b002010-02-24 15:57:54 -08004478 * @hide
4479 */
4480 public void dispatchStartTemporaryDetach() {
4481 onStartTemporaryDetach();
4482 }
4483
4484 /**
4485 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004486 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4487 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004488 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 */
4490 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004491 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004492 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004493 }
4494
4495 /**
4496 * @hide
4497 */
4498 public void dispatchFinishTemporaryDetach() {
4499 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 }
Romain Guy8506ab42009-06-11 17:35:47 -07004501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 /**
4503 * Called after {@link #onStartTemporaryDetach} when the container is done
4504 * changing the view.
4505 */
4506 public void onFinishTemporaryDetach() {
4507 }
Romain Guy8506ab42009-06-11 17:35:47 -07004508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509 /**
4510 * capture information of this view for later analysis: developement only
4511 * check dynamic switch to make sure we only dump view
4512 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4513 */
4514 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004515 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 return;
4517 }
4518 ViewDebug.dumpCapturedView(subTag, v);
4519 }
4520
4521 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004522 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4523 * for this view's window. Returns null if the view is not currently attached
4524 * to the window. Normally you will not need to use this directly, but
4525 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4526 */
4527 public KeyEvent.DispatcherState getKeyDispatcherState() {
4528 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4529 }
Joe Malin32736f02011-01-19 16:14:20 -08004530
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004531 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 * Dispatch a key event before it is processed by any input method
4533 * associated with the view hierarchy. This can be used to intercept
4534 * key events in special situations before the IME consumes them; a
4535 * typical example would be handling the BACK key to update the application's
4536 * UI instead of allowing the IME to see it and close itself.
4537 *
4538 * @param event The key event to be dispatched.
4539 * @return True if the event was handled, false otherwise.
4540 */
4541 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4542 return onKeyPreIme(event.getKeyCode(), event);
4543 }
4544
4545 /**
4546 * Dispatch a key event to the next view on the focus path. This path runs
4547 * from the top of the view tree down to the currently focused view. If this
4548 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4549 * the next node down the focus path. This method also fires any key
4550 * listeners.
4551 *
4552 * @param event The key event to be dispatched.
4553 * @return True if the event was handled, false otherwise.
4554 */
4555 public boolean dispatchKeyEvent(KeyEvent event) {
4556 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004557
Romain Guyf607bdc2010-09-10 19:20:06 -07004558 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004559 if (android.util.Config.LOGV) {
4560 captureViewInfo("captureViewKeyEvent", this);
4561 }
4562
Romain Guyf607bdc2010-09-10 19:20:06 -07004563 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004564 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4565 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4566 return true;
4567 }
4568
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004569 return event.dispatch(this, mAttachInfo != null
4570 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004571 }
4572
4573 /**
4574 * Dispatches a key shortcut event.
4575 *
4576 * @param event The key event to be dispatched.
4577 * @return True if the event was handled by the view, false otherwise.
4578 */
4579 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4580 return onKeyShortcut(event.getKeyCode(), event);
4581 }
4582
4583 /**
4584 * Pass the touch screen motion event down to the target view, or this
4585 * view if it is the target.
4586 *
4587 * @param event The motion event to be dispatched.
4588 * @return True if the event was handled by the view, false otherwise.
4589 */
4590 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004591 if (!onFilterTouchEventForSecurity(event)) {
4592 return false;
4593 }
4594
Romain Guyf607bdc2010-09-10 19:20:06 -07004595 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4597 mOnTouchListener.onTouch(this, event)) {
4598 return true;
4599 }
4600 return onTouchEvent(event);
4601 }
4602
4603 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004604 * Filter the touch event to apply security policies.
4605 *
4606 * @param event The motion event to be filtered.
4607 * @return True if the event should be dispatched, false if the event should be dropped.
Joe Malin32736f02011-01-19 16:14:20 -08004608 *
Jeff Brown85a31762010-09-01 17:01:00 -07004609 * @see #getFilterTouchesWhenObscured
4610 */
4611 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004612 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004613 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4614 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4615 // Window is obscured, drop this touch.
4616 return false;
4617 }
4618 return true;
4619 }
4620
4621 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 * Pass a trackball motion event down to the focused view.
4623 *
4624 * @param event The motion event to be dispatched.
4625 * @return True if the event was handled by the view, false otherwise.
4626 */
4627 public boolean dispatchTrackballEvent(MotionEvent event) {
4628 //Log.i("view", "view=" + this + ", " + event.toString());
4629 return onTrackballEvent(event);
4630 }
4631
4632 /**
4633 * Called when the window containing this view gains or loses window focus.
4634 * ViewGroups should override to route to their children.
4635 *
4636 * @param hasFocus True if the window containing this view now has focus,
4637 * false otherwise.
4638 */
4639 public void dispatchWindowFocusChanged(boolean hasFocus) {
4640 onWindowFocusChanged(hasFocus);
4641 }
4642
4643 /**
4644 * Called when the window containing this view gains or loses focus. Note
4645 * that this is separate from view focus: to receive key events, both
4646 * your view and its window must have focus. If a window is displayed
4647 * on top of yours that takes input focus, then your own window will lose
4648 * focus but the view focus will remain unchanged.
4649 *
4650 * @param hasWindowFocus True if the window containing this view now has
4651 * focus, false otherwise.
4652 */
4653 public void onWindowFocusChanged(boolean hasWindowFocus) {
4654 InputMethodManager imm = InputMethodManager.peekInstance();
4655 if (!hasWindowFocus) {
4656 if (isPressed()) {
4657 setPressed(false);
4658 }
4659 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4660 imm.focusOut(this);
4661 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004662 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004663 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004664 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4666 imm.focusIn(this);
4667 }
4668 refreshDrawableState();
4669 }
4670
4671 /**
4672 * Returns true if this view is in a window that currently has window focus.
4673 * Note that this is not the same as the view itself having focus.
4674 *
4675 * @return True if this view is in a window that currently has window focus.
4676 */
4677 public boolean hasWindowFocus() {
4678 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4679 }
4680
4681 /**
Adam Powell326d8082009-12-09 15:10:07 -08004682 * Dispatch a view visibility change down the view hierarchy.
4683 * ViewGroups should override to route to their children.
4684 * @param changedView The view whose visibility changed. Could be 'this' or
4685 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004686 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4687 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004688 */
4689 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4690 onVisibilityChanged(changedView, visibility);
4691 }
4692
4693 /**
4694 * Called when the visibility of the view or an ancestor of the view is changed.
4695 * @param changedView The view whose visibility changed. Could be 'this' or
4696 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004697 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4698 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004699 */
4700 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004701 if (visibility == VISIBLE) {
4702 if (mAttachInfo != null) {
4703 initialAwakenScrollBars();
4704 } else {
4705 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4706 }
4707 }
Adam Powell326d8082009-12-09 15:10:07 -08004708 }
4709
4710 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004711 * Dispatch a hint about whether this view is displayed. For instance, when
4712 * a View moves out of the screen, it might receives a display hint indicating
4713 * the view is not displayed. Applications should not <em>rely</em> on this hint
4714 * as there is no guarantee that they will receive one.
Joe Malin32736f02011-01-19 16:14:20 -08004715 *
Romain Guy43c9cdf2010-01-27 13:53:55 -08004716 * @param hint A hint about whether or not this view is displayed:
4717 * {@link #VISIBLE} or {@link #INVISIBLE}.
4718 */
4719 public void dispatchDisplayHint(int hint) {
4720 onDisplayHint(hint);
4721 }
4722
4723 /**
4724 * Gives this view a hint about whether is displayed or not. For instance, when
4725 * a View moves out of the screen, it might receives a display hint indicating
4726 * the view is not displayed. Applications should not <em>rely</em> on this hint
4727 * as there is no guarantee that they will receive one.
Joe Malin32736f02011-01-19 16:14:20 -08004728 *
Romain Guy43c9cdf2010-01-27 13:53:55 -08004729 * @param hint A hint about whether or not this view is displayed:
4730 * {@link #VISIBLE} or {@link #INVISIBLE}.
4731 */
4732 protected void onDisplayHint(int hint) {
4733 }
4734
4735 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004736 * Dispatch a window visibility change down the view hierarchy.
4737 * ViewGroups should override to route to their children.
4738 *
4739 * @param visibility The new visibility of the window.
4740 *
4741 * @see #onWindowVisibilityChanged
4742 */
4743 public void dispatchWindowVisibilityChanged(int visibility) {
4744 onWindowVisibilityChanged(visibility);
4745 }
4746
4747 /**
4748 * Called when the window containing has change its visibility
4749 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4750 * that this tells you whether or not your window is being made visible
4751 * to the window manager; this does <em>not</em> tell you whether or not
4752 * your window is obscured by other windows on the screen, even if it
4753 * is itself visible.
4754 *
4755 * @param visibility The new visibility of the window.
4756 */
4757 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004758 if (visibility == VISIBLE) {
4759 initialAwakenScrollBars();
4760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004761 }
4762
4763 /**
4764 * Returns the current visibility of the window this view is attached to
4765 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4766 *
4767 * @return Returns the current visibility of the view's window.
4768 */
4769 public int getWindowVisibility() {
4770 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4771 }
4772
4773 /**
4774 * Retrieve the overall visible display size in which the window this view is
4775 * attached to has been positioned in. This takes into account screen
4776 * decorations above the window, for both cases where the window itself
4777 * is being position inside of them or the window is being placed under
4778 * then and covered insets are used for the window to position its content
4779 * inside. In effect, this tells you the available area where content can
4780 * be placed and remain visible to users.
4781 *
4782 * <p>This function requires an IPC back to the window manager to retrieve
4783 * the requested information, so should not be used in performance critical
4784 * code like drawing.
4785 *
4786 * @param outRect Filled in with the visible display frame. If the view
4787 * is not attached to a window, this is simply the raw display size.
4788 */
4789 public void getWindowVisibleDisplayFrame(Rect outRect) {
4790 if (mAttachInfo != null) {
4791 try {
4792 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4793 } catch (RemoteException e) {
4794 return;
4795 }
4796 // XXX This is really broken, and probably all needs to be done
4797 // in the window manager, and we need to know more about whether
4798 // we want the area behind or in front of the IME.
4799 final Rect insets = mAttachInfo.mVisibleInsets;
4800 outRect.left += insets.left;
4801 outRect.top += insets.top;
4802 outRect.right -= insets.right;
4803 outRect.bottom -= insets.bottom;
4804 return;
4805 }
4806 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4807 outRect.set(0, 0, d.getWidth(), d.getHeight());
4808 }
4809
4810 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004811 * Dispatch a notification about a resource configuration change down
4812 * the view hierarchy.
4813 * ViewGroups should override to route to their children.
4814 *
4815 * @param newConfig The new resource configuration.
4816 *
4817 * @see #onConfigurationChanged
4818 */
4819 public void dispatchConfigurationChanged(Configuration newConfig) {
4820 onConfigurationChanged(newConfig);
4821 }
4822
4823 /**
4824 * Called when the current configuration of the resources being used
4825 * by the application have changed. You can use this to decide when
4826 * to reload resources that can changed based on orientation and other
4827 * configuration characterstics. You only need to use this if you are
4828 * not relying on the normal {@link android.app.Activity} mechanism of
4829 * recreating the activity instance upon a configuration change.
4830 *
4831 * @param newConfig The new resource configuration.
4832 */
4833 protected void onConfigurationChanged(Configuration newConfig) {
4834 }
4835
4836 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 * Private function to aggregate all per-view attributes in to the view
4838 * root.
4839 */
4840 void dispatchCollectViewAttributes(int visibility) {
4841 performCollectViewAttributes(visibility);
4842 }
4843
4844 void performCollectViewAttributes(int visibility) {
Romain Guyd30b36d2011-01-26 10:54:43 -08004845 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
Joe Onorato664644d2011-01-23 17:53:23 -08004846 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
4847 mAttachInfo.mKeepScreenOn = true;
4848 }
4849 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
4850 if (mOnSystemUiVisibilityChangeListener != null) {
4851 mAttachInfo.mHasSystemUiListeners = true;
4852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004853 }
4854 }
4855
4856 void needGlobalAttributesUpdate(boolean force) {
Joe Onorato664644d2011-01-23 17:53:23 -08004857 final AttachInfo ai = mAttachInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004858 if (ai != null) {
Joe Onorato664644d2011-01-23 17:53:23 -08004859 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
4860 || ai.mHasSystemUiListeners) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004861 ai.mRecomputeGlobalAttributes = true;
4862 }
4863 }
4864 }
4865
4866 /**
4867 * Returns whether the device is currently in touch mode. Touch mode is entered
4868 * once the user begins interacting with the device by touch, and affects various
4869 * things like whether focus is always visible to the user.
4870 *
4871 * @return Whether the device is in touch mode.
4872 */
4873 @ViewDebug.ExportedProperty
4874 public boolean isInTouchMode() {
4875 if (mAttachInfo != null) {
4876 return mAttachInfo.mInTouchMode;
4877 } else {
4878 return ViewRoot.isInTouchMode();
4879 }
4880 }
4881
4882 /**
4883 * Returns the context the view is running in, through which it can
4884 * access the current theme, resources, etc.
4885 *
4886 * @return The view's Context.
4887 */
4888 @ViewDebug.CapturedViewProperty
4889 public final Context getContext() {
4890 return mContext;
4891 }
4892
4893 /**
4894 * Handle a key event before it is processed by any input method
4895 * associated with the view hierarchy. This can be used to intercept
4896 * key events in special situations before the IME consumes them; a
4897 * typical example would be handling the BACK key to update the application's
4898 * UI instead of allowing the IME to see it and close itself.
4899 *
4900 * @param keyCode The value in event.getKeyCode().
4901 * @param event Description of the key event.
4902 * @return If you handled the event, return true. If you want to allow the
4903 * event to be handled by the next receiver, return false.
4904 */
4905 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4906 return false;
4907 }
4908
4909 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004910 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
4911 * KeyEvent.Callback.onKeyDown()}: perform press of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004912 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4913 * is released, if the view is enabled and clickable.
4914 *
4915 * @param keyCode A key code that represents the button pressed, from
4916 * {@link android.view.KeyEvent}.
4917 * @param event The KeyEvent object that defines the button action.
4918 */
4919 public boolean onKeyDown(int keyCode, KeyEvent event) {
4920 boolean result = false;
4921
4922 switch (keyCode) {
4923 case KeyEvent.KEYCODE_DPAD_CENTER:
4924 case KeyEvent.KEYCODE_ENTER: {
4925 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4926 return true;
4927 }
4928 // Long clickable items don't necessarily have to be clickable
4929 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4930 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4931 (event.getRepeatCount() == 0)) {
4932 setPressed(true);
4933 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004934 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004935 }
4936 return true;
4937 }
4938 break;
4939 }
4940 }
4941 return result;
4942 }
4943
4944 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004945 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4946 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4947 * the event).
4948 */
4949 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4950 return false;
4951 }
4952
4953 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004954 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
4955 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004956 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4957 * {@link KeyEvent#KEYCODE_ENTER} is released.
4958 *
4959 * @param keyCode A key code that represents the button pressed, from
4960 * {@link android.view.KeyEvent}.
4961 * @param event The KeyEvent object that defines the button action.
4962 */
4963 public boolean onKeyUp(int keyCode, KeyEvent event) {
4964 boolean result = false;
4965
4966 switch (keyCode) {
4967 case KeyEvent.KEYCODE_DPAD_CENTER:
4968 case KeyEvent.KEYCODE_ENTER: {
4969 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4970 return true;
4971 }
4972 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4973 setPressed(false);
4974
4975 if (!mHasPerformedLongPress) {
4976 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004977 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004978
4979 result = performClick();
4980 }
4981 }
4982 break;
4983 }
4984 }
4985 return result;
4986 }
4987
4988 /**
4989 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4990 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4991 * the event).
4992 *
4993 * @param keyCode A key code that represents the button pressed, from
4994 * {@link android.view.KeyEvent}.
4995 * @param repeatCount The number of times the action was made.
4996 * @param event The KeyEvent object that defines the button action.
4997 */
4998 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4999 return false;
5000 }
5001
5002 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08005003 * Called on the focused view when a key shortcut event is not handled.
5004 * Override this method to implement local key shortcuts for the View.
5005 * Key shortcuts can also be implemented by setting the
5006 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005007 *
5008 * @param keyCode The value in event.getKeyCode().
5009 * @param event Description of the key event.
5010 * @return If you handled the event, return true. If you want to allow the
5011 * event to be handled by the next receiver, return false.
5012 */
5013 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
5014 return false;
5015 }
5016
5017 /**
5018 * Check whether the called view is a text editor, in which case it
5019 * would make sense to automatically display a soft input window for
5020 * it. Subclasses should override this if they implement
5021 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07005022 * a call on that method would return a non-null InputConnection, and
5023 * they are really a first-class editor that the user would normally
5024 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07005025 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07005026 * <p>The default implementation always returns false. This does
5027 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
5028 * will not be called or the user can not otherwise perform edits on your
5029 * view; it is just a hint to the system that this is not the primary
5030 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07005031 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005032 * @return Returns true if this view is a text editor, else false.
5033 */
5034 public boolean onCheckIsTextEditor() {
5035 return false;
5036 }
Romain Guy8506ab42009-06-11 17:35:47 -07005037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 /**
5039 * Create a new InputConnection for an InputMethod to interact
5040 * with the view. The default implementation returns null, since it doesn't
5041 * support input methods. You can override this to implement such support.
5042 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07005043 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005044 * <p>When implementing this, you probably also want to implement
5045 * {@link #onCheckIsTextEditor()} to indicate you will return a
5046 * non-null InputConnection.
5047 *
5048 * @param outAttrs Fill in with attribute information about the connection.
5049 */
5050 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
5051 return null;
5052 }
5053
5054 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07005055 * Called by the {@link android.view.inputmethod.InputMethodManager}
5056 * when a view who is not the current
5057 * input connection target is trying to make a call on the manager. The
5058 * default implementation returns false; you can override this to return
5059 * true for certain views if you are performing InputConnection proxying
5060 * to them.
5061 * @param view The View that is making the InputMethodManager call.
5062 * @return Return true to allow the call, false to reject.
5063 */
5064 public boolean checkInputConnectionProxy(View view) {
5065 return false;
5066 }
Romain Guy8506ab42009-06-11 17:35:47 -07005067
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07005068 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 * Show the context menu for this view. It is not safe to hold on to the
5070 * menu after returning from this method.
5071 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07005072 * You should normally not overload this method. Overload
5073 * {@link #onCreateContextMenu(ContextMenu)} or define an
5074 * {@link OnCreateContextMenuListener} to add items to the context menu.
5075 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005076 * @param menu The context menu to populate
5077 */
5078 public void createContextMenu(ContextMenu menu) {
5079 ContextMenuInfo menuInfo = getContextMenuInfo();
5080
5081 // Sets the current menu info so all items added to menu will have
5082 // my extra info set.
5083 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
5084
5085 onCreateContextMenu(menu);
5086 if (mOnCreateContextMenuListener != null) {
5087 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
5088 }
5089
5090 // Clear the extra information so subsequent items that aren't mine don't
5091 // have my extra info.
5092 ((MenuBuilder)menu).setCurrentMenuInfo(null);
5093
5094 if (mParent != null) {
5095 mParent.createContextMenu(menu);
5096 }
5097 }
5098
5099 /**
5100 * Views should implement this if they have extra information to associate
5101 * with the context menu. The return result is supplied as a parameter to
5102 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
5103 * callback.
5104 *
5105 * @return Extra information about the item for which the context menu
5106 * should be shown. This information will vary across different
5107 * subclasses of View.
5108 */
5109 protected ContextMenuInfo getContextMenuInfo() {
5110 return null;
5111 }
5112
5113 /**
5114 * Views should implement this if the view itself is going to add items to
5115 * the context menu.
5116 *
5117 * @param menu the context menu to populate
5118 */
5119 protected void onCreateContextMenu(ContextMenu menu) {
5120 }
5121
5122 /**
5123 * Implement this method to handle trackball motion events. The
5124 * <em>relative</em> movement of the trackball since the last event
5125 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
5126 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
5127 * that a movement of 1 corresponds to the user pressing one DPAD key (so
5128 * they will often be fractional values, representing the more fine-grained
5129 * movement information available from a trackball).
5130 *
5131 * @param event The motion event.
5132 * @return True if the event was handled, false otherwise.
5133 */
5134 public boolean onTrackballEvent(MotionEvent event) {
5135 return false;
5136 }
5137
5138 /**
5139 * Implement this method to handle touch screen motion events.
5140 *
5141 * @param event The motion event.
5142 * @return True if the event was handled, false otherwise.
5143 */
5144 public boolean onTouchEvent(MotionEvent event) {
5145 final int viewFlags = mViewFlags;
5146
5147 if ((viewFlags & ENABLED_MASK) == DISABLED) {
5148 // A disabled view that is clickable still consumes the touch
5149 // events, it just doesn't respond to them.
5150 return (((viewFlags & CLICKABLE) == CLICKABLE ||
5151 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
5152 }
5153
5154 if (mTouchDelegate != null) {
5155 if (mTouchDelegate.onTouchEvent(event)) {
5156 return true;
5157 }
5158 }
5159
5160 if (((viewFlags & CLICKABLE) == CLICKABLE ||
5161 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
5162 switch (event.getAction()) {
5163 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08005164 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
5165 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005166 // take focus if we don't have it already and we should in
5167 // touch mode.
5168 boolean focusTaken = false;
5169 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
5170 focusTaken = requestFocus();
5171 }
5172
Dianne Hackbornbe1f6222011-01-20 15:24:28 -08005173 if (prepressed) {
5174 // The button is being released before we actually
5175 // showed it as pressed. Make it show the pressed
5176 // state now (before scheduling the click) to ensure
5177 // the user sees it.
5178 mPrivateFlags |= PRESSED;
5179 refreshDrawableState();
5180 }
Joe Malin32736f02011-01-19 16:14:20 -08005181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005182 if (!mHasPerformedLongPress) {
5183 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05005184 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005185
5186 // Only perform take click actions if we were in the pressed state
5187 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08005188 // Use a Runnable and post this rather than calling
5189 // performClick directly. This lets other visual state
5190 // of the view update before click actions start.
5191 if (mPerformClick == null) {
5192 mPerformClick = new PerformClick();
5193 }
5194 if (!post(mPerformClick)) {
5195 performClick();
5196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005197 }
5198 }
5199
5200 if (mUnsetPressedState == null) {
5201 mUnsetPressedState = new UnsetPressedState();
5202 }
5203
Adam Powelle14579b2009-12-16 18:39:52 -08005204 if (prepressed) {
Adam Powelle14579b2009-12-16 18:39:52 -08005205 postDelayed(mUnsetPressedState,
5206 ViewConfiguration.getPressedStateDuration());
5207 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005208 // If the post failed, unpress right now
5209 mUnsetPressedState.run();
5210 }
Adam Powelle14579b2009-12-16 18:39:52 -08005211 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005212 }
5213 break;
5214
5215 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08005216 if (mPendingCheckForTap == null) {
5217 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005218 }
Adam Powelle14579b2009-12-16 18:39:52 -08005219 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08005220 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08005221 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222 break;
5223
5224 case MotionEvent.ACTION_CANCEL:
5225 mPrivateFlags &= ~PRESSED;
5226 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08005227 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005228 break;
5229
5230 case MotionEvent.ACTION_MOVE:
5231 final int x = (int) event.getX();
5232 final int y = (int) event.getY();
5233
5234 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07005235 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005236 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08005237 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08005239 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05005240 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005241
5242 // Need to switch from pressed to not pressed
5243 mPrivateFlags &= ~PRESSED;
5244 refreshDrawableState();
5245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 }
5247 break;
5248 }
5249 return true;
5250 }
5251
5252 return false;
5253 }
5254
5255 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05005256 * Remove the longpress detection timer.
5257 */
5258 private void removeLongPressCallback() {
5259 if (mPendingCheckForLongPress != null) {
5260 removeCallbacks(mPendingCheckForLongPress);
5261 }
5262 }
Adam Powell3cb8b632011-01-21 15:34:14 -08005263
5264 /**
5265 * Remove the pending click action
5266 */
5267 private void removePerformClickCallback() {
5268 if (mPerformClick != null) {
5269 removeCallbacks(mPerformClick);
5270 }
5271 }
5272
Adam Powelle14579b2009-12-16 18:39:52 -08005273 /**
Romain Guya440b002010-02-24 15:57:54 -08005274 * Remove the prepress detection timer.
5275 */
5276 private void removeUnsetPressCallback() {
5277 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
5278 setPressed(false);
5279 removeCallbacks(mUnsetPressedState);
5280 }
5281 }
5282
5283 /**
Adam Powelle14579b2009-12-16 18:39:52 -08005284 * Remove the tap detection timer.
5285 */
5286 private void removeTapCallback() {
5287 if (mPendingCheckForTap != null) {
5288 mPrivateFlags &= ~PREPRESSED;
5289 removeCallbacks(mPendingCheckForTap);
5290 }
5291 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05005292
5293 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 * Cancels a pending long press. Your subclass can use this if you
5295 * want the context menu to come up if the user presses and holds
5296 * at the same place, but you don't want it to come up if they press
5297 * and then move around enough to cause scrolling.
5298 */
5299 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05005300 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08005301
5302 /*
5303 * The prepressed state handled by the tap callback is a display
5304 * construct, but the tap callback will post a long press callback
5305 * less its own timeout. Remove it here.
5306 */
5307 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005308 }
5309
5310 /**
5311 * Sets the TouchDelegate for this View.
5312 */
5313 public void setTouchDelegate(TouchDelegate delegate) {
5314 mTouchDelegate = delegate;
5315 }
5316
5317 /**
5318 * Gets the TouchDelegate for this View.
5319 */
5320 public TouchDelegate getTouchDelegate() {
5321 return mTouchDelegate;
5322 }
5323
5324 /**
5325 * Set flags controlling behavior of this view.
5326 *
5327 * @param flags Constant indicating the value which should be set
5328 * @param mask Constant indicating the bit range that should be changed
5329 */
5330 void setFlags(int flags, int mask) {
5331 int old = mViewFlags;
5332 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
5333
5334 int changed = mViewFlags ^ old;
5335 if (changed == 0) {
5336 return;
5337 }
5338 int privateFlags = mPrivateFlags;
5339
5340 /* Check if the FOCUSABLE bit has changed */
5341 if (((changed & FOCUSABLE_MASK) != 0) &&
5342 ((privateFlags & HAS_BOUNDS) !=0)) {
5343 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
5344 && ((privateFlags & FOCUSED) != 0)) {
5345 /* Give up focus if we are no longer focusable */
5346 clearFocus();
5347 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
5348 && ((privateFlags & FOCUSED) == 0)) {
5349 /*
5350 * Tell the view system that we are now available to take focus
5351 * if no one else already has it.
5352 */
5353 if (mParent != null) mParent.focusableViewAvailable(this);
5354 }
5355 }
5356
5357 if ((flags & VISIBILITY_MASK) == VISIBLE) {
5358 if ((changed & VISIBILITY_MASK) != 0) {
5359 /*
5360 * If this view is becoming visible, set the DRAWN flag so that
5361 * the next invalidate() will not be skipped.
5362 */
5363 mPrivateFlags |= DRAWN;
5364
5365 needGlobalAttributesUpdate(true);
5366
5367 // a view becoming visible is worth notifying the parent
5368 // about in case nothing has focus. even if this specific view
5369 // isn't focusable, it may contain something that is, so let
5370 // the root view try to give this focus if nothing else does.
5371 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
5372 mParent.focusableViewAvailable(this);
5373 }
5374 }
5375 }
5376
5377 /* Check if the GONE bit has changed */
5378 if ((changed & GONE) != 0) {
5379 needGlobalAttributesUpdate(false);
5380 requestLayout();
Romain Guy0fd89bf2011-01-26 15:41:30 -08005381 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005382
Romain Guyecd80ee2009-12-03 17:13:02 -08005383 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5384 if (hasFocus()) clearFocus();
5385 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 }
5387 if (mAttachInfo != null) {
5388 mAttachInfo.mViewVisibilityChanged = true;
5389 }
5390 }
5391
5392 /* Check if the VISIBLE bit has changed */
5393 if ((changed & INVISIBLE) != 0) {
5394 needGlobalAttributesUpdate(false);
Romain Guy0fd89bf2011-01-26 15:41:30 -08005395 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005396
5397 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5398 // root view becoming invisible shouldn't clear focus
5399 if (getRootView() != this) {
5400 clearFocus();
5401 }
5402 }
5403 if (mAttachInfo != null) {
5404 mAttachInfo.mViewVisibilityChanged = true;
5405 }
5406 }
5407
Adam Powell326d8082009-12-09 15:10:07 -08005408 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07005409 if (mParent instanceof ViewGroup) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005410 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
5411 ((View) mParent).invalidate(true);
Chet Haase5e25c2c2010-09-16 11:15:56 -07005412 }
Adam Powell326d8082009-12-09 15:10:07 -08005413 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5414 }
5415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005416 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5417 destroyDrawingCache();
5418 }
5419
5420 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5421 destroyDrawingCache();
5422 mPrivateFlags &= ~DRAWING_CACHE_VALID;
Romain Guy0fd89bf2011-01-26 15:41:30 -08005423 invalidateParentCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424 }
5425
5426 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5427 destroyDrawingCache();
5428 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5429 }
5430
5431 if ((changed & DRAW_MASK) != 0) {
5432 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5433 if (mBGDrawable != null) {
5434 mPrivateFlags &= ~SKIP_DRAW;
5435 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5436 } else {
5437 mPrivateFlags |= SKIP_DRAW;
5438 }
5439 } else {
5440 mPrivateFlags &= ~SKIP_DRAW;
5441 }
5442 requestLayout();
Romain Guy0fd89bf2011-01-26 15:41:30 -08005443 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444 }
5445
5446 if ((changed & KEEP_SCREEN_ON) != 0) {
Joe Onorato664644d2011-01-23 17:53:23 -08005447 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 mParent.recomputeViewAttributes(this);
5449 }
5450 }
5451 }
5452
5453 /**
5454 * Change the view's z order in the tree, so it's on top of other sibling
5455 * views
5456 */
5457 public void bringToFront() {
5458 if (mParent != null) {
5459 mParent.bringChildToFront(this);
5460 }
5461 }
5462
5463 /**
5464 * This is called in response to an internal scroll in this view (i.e., the
5465 * view scrolled its own contents). This is typically as a result of
5466 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5467 * called.
5468 *
5469 * @param l Current horizontal scroll origin.
5470 * @param t Current vertical scroll origin.
5471 * @param oldl Previous horizontal scroll origin.
5472 * @param oldt Previous vertical scroll origin.
5473 */
5474 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5475 mBackgroundSizeChanged = true;
5476
5477 final AttachInfo ai = mAttachInfo;
5478 if (ai != null) {
5479 ai.mViewScrollChanged = true;
5480 }
5481 }
5482
5483 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005484 * Interface definition for a callback to be invoked when the layout bounds of a view
5485 * changes due to layout processing.
5486 */
5487 public interface OnLayoutChangeListener {
5488 /**
5489 * Called when the focus state of a view has changed.
5490 *
5491 * @param v The view whose state has changed.
5492 * @param left The new value of the view's left property.
5493 * @param top The new value of the view's top property.
5494 * @param right The new value of the view's right property.
5495 * @param bottom The new value of the view's bottom property.
5496 * @param oldLeft The previous value of the view's left property.
5497 * @param oldTop The previous value of the view's top property.
5498 * @param oldRight The previous value of the view's right property.
5499 * @param oldBottom The previous value of the view's bottom property.
5500 */
5501 void onLayoutChange(View v, int left, int top, int right, int bottom,
5502 int oldLeft, int oldTop, int oldRight, int oldBottom);
5503 }
5504
5505 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506 * This is called during layout when the size of this view has changed. If
5507 * you were just added to the view hierarchy, you're called with the old
5508 * values of 0.
5509 *
5510 * @param w Current width of this view.
5511 * @param h Current height of this view.
5512 * @param oldw Old width of this view.
5513 * @param oldh Old height of this view.
5514 */
5515 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5516 }
5517
5518 /**
5519 * Called by draw to draw the child views. This may be overridden
5520 * by derived classes to gain control just before its children are drawn
5521 * (but after its own view has been drawn).
5522 * @param canvas the canvas on which to draw the view
5523 */
5524 protected void dispatchDraw(Canvas canvas) {
5525 }
5526
5527 /**
5528 * Gets the parent of this view. Note that the parent is a
5529 * ViewParent and not necessarily a View.
5530 *
5531 * @return Parent of this view.
5532 */
5533 public final ViewParent getParent() {
5534 return mParent;
5535 }
5536
5537 /**
5538 * Return the scrolled left position of this view. This is the left edge of
5539 * the displayed part of your view. You do not need to draw any pixels
5540 * farther left, since those are outside of the frame of your view on
5541 * screen.
5542 *
5543 * @return The left edge of the displayed part of your view, in pixels.
5544 */
5545 public final int getScrollX() {
5546 return mScrollX;
5547 }
5548
5549 /**
5550 * Return the scrolled top position of this view. This is the top edge of
5551 * the displayed part of your view. You do not need to draw any pixels above
5552 * it, since those are outside of the frame of your view on screen.
5553 *
5554 * @return The top edge of the displayed part of your view, in pixels.
5555 */
5556 public final int getScrollY() {
5557 return mScrollY;
5558 }
5559
5560 /**
5561 * Return the width of the your view.
5562 *
5563 * @return The width of your view, in pixels.
5564 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005565 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 public final int getWidth() {
5567 return mRight - mLeft;
5568 }
5569
5570 /**
5571 * Return the height of your view.
5572 *
5573 * @return The height of your view, in pixels.
5574 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005575 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005576 public final int getHeight() {
5577 return mBottom - mTop;
5578 }
5579
5580 /**
5581 * Return the visible drawing bounds of your view. Fills in the output
5582 * rectangle with the values from getScrollX(), getScrollY(),
5583 * getWidth(), and getHeight().
5584 *
5585 * @param outRect The (scrolled) drawing bounds of the view.
5586 */
5587 public void getDrawingRect(Rect outRect) {
5588 outRect.left = mScrollX;
5589 outRect.top = mScrollY;
5590 outRect.right = mScrollX + (mRight - mLeft);
5591 outRect.bottom = mScrollY + (mBottom - mTop);
5592 }
5593
5594 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005595 * Like {@link #getMeasuredWidthAndState()}, but only returns the
5596 * raw width component (that is the result is masked by
5597 * {@link #MEASURED_SIZE_MASK}).
5598 *
5599 * @return The raw measured width of this view.
5600 */
5601 public final int getMeasuredWidth() {
5602 return mMeasuredWidth & MEASURED_SIZE_MASK;
5603 }
5604
5605 /**
5606 * Return the full width measurement information for this view as computed
5607 * by the most recent call to {@link #measure}. This result is a bit mask
5608 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 * This should be used during measurement and layout calculations only. Use
5610 * {@link #getWidth()} to see how wide a view is after layout.
5611 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005612 * @return The measured width of this view as a bit mask.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08005614 public final int getMeasuredWidthAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005615 return mMeasuredWidth;
5616 }
5617
5618 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005619 * Like {@link #getMeasuredHeightAndState()}, but only returns the
5620 * raw width component (that is the result is masked by
5621 * {@link #MEASURED_SIZE_MASK}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005622 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005623 * @return The raw measured height of this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 */
5625 public final int getMeasuredHeight() {
Dianne Hackborn189ee182010-12-02 21:48:53 -08005626 return mMeasuredHeight & MEASURED_SIZE_MASK;
5627 }
5628
5629 /**
5630 * Return the full height measurement information for this view as computed
5631 * by the most recent call to {@link #measure}. This result is a bit mask
5632 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5633 * This should be used during measurement and layout calculations only. Use
5634 * {@link #getHeight()} to see how wide a view is after layout.
5635 *
5636 * @return The measured width of this view as a bit mask.
5637 */
5638 public final int getMeasuredHeightAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 return mMeasuredHeight;
5640 }
5641
5642 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005643 * Return only the state bits of {@link #getMeasuredWidthAndState()}
5644 * and {@link #getMeasuredHeightAndState()}, combined into one integer.
5645 * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
5646 * and the height component is at the shifted bits
5647 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
5648 */
5649 public final int getMeasuredState() {
5650 return (mMeasuredWidth&MEASURED_STATE_MASK)
5651 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
5652 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
5653 }
5654
5655 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005656 * The transform matrix of this view, which is calculated based on the current
5657 * roation, scale, and pivot properties.
5658 *
5659 * @see #getRotation()
5660 * @see #getScaleX()
5661 * @see #getScaleY()
5662 * @see #getPivotX()
5663 * @see #getPivotY()
5664 * @return The current transform matrix for the view
5665 */
5666 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005667 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005668 return mMatrix;
5669 }
5670
5671 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005672 * Utility function to determine if the value is far enough away from zero to be
5673 * considered non-zero.
5674 * @param value A floating point value to check for zero-ness
5675 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5676 */
5677 private static boolean nonzero(float value) {
5678 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5679 }
5680
5681 /**
Jeff Brown86671742010-09-30 20:00:15 -07005682 * Returns true if the transform matrix is the identity matrix.
5683 * Recomputes the matrix if necessary.
Joe Malin32736f02011-01-19 16:14:20 -08005684 *
Romain Guy33e72ae2010-07-17 12:40:29 -07005685 * @return True if the transform matrix is the identity matrix, false otherwise.
5686 */
Jeff Brown86671742010-09-30 20:00:15 -07005687 final boolean hasIdentityMatrix() {
5688 updateMatrix();
5689 return mMatrixIsIdentity;
5690 }
5691
5692 /**
5693 * Recomputes the transform matrix if necessary.
5694 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005695 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005696 if (mMatrixDirty) {
5697 // transform-related properties have changed since the last time someone
5698 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005699
5700 // Figure out if we need to update the pivot point
5701 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005702 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005703 mPrevWidth = mRight - mLeft;
5704 mPrevHeight = mBottom - mTop;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -08005705 mPivotX = mPrevWidth / 2f;
5706 mPivotY = mPrevHeight / 2f;
Chet Haasefd2b0022010-08-06 13:08:56 -07005707 }
5708 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005709 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005710 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5711 mMatrix.setTranslate(mTranslationX, mTranslationY);
5712 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5713 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5714 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005715 if (mCamera == null) {
5716 mCamera = new Camera();
5717 matrix3D = new Matrix();
5718 }
5719 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005720 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005721 mCamera.rotateX(mRotationX);
5722 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005723 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005724 mCamera.getMatrix(matrix3D);
5725 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005726 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005727 mMatrix.postConcat(matrix3D);
5728 mCamera.restore();
5729 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005730 mMatrixDirty = false;
5731 mMatrixIsIdentity = mMatrix.isIdentity();
5732 mInverseMatrixDirty = true;
5733 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005734 }
5735
5736 /**
5737 * Utility method to retrieve the inverse of the current mMatrix property.
5738 * We cache the matrix to avoid recalculating it when transform properties
5739 * have not changed.
5740 *
5741 * @return The inverse of the current matrix of this view.
5742 */
Jeff Brown86671742010-09-30 20:00:15 -07005743 final Matrix getInverseMatrix() {
5744 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005745 if (mInverseMatrixDirty) {
5746 if (mInverseMatrix == null) {
5747 mInverseMatrix = new Matrix();
5748 }
5749 mMatrix.invert(mInverseMatrix);
5750 mInverseMatrixDirty = false;
5751 }
5752 return mInverseMatrix;
5753 }
5754
5755 /**
5756 * The degrees that the view is rotated around the pivot point.
5757 *
5758 * @see #getPivotX()
5759 * @see #getPivotY()
5760 * @return The degrees of rotation.
5761 */
5762 public float getRotation() {
5763 return mRotation;
5764 }
5765
5766 /**
Chet Haase897247b2010-09-09 14:54:47 -07005767 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5768 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005769 *
5770 * @param rotation The degrees of rotation.
5771 * @see #getPivotX()
5772 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005773 *
5774 * @attr ref android.R.styleable#View_rotation
Chet Haasec3aa3612010-06-17 08:50:37 -07005775 */
5776 public void setRotation(float rotation) {
5777 if (mRotation != rotation) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005778 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005779 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005780 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005781 mRotation = rotation;
5782 mMatrixDirty = true;
5783 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005784 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005785 }
5786 }
5787
5788 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005789 * The degrees that the view is rotated around the vertical axis through the pivot point.
5790 *
5791 * @see #getPivotX()
5792 * @see #getPivotY()
5793 * @return The degrees of Y rotation.
5794 */
5795 public float getRotationY() {
5796 return mRotationY;
5797 }
5798
5799 /**
Chet Haase897247b2010-09-09 14:54:47 -07005800 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5801 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5802 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005803 *
5804 * @param rotationY The degrees of Y rotation.
5805 * @see #getPivotX()
5806 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005807 *
5808 * @attr ref android.R.styleable#View_rotationY
Chet Haasefd2b0022010-08-06 13:08:56 -07005809 */
5810 public void setRotationY(float rotationY) {
5811 if (mRotationY != rotationY) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005812 invalidateParentCaches();
Chet Haasefd2b0022010-08-06 13:08:56 -07005813 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005814 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005815 mRotationY = rotationY;
5816 mMatrixDirty = true;
5817 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005818 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005819 }
5820 }
5821
5822 /**
5823 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5824 *
5825 * @see #getPivotX()
5826 * @see #getPivotY()
5827 * @return The degrees of X rotation.
5828 */
5829 public float getRotationX() {
5830 return mRotationX;
5831 }
5832
5833 /**
Chet Haase897247b2010-09-09 14:54:47 -07005834 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5835 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5836 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005837 *
5838 * @param rotationX The degrees of X rotation.
5839 * @see #getPivotX()
5840 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005841 *
5842 * @attr ref android.R.styleable#View_rotationX
Chet Haasefd2b0022010-08-06 13:08:56 -07005843 */
5844 public void setRotationX(float rotationX) {
5845 if (mRotationX != rotationX) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005846 invalidateParentCaches();
Chet Haasefd2b0022010-08-06 13:08:56 -07005847 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005848 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005849 mRotationX = rotationX;
5850 mMatrixDirty = true;
5851 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005852 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005853 }
5854 }
5855
5856 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005857 * The amount that the view is scaled in x around the pivot point, as a proportion of
5858 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5859 *
Joe Onorato93162322010-09-16 15:42:01 -04005860 * <p>By default, this is 1.0f.
5861 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005862 * @see #getPivotX()
5863 * @see #getPivotY()
5864 * @return The scaling factor.
5865 */
5866 public float getScaleX() {
5867 return mScaleX;
5868 }
5869
5870 /**
5871 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5872 * the view's unscaled width. A value of 1 means that no scaling is applied.
5873 *
5874 * @param scaleX The scaling factor.
5875 * @see #getPivotX()
5876 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005877 *
5878 * @attr ref android.R.styleable#View_scaleX
Chet Haasec3aa3612010-06-17 08:50:37 -07005879 */
5880 public void setScaleX(float scaleX) {
5881 if (mScaleX != scaleX) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005882 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005883 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005884 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005885 mScaleX = scaleX;
5886 mMatrixDirty = true;
5887 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005888 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005889 }
5890 }
5891
5892 /**
5893 * The amount that the view is scaled in y around the pivot point, as a proportion of
5894 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5895 *
Joe Onorato93162322010-09-16 15:42:01 -04005896 * <p>By default, this is 1.0f.
5897 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005898 * @see #getPivotX()
5899 * @see #getPivotY()
5900 * @return The scaling factor.
5901 */
5902 public float getScaleY() {
5903 return mScaleY;
5904 }
5905
5906 /**
5907 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5908 * the view's unscaled width. A value of 1 means that no scaling is applied.
5909 *
5910 * @param scaleY The scaling factor.
5911 * @see #getPivotX()
5912 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005913 *
5914 * @attr ref android.R.styleable#View_scaleY
Chet Haasec3aa3612010-06-17 08:50:37 -07005915 */
5916 public void setScaleY(float scaleY) {
5917 if (mScaleY != scaleY) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005918 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005919 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005920 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005921 mScaleY = scaleY;
5922 mMatrixDirty = true;
5923 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005924 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005925 }
5926 }
5927
5928 /**
5929 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5930 * and {@link #setScaleX(float) scaled}.
5931 *
5932 * @see #getRotation()
5933 * @see #getScaleX()
5934 * @see #getScaleY()
5935 * @see #getPivotY()
5936 * @return The x location of the pivot point.
5937 */
5938 public float getPivotX() {
5939 return mPivotX;
5940 }
5941
5942 /**
5943 * Sets the x location of the point around which the view is
5944 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005945 * By default, the pivot point is centered on the object.
5946 * Setting this property disables this behavior and causes the view to use only the
5947 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005948 *
5949 * @param pivotX The x location of the pivot point.
5950 * @see #getRotation()
5951 * @see #getScaleX()
5952 * @see #getScaleY()
5953 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005954 *
5955 * @attr ref android.R.styleable#View_transformPivotX
Chet Haasec3aa3612010-06-17 08:50:37 -07005956 */
5957 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005958 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005959 if (mPivotX != pivotX) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005960 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005961 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005962 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005963 mPivotX = pivotX;
5964 mMatrixDirty = true;
5965 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005966 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005967 }
5968 }
5969
5970 /**
5971 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5972 * and {@link #setScaleY(float) scaled}.
5973 *
5974 * @see #getRotation()
5975 * @see #getScaleX()
5976 * @see #getScaleY()
5977 * @see #getPivotY()
5978 * @return The y location of the pivot point.
5979 */
5980 public float getPivotY() {
5981 return mPivotY;
5982 }
5983
5984 /**
5985 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005986 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5987 * Setting this property disables this behavior and causes the view to use only the
5988 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005989 *
5990 * @param pivotY The y location of the pivot point.
5991 * @see #getRotation()
5992 * @see #getScaleX()
5993 * @see #getScaleY()
5994 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005995 *
5996 * @attr ref android.R.styleable#View_transformPivotY
Chet Haasec3aa3612010-06-17 08:50:37 -07005997 */
5998 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005999 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07006000 if (mPivotY != pivotY) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006001 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07006002 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006003 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006004 mPivotY = pivotY;
6005 mMatrixDirty = true;
6006 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006007 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006008 }
6009 }
6010
6011 /**
6012 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
6013 * completely transparent and 1 means the view is completely opaque.
6014 *
Joe Onorato93162322010-09-16 15:42:01 -04006015 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07006016 * @return The opacity of the view.
6017 */
6018 public float getAlpha() {
6019 return mAlpha;
6020 }
6021
6022 /**
Romain Guy171c5922011-01-06 10:04:23 -08006023 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
6024 * completely transparent and 1 means the view is completely opaque.</p>
Joe Malin32736f02011-01-19 16:14:20 -08006025 *
Romain Guy171c5922011-01-06 10:04:23 -08006026 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
6027 * responsible for applying the opacity itself. Otherwise, calling this method is
6028 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
Joe Malin32736f02011-01-19 16:14:20 -08006029 * setting a hardware layer.</p>
Chet Haasec3aa3612010-06-17 08:50:37 -07006030 *
6031 * @param alpha The opacity of the view.
Chet Haase73066682010-11-29 15:55:32 -08006032 *
Joe Malin32736f02011-01-19 16:14:20 -08006033 * @see #setLayerType(int, android.graphics.Paint)
6034 *
Chet Haase73066682010-11-29 15:55:32 -08006035 * @attr ref android.R.styleable#View_alpha
Chet Haasec3aa3612010-06-17 08:50:37 -07006036 */
6037 public void setAlpha(float alpha) {
6038 mAlpha = alpha;
Romain Guy0fd89bf2011-01-26 15:41:30 -08006039 invalidateParentCaches();
Chet Haaseed032702010-10-01 14:05:54 -07006040 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07006041 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07006042 // subclass is handling alpha - don't optimize rendering cache invalidation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006043 invalidate(true);
Chet Haaseed032702010-10-01 14:05:54 -07006044 } else {
Romain Guya3496a92010-10-12 11:53:24 -07006045 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07006046 invalidate(false);
6047 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006048 }
6049
6050 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 * Top position of this view relative to its parent.
6052 *
6053 * @return The top of this view, in pixels.
6054 */
6055 @ViewDebug.CapturedViewProperty
6056 public final int getTop() {
6057 return mTop;
6058 }
6059
6060 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006061 * Sets the top position of this view relative to its parent. This method is meant to be called
6062 * by the layout system and should not generally be called otherwise, because the property
6063 * may be changed at any time by the layout.
6064 *
6065 * @param top The top of this view, in pixels.
6066 */
6067 public final void setTop(int top) {
6068 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07006069 updateMatrix();
6070 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006071 final ViewParent p = mParent;
6072 if (p != null && mAttachInfo != null) {
6073 final Rect r = mAttachInfo.mTmpInvalRect;
6074 int minTop;
6075 int yLoc;
6076 if (top < mTop) {
6077 minTop = top;
6078 yLoc = top - mTop;
6079 } else {
6080 minTop = mTop;
6081 yLoc = 0;
6082 }
6083 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
6084 p.invalidateChild(this, r);
6085 }
6086 } else {
6087 // Double-invalidation is necessary to capture view's old and new areas
Romain Guy0fd89bf2011-01-26 15:41:30 -08006088 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006089 }
6090
Chet Haaseed032702010-10-01 14:05:54 -07006091 int width = mRight - mLeft;
6092 int oldHeight = mBottom - mTop;
6093
Chet Haase21cd1382010-09-01 17:42:29 -07006094 mTop = top;
6095
Chet Haaseed032702010-10-01 14:05:54 -07006096 onSizeChanged(width, mBottom - mTop, width, oldHeight);
6097
Chet Haase21cd1382010-09-01 17:42:29 -07006098 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006099 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6100 // A change in dimension means an auto-centered pivot point changes, too
6101 mMatrixDirty = true;
6102 }
Chet Haase21cd1382010-09-01 17:42:29 -07006103 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006104 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006105 }
Chet Haase55dbb652010-12-21 20:15:08 -08006106 mBackgroundSizeChanged = true;
Chet Haase678e0ad2011-01-25 09:37:18 -08006107 invalidateParentIfNeeded();
Chet Haase21cd1382010-09-01 17:42:29 -07006108 }
6109 }
6110
6111 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006112 * Bottom position of this view relative to its parent.
6113 *
6114 * @return The bottom of this view, in pixels.
6115 */
6116 @ViewDebug.CapturedViewProperty
6117 public final int getBottom() {
6118 return mBottom;
6119 }
6120
6121 /**
Michael Jurkadab559a2011-01-04 20:31:51 -08006122 * True if this view has changed since the last time being drawn.
6123 *
6124 * @return The dirty state of this view.
6125 */
6126 public boolean isDirty() {
6127 return (mPrivateFlags & DIRTY_MASK) != 0;
6128 }
6129
6130 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006131 * Sets the bottom position of this view relative to its parent. This method is meant to be
6132 * called by the layout system and should not generally be called otherwise, because the
6133 * property may be changed at any time by the layout.
6134 *
6135 * @param bottom The bottom of this view, in pixels.
6136 */
6137 public final void setBottom(int bottom) {
6138 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07006139 updateMatrix();
6140 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006141 final ViewParent p = mParent;
6142 if (p != null && mAttachInfo != null) {
6143 final Rect r = mAttachInfo.mTmpInvalRect;
6144 int maxBottom;
6145 if (bottom < mBottom) {
6146 maxBottom = mBottom;
6147 } else {
6148 maxBottom = bottom;
6149 }
6150 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
6151 p.invalidateChild(this, r);
6152 }
6153 } else {
6154 // Double-invalidation is necessary to capture view's old and new areas
Romain Guy0fd89bf2011-01-26 15:41:30 -08006155 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006156 }
6157
Chet Haaseed032702010-10-01 14:05:54 -07006158 int width = mRight - mLeft;
6159 int oldHeight = mBottom - mTop;
6160
Chet Haase21cd1382010-09-01 17:42:29 -07006161 mBottom = bottom;
6162
Chet Haaseed032702010-10-01 14:05:54 -07006163 onSizeChanged(width, mBottom - mTop, width, oldHeight);
6164
Chet Haase21cd1382010-09-01 17:42:29 -07006165 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006166 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6167 // A change in dimension means an auto-centered pivot point changes, too
6168 mMatrixDirty = true;
6169 }
Chet Haase21cd1382010-09-01 17:42:29 -07006170 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006171 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006172 }
Chet Haase55dbb652010-12-21 20:15:08 -08006173 mBackgroundSizeChanged = true;
Chet Haase678e0ad2011-01-25 09:37:18 -08006174 invalidateParentIfNeeded();
Chet Haase21cd1382010-09-01 17:42:29 -07006175 }
6176 }
6177
6178 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 * Left position of this view relative to its parent.
6180 *
6181 * @return The left edge of this view, in pixels.
6182 */
6183 @ViewDebug.CapturedViewProperty
6184 public final int getLeft() {
6185 return mLeft;
6186 }
6187
6188 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006189 * Sets the left position of this view relative to its parent. This method is meant to be called
6190 * by the layout system and should not generally be called otherwise, because the property
6191 * may be changed at any time by the layout.
6192 *
6193 * @param left The bottom of this view, in pixels.
6194 */
6195 public final void setLeft(int left) {
6196 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07006197 updateMatrix();
6198 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006199 final ViewParent p = mParent;
6200 if (p != null && mAttachInfo != null) {
6201 final Rect r = mAttachInfo.mTmpInvalRect;
6202 int minLeft;
6203 int xLoc;
6204 if (left < mLeft) {
6205 minLeft = left;
6206 xLoc = left - mLeft;
6207 } else {
6208 minLeft = mLeft;
6209 xLoc = 0;
6210 }
6211 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
6212 p.invalidateChild(this, r);
6213 }
6214 } else {
6215 // Double-invalidation is necessary to capture view's old and new areas
Romain Guy0fd89bf2011-01-26 15:41:30 -08006216 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006217 }
6218
Chet Haaseed032702010-10-01 14:05:54 -07006219 int oldWidth = mRight - mLeft;
6220 int height = mBottom - mTop;
6221
Chet Haase21cd1382010-09-01 17:42:29 -07006222 mLeft = left;
6223
Chet Haaseed032702010-10-01 14:05:54 -07006224 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6225
Chet Haase21cd1382010-09-01 17:42:29 -07006226 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006227 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6228 // A change in dimension means an auto-centered pivot point changes, too
6229 mMatrixDirty = true;
6230 }
Chet Haase21cd1382010-09-01 17:42:29 -07006231 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006232 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006233 }
Chet Haase55dbb652010-12-21 20:15:08 -08006234 mBackgroundSizeChanged = true;
Chet Haase678e0ad2011-01-25 09:37:18 -08006235 invalidateParentIfNeeded();
Chet Haase21cd1382010-09-01 17:42:29 -07006236 }
6237 }
6238
6239 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006240 * Right position of this view relative to its parent.
6241 *
6242 * @return The right edge of this view, in pixels.
6243 */
6244 @ViewDebug.CapturedViewProperty
6245 public final int getRight() {
6246 return mRight;
6247 }
6248
6249 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006250 * Sets the right position of this view relative to its parent. This method is meant to be called
6251 * by the layout system and should not generally be called otherwise, because the property
6252 * may be changed at any time by the layout.
6253 *
6254 * @param right The bottom of this view, in pixels.
6255 */
6256 public final void setRight(int right) {
6257 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07006258 updateMatrix();
6259 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006260 final ViewParent p = mParent;
6261 if (p != null && mAttachInfo != null) {
6262 final Rect r = mAttachInfo.mTmpInvalRect;
6263 int maxRight;
6264 if (right < mRight) {
6265 maxRight = mRight;
6266 } else {
6267 maxRight = right;
6268 }
6269 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
6270 p.invalidateChild(this, r);
6271 }
6272 } else {
6273 // Double-invalidation is necessary to capture view's old and new areas
Romain Guy0fd89bf2011-01-26 15:41:30 -08006274 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006275 }
6276
Chet Haaseed032702010-10-01 14:05:54 -07006277 int oldWidth = mRight - mLeft;
6278 int height = mBottom - mTop;
6279
Chet Haase21cd1382010-09-01 17:42:29 -07006280 mRight = right;
6281
Chet Haaseed032702010-10-01 14:05:54 -07006282 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6283
Chet Haase21cd1382010-09-01 17:42:29 -07006284 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006285 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6286 // A change in dimension means an auto-centered pivot point changes, too
6287 mMatrixDirty = true;
6288 }
Chet Haase21cd1382010-09-01 17:42:29 -07006289 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006290 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006291 }
Chet Haase55dbb652010-12-21 20:15:08 -08006292 mBackgroundSizeChanged = true;
Chet Haase678e0ad2011-01-25 09:37:18 -08006293 invalidateParentIfNeeded();
Chet Haase21cd1382010-09-01 17:42:29 -07006294 }
6295 }
6296
6297 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006298 * The visual x position of this view, in pixels. This is equivalent to the
6299 * {@link #setTranslationX(float) translationX} property plus the current
Joe Malin32736f02011-01-19 16:14:20 -08006300 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07006301 *
Chet Haasedf030d22010-07-30 17:22:38 -07006302 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006303 */
Chet Haasedf030d22010-07-30 17:22:38 -07006304 public float getX() {
6305 return mLeft + mTranslationX;
6306 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006307
Chet Haasedf030d22010-07-30 17:22:38 -07006308 /**
6309 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
6310 * {@link #setTranslationX(float) translationX} property to be the difference between
6311 * the x value passed in and the current {@link #getLeft() left} property.
6312 *
6313 * @param x The visual x position of this view, in pixels.
6314 */
6315 public void setX(float x) {
6316 setTranslationX(x - mLeft);
6317 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006318
Chet Haasedf030d22010-07-30 17:22:38 -07006319 /**
6320 * The visual y position of this view, in pixels. This is equivalent to the
6321 * {@link #setTranslationY(float) translationY} property plus the current
6322 * {@link #getTop() top} property.
6323 *
6324 * @return The visual y position of this view, in pixels.
6325 */
6326 public float getY() {
6327 return mTop + mTranslationY;
6328 }
6329
6330 /**
6331 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
6332 * {@link #setTranslationY(float) translationY} property to be the difference between
6333 * the y value passed in and the current {@link #getTop() top} property.
6334 *
6335 * @param y The visual y position of this view, in pixels.
6336 */
6337 public void setY(float y) {
6338 setTranslationY(y - mTop);
6339 }
6340
6341
6342 /**
6343 * The horizontal location of this view relative to its {@link #getLeft() left} position.
6344 * This position is post-layout, in addition to wherever the object's
6345 * layout placed it.
6346 *
6347 * @return The horizontal position of this view relative to its left position, in pixels.
6348 */
6349 public float getTranslationX() {
6350 return mTranslationX;
6351 }
6352
6353 /**
6354 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
6355 * This effectively positions the object post-layout, in addition to wherever the object's
6356 * layout placed it.
6357 *
6358 * @param translationX The horizontal position of this view relative to its left position,
6359 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006360 *
6361 * @attr ref android.R.styleable#View_translationX
Chet Haasedf030d22010-07-30 17:22:38 -07006362 */
6363 public void setTranslationX(float translationX) {
6364 if (mTranslationX != translationX) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006365 invalidateParentCaches();
Chet Haasedf030d22010-07-30 17:22:38 -07006366 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006367 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006368 mTranslationX = translationX;
6369 mMatrixDirty = true;
6370 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006371 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006372 }
6373 }
6374
6375 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006376 * The horizontal location of this view relative to its {@link #getTop() top} position.
6377 * This position is post-layout, in addition to wherever the object's
6378 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006379 *
Chet Haasedf030d22010-07-30 17:22:38 -07006380 * @return The vertical position of this view relative to its top position,
6381 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006382 */
Chet Haasedf030d22010-07-30 17:22:38 -07006383 public float getTranslationY() {
6384 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07006385 }
6386
6387 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006388 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
6389 * This effectively positions the object post-layout, in addition to wherever the object's
6390 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006391 *
Chet Haasedf030d22010-07-30 17:22:38 -07006392 * @param translationY The vertical position of this view relative to its top position,
6393 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006394 *
6395 * @attr ref android.R.styleable#View_translationY
Chet Haasec3aa3612010-06-17 08:50:37 -07006396 */
Chet Haasedf030d22010-07-30 17:22:38 -07006397 public void setTranslationY(float translationY) {
6398 if (mTranslationY != translationY) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006399 invalidateParentCaches();
Chet Haasedf030d22010-07-30 17:22:38 -07006400 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006401 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006402 mTranslationY = translationY;
6403 mMatrixDirty = true;
6404 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006405 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006406 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006407 }
6408
6409 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 * Hit rectangle in parent's coordinates
6411 *
6412 * @param outRect The hit rectangle of the view.
6413 */
6414 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07006415 updateMatrix();
6416 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006417 outRect.set(mLeft, mTop, mRight, mBottom);
6418 } else {
6419 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07006420 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07006421 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07006422 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
6423 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07006424 }
6425 }
6426
6427 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07006428 * Determines whether the given point, in local coordinates is inside the view.
6429 */
6430 /*package*/ final boolean pointInView(float localX, float localY) {
6431 return localX >= 0 && localX < (mRight - mLeft)
6432 && localY >= 0 && localY < (mBottom - mTop);
6433 }
6434
6435 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07006436 * Utility method to determine whether the given point, in local coordinates,
6437 * is inside the view, where the area of the view is expanded by the slop factor.
6438 * This method is called while processing touch-move events to determine if the event
6439 * is still within the view.
6440 */
6441 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07006442 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07006443 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 }
6445
6446 /**
6447 * When a view has focus and the user navigates away from it, the next view is searched for
6448 * starting from the rectangle filled in by this method.
6449 *
6450 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
6451 * view maintains some idea of internal selection, such as a cursor, or a selected row
6452 * or column, you should override this method and fill in a more specific rectangle.
6453 *
6454 * @param r The rectangle to fill in, in this view's coordinates.
6455 */
6456 public void getFocusedRect(Rect r) {
6457 getDrawingRect(r);
6458 }
6459
6460 /**
6461 * If some part of this view is not clipped by any of its parents, then
6462 * return that area in r in global (root) coordinates. To convert r to local
6463 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
6464 * -globalOffset.y)) If the view is completely clipped or translated out,
6465 * return false.
6466 *
6467 * @param r If true is returned, r holds the global coordinates of the
6468 * visible portion of this view.
6469 * @param globalOffset If true is returned, globalOffset holds the dx,dy
6470 * between this view and its root. globalOffet may be null.
6471 * @return true if r is non-empty (i.e. part of the view is visible at the
6472 * root level.
6473 */
6474 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6475 int width = mRight - mLeft;
6476 int height = mBottom - mTop;
6477 if (width > 0 && height > 0) {
6478 r.set(0, 0, width, height);
6479 if (globalOffset != null) {
6480 globalOffset.set(-mScrollX, -mScrollY);
6481 }
6482 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6483 }
6484 return false;
6485 }
6486
6487 public final boolean getGlobalVisibleRect(Rect r) {
6488 return getGlobalVisibleRect(r, null);
6489 }
6490
6491 public final boolean getLocalVisibleRect(Rect r) {
6492 Point offset = new Point();
6493 if (getGlobalVisibleRect(r, offset)) {
6494 r.offset(-offset.x, -offset.y); // make r local
6495 return true;
6496 }
6497 return false;
6498 }
6499
6500 /**
6501 * Offset this view's vertical location by the specified number of pixels.
6502 *
6503 * @param offset the number of pixels to offset the view by
6504 */
6505 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006506 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006507 updateMatrix();
6508 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006509 final ViewParent p = mParent;
6510 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006511 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006512 int minTop;
6513 int maxBottom;
6514 int yLoc;
6515 if (offset < 0) {
6516 minTop = mTop + offset;
6517 maxBottom = mBottom;
6518 yLoc = offset;
6519 } else {
6520 minTop = mTop;
6521 maxBottom = mBottom + offset;
6522 yLoc = 0;
6523 }
6524 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6525 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006526 }
6527 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006528 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006529 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006530
Chet Haasec3aa3612010-06-17 08:50:37 -07006531 mTop += offset;
6532 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006533
Chet Haasec3aa3612010-06-17 08:50:37 -07006534 if (!mMatrixIsIdentity) {
6535 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006536 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006537 }
Chet Haase678e0ad2011-01-25 09:37:18 -08006538 invalidateParentIfNeeded();
Chet Haasec3aa3612010-06-17 08:50:37 -07006539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 }
6541
6542 /**
6543 * Offset this view's horizontal location by the specified amount of pixels.
6544 *
6545 * @param offset the numer of pixels to offset the view by
6546 */
6547 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006548 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006549 updateMatrix();
6550 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006551 final ViewParent p = mParent;
6552 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006553 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006554 int minLeft;
6555 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006556 if (offset < 0) {
6557 minLeft = mLeft + offset;
6558 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006559 } else {
6560 minLeft = mLeft;
6561 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006562 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006563 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07006564 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006565 }
6566 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006567 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006568 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006569
Chet Haasec3aa3612010-06-17 08:50:37 -07006570 mLeft += offset;
6571 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006572
Chet Haasec3aa3612010-06-17 08:50:37 -07006573 if (!mMatrixIsIdentity) {
6574 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006575 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006576 }
Chet Haase678e0ad2011-01-25 09:37:18 -08006577 invalidateParentIfNeeded();
Chet Haasec3aa3612010-06-17 08:50:37 -07006578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 }
6580
6581 /**
6582 * Get the LayoutParams associated with this view. All views should have
6583 * layout parameters. These supply parameters to the <i>parent</i> of this
6584 * view specifying how it should be arranged. There are many subclasses of
6585 * ViewGroup.LayoutParams, and these correspond to the different subclasses
6586 * of ViewGroup that are responsible for arranging their children.
6587 * @return The LayoutParams associated with this view
6588 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07006589 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 public ViewGroup.LayoutParams getLayoutParams() {
6591 return mLayoutParams;
6592 }
6593
6594 /**
6595 * Set the layout parameters associated with this view. These supply
6596 * parameters to the <i>parent</i> of this view specifying how it should be
6597 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6598 * correspond to the different subclasses of ViewGroup that are responsible
6599 * for arranging their children.
6600 *
6601 * @param params the layout parameters for this view
6602 */
6603 public void setLayoutParams(ViewGroup.LayoutParams params) {
6604 if (params == null) {
6605 throw new NullPointerException("params == null");
6606 }
6607 mLayoutParams = params;
6608 requestLayout();
6609 }
6610
6611 /**
6612 * Set the scrolled position of your view. This will cause a call to
6613 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6614 * invalidated.
6615 * @param x the x position to scroll to
6616 * @param y the y position to scroll to
6617 */
6618 public void scrollTo(int x, int y) {
6619 if (mScrollX != x || mScrollY != y) {
6620 int oldX = mScrollX;
6621 int oldY = mScrollY;
6622 mScrollX = x;
6623 mScrollY = y;
Romain Guy0fd89bf2011-01-26 15:41:30 -08006624 invalidateParentCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006625 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006626 if (!awakenScrollBars()) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006627 invalidate(true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 }
6630 }
6631
6632 /**
6633 * Move the scrolled position of your view. This will cause a call to
6634 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6635 * invalidated.
6636 * @param x the amount of pixels to scroll by horizontally
6637 * @param y the amount of pixels to scroll by vertically
6638 */
6639 public void scrollBy(int x, int y) {
6640 scrollTo(mScrollX + x, mScrollY + y);
6641 }
6642
6643 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006644 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6645 * animation to fade the scrollbars out after a default delay. If a subclass
6646 * provides animated scrolling, the start delay should equal the duration
6647 * of the scrolling animation.</p>
6648 *
6649 * <p>The animation starts only if at least one of the scrollbars is
6650 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6651 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6652 * this method returns true, and false otherwise. If the animation is
6653 * started, this method calls {@link #invalidate()}; in that case the
6654 * caller should not call {@link #invalidate()}.</p>
6655 *
6656 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006657 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006658 *
6659 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6660 * and {@link #scrollTo(int, int)}.</p>
6661 *
6662 * @return true if the animation is played, false otherwise
6663 *
6664 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006665 * @see #scrollBy(int, int)
6666 * @see #scrollTo(int, int)
6667 * @see #isHorizontalScrollBarEnabled()
6668 * @see #isVerticalScrollBarEnabled()
6669 * @see #setHorizontalScrollBarEnabled(boolean)
6670 * @see #setVerticalScrollBarEnabled(boolean)
6671 */
6672 protected boolean awakenScrollBars() {
6673 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006674 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006675 }
6676
6677 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006678 * Trigger the scrollbars to draw.
6679 * This method differs from awakenScrollBars() only in its default duration.
6680 * initialAwakenScrollBars() will show the scroll bars for longer than
6681 * usual to give the user more of a chance to notice them.
6682 *
6683 * @return true if the animation is played, false otherwise.
6684 */
6685 private boolean initialAwakenScrollBars() {
6686 return mScrollCache != null &&
6687 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6688 }
6689
6690 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006691 * <p>
6692 * Trigger the scrollbars to draw. When invoked this method starts an
6693 * animation to fade the scrollbars out after a fixed delay. If a subclass
6694 * provides animated scrolling, the start delay should equal the duration of
6695 * the scrolling animation.
6696 * </p>
Joe Malin32736f02011-01-19 16:14:20 -08006697 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006698 * <p>
6699 * The animation starts only if at least one of the scrollbars is enabled,
6700 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6701 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6702 * this method returns true, and false otherwise. If the animation is
6703 * started, this method calls {@link #invalidate()}; in that case the caller
6704 * should not call {@link #invalidate()}.
6705 * </p>
Joe Malin32736f02011-01-19 16:14:20 -08006706 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006707 * <p>
6708 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006709 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006710 * </p>
Joe Malin32736f02011-01-19 16:14:20 -08006711 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006712 * @param startDelay the delay, in milliseconds, after which the animation
6713 * should start; when the delay is 0, the animation starts
6714 * immediately
6715 * @return true if the animation is played, false otherwise
Joe Malin32736f02011-01-19 16:14:20 -08006716 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006717 * @see #scrollBy(int, int)
6718 * @see #scrollTo(int, int)
6719 * @see #isHorizontalScrollBarEnabled()
6720 * @see #isVerticalScrollBarEnabled()
6721 * @see #setHorizontalScrollBarEnabled(boolean)
6722 * @see #setVerticalScrollBarEnabled(boolean)
6723 */
6724 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006725 return awakenScrollBars(startDelay, true);
6726 }
Joe Malin32736f02011-01-19 16:14:20 -08006727
Mike Cleron290947b2009-09-29 18:34:32 -07006728 /**
6729 * <p>
6730 * Trigger the scrollbars to draw. When invoked this method starts an
6731 * animation to fade the scrollbars out after a fixed delay. If a subclass
6732 * provides animated scrolling, the start delay should equal the duration of
6733 * the scrolling animation.
6734 * </p>
Joe Malin32736f02011-01-19 16:14:20 -08006735 *
Mike Cleron290947b2009-09-29 18:34:32 -07006736 * <p>
6737 * The animation starts only if at least one of the scrollbars is enabled,
6738 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6739 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6740 * this method returns true, and false otherwise. If the animation is
Joe Malin32736f02011-01-19 16:14:20 -08006741 * started, this method calls {@link #invalidate()} if the invalidate parameter
Mike Cleron290947b2009-09-29 18:34:32 -07006742 * is set to true; in that case the caller
6743 * should not call {@link #invalidate()}.
6744 * </p>
Joe Malin32736f02011-01-19 16:14:20 -08006745 *
Mike Cleron290947b2009-09-29 18:34:32 -07006746 * <p>
6747 * This method should be invoked everytime a subclass directly updates the
6748 * scroll parameters.
6749 * </p>
Joe Malin32736f02011-01-19 16:14:20 -08006750 *
Mike Cleron290947b2009-09-29 18:34:32 -07006751 * @param startDelay the delay, in milliseconds, after which the animation
6752 * should start; when the delay is 0, the animation starts
6753 * immediately
Joe Malin32736f02011-01-19 16:14:20 -08006754 *
Mike Cleron290947b2009-09-29 18:34:32 -07006755 * @param invalidate Wheter this method should call invalidate
Joe Malin32736f02011-01-19 16:14:20 -08006756 *
Mike Cleron290947b2009-09-29 18:34:32 -07006757 * @return true if the animation is played, false otherwise
Joe Malin32736f02011-01-19 16:14:20 -08006758 *
Mike Cleron290947b2009-09-29 18:34:32 -07006759 * @see #scrollBy(int, int)
6760 * @see #scrollTo(int, int)
6761 * @see #isHorizontalScrollBarEnabled()
6762 * @see #isVerticalScrollBarEnabled()
6763 * @see #setHorizontalScrollBarEnabled(boolean)
6764 * @see #setVerticalScrollBarEnabled(boolean)
6765 */
6766 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006767 final ScrollabilityCache scrollCache = mScrollCache;
Joe Malin32736f02011-01-19 16:14:20 -08006768
Mike Cleronf116bf82009-09-27 19:14:12 -07006769 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6770 return false;
6771 }
6772
6773 if (scrollCache.scrollBar == null) {
6774 scrollCache.scrollBar = new ScrollBarDrawable();
6775 }
6776
6777 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6778
Mike Cleron290947b2009-09-29 18:34:32 -07006779 if (invalidate) {
6780 // Invalidate to show the scrollbars
Romain Guy0fd89bf2011-01-26 15:41:30 -08006781 invalidate(true);
Mike Cleron290947b2009-09-29 18:34:32 -07006782 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006783
6784 if (scrollCache.state == ScrollabilityCache.OFF) {
6785 // FIXME: this is copied from WindowManagerService.
6786 // We should get this value from the system when it
6787 // is possible to do so.
6788 final int KEY_REPEAT_FIRST_DELAY = 750;
6789 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6790 }
6791
6792 // Tell mScrollCache when we should start fading. This may
6793 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006794 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006795 scrollCache.fadeStartTime = fadeStartTime;
6796 scrollCache.state = ScrollabilityCache.ON;
6797
6798 // Schedule our fader to run, unscheduling any old ones first
6799 if (mAttachInfo != null) {
6800 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6801 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6802 }
6803
6804 return true;
6805 }
6806
6807 return false;
6808 }
6809
6810 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 * Mark the the area defined by dirty as needing to be drawn. If the view is
6812 * visible, {@link #onDraw} will be called at some point in the future.
6813 * This must be called from a UI thread. To call from a non-UI thread, call
6814 * {@link #postInvalidate()}.
6815 *
6816 * WARNING: This method is destructive to dirty.
6817 * @param dirty the rectangle representing the bounds of the dirty region
6818 */
6819 public void invalidate(Rect dirty) {
6820 if (ViewDebug.TRACE_HIERARCHY) {
6821 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6822 }
6823
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006824 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
Chet Haasedaf98e92011-01-10 14:10:36 -08006825 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
6826 (mPrivateFlags & INVALIDATED) != INVALIDATED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006827 mPrivateFlags &= ~DRAWING_CACHE_VALID;
Chet Haasedaf98e92011-01-10 14:10:36 -08006828 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006829 final ViewParent p = mParent;
6830 final AttachInfo ai = mAttachInfo;
Romain Guy7d7b5492011-01-24 16:33:45 -08006831 //noinspection PointlessBooleanExpression,ConstantConditions
6832 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
6833 if (p != null && ai != null && ai.mHardwareAccelerated) {
6834 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6835 // with a null dirty rect, which tells the ViewRoot to redraw everything
6836 p.invalidateChild(this, null);
6837 return;
6838 }
Romain Guyaf636eb2010-12-09 17:47:21 -08006839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 if (p != null && ai != null) {
6841 final int scrollX = mScrollX;
6842 final int scrollY = mScrollY;
6843 final Rect r = ai.mTmpInvalRect;
6844 r.set(dirty.left - scrollX, dirty.top - scrollY,
6845 dirty.right - scrollX, dirty.bottom - scrollY);
6846 mParent.invalidateChild(this, r);
6847 }
6848 }
6849 }
6850
6851 /**
6852 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6853 * The coordinates of the dirty rect are relative to the view.
6854 * If the view is visible, {@link #onDraw} will be called at some point
6855 * in the future. This must be called from a UI thread. To call
6856 * from a non-UI thread, call {@link #postInvalidate()}.
6857 * @param l the left position of the dirty region
6858 * @param t the top position of the dirty region
6859 * @param r the right position of the dirty region
6860 * @param b the bottom position of the dirty region
6861 */
6862 public void invalidate(int l, int t, int r, int b) {
6863 if (ViewDebug.TRACE_HIERARCHY) {
6864 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6865 }
6866
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006867 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
Chet Haasedaf98e92011-01-10 14:10:36 -08006868 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
6869 (mPrivateFlags & INVALIDATED) != INVALIDATED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006870 mPrivateFlags &= ~DRAWING_CACHE_VALID;
Chet Haasedaf98e92011-01-10 14:10:36 -08006871 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006872 final ViewParent p = mParent;
6873 final AttachInfo ai = mAttachInfo;
Romain Guy7d7b5492011-01-24 16:33:45 -08006874 //noinspection PointlessBooleanExpression,ConstantConditions
6875 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
6876 if (p != null && ai != null && ai.mHardwareAccelerated) {
6877 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6878 // with a null dirty rect, which tells the ViewRoot to redraw everything
6879 p.invalidateChild(this, null);
6880 return;
6881 }
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006883 if (p != null && ai != null && l < r && t < b) {
6884 final int scrollX = mScrollX;
6885 final int scrollY = mScrollY;
6886 final Rect tmpr = ai.mTmpInvalRect;
6887 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6888 p.invalidateChild(this, tmpr);
6889 }
6890 }
6891 }
6892
6893 /**
6894 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6895 * be called at some point in the future. This must be called from a
6896 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6897 */
6898 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006899 invalidate(true);
6900 }
Joe Malin32736f02011-01-19 16:14:20 -08006901
Chet Haaseed032702010-10-01 14:05:54 -07006902 /**
6903 * This is where the invalidate() work actually happens. A full invalidate()
6904 * causes the drawing cache to be invalidated, but this function can be called with
6905 * invalidateCache set to false to skip that invalidation step for cases that do not
6906 * need it (for example, a component that remains at the same dimensions with the same
6907 * content).
6908 *
6909 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6910 * well. This is usually true for a full invalidate, but may be set to false if the
6911 * View's contents or dimensions have not changed.
6912 */
6913 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006914 if (ViewDebug.TRACE_HIERARCHY) {
6915 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6916 }
6917
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006918 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
Romain Guyc5d55862011-01-21 19:01:46 -08006919 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
Romain Guy0fd89bf2011-01-26 15:41:30 -08006920 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
6921 mLastIsOpaque = isOpaque();
Chet Haaseed032702010-10-01 14:05:54 -07006922 mPrivateFlags &= ~DRAWN;
6923 if (invalidateCache) {
Chet Haasedaf98e92011-01-10 14:10:36 -08006924 mPrivateFlags |= INVALIDATED;
Chet Haaseed032702010-10-01 14:05:54 -07006925 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006928 final ViewParent p = mParent;
Romain Guy7d7b5492011-01-24 16:33:45 -08006929 //noinspection PointlessBooleanExpression,ConstantConditions
6930 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
6931 if (p != null && ai != null && ai.mHardwareAccelerated) {
6932 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6933 // with a null dirty rect, which tells the ViewRoot to redraw everything
6934 p.invalidateChild(this, null);
6935 return;
6936 }
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006937 }
Michael Jurkaebefea42010-11-15 16:04:01 -08006938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006939 if (p != null && ai != null) {
6940 final Rect r = ai.mTmpInvalRect;
6941 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6942 // Don't call invalidate -- we don't want to internally scroll
6943 // our own bounds
6944 p.invalidateChild(this, r);
6945 }
6946 }
6947 }
6948
6949 /**
Romain Guy0fd89bf2011-01-26 15:41:30 -08006950 * Used to indicate that the parent of this view should clear its caches. This functionality
Chet Haasedaf98e92011-01-10 14:10:36 -08006951 * is used to force the parent to rebuild its display list (when hardware-accelerated),
6952 * which is necessary when various parent-managed properties of the view change, such as
Romain Guy0fd89bf2011-01-26 15:41:30 -08006953 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
6954 * clears the parent caches and does not causes an invalidate event.
Chet Haasedaf98e92011-01-10 14:10:36 -08006955 *
6956 * @hide
6957 */
Romain Guy0fd89bf2011-01-26 15:41:30 -08006958 protected void invalidateParentCaches() {
6959 if (mParent instanceof View) {
6960 ((View) mParent).mPrivateFlags |= INVALIDATED;
6961 }
6962 }
Joe Malin32736f02011-01-19 16:14:20 -08006963
Romain Guy0fd89bf2011-01-26 15:41:30 -08006964 /**
6965 * Used to indicate that the parent of this view should be invalidated. This functionality
6966 * is used to force the parent to rebuild its display list (when hardware-accelerated),
6967 * which is necessary when various parent-managed properties of the view change, such as
6968 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
6969 * an invalidation event to the parent.
6970 *
6971 * @hide
6972 */
6973 protected void invalidateParentIfNeeded() {
Chet Haasedaf98e92011-01-10 14:10:36 -08006974 if (isHardwareAccelerated() && mParent instanceof View) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006975 ((View) mParent).invalidate(true);
Chet Haasedaf98e92011-01-10 14:10:36 -08006976 }
6977 }
6978
6979 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006980 * Indicates whether this View is opaque. An opaque View guarantees that it will
6981 * draw all the pixels overlapping its bounds using a fully opaque color.
6982 *
6983 * Subclasses of View should override this method whenever possible to indicate
6984 * whether an instance is opaque. Opaque Views are treated in a special way by
6985 * the View hierarchy, possibly allowing it to perform optimizations during
6986 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006987 *
Romain Guy24443ea2009-05-11 11:56:30 -07006988 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006989 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006990 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006991 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006992 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6993 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006994 }
6995
Adam Powell20232d02010-12-08 21:08:53 -08006996 /**
6997 * @hide
6998 */
6999 protected void computeOpaqueFlags() {
Romain Guy8f1344f52009-05-15 16:03:59 -07007000 // Opaque if:
7001 // - Has a background
7002 // - Background is opaque
7003 // - Doesn't have scrollbars or scrollbars are inside overlay
7004
7005 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
7006 mPrivateFlags |= OPAQUE_BACKGROUND;
7007 } else {
7008 mPrivateFlags &= ~OPAQUE_BACKGROUND;
7009 }
7010
7011 final int flags = mViewFlags;
7012 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
7013 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
7014 mPrivateFlags |= OPAQUE_SCROLLBARS;
7015 } else {
7016 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
7017 }
7018 }
7019
7020 /**
7021 * @hide
7022 */
7023 protected boolean hasOpaqueScrollbars() {
7024 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07007025 }
7026
7027 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 * @return A handler associated with the thread running the View. This
7029 * handler can be used to pump events in the UI events queue.
7030 */
7031 public Handler getHandler() {
7032 if (mAttachInfo != null) {
7033 return mAttachInfo.mHandler;
7034 }
7035 return null;
7036 }
7037
7038 /**
7039 * Causes the Runnable to be added to the message queue.
7040 * The runnable will be run on the user interface thread.
7041 *
7042 * @param action The Runnable that will be executed.
7043 *
7044 * @return Returns true if the Runnable was successfully placed in to the
7045 * message queue. Returns false on failure, usually because the
7046 * looper processing the message queue is exiting.
7047 */
7048 public boolean post(Runnable action) {
7049 Handler handler;
7050 if (mAttachInfo != null) {
7051 handler = mAttachInfo.mHandler;
7052 } else {
7053 // Assume that post will succeed later
7054 ViewRoot.getRunQueue().post(action);
7055 return true;
7056 }
7057
7058 return handler.post(action);
7059 }
7060
7061 /**
7062 * Causes the Runnable to be added to the message queue, to be run
7063 * after the specified amount of time elapses.
7064 * The runnable will be run on the user interface thread.
7065 *
7066 * @param action The Runnable that will be executed.
7067 * @param delayMillis The delay (in milliseconds) until the Runnable
7068 * will be executed.
7069 *
7070 * @return true if the Runnable was successfully placed in to the
7071 * message queue. Returns false on failure, usually because the
7072 * looper processing the message queue is exiting. Note that a
7073 * result of true does not mean the Runnable will be processed --
7074 * if the looper is quit before the delivery time of the message
7075 * occurs then the message will be dropped.
7076 */
7077 public boolean postDelayed(Runnable action, long delayMillis) {
7078 Handler handler;
7079 if (mAttachInfo != null) {
7080 handler = mAttachInfo.mHandler;
7081 } else {
7082 // Assume that post will succeed later
7083 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
7084 return true;
7085 }
7086
7087 return handler.postDelayed(action, delayMillis);
7088 }
7089
7090 /**
7091 * Removes the specified Runnable from the message queue.
7092 *
7093 * @param action The Runnable to remove from the message handling queue
7094 *
7095 * @return true if this view could ask the Handler to remove the Runnable,
7096 * false otherwise. When the returned value is true, the Runnable
7097 * may or may not have been actually removed from the message queue
7098 * (for instance, if the Runnable was not in the queue already.)
7099 */
7100 public boolean removeCallbacks(Runnable action) {
7101 Handler handler;
7102 if (mAttachInfo != null) {
7103 handler = mAttachInfo.mHandler;
7104 } else {
7105 // Assume that post will succeed later
7106 ViewRoot.getRunQueue().removeCallbacks(action);
7107 return true;
7108 }
7109
7110 handler.removeCallbacks(action);
7111 return true;
7112 }
7113
7114 /**
7115 * Cause an invalidate to happen on a subsequent cycle through the event loop.
7116 * Use this to invalidate the View from a non-UI thread.
7117 *
7118 * @see #invalidate()
7119 */
7120 public void postInvalidate() {
7121 postInvalidateDelayed(0);
7122 }
7123
7124 /**
7125 * Cause an invalidate of the specified area to happen on a subsequent cycle
7126 * through the event loop. Use this to invalidate the View from a non-UI thread.
7127 *
7128 * @param left The left coordinate of the rectangle to invalidate.
7129 * @param top The top coordinate of the rectangle to invalidate.
7130 * @param right The right coordinate of the rectangle to invalidate.
7131 * @param bottom The bottom coordinate of the rectangle to invalidate.
7132 *
7133 * @see #invalidate(int, int, int, int)
7134 * @see #invalidate(Rect)
7135 */
7136 public void postInvalidate(int left, int top, int right, int bottom) {
7137 postInvalidateDelayed(0, left, top, right, bottom);
7138 }
7139
7140 /**
7141 * Cause an invalidate to happen on a subsequent cycle through the event
7142 * loop. Waits for the specified amount of time.
7143 *
7144 * @param delayMilliseconds the duration in milliseconds to delay the
7145 * invalidation by
7146 */
7147 public void postInvalidateDelayed(long delayMilliseconds) {
7148 // We try only with the AttachInfo because there's no point in invalidating
7149 // if we are not attached to our window
7150 if (mAttachInfo != null) {
7151 Message msg = Message.obtain();
7152 msg.what = AttachInfo.INVALIDATE_MSG;
7153 msg.obj = this;
7154 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
7155 }
7156 }
7157
7158 /**
7159 * Cause an invalidate of the specified area to happen on a subsequent cycle
7160 * through the event loop. Waits for the specified amount of time.
7161 *
7162 * @param delayMilliseconds the duration in milliseconds to delay the
7163 * invalidation by
7164 * @param left The left coordinate of the rectangle to invalidate.
7165 * @param top The top coordinate of the rectangle to invalidate.
7166 * @param right The right coordinate of the rectangle to invalidate.
7167 * @param bottom The bottom coordinate of the rectangle to invalidate.
7168 */
7169 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
7170 int right, int bottom) {
7171
7172 // We try only with the AttachInfo because there's no point in invalidating
7173 // if we are not attached to our window
7174 if (mAttachInfo != null) {
7175 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
7176 info.target = this;
7177 info.left = left;
7178 info.top = top;
7179 info.right = right;
7180 info.bottom = bottom;
7181
7182 final Message msg = Message.obtain();
7183 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
7184 msg.obj = info;
7185 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
7186 }
7187 }
7188
7189 /**
7190 * Called by a parent to request that a child update its values for mScrollX
7191 * and mScrollY if necessary. This will typically be done if the child is
7192 * animating a scroll using a {@link android.widget.Scroller Scroller}
7193 * object.
7194 */
7195 public void computeScroll() {
7196 }
7197
7198 /**
7199 * <p>Indicate whether the horizontal edges are faded when the view is
7200 * scrolled horizontally.</p>
7201 *
7202 * @return true if the horizontal edges should are faded on scroll, false
7203 * otherwise
7204 *
7205 * @see #setHorizontalFadingEdgeEnabled(boolean)
7206 * @attr ref android.R.styleable#View_fadingEdge
7207 */
7208 public boolean isHorizontalFadingEdgeEnabled() {
7209 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
7210 }
7211
7212 /**
7213 * <p>Define whether the horizontal edges should be faded when this view
7214 * is scrolled horizontally.</p>
7215 *
7216 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
7217 * be faded when the view is scrolled
7218 * horizontally
7219 *
7220 * @see #isHorizontalFadingEdgeEnabled()
7221 * @attr ref android.R.styleable#View_fadingEdge
7222 */
7223 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
7224 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
7225 if (horizontalFadingEdgeEnabled) {
7226 initScrollCache();
7227 }
7228
7229 mViewFlags ^= FADING_EDGE_HORIZONTAL;
7230 }
7231 }
7232
7233 /**
7234 * <p>Indicate whether the vertical edges are faded when the view is
7235 * scrolled horizontally.</p>
7236 *
7237 * @return true if the vertical edges should are faded on scroll, false
7238 * otherwise
7239 *
7240 * @see #setVerticalFadingEdgeEnabled(boolean)
7241 * @attr ref android.R.styleable#View_fadingEdge
7242 */
7243 public boolean isVerticalFadingEdgeEnabled() {
7244 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
7245 }
7246
7247 /**
7248 * <p>Define whether the vertical edges should be faded when this view
7249 * is scrolled vertically.</p>
7250 *
7251 * @param verticalFadingEdgeEnabled true if the vertical edges should
7252 * be faded when the view is scrolled
7253 * vertically
7254 *
7255 * @see #isVerticalFadingEdgeEnabled()
7256 * @attr ref android.R.styleable#View_fadingEdge
7257 */
7258 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
7259 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
7260 if (verticalFadingEdgeEnabled) {
7261 initScrollCache();
7262 }
7263
7264 mViewFlags ^= FADING_EDGE_VERTICAL;
7265 }
7266 }
7267
7268 /**
7269 * Returns the strength, or intensity, of the top faded edge. The strength is
7270 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7271 * returns 0.0 or 1.0 but no value in between.
7272 *
7273 * Subclasses should override this method to provide a smoother fade transition
7274 * when scrolling occurs.
7275 *
7276 * @return the intensity of the top fade as a float between 0.0f and 1.0f
7277 */
7278 protected float getTopFadingEdgeStrength() {
7279 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
7280 }
7281
7282 /**
7283 * Returns the strength, or intensity, of the bottom faded edge. The strength is
7284 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7285 * returns 0.0 or 1.0 but no value in between.
7286 *
7287 * Subclasses should override this method to provide a smoother fade transition
7288 * when scrolling occurs.
7289 *
7290 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
7291 */
7292 protected float getBottomFadingEdgeStrength() {
7293 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
7294 computeVerticalScrollRange() ? 1.0f : 0.0f;
7295 }
7296
7297 /**
7298 * Returns the strength, or intensity, of the left faded edge. The strength is
7299 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7300 * returns 0.0 or 1.0 but no value in between.
7301 *
7302 * Subclasses should override this method to provide a smoother fade transition
7303 * when scrolling occurs.
7304 *
7305 * @return the intensity of the left fade as a float between 0.0f and 1.0f
7306 */
7307 protected float getLeftFadingEdgeStrength() {
7308 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
7309 }
7310
7311 /**
7312 * Returns the strength, or intensity, of the right faded edge. The strength is
7313 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7314 * returns 0.0 or 1.0 but no value in between.
7315 *
7316 * Subclasses should override this method to provide a smoother fade transition
7317 * when scrolling occurs.
7318 *
7319 * @return the intensity of the right fade as a float between 0.0f and 1.0f
7320 */
7321 protected float getRightFadingEdgeStrength() {
7322 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
7323 computeHorizontalScrollRange() ? 1.0f : 0.0f;
7324 }
7325
7326 /**
7327 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
7328 * scrollbar is not drawn by default.</p>
7329 *
7330 * @return true if the horizontal scrollbar should be painted, false
7331 * otherwise
7332 *
7333 * @see #setHorizontalScrollBarEnabled(boolean)
7334 */
7335 public boolean isHorizontalScrollBarEnabled() {
7336 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7337 }
7338
7339 /**
7340 * <p>Define whether the horizontal scrollbar should be drawn or not. The
7341 * scrollbar is not drawn by default.</p>
7342 *
7343 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
7344 * be painted
7345 *
7346 * @see #isHorizontalScrollBarEnabled()
7347 */
7348 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
7349 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
7350 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007351 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007352 recomputePadding();
7353 }
7354 }
7355
7356 /**
7357 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
7358 * scrollbar is not drawn by default.</p>
7359 *
7360 * @return true if the vertical scrollbar should be painted, false
7361 * otherwise
7362 *
7363 * @see #setVerticalScrollBarEnabled(boolean)
7364 */
7365 public boolean isVerticalScrollBarEnabled() {
7366 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
7367 }
7368
7369 /**
7370 * <p>Define whether the vertical scrollbar should be drawn or not. The
7371 * scrollbar is not drawn by default.</p>
7372 *
7373 * @param verticalScrollBarEnabled true if the vertical scrollbar should
7374 * be painted
7375 *
7376 * @see #isVerticalScrollBarEnabled()
7377 */
7378 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
7379 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
7380 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007381 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007382 recomputePadding();
7383 }
7384 }
7385
Adam Powell20232d02010-12-08 21:08:53 -08007386 /**
7387 * @hide
7388 */
7389 protected void recomputePadding() {
7390 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007391 }
Joe Malin32736f02011-01-19 16:14:20 -08007392
Mike Cleronfe81d382009-09-28 14:22:16 -07007393 /**
7394 * Define whether scrollbars will fade when the view is not scrolling.
Joe Malin32736f02011-01-19 16:14:20 -08007395 *
Mike Cleronfe81d382009-09-28 14:22:16 -07007396 * @param fadeScrollbars wheter to enable fading
Joe Malin32736f02011-01-19 16:14:20 -08007397 *
Mike Cleronfe81d382009-09-28 14:22:16 -07007398 */
7399 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
7400 initScrollCache();
7401 final ScrollabilityCache scrollabilityCache = mScrollCache;
7402 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07007403 if (fadeScrollbars) {
7404 scrollabilityCache.state = ScrollabilityCache.OFF;
7405 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07007406 scrollabilityCache.state = ScrollabilityCache.ON;
7407 }
7408 }
Joe Malin32736f02011-01-19 16:14:20 -08007409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007410 /**
Joe Malin32736f02011-01-19 16:14:20 -08007411 *
Mike Cleron52f0a642009-09-28 18:21:37 -07007412 * Returns true if scrollbars will fade when this view is not scrolling
Joe Malin32736f02011-01-19 16:14:20 -08007413 *
Mike Cleron52f0a642009-09-28 18:21:37 -07007414 * @return true if scrollbar fading is enabled
7415 */
7416 public boolean isScrollbarFadingEnabled() {
Joe Malin32736f02011-01-19 16:14:20 -08007417 return mScrollCache != null && mScrollCache.fadeScrollBars;
Mike Cleron52f0a642009-09-28 18:21:37 -07007418 }
Joe Malin32736f02011-01-19 16:14:20 -08007419
Mike Cleron52f0a642009-09-28 18:21:37 -07007420 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
7422 * inset. When inset, they add to the padding of the view. And the scrollbars
7423 * can be drawn inside the padding area or on the edge of the view. For example,
7424 * if a view has a background drawable and you want to draw the scrollbars
7425 * inside the padding specified by the drawable, you can use
7426 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
7427 * appear at the edge of the view, ignoring the padding, then you can use
7428 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
7429 * @param style the style of the scrollbars. Should be one of
7430 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
7431 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
7432 * @see #SCROLLBARS_INSIDE_OVERLAY
7433 * @see #SCROLLBARS_INSIDE_INSET
7434 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7435 * @see #SCROLLBARS_OUTSIDE_INSET
7436 */
7437 public void setScrollBarStyle(int style) {
7438 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
7439 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07007440 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 recomputePadding();
7442 }
7443 }
7444
7445 /**
7446 * <p>Returns the current scrollbar style.</p>
7447 * @return the current scrollbar style
7448 * @see #SCROLLBARS_INSIDE_OVERLAY
7449 * @see #SCROLLBARS_INSIDE_INSET
7450 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7451 * @see #SCROLLBARS_OUTSIDE_INSET
7452 */
7453 public int getScrollBarStyle() {
7454 return mViewFlags & SCROLLBARS_STYLE_MASK;
7455 }
7456
7457 /**
7458 * <p>Compute the horizontal range that the horizontal scrollbar
7459 * represents.</p>
7460 *
7461 * <p>The range is expressed in arbitrary units that must be the same as the
7462 * units used by {@link #computeHorizontalScrollExtent()} and
7463 * {@link #computeHorizontalScrollOffset()}.</p>
7464 *
7465 * <p>The default range is the drawing width of this view.</p>
7466 *
7467 * @return the total horizontal range represented by the horizontal
7468 * scrollbar
7469 *
7470 * @see #computeHorizontalScrollExtent()
7471 * @see #computeHorizontalScrollOffset()
7472 * @see android.widget.ScrollBarDrawable
7473 */
7474 protected int computeHorizontalScrollRange() {
7475 return getWidth();
7476 }
7477
7478 /**
7479 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7480 * within the horizontal range. This value is used to compute the position
7481 * of the thumb within the scrollbar's track.</p>
7482 *
7483 * <p>The range is expressed in arbitrary units that must be the same as the
7484 * units used by {@link #computeHorizontalScrollRange()} and
7485 * {@link #computeHorizontalScrollExtent()}.</p>
7486 *
7487 * <p>The default offset is the scroll offset of this view.</p>
7488 *
7489 * @return the horizontal offset of the scrollbar's thumb
7490 *
7491 * @see #computeHorizontalScrollRange()
7492 * @see #computeHorizontalScrollExtent()
7493 * @see android.widget.ScrollBarDrawable
7494 */
7495 protected int computeHorizontalScrollOffset() {
7496 return mScrollX;
7497 }
7498
7499 /**
7500 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7501 * within the horizontal range. This value is used to compute the length
7502 * of the thumb within the scrollbar's track.</p>
7503 *
7504 * <p>The range is expressed in arbitrary units that must be the same as the
7505 * units used by {@link #computeHorizontalScrollRange()} and
7506 * {@link #computeHorizontalScrollOffset()}.</p>
7507 *
7508 * <p>The default extent is the drawing width of this view.</p>
7509 *
7510 * @return the horizontal extent of the scrollbar's thumb
7511 *
7512 * @see #computeHorizontalScrollRange()
7513 * @see #computeHorizontalScrollOffset()
7514 * @see android.widget.ScrollBarDrawable
7515 */
7516 protected int computeHorizontalScrollExtent() {
7517 return getWidth();
7518 }
7519
7520 /**
7521 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7522 *
7523 * <p>The range is expressed in arbitrary units that must be the same as the
7524 * units used by {@link #computeVerticalScrollExtent()} and
7525 * {@link #computeVerticalScrollOffset()}.</p>
7526 *
7527 * @return the total vertical range represented by the vertical scrollbar
7528 *
7529 * <p>The default range is the drawing height of this view.</p>
7530 *
7531 * @see #computeVerticalScrollExtent()
7532 * @see #computeVerticalScrollOffset()
7533 * @see android.widget.ScrollBarDrawable
7534 */
7535 protected int computeVerticalScrollRange() {
7536 return getHeight();
7537 }
7538
7539 /**
7540 * <p>Compute the vertical offset of the vertical scrollbar's thumb
7541 * within the horizontal range. This value is used to compute the position
7542 * of the thumb within the scrollbar's track.</p>
7543 *
7544 * <p>The range is expressed in arbitrary units that must be the same as the
7545 * units used by {@link #computeVerticalScrollRange()} and
7546 * {@link #computeVerticalScrollExtent()}.</p>
7547 *
7548 * <p>The default offset is the scroll offset of this view.</p>
7549 *
7550 * @return the vertical offset of the scrollbar's thumb
7551 *
7552 * @see #computeVerticalScrollRange()
7553 * @see #computeVerticalScrollExtent()
7554 * @see android.widget.ScrollBarDrawable
7555 */
7556 protected int computeVerticalScrollOffset() {
7557 return mScrollY;
7558 }
7559
7560 /**
7561 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7562 * within the vertical range. This value is used to compute the length
7563 * of the thumb within the scrollbar's track.</p>
7564 *
7565 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08007566 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007567 * {@link #computeVerticalScrollOffset()}.</p>
7568 *
7569 * <p>The default extent is the drawing height of this view.</p>
7570 *
7571 * @return the vertical extent of the scrollbar's thumb
7572 *
7573 * @see #computeVerticalScrollRange()
7574 * @see #computeVerticalScrollOffset()
7575 * @see android.widget.ScrollBarDrawable
7576 */
7577 protected int computeVerticalScrollExtent() {
7578 return getHeight();
7579 }
7580
7581 /**
7582 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7583 * scrollbars are painted only if they have been awakened first.</p>
7584 *
7585 * @param canvas the canvas on which to draw the scrollbars
Joe Malin32736f02011-01-19 16:14:20 -08007586 *
Mike Cleronf116bf82009-09-27 19:14:12 -07007587 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08007589 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590 // scrollbars are drawn only when the animation is running
7591 final ScrollabilityCache cache = mScrollCache;
7592 if (cache != null) {
Joe Malin32736f02011-01-19 16:14:20 -08007593
Mike Cleronf116bf82009-09-27 19:14:12 -07007594 int state = cache.state;
Joe Malin32736f02011-01-19 16:14:20 -08007595
Mike Cleronf116bf82009-09-27 19:14:12 -07007596 if (state == ScrollabilityCache.OFF) {
7597 return;
7598 }
Joe Malin32736f02011-01-19 16:14:20 -08007599
Mike Cleronf116bf82009-09-27 19:14:12 -07007600 boolean invalidate = false;
Joe Malin32736f02011-01-19 16:14:20 -08007601
Mike Cleronf116bf82009-09-27 19:14:12 -07007602 if (state == ScrollabilityCache.FADING) {
7603 // We're fading -- get our fade interpolation
7604 if (cache.interpolatorValues == null) {
7605 cache.interpolatorValues = new float[1];
7606 }
Joe Malin32736f02011-01-19 16:14:20 -08007607
Mike Cleronf116bf82009-09-27 19:14:12 -07007608 float[] values = cache.interpolatorValues;
Joe Malin32736f02011-01-19 16:14:20 -08007609
Mike Cleronf116bf82009-09-27 19:14:12 -07007610 // Stops the animation if we're done
7611 if (cache.scrollBarInterpolator.timeToValues(values) ==
7612 Interpolator.Result.FREEZE_END) {
7613 cache.state = ScrollabilityCache.OFF;
7614 } else {
7615 cache.scrollBar.setAlpha(Math.round(values[0]));
7616 }
Joe Malin32736f02011-01-19 16:14:20 -08007617
7618 // This will make the scroll bars inval themselves after
Mike Cleronf116bf82009-09-27 19:14:12 -07007619 // drawing. We only want this when we're fading so that
7620 // we prevent excessive redraws
7621 invalidate = true;
7622 } else {
7623 // We're just on -- but we may have been fading before so
7624 // reset alpha
7625 cache.scrollBar.setAlpha(255);
7626 }
7627
Joe Malin32736f02011-01-19 16:14:20 -08007628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 final int viewFlags = mViewFlags;
7630
7631 final boolean drawHorizontalScrollBar =
7632 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7633 final boolean drawVerticalScrollBar =
7634 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7635 && !isVerticalScrollBarHidden();
7636
7637 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7638 final int width = mRight - mLeft;
7639 final int height = mBottom - mTop;
7640
7641 final ScrollBarDrawable scrollBar = cache.scrollBar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007642
Mike Reede8853fc2009-09-04 14:01:48 -04007643 final int scrollX = mScrollX;
7644 final int scrollY = mScrollY;
7645 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7646
Mike Cleronf116bf82009-09-27 19:14:12 -07007647 int left, top, right, bottom;
Joe Malin32736f02011-01-19 16:14:20 -08007648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 if (drawHorizontalScrollBar) {
Adam Powell3ba67742011-01-27 14:16:55 -08007650 int size = scrollBar.getSize(false);
7651 if (size <= 0) {
7652 size = cache.scrollBarSize;
7653 }
7654
Mike Cleronf116bf82009-09-27 19:14:12 -07007655 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04007656 computeHorizontalScrollOffset(),
7657 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04007658 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07007659 getVerticalScrollbarWidth() : 0;
Joe Malin32736f02011-01-19 16:14:20 -08007660 top = scrollY + height - size - (mUserPaddingBottom & inside);
Mike Cleronf116bf82009-09-27 19:14:12 -07007661 left = scrollX + (mPaddingLeft & inside);
7662 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7663 bottom = top + size;
7664 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7665 if (invalidate) {
7666 invalidate(left, top, right, bottom);
7667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 }
7669
7670 if (drawVerticalScrollBar) {
Adam Powell3ba67742011-01-27 14:16:55 -08007671 int size = scrollBar.getSize(true);
7672 if (size <= 0) {
7673 size = cache.scrollBarSize;
7674 }
7675
Mike Reede8853fc2009-09-04 14:01:48 -04007676 scrollBar.setParameters(computeVerticalScrollRange(),
7677 computeVerticalScrollOffset(),
7678 computeVerticalScrollExtent(), true);
Adam Powell20232d02010-12-08 21:08:53 -08007679 switch (mVerticalScrollbarPosition) {
7680 default:
7681 case SCROLLBAR_POSITION_DEFAULT:
7682 case SCROLLBAR_POSITION_RIGHT:
7683 left = scrollX + width - size - (mUserPaddingRight & inside);
7684 break;
7685 case SCROLLBAR_POSITION_LEFT:
7686 left = scrollX + (mUserPaddingLeft & inside);
7687 break;
7688 }
Mike Cleronf116bf82009-09-27 19:14:12 -07007689 top = scrollY + (mPaddingTop & inside);
7690 right = left + size;
7691 bottom = scrollY + height - (mUserPaddingBottom & inside);
7692 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7693 if (invalidate) {
7694 invalidate(left, top, right, bottom);
7695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007696 }
7697 }
7698 }
7699 }
Romain Guy8506ab42009-06-11 17:35:47 -07007700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007701 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007702 * 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 -08007703 * FastScroller is visible.
7704 * @return whether to temporarily hide the vertical scrollbar
7705 * @hide
7706 */
7707 protected boolean isVerticalScrollBarHidden() {
7708 return false;
7709 }
7710
7711 /**
7712 * <p>Draw the horizontal scrollbar if
7713 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7714 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 * @param canvas the canvas on which to draw the scrollbar
7716 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007717 *
7718 * @see #isHorizontalScrollBarEnabled()
7719 * @see #computeHorizontalScrollRange()
7720 * @see #computeHorizontalScrollExtent()
7721 * @see #computeHorizontalScrollOffset()
7722 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007723 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007724 */
Romain Guy8fb95422010-08-17 18:38:51 -07007725 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7726 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007727 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007728 scrollBar.draw(canvas);
7729 }
Mike Reede8853fc2009-09-04 14:01:48 -04007730
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007731 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007732 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7733 * returns true.</p>
7734 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 * @param canvas the canvas on which to draw the scrollbar
7736 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737 *
7738 * @see #isVerticalScrollBarEnabled()
7739 * @see #computeVerticalScrollRange()
7740 * @see #computeVerticalScrollExtent()
7741 * @see #computeVerticalScrollOffset()
7742 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007743 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007744 */
Romain Guy8fb95422010-08-17 18:38:51 -07007745 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7746 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007747 scrollBar.setBounds(l, t, r, b);
7748 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007749 }
7750
7751 /**
7752 * Implement this to do your drawing.
7753 *
7754 * @param canvas the canvas on which the background will be drawn
7755 */
7756 protected void onDraw(Canvas canvas) {
7757 }
7758
7759 /*
7760 * Caller is responsible for calling requestLayout if necessary.
7761 * (This allows addViewInLayout to not request a new layout.)
7762 */
7763 void assignParent(ViewParent parent) {
7764 if (mParent == null) {
7765 mParent = parent;
7766 } else if (parent == null) {
7767 mParent = null;
7768 } else {
7769 throw new RuntimeException("view " + this + " being added, but"
7770 + " it already has a parent");
7771 }
7772 }
7773
7774 /**
7775 * This is called when the view is attached to a window. At this point it
7776 * has a Surface and will start drawing. Note that this function is
7777 * guaranteed to be called before {@link #onDraw}, however it may be called
7778 * any time before the first onDraw -- including before or after
7779 * {@link #onMeasure}.
7780 *
7781 * @see #onDetachedFromWindow()
7782 */
7783 protected void onAttachedToWindow() {
7784 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7785 mParent.requestTransparentRegion(this);
7786 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007787 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7788 initialAwakenScrollBars();
7789 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7790 }
Chet Haasea9b61ac2010-12-20 07:40:25 -08007791 jumpDrawablesToCurrentState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007792 }
7793
7794 /**
7795 * This is called when the view is detached from a window. At this point it
7796 * no longer has a surface for drawing.
7797 *
7798 * @see #onAttachedToWindow()
7799 */
7800 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007801 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guy6c319ca2011-01-11 14:29:25 -08007802
Romain Guya440b002010-02-24 15:57:54 -08007803 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007804 removeLongPressCallback();
Adam Powell3cb8b632011-01-21 15:34:14 -08007805 removePerformClickCallback();
Romain Guy6c319ca2011-01-11 14:29:25 -08007806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 destroyDrawingCache();
Romain Guy6c319ca2011-01-11 14:29:25 -08007808
7809 if (mHardwareLayer != null) {
7810 mHardwareLayer.destroy();
7811 mHardwareLayer = null;
7812 }
Romain Guy8dd5b1e2011-01-14 17:28:51 -08007813
Chet Haasedaf98e92011-01-10 14:10:36 -08007814 if (mDisplayList != null) {
7815 mDisplayList.invalidate();
7816 }
7817
Romain Guy8dd5b1e2011-01-14 17:28:51 -08007818 if (mAttachInfo != null) {
7819 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
7820 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this);
7821 }
7822
Patrick Dubroyec84c3a2011-01-13 17:55:37 -08007823 mCurrentAnimation = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 }
7825
7826 /**
7827 * @return The number of times this view has been attached to a window
7828 */
7829 protected int getWindowAttachCount() {
7830 return mWindowAttachCount;
7831 }
7832
7833 /**
7834 * Retrieve a unique token identifying the window this view is attached to.
7835 * @return Return the window's token for use in
7836 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7837 */
7838 public IBinder getWindowToken() {
7839 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7840 }
7841
7842 /**
7843 * Retrieve a unique token identifying the top-level "real" window of
7844 * the window that this view is attached to. That is, this is like
7845 * {@link #getWindowToken}, except if the window this view in is a panel
7846 * window (attached to another containing window), then the token of
7847 * the containing window is returned instead.
7848 *
7849 * @return Returns the associated window token, either
7850 * {@link #getWindowToken()} or the containing window's token.
7851 */
7852 public IBinder getApplicationWindowToken() {
7853 AttachInfo ai = mAttachInfo;
7854 if (ai != null) {
7855 IBinder appWindowToken = ai.mPanelParentWindowToken;
7856 if (appWindowToken == null) {
7857 appWindowToken = ai.mWindowToken;
7858 }
7859 return appWindowToken;
7860 }
7861 return null;
7862 }
7863
7864 /**
7865 * Retrieve private session object this view hierarchy is using to
7866 * communicate with the window manager.
7867 * @return the session object to communicate with the window manager
7868 */
7869 /*package*/ IWindowSession getWindowSession() {
7870 return mAttachInfo != null ? mAttachInfo.mSession : null;
7871 }
7872
7873 /**
7874 * @param info the {@link android.view.View.AttachInfo} to associated with
7875 * this view
7876 */
7877 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7878 //System.out.println("Attached! " + this);
7879 mAttachInfo = info;
7880 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007881 // We will need to evaluate the drawable state at least once.
7882 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 if (mFloatingTreeObserver != null) {
7884 info.mTreeObserver.merge(mFloatingTreeObserver);
7885 mFloatingTreeObserver = null;
7886 }
7887 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7888 mAttachInfo.mScrollContainers.add(this);
7889 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7890 }
7891 performCollectViewAttributes(visibility);
7892 onAttachedToWindow();
7893 int vis = info.mWindowVisibility;
7894 if (vis != GONE) {
7895 onWindowVisibilityChanged(vis);
7896 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007897 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7898 // If nobody has evaluated the drawable state yet, then do it now.
7899 refreshDrawableState();
7900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007901 }
7902
7903 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007904 AttachInfo info = mAttachInfo;
7905 if (info != null) {
7906 int vis = info.mWindowVisibility;
7907 if (vis != GONE) {
7908 onWindowVisibilityChanged(GONE);
7909 }
7910 }
7911
7912 onDetachedFromWindow();
Romain Guy01d5edc2011-01-28 11:28:53 -08007913
7914 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007915 mAttachInfo.mScrollContainers.remove(this);
7916 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7917 }
Romain Guy01d5edc2011-01-28 11:28:53 -08007918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 mAttachInfo = null;
7920 }
7921
7922 /**
7923 * Store this view hierarchy's frozen state into the given container.
7924 *
7925 * @param container The SparseArray in which to save the view's state.
7926 *
7927 * @see #restoreHierarchyState
7928 * @see #dispatchSaveInstanceState
7929 * @see #onSaveInstanceState
7930 */
7931 public void saveHierarchyState(SparseArray<Parcelable> container) {
7932 dispatchSaveInstanceState(container);
7933 }
7934
7935 /**
7936 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7937 * May be overridden to modify how freezing happens to a view's children; for example, some
7938 * views may want to not store state for their children.
7939 *
7940 * @param container The SparseArray in which to save the view's state.
7941 *
7942 * @see #dispatchRestoreInstanceState
7943 * @see #saveHierarchyState
7944 * @see #onSaveInstanceState
7945 */
7946 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7947 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7948 mPrivateFlags &= ~SAVE_STATE_CALLED;
7949 Parcelable state = onSaveInstanceState();
7950 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7951 throw new IllegalStateException(
7952 "Derived class did not call super.onSaveInstanceState()");
7953 }
7954 if (state != null) {
7955 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7956 // + ": " + state);
7957 container.put(mID, state);
7958 }
7959 }
7960 }
7961
7962 /**
7963 * Hook allowing a view to generate a representation of its internal state
7964 * that can later be used to create a new instance with that same state.
7965 * This state should only contain information that is not persistent or can
7966 * not be reconstructed later. For example, you will never store your
7967 * current position on screen because that will be computed again when a
7968 * new instance of the view is placed in its view hierarchy.
7969 * <p>
7970 * Some examples of things you may store here: the current cursor position
7971 * in a text view (but usually not the text itself since that is stored in a
7972 * content provider or other persistent storage), the currently selected
7973 * item in a list view.
7974 *
7975 * @return Returns a Parcelable object containing the view's current dynamic
7976 * state, or null if there is nothing interesting to save. The
7977 * default implementation returns null.
7978 * @see #onRestoreInstanceState
7979 * @see #saveHierarchyState
7980 * @see #dispatchSaveInstanceState
7981 * @see #setSaveEnabled(boolean)
7982 */
7983 protected Parcelable onSaveInstanceState() {
7984 mPrivateFlags |= SAVE_STATE_CALLED;
7985 return BaseSavedState.EMPTY_STATE;
7986 }
7987
7988 /**
7989 * Restore this view hierarchy's frozen state from the given container.
7990 *
7991 * @param container The SparseArray which holds previously frozen states.
7992 *
7993 * @see #saveHierarchyState
7994 * @see #dispatchRestoreInstanceState
7995 * @see #onRestoreInstanceState
7996 */
7997 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7998 dispatchRestoreInstanceState(container);
7999 }
8000
8001 /**
8002 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
8003 * children. May be overridden to modify how restoreing happens to a view's children; for
8004 * example, some views may want to not store state for their children.
8005 *
8006 * @param container The SparseArray which holds previously saved state.
8007 *
8008 * @see #dispatchSaveInstanceState
8009 * @see #restoreHierarchyState
8010 * @see #onRestoreInstanceState
8011 */
8012 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
8013 if (mID != NO_ID) {
8014 Parcelable state = container.get(mID);
8015 if (state != null) {
8016 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
8017 // + ": " + state);
8018 mPrivateFlags &= ~SAVE_STATE_CALLED;
8019 onRestoreInstanceState(state);
8020 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
8021 throw new IllegalStateException(
8022 "Derived class did not call super.onRestoreInstanceState()");
8023 }
8024 }
8025 }
8026 }
8027
8028 /**
8029 * Hook allowing a view to re-apply a representation of its internal state that had previously
8030 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
8031 * null state.
8032 *
8033 * @param state The frozen state that had previously been returned by
8034 * {@link #onSaveInstanceState}.
8035 *
8036 * @see #onSaveInstanceState
8037 * @see #restoreHierarchyState
8038 * @see #dispatchRestoreInstanceState
8039 */
8040 protected void onRestoreInstanceState(Parcelable state) {
8041 mPrivateFlags |= SAVE_STATE_CALLED;
8042 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08008043 throw new IllegalArgumentException("Wrong state class, expecting View State but "
8044 + "received " + state.getClass().toString() + " instead. This usually happens "
Joe Malin32736f02011-01-19 16:14:20 -08008045 + "when two views of different type have the same id in the same hierarchy. "
8046 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
Romain Guy237c1ce2009-12-08 11:30:25 -08008047 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008048 }
8049 }
8050
8051 /**
8052 * <p>Return the time at which the drawing of the view hierarchy started.</p>
8053 *
8054 * @return the drawing start time in milliseconds
8055 */
8056 public long getDrawingTime() {
8057 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
8058 }
8059
8060 /**
8061 * <p>Enables or disables the duplication of the parent's state into this view. When
8062 * duplication is enabled, this view gets its drawable state from its parent rather
8063 * than from its own internal properties.</p>
8064 *
8065 * <p>Note: in the current implementation, setting this property to true after the
8066 * view was added to a ViewGroup might have no effect at all. This property should
8067 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
8068 *
8069 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
8070 * property is enabled, an exception will be thrown.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008071 *
Gilles Debunnefb817032011-01-13 13:52:49 -08008072 * <p>Note: if the child view uses and updates additionnal states which are unknown to the
8073 * parent, these states should not be affected by this method.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 *
8075 * @param enabled True to enable duplication of the parent's drawable state, false
8076 * to disable it.
8077 *
8078 * @see #getDrawableState()
8079 * @see #isDuplicateParentStateEnabled()
8080 */
8081 public void setDuplicateParentStateEnabled(boolean enabled) {
8082 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
8083 }
8084
8085 /**
8086 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
8087 *
8088 * @return True if this view's drawable state is duplicated from the parent,
8089 * false otherwise
8090 *
8091 * @see #getDrawableState()
8092 * @see #setDuplicateParentStateEnabled(boolean)
8093 */
8094 public boolean isDuplicateParentStateEnabled() {
8095 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
8096 }
8097
8098 /**
Romain Guy171c5922011-01-06 10:04:23 -08008099 * <p>Specifies the type of layer backing this view. The layer can be
8100 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
8101 * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008102 *
Romain Guy171c5922011-01-06 10:04:23 -08008103 * <p>A layer is associated with an optional {@link android.graphics.Paint}
8104 * instance that controls how the layer is composed on screen. The following
8105 * properties of the paint are taken into account when composing the layer:</p>
8106 * <ul>
8107 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
8108 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
8109 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
8110 * </ul>
Joe Malin32736f02011-01-19 16:14:20 -08008111 *
Romain Guy171c5922011-01-06 10:04:23 -08008112 * <p>If this view has an alpha value set to < 1.0 by calling
8113 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
8114 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
8115 * equivalent to setting a hardware layer on this view and providing a paint with
8116 * the desired alpha value.<p>
Joe Malin32736f02011-01-19 16:14:20 -08008117 *
Romain Guy171c5922011-01-06 10:04:23 -08008118 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
8119 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
8120 * for more information on when and how to use layers.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008121 *
Romain Guy171c5922011-01-06 10:04:23 -08008122 * @param layerType The ype of layer to use with this view, must be one of
8123 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
8124 * {@link #LAYER_TYPE_HARDWARE}
8125 * @param paint The paint used to compose the layer. This argument is optional
8126 * and can be null. It is ignored when the layer type is
8127 * {@link #LAYER_TYPE_NONE}
Joe Malin32736f02011-01-19 16:14:20 -08008128 *
8129 * @see #getLayerType()
Romain Guy171c5922011-01-06 10:04:23 -08008130 * @see #LAYER_TYPE_NONE
8131 * @see #LAYER_TYPE_SOFTWARE
8132 * @see #LAYER_TYPE_HARDWARE
Joe Malin32736f02011-01-19 16:14:20 -08008133 * @see #setAlpha(float)
8134 *
Romain Guy171c5922011-01-06 10:04:23 -08008135 * @attr ref android.R.styleable#View_layerType
8136 */
8137 public void setLayerType(int layerType, Paint paint) {
8138 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
Joe Malin32736f02011-01-19 16:14:20 -08008139 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
Romain Guy171c5922011-01-06 10:04:23 -08008140 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
8141 }
Chet Haasedaf98e92011-01-10 14:10:36 -08008142
Romain Guyd6cd5722011-01-17 14:42:41 -08008143 if (layerType == mLayerType) {
8144 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
8145 mLayerPaint = paint == null ? new Paint() : paint;
Romain Guy0fd89bf2011-01-26 15:41:30 -08008146 invalidateParentCaches();
8147 invalidate(true);
Romain Guyd6cd5722011-01-17 14:42:41 -08008148 }
8149 return;
8150 }
Romain Guy171c5922011-01-06 10:04:23 -08008151
8152 // Destroy any previous software drawing cache if needed
Romain Guy6c319ca2011-01-11 14:29:25 -08008153 switch (mLayerType) {
8154 case LAYER_TYPE_SOFTWARE:
8155 if (mDrawingCache != null) {
8156 mDrawingCache.recycle();
8157 mDrawingCache = null;
8158 }
Joe Malin32736f02011-01-19 16:14:20 -08008159
Romain Guy6c319ca2011-01-11 14:29:25 -08008160 if (mUnscaledDrawingCache != null) {
8161 mUnscaledDrawingCache.recycle();
8162 mUnscaledDrawingCache = null;
8163 }
8164 break;
8165 case LAYER_TYPE_HARDWARE:
8166 if (mHardwareLayer != null) {
8167 mHardwareLayer.destroy();
8168 mHardwareLayer = null;
8169 }
8170 break;
8171 default:
8172 break;
Romain Guy171c5922011-01-06 10:04:23 -08008173 }
8174
8175 mLayerType = layerType;
Romain Guyd6cd5722011-01-17 14:42:41 -08008176 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : (paint == null ? new Paint() : paint);
Romain Guy171c5922011-01-06 10:04:23 -08008177
Romain Guy0fd89bf2011-01-26 15:41:30 -08008178 invalidateParentCaches();
8179 invalidate(true);
Romain Guy171c5922011-01-06 10:04:23 -08008180 }
8181
8182 /**
8183 * Indicates what type of layer is currently associated with this view. By default
8184 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
8185 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
8186 * for more information on the different types of layers.
Joe Malin32736f02011-01-19 16:14:20 -08008187 *
Romain Guy171c5922011-01-06 10:04:23 -08008188 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
8189 * {@link #LAYER_TYPE_HARDWARE}
Joe Malin32736f02011-01-19 16:14:20 -08008190 *
8191 * @see #setLayerType(int, android.graphics.Paint)
Romain Guy171c5922011-01-06 10:04:23 -08008192 * @see #LAYER_TYPE_NONE
8193 * @see #LAYER_TYPE_SOFTWARE
8194 * @see #LAYER_TYPE_HARDWARE
8195 */
8196 public int getLayerType() {
8197 return mLayerType;
8198 }
Joe Malin32736f02011-01-19 16:14:20 -08008199
Romain Guy6c319ca2011-01-11 14:29:25 -08008200 /**
8201 * <p>Returns a hardware layer that can be used to draw this view again
8202 * without executing its draw method.</p>
8203 *
8204 * @return A HardwareLayer ready to render, or null if an error occurred.
8205 */
Romain Guy5e7f7662011-01-24 22:35:56 -08008206 HardwareLayer getHardwareLayer() {
Romain Guy6c319ca2011-01-11 14:29:25 -08008207 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8208 return null;
8209 }
8210
8211 final int width = mRight - mLeft;
8212 final int height = mBottom - mTop;
Joe Malin32736f02011-01-19 16:14:20 -08008213
Romain Guy6c319ca2011-01-11 14:29:25 -08008214 if (width == 0 || height == 0) {
8215 return null;
8216 }
8217
8218 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
8219 if (mHardwareLayer == null) {
8220 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
8221 width, height, isOpaque());
8222 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
8223 mHardwareLayer.resize(width, height);
8224 }
8225
Romain Guy5e7f7662011-01-24 22:35:56 -08008226 Canvas currentCanvas = mAttachInfo.mHardwareCanvas;
8227 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
8228 mAttachInfo.mHardwareCanvas = canvas;
Romain Guy6c319ca2011-01-11 14:29:25 -08008229 try {
8230 canvas.setViewport(width, height);
Romain Guy7d7b5492011-01-24 16:33:45 -08008231 // TODO: We should pass the dirty rect
8232 canvas.onPreDraw(null);
Romain Guy6c319ca2011-01-11 14:29:25 -08008233
Romain Guy4f09f542011-01-26 22:41:43 -08008234 final int restoreCount = canvas.save();
8235
Romain Guy6c319ca2011-01-11 14:29:25 -08008236 computeScroll();
8237 canvas.translate(-mScrollX, -mScrollY);
8238
Romain Guy6c319ca2011-01-11 14:29:25 -08008239 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Joe Malin32736f02011-01-19 16:14:20 -08008240
Romain Guy6c319ca2011-01-11 14:29:25 -08008241 // Fast path for layouts with no backgrounds
8242 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8243 mPrivateFlags &= ~DIRTY_MASK;
8244 dispatchDraw(canvas);
8245 } else {
8246 draw(canvas);
8247 }
Joe Malin32736f02011-01-19 16:14:20 -08008248
Romain Guy6c319ca2011-01-11 14:29:25 -08008249 canvas.restoreToCount(restoreCount);
8250 } finally {
8251 canvas.onPostDraw();
Romain Guy5e7f7662011-01-24 22:35:56 -08008252 mHardwareLayer.end(currentCanvas);
8253 mAttachInfo.mHardwareCanvas = currentCanvas;
Romain Guy6c319ca2011-01-11 14:29:25 -08008254 }
8255 }
8256
8257 return mHardwareLayer;
8258 }
Romain Guy171c5922011-01-06 10:04:23 -08008259
8260 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008261 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
8262 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
8263 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
8264 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
8265 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
8266 * null.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008267 *
Romain Guy171c5922011-01-06 10:04:23 -08008268 * <p>Enabling the drawing cache is similar to
8269 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
Chet Haasedaf98e92011-01-10 14:10:36 -08008270 * acceleration is turned off. When hardware acceleration is turned on, enabling the
8271 * drawing cache has no effect on rendering because the system uses a different mechanism
8272 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
8273 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
8274 * for information on how to enable software and hardware layers.</p>
8275 *
8276 * <p>This API can be used to manually generate
8277 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
8278 * {@link #getDrawingCache()}.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008279 *
8280 * @param enabled true to enable the drawing cache, false otherwise
8281 *
8282 * @see #isDrawingCacheEnabled()
8283 * @see #getDrawingCache()
8284 * @see #buildDrawingCache()
Joe Malin32736f02011-01-19 16:14:20 -08008285 * @see #setLayerType(int, android.graphics.Paint)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008286 */
8287 public void setDrawingCacheEnabled(boolean enabled) {
8288 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
8289 }
8290
8291 /**
8292 * <p>Indicates whether the drawing cache is enabled for this view.</p>
8293 *
8294 * @return true if the drawing cache is enabled
8295 *
8296 * @see #setDrawingCacheEnabled(boolean)
8297 * @see #getDrawingCache()
8298 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07008299 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008300 public boolean isDrawingCacheEnabled() {
8301 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
8302 }
8303
8304 /**
Chet Haasedaf98e92011-01-10 14:10:36 -08008305 * Debugging utility which recursively outputs the dirty state of a view and its
8306 * descendants.
Joe Malin32736f02011-01-19 16:14:20 -08008307 *
Chet Haasedaf98e92011-01-10 14:10:36 -08008308 * @hide
8309 */
8310 public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
8311 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
8312 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
8313 (mPrivateFlags & View.DRAWING_CACHE_VALID) +
8314 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
8315 if (clear) {
8316 mPrivateFlags &= clearMask;
8317 }
8318 if (this instanceof ViewGroup) {
8319 ViewGroup parent = (ViewGroup) this;
8320 final int count = parent.getChildCount();
8321 for (int i = 0; i < count; i++) {
Romain Guy7d7b5492011-01-24 16:33:45 -08008322 final View child = parent.getChildAt(i);
Chet Haasedaf98e92011-01-10 14:10:36 -08008323 child.outputDirtyFlags(indent + " ", clear, clearMask);
8324 }
8325 }
8326 }
8327
8328 /**
8329 * This method is used by ViewGroup to cause its children to restore or recreate their
8330 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
8331 * to recreate its own display list, which would happen if it went through the normal
8332 * draw/dispatchDraw mechanisms.
8333 *
8334 * @hide
8335 */
8336 protected void dispatchGetDisplayList() {}
Chet Haasef4ac5472011-01-27 10:30:25 -08008337
8338 /**
8339 * A view that is not attached or hardware accelerated cannot create a display list.
8340 * This method checks these conditions and returns the appropriate result.
8341 *
8342 * @return true if view has the ability to create a display list, false otherwise.
8343 *
8344 * @hide
8345 */
8346 public boolean canHaveDisplayList() {
8347 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8348 return false;
8349 }
8350 return true;
8351 }
Joe Malin32736f02011-01-19 16:14:20 -08008352
Chet Haasedaf98e92011-01-10 14:10:36 -08008353 /**
Romain Guyb051e892010-09-28 19:09:36 -07008354 * <p>Returns a display list that can be used to draw this view again
8355 * without executing its draw method.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008356 *
Romain Guyb051e892010-09-28 19:09:36 -07008357 * @return A DisplayList ready to replay, or null if caching is not enabled.
Chet Haasedaf98e92011-01-10 14:10:36 -08008358 *
8359 * @hide
Romain Guyb051e892010-09-28 19:09:36 -07008360 */
Chet Haasedaf98e92011-01-10 14:10:36 -08008361 public DisplayList getDisplayList() {
Chet Haasef4ac5472011-01-27 10:30:25 -08008362 if (!canHaveDisplayList()) {
Romain Guyb051e892010-09-28 19:09:36 -07008363 return null;
8364 }
8365
Chet Haasedaf98e92011-01-10 14:10:36 -08008366 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
8367 mDisplayList == null || !mDisplayList.isValid() ||
8368 mRecreateDisplayList)) {
8369 // Don't need to recreate the display list, just need to tell our
8370 // children to restore/recreate theirs
8371 if (mDisplayList != null && mDisplayList.isValid() &&
8372 !mRecreateDisplayList) {
8373 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8374 mPrivateFlags &= ~DIRTY_MASK;
8375 dispatchGetDisplayList();
8376
8377 return mDisplayList;
8378 }
8379
8380 // If we got here, we're recreating it. Mark it as such to ensure that
8381 // we copy in child display lists into ours in drawChild()
8382 mRecreateDisplayList = true;
Chet Haase9e90a992011-01-04 16:23:21 -08008383 if (mDisplayList == null) {
Chet Haasedaf98e92011-01-10 14:10:36 -08008384 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this);
8385 // If we're creating a new display list, make sure our parent gets invalidated
8386 // since they will need to recreate their display list to account for this
8387 // new child display list.
Romain Guy0fd89bf2011-01-26 15:41:30 -08008388 invalidateParentCaches();
Chet Haase9e90a992011-01-04 16:23:21 -08008389 }
Romain Guyb051e892010-09-28 19:09:36 -07008390
8391 final HardwareCanvas canvas = mDisplayList.start();
8392 try {
8393 int width = mRight - mLeft;
8394 int height = mBottom - mTop;
8395
8396 canvas.setViewport(width, height);
Romain Guy7d7b5492011-01-24 16:33:45 -08008397 // The dirty rect should always be null for a display list
8398 canvas.onPreDraw(null);
Romain Guyb051e892010-09-28 19:09:36 -07008399
8400 final int restoreCount = canvas.save();
8401
Chet Haasedaf98e92011-01-10 14:10:36 -08008402 computeScroll();
8403 canvas.translate(-mScrollX, -mScrollY);
Romain Guy2fe9a8f2010-10-04 20:17:01 -07008404 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Joe Malin32736f02011-01-19 16:14:20 -08008405
Romain Guyb051e892010-09-28 19:09:36 -07008406 // Fast path for layouts with no backgrounds
8407 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8408 mPrivateFlags &= ~DIRTY_MASK;
8409 dispatchDraw(canvas);
8410 } else {
8411 draw(canvas);
8412 }
Joe Malin32736f02011-01-19 16:14:20 -08008413
Romain Guyb051e892010-09-28 19:09:36 -07008414 canvas.restoreToCount(restoreCount);
8415 } finally {
8416 canvas.onPostDraw();
8417
8418 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07008419 }
Chet Haase77785f92011-01-25 23:22:09 -08008420 } else {
8421 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8422 mPrivateFlags &= ~DIRTY_MASK;
Romain Guyb051e892010-09-28 19:09:36 -07008423 }
8424
8425 return mDisplayList;
8426 }
8427
8428 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008429 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008430 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008431 * @return A non-scaled bitmap representing this view or null if cache is disabled.
Joe Malin32736f02011-01-19 16:14:20 -08008432 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008433 * @see #getDrawingCache(boolean)
8434 */
8435 public Bitmap getDrawingCache() {
8436 return getDrawingCache(false);
8437 }
8438
8439 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008440 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
8441 * is null when caching is disabled. If caching is enabled and the cache is not ready,
8442 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
8443 * draw from the cache when the cache is enabled. To benefit from the cache, you must
8444 * request the drawing cache by calling this method and draw it on screen if the
8445 * returned bitmap is not null.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008446 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008447 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8448 * this method will create a bitmap of the same size as this view. Because this bitmap
8449 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8450 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8451 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8452 * size than the view. This implies that your application must be able to handle this
8453 * size.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008454 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008455 * @param autoScale Indicates whether the generated bitmap should be scaled based on
8456 * the current density of the screen when the application is in compatibility
8457 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008459 * @return A bitmap representing this view or null if cache is disabled.
Joe Malin32736f02011-01-19 16:14:20 -08008460 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008461 * @see #setDrawingCacheEnabled(boolean)
8462 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07008463 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008464 * @see #destroyDrawingCache()
8465 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008466 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008467 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8468 return null;
8469 }
8470 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008471 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008472 }
Romain Guy02890fd2010-08-06 17:58:44 -07008473 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008474 }
8475
8476 /**
8477 * <p>Frees the resources used by the drawing cache. If you call
8478 * {@link #buildDrawingCache()} manually without calling
8479 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8480 * should cleanup the cache with this method afterwards.</p>
8481 *
8482 * @see #setDrawingCacheEnabled(boolean)
8483 * @see #buildDrawingCache()
8484 * @see #getDrawingCache()
8485 */
8486 public void destroyDrawingCache() {
8487 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008488 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008489 mDrawingCache = null;
8490 }
Romain Guyfbd8f692009-06-26 14:51:58 -07008491 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008492 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07008493 mUnscaledDrawingCache = null;
8494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008495 }
8496
8497 /**
8498 * Setting a solid background color for the drawing cache's bitmaps will improve
8499 * perfromance and memory usage. Note, though that this should only be used if this
8500 * view will always be drawn on top of a solid color.
8501 *
8502 * @param color The background color to use for the drawing cache's bitmap
8503 *
8504 * @see #setDrawingCacheEnabled(boolean)
8505 * @see #buildDrawingCache()
8506 * @see #getDrawingCache()
8507 */
8508 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08008509 if (color != mDrawingCacheBackgroundColor) {
8510 mDrawingCacheBackgroundColor = color;
8511 mPrivateFlags &= ~DRAWING_CACHE_VALID;
8512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008513 }
8514
8515 /**
8516 * @see #setDrawingCacheBackgroundColor(int)
8517 *
8518 * @return The background color to used for the drawing cache's bitmap
8519 */
8520 public int getDrawingCacheBackgroundColor() {
8521 return mDrawingCacheBackgroundColor;
8522 }
8523
8524 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008525 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008526 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008527 * @see #buildDrawingCache(boolean)
8528 */
8529 public void buildDrawingCache() {
8530 buildDrawingCache(false);
8531 }
8532
8533 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008534 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
8535 *
8536 * <p>If you call {@link #buildDrawingCache()} manually without calling
8537 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8538 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008539 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008540 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8541 * this method will create a bitmap of the same size as this view. Because this bitmap
8542 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8543 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8544 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8545 * size than the view. This implies that your application must be able to handle this
8546 * size.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008547 *
Romain Guy0d9275e2010-10-26 14:22:30 -07008548 * <p>You should avoid calling this method when hardware acceleration is enabled. If
8549 * you do not need the drawing cache bitmap, calling this method will increase memory
Joe Malin32736f02011-01-19 16:14:20 -08008550 * usage and cause the view to be rendered in software once, thus negatively impacting
Romain Guy0d9275e2010-10-26 14:22:30 -07008551 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552 *
8553 * @see #getDrawingCache()
8554 * @see #destroyDrawingCache()
8555 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008556 public void buildDrawingCache(boolean autoScale) {
8557 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07008558 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008559
8560 if (ViewDebug.TRACE_HIERARCHY) {
8561 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
8562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563
Romain Guy8506ab42009-06-11 17:35:47 -07008564 int width = mRight - mLeft;
8565 int height = mBottom - mTop;
8566
8567 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07008568 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07008569
Romain Guye1123222009-06-29 14:24:56 -07008570 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008571 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
8572 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07008573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574
8575 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07008576 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08008577 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008578
8579 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07008580 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08008581 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
8583 destroyDrawingCache();
8584 return;
8585 }
8586
8587 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07008588 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008589
8590 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 Bitmap.Config quality;
8592 if (!opaque) {
8593 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
8594 case DRAWING_CACHE_QUALITY_AUTO:
8595 quality = Bitmap.Config.ARGB_8888;
8596 break;
8597 case DRAWING_CACHE_QUALITY_LOW:
8598 quality = Bitmap.Config.ARGB_4444;
8599 break;
8600 case DRAWING_CACHE_QUALITY_HIGH:
8601 quality = Bitmap.Config.ARGB_8888;
8602 break;
8603 default:
8604 quality = Bitmap.Config.ARGB_8888;
8605 break;
8606 }
8607 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07008608 // Optimization for translucent windows
8609 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08008610 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 }
8612
8613 // Try to cleanup memory
8614 if (bitmap != null) bitmap.recycle();
8615
8616 try {
8617 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07008618 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07008619 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07008620 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008621 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07008622 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008623 }
Adam Powell26153a32010-11-08 15:22:27 -08008624 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625 } catch (OutOfMemoryError e) {
8626 // If there is not enough memory to create the bitmap cache, just
8627 // ignore the issue as bitmap caches are not required to draw the
8628 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07008629 if (autoScale) {
8630 mDrawingCache = null;
8631 } else {
8632 mUnscaledDrawingCache = null;
8633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634 return;
8635 }
8636
8637 clear = drawingCacheBackgroundColor != 0;
8638 }
8639
8640 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 if (attachInfo != null) {
8642 canvas = attachInfo.mCanvas;
8643 if (canvas == null) {
8644 canvas = new Canvas();
8645 }
8646 canvas.setBitmap(bitmap);
8647 // Temporarily clobber the cached Canvas in case one of our children
8648 // is also using a drawing cache. Without this, the children would
8649 // steal the canvas by attaching their own bitmap to it and bad, bad
8650 // thing would happen (invisible views, corrupted drawings, etc.)
8651 attachInfo.mCanvas = null;
8652 } else {
8653 // This case should hopefully never or seldom happen
8654 canvas = new Canvas(bitmap);
8655 }
8656
8657 if (clear) {
8658 bitmap.eraseColor(drawingCacheBackgroundColor);
8659 }
8660
8661 computeScroll();
8662 final int restoreCount = canvas.save();
Joe Malin32736f02011-01-19 16:14:20 -08008663
Romain Guye1123222009-06-29 14:24:56 -07008664 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008665 final float scale = attachInfo.mApplicationScale;
8666 canvas.scale(scale, scale);
8667 }
Joe Malin32736f02011-01-19 16:14:20 -08008668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008669 canvas.translate(-mScrollX, -mScrollY);
8670
Romain Guy5bcdff42009-05-14 21:27:18 -07008671 mPrivateFlags |= DRAWN;
Romain Guy171c5922011-01-06 10:04:23 -08008672 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
8673 mLayerType != LAYER_TYPE_NONE) {
Romain Guy0d9275e2010-10-26 14:22:30 -07008674 mPrivateFlags |= DRAWING_CACHE_VALID;
8675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008676
8677 // Fast path for layouts with no backgrounds
8678 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8679 if (ViewDebug.TRACE_HIERARCHY) {
8680 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8681 }
Romain Guy5bcdff42009-05-14 21:27:18 -07008682 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008683 dispatchDraw(canvas);
8684 } else {
8685 draw(canvas);
8686 }
8687
8688 canvas.restoreToCount(restoreCount);
8689
8690 if (attachInfo != null) {
8691 // Restore the cached Canvas for our siblings
8692 attachInfo.mCanvas = canvas;
8693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008694 }
8695 }
8696
8697 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008698 * Create a snapshot of the view into a bitmap. We should probably make
8699 * some form of this public, but should think about the API.
8700 */
Romain Guy223ff5c2010-03-02 17:07:47 -08008701 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008702 int width = mRight - mLeft;
8703 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008704
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008705 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07008706 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008707 width = (int) ((width * scale) + 0.5f);
8708 height = (int) ((height * scale) + 0.5f);
Joe Malin32736f02011-01-19 16:14:20 -08008709
Romain Guy8c11e312009-09-14 15:15:30 -07008710 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008711 if (bitmap == null) {
8712 throw new OutOfMemoryError();
8713 }
8714
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008715 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Joe Malin32736f02011-01-19 16:14:20 -08008716
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008717 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008718 if (attachInfo != null) {
8719 canvas = attachInfo.mCanvas;
8720 if (canvas == null) {
8721 canvas = new Canvas();
8722 }
8723 canvas.setBitmap(bitmap);
8724 // Temporarily clobber the cached Canvas in case one of our children
8725 // is also using a drawing cache. Without this, the children would
8726 // steal the canvas by attaching their own bitmap to it and bad, bad
8727 // things would happen (invisible views, corrupted drawings, etc.)
8728 attachInfo.mCanvas = null;
8729 } else {
8730 // This case should hopefully never or seldom happen
8731 canvas = new Canvas(bitmap);
8732 }
8733
Romain Guy5bcdff42009-05-14 21:27:18 -07008734 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008735 bitmap.eraseColor(backgroundColor);
8736 }
8737
8738 computeScroll();
8739 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008740 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008741 canvas.translate(-mScrollX, -mScrollY);
8742
Romain Guy5bcdff42009-05-14 21:27:18 -07008743 // Temporarily remove the dirty mask
8744 int flags = mPrivateFlags;
8745 mPrivateFlags &= ~DIRTY_MASK;
8746
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008747 // Fast path for layouts with no backgrounds
8748 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8749 dispatchDraw(canvas);
8750 } else {
8751 draw(canvas);
8752 }
8753
Romain Guy5bcdff42009-05-14 21:27:18 -07008754 mPrivateFlags = flags;
8755
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008756 canvas.restoreToCount(restoreCount);
8757
8758 if (attachInfo != null) {
8759 // Restore the cached Canvas for our siblings
8760 attachInfo.mCanvas = canvas;
8761 }
Romain Guy8506ab42009-06-11 17:35:47 -07008762
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008763 return bitmap;
8764 }
8765
8766 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008767 * Indicates whether this View is currently in edit mode. A View is usually
8768 * in edit mode when displayed within a developer tool. For instance, if
8769 * this View is being drawn by a visual user interface builder, this method
8770 * should return true.
8771 *
8772 * Subclasses should check the return value of this method to provide
8773 * different behaviors if their normal behavior might interfere with the
8774 * host environment. For instance: the class spawns a thread in its
8775 * constructor, the drawing code relies on device-specific features, etc.
8776 *
8777 * This method is usually checked in the drawing code of custom widgets.
8778 *
8779 * @return True if this View is in edit mode, false otherwise.
8780 */
8781 public boolean isInEditMode() {
8782 return false;
8783 }
8784
8785 /**
8786 * If the View draws content inside its padding and enables fading edges,
8787 * it needs to support padding offsets. Padding offsets are added to the
8788 * fading edges to extend the length of the fade so that it covers pixels
8789 * drawn inside the padding.
8790 *
8791 * Subclasses of this class should override this method if they need
8792 * to draw content inside the padding.
8793 *
8794 * @return True if padding offset must be applied, false otherwise.
8795 *
8796 * @see #getLeftPaddingOffset()
8797 * @see #getRightPaddingOffset()
8798 * @see #getTopPaddingOffset()
8799 * @see #getBottomPaddingOffset()
8800 *
8801 * @since CURRENT
8802 */
8803 protected boolean isPaddingOffsetRequired() {
8804 return false;
8805 }
8806
8807 /**
8808 * Amount by which to extend the left fading region. Called only when
8809 * {@link #isPaddingOffsetRequired()} returns true.
8810 *
8811 * @return The left padding offset in pixels.
8812 *
8813 * @see #isPaddingOffsetRequired()
8814 *
8815 * @since CURRENT
8816 */
8817 protected int getLeftPaddingOffset() {
8818 return 0;
8819 }
8820
8821 /**
8822 * Amount by which to extend the right fading region. Called only when
8823 * {@link #isPaddingOffsetRequired()} returns true.
8824 *
8825 * @return The right padding offset in pixels.
8826 *
8827 * @see #isPaddingOffsetRequired()
8828 *
8829 * @since CURRENT
8830 */
8831 protected int getRightPaddingOffset() {
8832 return 0;
8833 }
8834
8835 /**
8836 * Amount by which to extend the top fading region. Called only when
8837 * {@link #isPaddingOffsetRequired()} returns true.
8838 *
8839 * @return The top padding offset in pixels.
8840 *
8841 * @see #isPaddingOffsetRequired()
8842 *
8843 * @since CURRENT
8844 */
8845 protected int getTopPaddingOffset() {
8846 return 0;
8847 }
8848
8849 /**
8850 * Amount by which to extend the bottom fading region. Called only when
8851 * {@link #isPaddingOffsetRequired()} returns true.
8852 *
8853 * @return The bottom padding offset in pixels.
8854 *
8855 * @see #isPaddingOffsetRequired()
8856 *
8857 * @since CURRENT
8858 */
8859 protected int getBottomPaddingOffset() {
8860 return 0;
8861 }
8862
8863 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008864 * <p>Indicates whether this view is attached to an hardware accelerated
8865 * window or not.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008866 *
Romain Guy2bffd262010-09-12 17:40:02 -07008867 * <p>Even if this method returns true, it does not mean that every call
8868 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8869 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8870 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8871 * window is hardware accelerated,
8872 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8873 * return false, and this method will return true.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008874 *
Romain Guy2bffd262010-09-12 17:40:02 -07008875 * @return True if the view is attached to a window and the window is
8876 * hardware accelerated; false in any other case.
8877 */
8878 public boolean isHardwareAccelerated() {
8879 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8880 }
Joe Malin32736f02011-01-19 16:14:20 -08008881
Romain Guy2bffd262010-09-12 17:40:02 -07008882 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 * Manually render this view (and all of its children) to the given Canvas.
8884 * The view must have already done a full layout before this function is
Chet Haasec75ec332010-12-17 07:44:30 -08008885 * called. When implementing a view, implement {@link #onDraw} instead of
8886 * overriding this method. If you do need to override this method, call
8887 * the superclass version.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008888 *
8889 * @param canvas The Canvas to which the View is rendered.
8890 */
8891 public void draw(Canvas canvas) {
8892 if (ViewDebug.TRACE_HIERARCHY) {
8893 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8894 }
8895
Romain Guy5bcdff42009-05-14 21:27:18 -07008896 final int privateFlags = mPrivateFlags;
8897 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8898 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8899 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008901 /*
8902 * Draw traversal performs several drawing steps which must be executed
8903 * in the appropriate order:
8904 *
8905 * 1. Draw the background
8906 * 2. If necessary, save the canvas' layers to prepare for fading
8907 * 3. Draw view's content
8908 * 4. Draw children
8909 * 5. If necessary, draw the fading edges and restore layers
8910 * 6. Draw decorations (scrollbars for instance)
8911 */
8912
8913 // Step 1, draw the background, if needed
8914 int saveCount;
8915
Romain Guy24443ea2009-05-11 11:56:30 -07008916 if (!dirtyOpaque) {
8917 final Drawable background = mBGDrawable;
8918 if (background != null) {
8919 final int scrollX = mScrollX;
8920 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008921
Romain Guy24443ea2009-05-11 11:56:30 -07008922 if (mBackgroundSizeChanged) {
8923 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8924 mBackgroundSizeChanged = false;
8925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926
Romain Guy24443ea2009-05-11 11:56:30 -07008927 if ((scrollX | scrollY) == 0) {
8928 background.draw(canvas);
8929 } else {
8930 canvas.translate(scrollX, scrollY);
8931 background.draw(canvas);
8932 canvas.translate(-scrollX, -scrollY);
8933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 }
8935 }
8936
8937 // skip step 2 & 5 if possible (common case)
8938 final int viewFlags = mViewFlags;
8939 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8940 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8941 if (!verticalEdges && !horizontalEdges) {
8942 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008943 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944
8945 // Step 4, draw the children
8946 dispatchDraw(canvas);
8947
8948 // Step 6, draw decorations (scrollbars)
8949 onDrawScrollBars(canvas);
8950
8951 // we're done...
8952 return;
8953 }
8954
8955 /*
8956 * Here we do the full fledged routine...
8957 * (this is an uncommon case where speed matters less,
8958 * this is why we repeat some of the tests that have been
8959 * done above)
8960 */
8961
8962 boolean drawTop = false;
8963 boolean drawBottom = false;
8964 boolean drawLeft = false;
8965 boolean drawRight = false;
8966
8967 float topFadeStrength = 0.0f;
8968 float bottomFadeStrength = 0.0f;
8969 float leftFadeStrength = 0.0f;
8970 float rightFadeStrength = 0.0f;
8971
8972 // Step 2, save the canvas' layers
8973 int paddingLeft = mPaddingLeft;
8974 int paddingTop = mPaddingTop;
8975
8976 final boolean offsetRequired = isPaddingOffsetRequired();
8977 if (offsetRequired) {
8978 paddingLeft += getLeftPaddingOffset();
8979 paddingTop += getTopPaddingOffset();
8980 }
8981
8982 int left = mScrollX + paddingLeft;
8983 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8984 int top = mScrollY + paddingTop;
8985 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8986
8987 if (offsetRequired) {
8988 right += getRightPaddingOffset();
8989 bottom += getBottomPaddingOffset();
8990 }
8991
8992 final ScrollabilityCache scrollabilityCache = mScrollCache;
8993 int length = scrollabilityCache.fadingEdgeLength;
8994
8995 // clip the fade length if top and bottom fades overlap
8996 // overlapping fades produce odd-looking artifacts
8997 if (verticalEdges && (top + length > bottom - length)) {
8998 length = (bottom - top) / 2;
8999 }
9000
9001 // also clip horizontal fades if necessary
9002 if (horizontalEdges && (left + length > right - length)) {
9003 length = (right - left) / 2;
9004 }
9005
9006 if (verticalEdges) {
9007 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07009008 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009009 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07009010 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009011 }
9012
9013 if (horizontalEdges) {
9014 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07009015 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07009017 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009018 }
9019
9020 saveCount = canvas.getSaveCount();
9021
9022 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07009023 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009024 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
9025
9026 if (drawTop) {
9027 canvas.saveLayer(left, top, right, top + length, null, flags);
9028 }
9029
9030 if (drawBottom) {
9031 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
9032 }
9033
9034 if (drawLeft) {
9035 canvas.saveLayer(left, top, left + length, bottom, null, flags);
9036 }
9037
9038 if (drawRight) {
9039 canvas.saveLayer(right - length, top, right, bottom, null, flags);
9040 }
9041 } else {
9042 scrollabilityCache.setFadeColor(solidColor);
9043 }
9044
9045 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07009046 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009047
9048 // Step 4, draw the children
9049 dispatchDraw(canvas);
9050
9051 // Step 5, draw the fade effect and restore layers
9052 final Paint p = scrollabilityCache.paint;
9053 final Matrix matrix = scrollabilityCache.matrix;
9054 final Shader fade = scrollabilityCache.shader;
9055 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
9056
9057 if (drawTop) {
9058 matrix.setScale(1, fadeHeight * topFadeStrength);
9059 matrix.postTranslate(left, top);
9060 fade.setLocalMatrix(matrix);
9061 canvas.drawRect(left, top, right, top + length, p);
9062 }
9063
9064 if (drawBottom) {
9065 matrix.setScale(1, fadeHeight * bottomFadeStrength);
9066 matrix.postRotate(180);
9067 matrix.postTranslate(left, bottom);
9068 fade.setLocalMatrix(matrix);
9069 canvas.drawRect(left, bottom - length, right, bottom, p);
9070 }
9071
9072 if (drawLeft) {
9073 matrix.setScale(1, fadeHeight * leftFadeStrength);
9074 matrix.postRotate(-90);
9075 matrix.postTranslate(left, top);
9076 fade.setLocalMatrix(matrix);
9077 canvas.drawRect(left, top, left + length, bottom, p);
9078 }
9079
9080 if (drawRight) {
9081 matrix.setScale(1, fadeHeight * rightFadeStrength);
9082 matrix.postRotate(90);
9083 matrix.postTranslate(right, top);
9084 fade.setLocalMatrix(matrix);
9085 canvas.drawRect(right - length, top, right, bottom, p);
9086 }
9087
9088 canvas.restoreToCount(saveCount);
9089
9090 // Step 6, draw decorations (scrollbars)
9091 onDrawScrollBars(canvas);
9092 }
9093
9094 /**
9095 * Override this if your view is known to always be drawn on top of a solid color background,
9096 * and needs to draw fading edges. Returning a non-zero color enables the view system to
9097 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
9098 * should be set to 0xFF.
9099 *
9100 * @see #setVerticalFadingEdgeEnabled
9101 * @see #setHorizontalFadingEdgeEnabled
9102 *
9103 * @return The known solid color background for this view, or 0 if the color may vary
9104 */
9105 public int getSolidColor() {
9106 return 0;
9107 }
9108
9109 /**
9110 * Build a human readable string representation of the specified view flags.
9111 *
9112 * @param flags the view flags to convert to a string
9113 * @return a String representing the supplied flags
9114 */
9115 private static String printFlags(int flags) {
9116 String output = "";
9117 int numFlags = 0;
9118 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
9119 output += "TAKES_FOCUS";
9120 numFlags++;
9121 }
9122
9123 switch (flags & VISIBILITY_MASK) {
9124 case INVISIBLE:
9125 if (numFlags > 0) {
9126 output += " ";
9127 }
9128 output += "INVISIBLE";
9129 // USELESS HERE numFlags++;
9130 break;
9131 case GONE:
9132 if (numFlags > 0) {
9133 output += " ";
9134 }
9135 output += "GONE";
9136 // USELESS HERE numFlags++;
9137 break;
9138 default:
9139 break;
9140 }
9141 return output;
9142 }
9143
9144 /**
9145 * Build a human readable string representation of the specified private
9146 * view flags.
9147 *
9148 * @param privateFlags the private view flags to convert to a string
9149 * @return a String representing the supplied flags
9150 */
9151 private static String printPrivateFlags(int privateFlags) {
9152 String output = "";
9153 int numFlags = 0;
9154
9155 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
9156 output += "WANTS_FOCUS";
9157 numFlags++;
9158 }
9159
9160 if ((privateFlags & FOCUSED) == FOCUSED) {
9161 if (numFlags > 0) {
9162 output += " ";
9163 }
9164 output += "FOCUSED";
9165 numFlags++;
9166 }
9167
9168 if ((privateFlags & SELECTED) == SELECTED) {
9169 if (numFlags > 0) {
9170 output += " ";
9171 }
9172 output += "SELECTED";
9173 numFlags++;
9174 }
9175
9176 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
9177 if (numFlags > 0) {
9178 output += " ";
9179 }
9180 output += "IS_ROOT_NAMESPACE";
9181 numFlags++;
9182 }
9183
9184 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
9185 if (numFlags > 0) {
9186 output += " ";
9187 }
9188 output += "HAS_BOUNDS";
9189 numFlags++;
9190 }
9191
9192 if ((privateFlags & DRAWN) == DRAWN) {
9193 if (numFlags > 0) {
9194 output += " ";
9195 }
9196 output += "DRAWN";
9197 // USELESS HERE numFlags++;
9198 }
9199 return output;
9200 }
9201
9202 /**
9203 * <p>Indicates whether or not this view's layout will be requested during
9204 * the next hierarchy layout pass.</p>
9205 *
9206 * @return true if the layout will be forced during next layout pass
9207 */
9208 public boolean isLayoutRequested() {
9209 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
9210 }
9211
9212 /**
9213 * Assign a size and position to a view and all of its
9214 * descendants
9215 *
9216 * <p>This is the second phase of the layout mechanism.
9217 * (The first is measuring). In this phase, each parent calls
9218 * layout on all of its children to position them.
9219 * This is typically done using the child measurements
Chet Haase9c087442011-01-12 16:20:16 -08009220 * that were stored in the measure pass().</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009221 *
Chet Haase9c087442011-01-12 16:20:16 -08009222 * <p>Derived classes should not override this method.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009223 * Derived classes with children should override
9224 * onLayout. In that method, they should
Chet Haase9c087442011-01-12 16:20:16 -08009225 * call layout on each of their children.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009226 *
9227 * @param l Left position, relative to parent
9228 * @param t Top position, relative to parent
9229 * @param r Right position, relative to parent
9230 * @param b Bottom position, relative to parent
9231 */
Romain Guy5429e1d2010-09-07 12:38:00 -07009232 @SuppressWarnings({"unchecked"})
Chet Haase9c087442011-01-12 16:20:16 -08009233 public void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07009234 int oldL = mLeft;
9235 int oldT = mTop;
9236 int oldB = mBottom;
9237 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009238 boolean changed = setFrame(l, t, r, b);
9239 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
9240 if (ViewDebug.TRACE_HIERARCHY) {
9241 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
9242 }
9243
9244 onLayout(changed, l, t, r, b);
9245 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07009246
9247 if (mOnLayoutChangeListeners != null) {
9248 ArrayList<OnLayoutChangeListener> listenersCopy =
9249 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
9250 int numListeners = listenersCopy.size();
9251 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07009252 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07009253 }
9254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009255 }
9256 mPrivateFlags &= ~FORCE_LAYOUT;
9257 }
9258
9259 /**
9260 * Called from layout when this view should
9261 * assign a size and position to each of its children.
9262 *
9263 * Derived classes with children should override
9264 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07009265 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266 * @param changed This is a new size or position for this view
9267 * @param left Left position, relative to parent
9268 * @param top Top position, relative to parent
9269 * @param right Right position, relative to parent
9270 * @param bottom Bottom position, relative to parent
9271 */
9272 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
9273 }
9274
9275 /**
9276 * Assign a size and position to this view.
9277 *
9278 * This is called from layout.
9279 *
9280 * @param left Left position, relative to parent
9281 * @param top Top position, relative to parent
9282 * @param right Right position, relative to parent
9283 * @param bottom Bottom position, relative to parent
9284 * @return true if the new size and position are different than the
9285 * previous ones
9286 * {@hide}
9287 */
9288 protected boolean setFrame(int left, int top, int right, int bottom) {
9289 boolean changed = false;
9290
9291 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07009292 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009293 + right + "," + bottom + ")");
9294 }
9295
9296 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
9297 changed = true;
9298
9299 // Remember our drawn bit
9300 int drawn = mPrivateFlags & DRAWN;
9301
9302 // Invalidate our old position
Romain Guy0fd89bf2011-01-26 15:41:30 -08009303 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009304
9305
9306 int oldWidth = mRight - mLeft;
9307 int oldHeight = mBottom - mTop;
9308
9309 mLeft = left;
9310 mTop = top;
9311 mRight = right;
9312 mBottom = bottom;
9313
9314 mPrivateFlags |= HAS_BOUNDS;
9315
9316 int newWidth = right - left;
9317 int newHeight = bottom - top;
9318
9319 if (newWidth != oldWidth || newHeight != oldHeight) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009320 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9321 // A change in dimension means an auto-centered pivot point changes, too
9322 mMatrixDirty = true;
9323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009324 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
9325 }
9326
9327 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
9328 // If we are visible, force the DRAWN bit to on so that
9329 // this invalidate will go through (at least to our parent).
9330 // This is because someone may have invalidated this view
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009331 // before this call to setFrame came in, thereby clearing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009332 // the DRAWN bit.
9333 mPrivateFlags |= DRAWN;
Romain Guy0fd89bf2011-01-26 15:41:30 -08009334 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009335 }
9336
9337 // Reset drawn bit to original value (invalidate turns it off)
9338 mPrivateFlags |= drawn;
9339
9340 mBackgroundSizeChanged = true;
9341 }
9342 return changed;
9343 }
9344
9345 /**
9346 * Finalize inflating a view from XML. This is called as the last phase
9347 * of inflation, after all child views have been added.
9348 *
9349 * <p>Even if the subclass overrides onFinishInflate, they should always be
9350 * sure to call the super method, so that we get called.
9351 */
9352 protected void onFinishInflate() {
9353 }
9354
9355 /**
9356 * Returns the resources associated with this view.
9357 *
9358 * @return Resources object.
9359 */
9360 public Resources getResources() {
9361 return mResources;
9362 }
9363
9364 /**
9365 * Invalidates the specified Drawable.
9366 *
9367 * @param drawable the drawable to invalidate
9368 */
9369 public void invalidateDrawable(Drawable drawable) {
9370 if (verifyDrawable(drawable)) {
9371 final Rect dirty = drawable.getBounds();
9372 final int scrollX = mScrollX;
9373 final int scrollY = mScrollY;
9374
9375 invalidate(dirty.left + scrollX, dirty.top + scrollY,
9376 dirty.right + scrollX, dirty.bottom + scrollY);
9377 }
9378 }
9379
9380 /**
9381 * Schedules an action on a drawable to occur at a specified time.
9382 *
9383 * @param who the recipient of the action
9384 * @param what the action to run on the drawable
9385 * @param when the time at which the action must occur. Uses the
9386 * {@link SystemClock#uptimeMillis} timebase.
9387 */
9388 public void scheduleDrawable(Drawable who, Runnable what, long when) {
9389 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9390 mAttachInfo.mHandler.postAtTime(what, who, when);
9391 }
9392 }
9393
9394 /**
9395 * Cancels a scheduled action on a drawable.
9396 *
9397 * @param who the recipient of the action
9398 * @param what the action to cancel
9399 */
9400 public void unscheduleDrawable(Drawable who, Runnable what) {
9401 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9402 mAttachInfo.mHandler.removeCallbacks(what, who);
9403 }
9404 }
9405
9406 /**
9407 * Unschedule any events associated with the given Drawable. This can be
9408 * used when selecting a new Drawable into a view, so that the previous
9409 * one is completely unscheduled.
9410 *
9411 * @param who The Drawable to unschedule.
9412 *
9413 * @see #drawableStateChanged
9414 */
9415 public void unscheduleDrawable(Drawable who) {
9416 if (mAttachInfo != null) {
9417 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
9418 }
9419 }
9420
9421 /**
9422 * If your view subclass is displaying its own Drawable objects, it should
9423 * override this function and return true for any Drawable it is
9424 * displaying. This allows animations for those drawables to be
9425 * scheduled.
9426 *
9427 * <p>Be sure to call through to the super class when overriding this
9428 * function.
9429 *
9430 * @param who The Drawable to verify. Return true if it is one you are
9431 * displaying, else return the result of calling through to the
9432 * super class.
9433 *
9434 * @return boolean If true than the Drawable is being displayed in the
9435 * view; else false and it is not allowed to animate.
9436 *
9437 * @see #unscheduleDrawable
9438 * @see #drawableStateChanged
9439 */
9440 protected boolean verifyDrawable(Drawable who) {
9441 return who == mBGDrawable;
9442 }
9443
9444 /**
9445 * This function is called whenever the state of the view changes in such
9446 * a way that it impacts the state of drawables being shown.
9447 *
9448 * <p>Be sure to call through to the superclass when overriding this
9449 * function.
9450 *
9451 * @see Drawable#setState
9452 */
9453 protected void drawableStateChanged() {
9454 Drawable d = mBGDrawable;
9455 if (d != null && d.isStateful()) {
9456 d.setState(getDrawableState());
9457 }
9458 }
9459
9460 /**
9461 * Call this to force a view to update its drawable state. This will cause
9462 * drawableStateChanged to be called on this view. Views that are interested
9463 * in the new state should call getDrawableState.
9464 *
9465 * @see #drawableStateChanged
9466 * @see #getDrawableState
9467 */
9468 public void refreshDrawableState() {
9469 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9470 drawableStateChanged();
9471
9472 ViewParent parent = mParent;
9473 if (parent != null) {
9474 parent.childDrawableStateChanged(this);
9475 }
9476 }
9477
9478 /**
9479 * Return an array of resource IDs of the drawable states representing the
9480 * current state of the view.
9481 *
9482 * @return The current drawable state
9483 *
9484 * @see Drawable#setState
9485 * @see #drawableStateChanged
9486 * @see #onCreateDrawableState
9487 */
9488 public final int[] getDrawableState() {
9489 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
9490 return mDrawableState;
9491 } else {
9492 mDrawableState = onCreateDrawableState(0);
9493 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
9494 return mDrawableState;
9495 }
9496 }
9497
9498 /**
9499 * Generate the new {@link android.graphics.drawable.Drawable} state for
9500 * this view. This is called by the view
9501 * system when the cached Drawable state is determined to be invalid. To
9502 * retrieve the current state, you should use {@link #getDrawableState}.
9503 *
9504 * @param extraSpace if non-zero, this is the number of extra entries you
9505 * would like in the returned array in which you can place your own
9506 * states.
9507 *
9508 * @return Returns an array holding the current {@link Drawable} state of
9509 * the view.
9510 *
9511 * @see #mergeDrawableStates
9512 */
9513 protected int[] onCreateDrawableState(int extraSpace) {
9514 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
9515 mParent instanceof View) {
9516 return ((View) mParent).onCreateDrawableState(extraSpace);
9517 }
9518
9519 int[] drawableState;
9520
9521 int privateFlags = mPrivateFlags;
9522
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009523 int viewStateIndex = 0;
9524 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
9525 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
9526 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07009527 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009528 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
9529 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08009530 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
9531 // This is set if HW acceleration is requested, even if the current
9532 // process doesn't allow it. This is just to allow app preview
9533 // windows to better match their app.
9534 viewStateIndex |= VIEW_STATE_ACCELERATED;
9535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009536
9537 drawableState = VIEW_STATE_SETS[viewStateIndex];
9538
9539 //noinspection ConstantIfStatement
9540 if (false) {
9541 Log.i("View", "drawableStateIndex=" + viewStateIndex);
9542 Log.i("View", toString()
9543 + " pressed=" + ((privateFlags & PRESSED) != 0)
9544 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
9545 + " fo=" + hasFocus()
9546 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009547 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009548 + ": " + Arrays.toString(drawableState));
9549 }
9550
9551 if (extraSpace == 0) {
9552 return drawableState;
9553 }
9554
9555 final int[] fullState;
9556 if (drawableState != null) {
9557 fullState = new int[drawableState.length + extraSpace];
9558 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
9559 } else {
9560 fullState = new int[extraSpace];
9561 }
9562
9563 return fullState;
9564 }
9565
9566 /**
9567 * Merge your own state values in <var>additionalState</var> into the base
9568 * state values <var>baseState</var> that were returned by
9569 * {@link #onCreateDrawableState}.
9570 *
9571 * @param baseState The base state values returned by
9572 * {@link #onCreateDrawableState}, which will be modified to also hold your
9573 * own additional state values.
9574 *
9575 * @param additionalState The additional state values you would like
9576 * added to <var>baseState</var>; this array is not modified.
9577 *
9578 * @return As a convenience, the <var>baseState</var> array you originally
9579 * passed into the function is returned.
9580 *
9581 * @see #onCreateDrawableState
9582 */
9583 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
9584 final int N = baseState.length;
9585 int i = N - 1;
9586 while (i >= 0 && baseState[i] == 0) {
9587 i--;
9588 }
9589 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
9590 return baseState;
9591 }
9592
9593 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07009594 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
9595 * on all Drawable objects associated with this view.
9596 */
9597 public void jumpDrawablesToCurrentState() {
9598 if (mBGDrawable != null) {
9599 mBGDrawable.jumpToCurrentState();
9600 }
9601 }
9602
9603 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009604 * Sets the background color for this view.
9605 * @param color the color of the background
9606 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009607 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009608 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07009609 if (mBGDrawable instanceof ColorDrawable) {
9610 ((ColorDrawable) mBGDrawable).setColor(color);
9611 } else {
9612 setBackgroundDrawable(new ColorDrawable(color));
9613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009614 }
9615
9616 /**
9617 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07009618 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009619 * @param resid The identifier of the resource.
9620 * @attr ref android.R.styleable#View_background
9621 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009622 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009623 public void setBackgroundResource(int resid) {
9624 if (resid != 0 && resid == mBackgroundResource) {
9625 return;
9626 }
9627
9628 Drawable d= null;
9629 if (resid != 0) {
9630 d = mResources.getDrawable(resid);
9631 }
9632 setBackgroundDrawable(d);
9633
9634 mBackgroundResource = resid;
9635 }
9636
9637 /**
9638 * Set the background to a given Drawable, or remove the background. If the
9639 * background has padding, this View's padding is set to the background's
9640 * padding. However, when a background is removed, this View's padding isn't
9641 * touched. If setting the padding is desired, please use
9642 * {@link #setPadding(int, int, int, int)}.
9643 *
9644 * @param d The Drawable to use as the background, or null to remove the
9645 * background
9646 */
9647 public void setBackgroundDrawable(Drawable d) {
9648 boolean requestLayout = false;
9649
9650 mBackgroundResource = 0;
9651
9652 /*
9653 * Regardless of whether we're setting a new background or not, we want
9654 * to clear the previous drawable.
9655 */
9656 if (mBGDrawable != null) {
9657 mBGDrawable.setCallback(null);
9658 unscheduleDrawable(mBGDrawable);
9659 }
9660
9661 if (d != null) {
9662 Rect padding = sThreadLocal.get();
9663 if (padding == null) {
9664 padding = new Rect();
9665 sThreadLocal.set(padding);
9666 }
9667 if (d.getPadding(padding)) {
9668 setPadding(padding.left, padding.top, padding.right, padding.bottom);
9669 }
9670
9671 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
9672 // if it has a different minimum size, we should layout again
9673 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9674 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9675 requestLayout = true;
9676 }
9677
9678 d.setCallback(this);
9679 if (d.isStateful()) {
9680 d.setState(getDrawableState());
9681 }
9682 d.setVisible(getVisibility() == VISIBLE, false);
9683 mBGDrawable = d;
9684
9685 if ((mPrivateFlags & SKIP_DRAW) != 0) {
9686 mPrivateFlags &= ~SKIP_DRAW;
9687 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9688 requestLayout = true;
9689 }
9690 } else {
9691 /* Remove the background */
9692 mBGDrawable = null;
9693
9694 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9695 /*
9696 * This view ONLY drew the background before and we're removing
9697 * the background, so now it won't draw anything
9698 * (hence we SKIP_DRAW)
9699 */
9700 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9701 mPrivateFlags |= SKIP_DRAW;
9702 }
9703
9704 /*
9705 * When the background is set, we try to apply its padding to this
9706 * View. When the background is removed, we don't touch this View's
9707 * padding. This is noted in the Javadocs. Hence, we don't need to
9708 * requestLayout(), the invalidate() below is sufficient.
9709 */
9710
9711 // The old background's minimum size could have affected this
9712 // View's layout, so let's requestLayout
9713 requestLayout = true;
9714 }
9715
Romain Guy8f1344f52009-05-15 16:03:59 -07009716 computeOpaqueFlags();
9717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009718 if (requestLayout) {
9719 requestLayout();
9720 }
9721
9722 mBackgroundSizeChanged = true;
Romain Guy0fd89bf2011-01-26 15:41:30 -08009723 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009724 }
9725
9726 /**
9727 * Gets the background drawable
9728 * @return The drawable used as the background for this view, if any.
9729 */
9730 public Drawable getBackground() {
9731 return mBGDrawable;
9732 }
9733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009734 /**
9735 * Sets the padding. The view may add on the space required to display
9736 * the scrollbars, depending on the style and visibility of the scrollbars.
9737 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9738 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9739 * from the values set in this call.
9740 *
9741 * @attr ref android.R.styleable#View_padding
9742 * @attr ref android.R.styleable#View_paddingBottom
9743 * @attr ref android.R.styleable#View_paddingLeft
9744 * @attr ref android.R.styleable#View_paddingRight
9745 * @attr ref android.R.styleable#View_paddingTop
9746 * @param left the left padding in pixels
9747 * @param top the top padding in pixels
9748 * @param right the right padding in pixels
9749 * @param bottom the bottom padding in pixels
9750 */
9751 public void setPadding(int left, int top, int right, int bottom) {
9752 boolean changed = false;
9753
Adam Powell20232d02010-12-08 21:08:53 -08009754 mUserPaddingLeft = left;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009755 mUserPaddingRight = right;
9756 mUserPaddingBottom = bottom;
9757
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009758 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07009759
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009760 // Common case is there are no scroll bars.
9761 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009762 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
Adam Powell20232d02010-12-08 21:08:53 -08009763 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9764 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009765 ? 0 : getVerticalScrollbarWidth();
Adam Powell20232d02010-12-08 21:08:53 -08009766 switch (mVerticalScrollbarPosition) {
9767 case SCROLLBAR_POSITION_DEFAULT:
9768 case SCROLLBAR_POSITION_RIGHT:
9769 right += offset;
9770 break;
9771 case SCROLLBAR_POSITION_LEFT:
9772 left += offset;
9773 break;
9774 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009775 }
Adam Powell20232d02010-12-08 21:08:53 -08009776 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009777 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9778 ? 0 : getHorizontalScrollbarHeight();
9779 }
9780 }
Romain Guy8506ab42009-06-11 17:35:47 -07009781
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009782 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009783 changed = true;
9784 mPaddingLeft = left;
9785 }
9786 if (mPaddingTop != top) {
9787 changed = true;
9788 mPaddingTop = top;
9789 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009790 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009791 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009792 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009793 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009794 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009795 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009796 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009797 }
9798
9799 if (changed) {
9800 requestLayout();
9801 }
9802 }
9803
9804 /**
9805 * Returns the top padding of this view.
9806 *
9807 * @return the top padding in pixels
9808 */
9809 public int getPaddingTop() {
9810 return mPaddingTop;
9811 }
9812
9813 /**
9814 * Returns the bottom padding of this view. If there are inset and enabled
9815 * scrollbars, this value may include the space required to display the
9816 * scrollbars as well.
9817 *
9818 * @return the bottom padding in pixels
9819 */
9820 public int getPaddingBottom() {
9821 return mPaddingBottom;
9822 }
9823
9824 /**
9825 * Returns the left padding of this view. If there are inset and enabled
9826 * scrollbars, this value may include the space required to display the
9827 * scrollbars as well.
9828 *
9829 * @return the left padding in pixels
9830 */
9831 public int getPaddingLeft() {
9832 return mPaddingLeft;
9833 }
9834
9835 /**
9836 * Returns the right padding of this view. If there are inset and enabled
9837 * scrollbars, this value may include the space required to display the
9838 * scrollbars as well.
9839 *
9840 * @return the right padding in pixels
9841 */
9842 public int getPaddingRight() {
9843 return mPaddingRight;
9844 }
9845
9846 /**
9847 * Changes the selection state of this view. A view can be selected or not.
9848 * Note that selection is not the same as focus. Views are typically
9849 * selected in the context of an AdapterView like ListView or GridView;
9850 * the selected view is the view that is highlighted.
9851 *
9852 * @param selected true if the view must be selected, false otherwise
9853 */
9854 public void setSelected(boolean selected) {
9855 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9856 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009857 if (!selected) resetPressedState();
Romain Guy0fd89bf2011-01-26 15:41:30 -08009858 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009859 refreshDrawableState();
9860 dispatchSetSelected(selected);
9861 }
9862 }
9863
9864 /**
9865 * Dispatch setSelected to all of this View's children.
9866 *
9867 * @see #setSelected(boolean)
9868 *
9869 * @param selected The new selected state
9870 */
9871 protected void dispatchSetSelected(boolean selected) {
9872 }
9873
9874 /**
9875 * Indicates the selection state of this view.
9876 *
9877 * @return true if the view is selected, false otherwise
9878 */
9879 @ViewDebug.ExportedProperty
9880 public boolean isSelected() {
9881 return (mPrivateFlags & SELECTED) != 0;
9882 }
9883
9884 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009885 * Changes the activated state of this view. A view can be activated or not.
9886 * Note that activation is not the same as selection. Selection is
9887 * a transient property, representing the view (hierarchy) the user is
9888 * currently interacting with. Activation is a longer-term state that the
9889 * user can move views in and out of. For example, in a list view with
9890 * single or multiple selection enabled, the views in the current selection
9891 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9892 * here.) The activated state is propagated down to children of the view it
9893 * is set on.
9894 *
9895 * @param activated true if the view must be activated, false otherwise
9896 */
9897 public void setActivated(boolean activated) {
9898 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9899 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
Romain Guy0fd89bf2011-01-26 15:41:30 -08009900 invalidate(true);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009901 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009902 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009903 }
9904 }
9905
9906 /**
9907 * Dispatch setActivated to all of this View's children.
9908 *
9909 * @see #setActivated(boolean)
9910 *
9911 * @param activated The new activated state
9912 */
9913 protected void dispatchSetActivated(boolean activated) {
9914 }
9915
9916 /**
9917 * Indicates the activation state of this view.
9918 *
9919 * @return true if the view is activated, false otherwise
9920 */
9921 @ViewDebug.ExportedProperty
9922 public boolean isActivated() {
9923 return (mPrivateFlags & ACTIVATED) != 0;
9924 }
9925
9926 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009927 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9928 * observer can be used to get notifications when global events, like
9929 * layout, happen.
9930 *
9931 * The returned ViewTreeObserver observer is not guaranteed to remain
9932 * valid for the lifetime of this View. If the caller of this method keeps
9933 * a long-lived reference to ViewTreeObserver, it should always check for
9934 * the return value of {@link ViewTreeObserver#isAlive()}.
9935 *
9936 * @return The ViewTreeObserver for this view's hierarchy.
9937 */
9938 public ViewTreeObserver getViewTreeObserver() {
9939 if (mAttachInfo != null) {
9940 return mAttachInfo.mTreeObserver;
9941 }
9942 if (mFloatingTreeObserver == null) {
9943 mFloatingTreeObserver = new ViewTreeObserver();
9944 }
9945 return mFloatingTreeObserver;
9946 }
9947
9948 /**
9949 * <p>Finds the topmost view in the current view hierarchy.</p>
9950 *
9951 * @return the topmost view containing this view
9952 */
9953 public View getRootView() {
9954 if (mAttachInfo != null) {
9955 final View v = mAttachInfo.mRootView;
9956 if (v != null) {
9957 return v;
9958 }
9959 }
Romain Guy8506ab42009-06-11 17:35:47 -07009960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009961 View parent = this;
9962
9963 while (parent.mParent != null && parent.mParent instanceof View) {
9964 parent = (View) parent.mParent;
9965 }
9966
9967 return parent;
9968 }
9969
9970 /**
9971 * <p>Computes the coordinates of this view on the screen. The argument
9972 * must be an array of two integers. After the method returns, the array
9973 * contains the x and y location in that order.</p>
9974 *
9975 * @param location an array of two integers in which to hold the coordinates
9976 */
9977 public void getLocationOnScreen(int[] location) {
9978 getLocationInWindow(location);
9979
9980 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009981 if (info != null) {
9982 location[0] += info.mWindowLeft;
9983 location[1] += info.mWindowTop;
9984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009985 }
9986
9987 /**
9988 * <p>Computes the coordinates of this view in its window. The argument
9989 * must be an array of two integers. After the method returns, the array
9990 * contains the x and y location in that order.</p>
9991 *
9992 * @param location an array of two integers in which to hold the coordinates
9993 */
9994 public void getLocationInWindow(int[] location) {
9995 if (location == null || location.length < 2) {
9996 throw new IllegalArgumentException("location must be an array of "
9997 + "two integers");
9998 }
9999
Michael Jurka4d2bd4c2010-11-30 18:15:11 -080010000 location[0] = mLeft + (int) (mTranslationX + 0.5f);
10001 location[1] = mTop + (int) (mTranslationY + 0.5f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010002
10003 ViewParent viewParent = mParent;
10004 while (viewParent instanceof View) {
10005 final View view = (View)viewParent;
Michael Jurka4d2bd4c2010-11-30 18:15:11 -080010006 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
10007 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010008 viewParent = view.mParent;
10009 }
Romain Guy8506ab42009-06-11 17:35:47 -070010010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010011 if (viewParent instanceof ViewRoot) {
10012 // *cough*
10013 final ViewRoot vr = (ViewRoot)viewParent;
10014 location[1] -= vr.mCurScrollY;
10015 }
10016 }
10017
10018 /**
10019 * {@hide}
10020 * @param id the id of the view to be found
10021 * @return the view of the specified id, null if cannot be found
10022 */
10023 protected View findViewTraversal(int id) {
10024 if (id == mID) {
10025 return this;
10026 }
10027 return null;
10028 }
10029
10030 /**
10031 * {@hide}
10032 * @param tag the tag of the view to be found
10033 * @return the view of specified tag, null if cannot be found
10034 */
10035 protected View findViewWithTagTraversal(Object tag) {
10036 if (tag != null && tag.equals(mTag)) {
10037 return this;
10038 }
10039 return null;
10040 }
10041
10042 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -080010043 * {@hide}
10044 * @param predicate The predicate to evaluate.
10045 * @return The first view that matches the predicate or null.
10046 */
10047 protected View findViewByPredicateTraversal(Predicate<View> predicate) {
10048 if (predicate.apply(this)) {
10049 return this;
10050 }
10051 return null;
10052 }
10053
10054 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010055 * Look for a child view with the given id. If this view has the given
10056 * id, return this view.
10057 *
10058 * @param id The id to search for.
10059 * @return The view that has the given id in the hierarchy or null
10060 */
10061 public final View findViewById(int id) {
10062 if (id < 0) {
10063 return null;
10064 }
10065 return findViewTraversal(id);
10066 }
10067
10068 /**
10069 * Look for a child view with the given tag. If this view has the given
10070 * tag, return this view.
10071 *
10072 * @param tag The tag to search for, using "tag.equals(getTag())".
10073 * @return The View that has the given tag in the hierarchy or null
10074 */
10075 public final View findViewWithTag(Object tag) {
10076 if (tag == null) {
10077 return null;
10078 }
10079 return findViewWithTagTraversal(tag);
10080 }
10081
10082 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -080010083 * {@hide}
10084 * Look for a child view that matches the specified predicate.
10085 * If this view matches the predicate, return this view.
10086 *
10087 * @param predicate The predicate to evaluate.
10088 * @return The first view that matches the predicate or null.
10089 */
10090 public final View findViewByPredicate(Predicate<View> predicate) {
10091 return findViewByPredicateTraversal(predicate);
10092 }
10093
10094 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010095 * Sets the identifier for this view. The identifier does not have to be
10096 * unique in this view's hierarchy. The identifier should be a positive
10097 * number.
10098 *
10099 * @see #NO_ID
10100 * @see #getId
10101 * @see #findViewById
10102 *
10103 * @param id a number used to identify the view
10104 *
10105 * @attr ref android.R.styleable#View_id
10106 */
10107 public void setId(int id) {
10108 mID = id;
10109 }
10110
10111 /**
10112 * {@hide}
10113 *
10114 * @param isRoot true if the view belongs to the root namespace, false
10115 * otherwise
10116 */
10117 public void setIsRootNamespace(boolean isRoot) {
10118 if (isRoot) {
10119 mPrivateFlags |= IS_ROOT_NAMESPACE;
10120 } else {
10121 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
10122 }
10123 }
10124
10125 /**
10126 * {@hide}
10127 *
10128 * @return true if the view belongs to the root namespace, false otherwise
10129 */
10130 public boolean isRootNamespace() {
10131 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
10132 }
10133
10134 /**
10135 * Returns this view's identifier.
10136 *
10137 * @return a positive integer used to identify the view or {@link #NO_ID}
10138 * if the view has no ID
10139 *
10140 * @see #setId
10141 * @see #findViewById
10142 * @attr ref android.R.styleable#View_id
10143 */
10144 @ViewDebug.CapturedViewProperty
10145 public int getId() {
10146 return mID;
10147 }
10148
10149 /**
10150 * Returns this view's tag.
10151 *
10152 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -070010153 *
10154 * @see #setTag(Object)
10155 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010156 */
10157 @ViewDebug.ExportedProperty
10158 public Object getTag() {
10159 return mTag;
10160 }
10161
10162 /**
10163 * Sets the tag associated with this view. A tag can be used to mark
10164 * a view in its hierarchy and does not have to be unique within the
10165 * hierarchy. Tags can also be used to store data within a view without
10166 * resorting to another data structure.
10167 *
10168 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -070010169 *
10170 * @see #getTag()
10171 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010172 */
10173 public void setTag(final Object tag) {
10174 mTag = tag;
10175 }
10176
10177 /**
Romain Guyd90a3312009-05-06 14:54:28 -070010178 * Returns the tag associated with this view and the specified key.
10179 *
10180 * @param key The key identifying the tag
10181 *
10182 * @return the Object stored in this view as a tag
10183 *
10184 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -070010185 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -070010186 */
10187 public Object getTag(int key) {
10188 SparseArray<Object> tags = null;
10189 synchronized (sTagsLock) {
10190 if (sTags != null) {
10191 tags = sTags.get(this);
10192 }
10193 }
10194
10195 if (tags != null) return tags.get(key);
10196 return null;
10197 }
10198
10199 /**
10200 * Sets a tag associated with this view and a key. A tag can be used
10201 * to mark a view in its hierarchy and does not have to be unique within
10202 * the hierarchy. Tags can also be used to store data within a view
10203 * without resorting to another data structure.
10204 *
10205 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -070010206 * application to ensure it is unique (see the <a
10207 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
10208 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -070010209 * the Android framework or not associated with any package will cause
10210 * an {@link IllegalArgumentException} to be thrown.
10211 *
10212 * @param key The key identifying the tag
10213 * @param tag An Object to tag the view with
10214 *
10215 * @throws IllegalArgumentException If they specified key is not valid
10216 *
10217 * @see #setTag(Object)
10218 * @see #getTag(int)
10219 */
10220 public void setTag(int key, final Object tag) {
10221 // If the package id is 0x00 or 0x01, it's either an undefined package
10222 // or a framework id
10223 if ((key >>> 24) < 2) {
10224 throw new IllegalArgumentException("The key must be an application-specific "
10225 + "resource id.");
10226 }
10227
10228 setTagInternal(this, key, tag);
10229 }
10230
10231 /**
10232 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
10233 * framework id.
10234 *
10235 * @hide
10236 */
10237 public void setTagInternal(int key, Object tag) {
10238 if ((key >>> 24) != 0x1) {
10239 throw new IllegalArgumentException("The key must be a framework-specific "
10240 + "resource id.");
10241 }
10242
Romain Guy8506ab42009-06-11 17:35:47 -070010243 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -070010244 }
10245
10246 private static void setTagInternal(View view, int key, Object tag) {
10247 SparseArray<Object> tags = null;
10248 synchronized (sTagsLock) {
10249 if (sTags == null) {
10250 sTags = new WeakHashMap<View, SparseArray<Object>>();
10251 } else {
10252 tags = sTags.get(view);
10253 }
10254 }
10255
10256 if (tags == null) {
10257 tags = new SparseArray<Object>(2);
10258 synchronized (sTagsLock) {
10259 sTags.put(view, tags);
10260 }
10261 }
10262
10263 tags.put(key, tag);
10264 }
10265
10266 /**
Romain Guy13922e02009-05-12 17:56:14 -070010267 * @param consistency The type of consistency. See ViewDebug for more information.
10268 *
10269 * @hide
10270 */
10271 protected boolean dispatchConsistencyCheck(int consistency) {
10272 return onConsistencyCheck(consistency);
10273 }
10274
10275 /**
10276 * Method that subclasses should implement to check their consistency. The type of
10277 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -070010278 *
Romain Guy13922e02009-05-12 17:56:14 -070010279 * @param consistency The type of consistency. See ViewDebug for more information.
10280 *
10281 * @throws IllegalStateException if the view is in an inconsistent state.
10282 *
10283 * @hide
10284 */
10285 protected boolean onConsistencyCheck(int consistency) {
10286 boolean result = true;
10287
10288 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
10289 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
10290
10291 if (checkLayout) {
10292 if (getParent() == null) {
10293 result = false;
10294 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10295 "View " + this + " does not have a parent.");
10296 }
10297
10298 if (mAttachInfo == null) {
10299 result = false;
10300 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10301 "View " + this + " is not attached to a window.");
10302 }
10303 }
10304
10305 if (checkDrawing) {
10306 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
10307 // from their draw() method
10308
10309 if ((mPrivateFlags & DRAWN) != DRAWN &&
10310 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
10311 result = false;
10312 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10313 "View " + this + " was invalidated but its drawing cache is valid.");
10314 }
10315 }
10316
10317 return result;
10318 }
10319
10320 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010321 * Prints information about this view in the log output, with the tag
10322 * {@link #VIEW_LOG_TAG}.
10323 *
10324 * @hide
10325 */
10326 public void debug() {
10327 debug(0);
10328 }
10329
10330 /**
10331 * Prints information about this view in the log output, with the tag
10332 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
10333 * indentation defined by the <code>depth</code>.
10334 *
10335 * @param depth the indentation level
10336 *
10337 * @hide
10338 */
10339 protected void debug(int depth) {
10340 String output = debugIndent(depth - 1);
10341
10342 output += "+ " + this;
10343 int id = getId();
10344 if (id != -1) {
10345 output += " (id=" + id + ")";
10346 }
10347 Object tag = getTag();
10348 if (tag != null) {
10349 output += " (tag=" + tag + ")";
10350 }
10351 Log.d(VIEW_LOG_TAG, output);
10352
10353 if ((mPrivateFlags & FOCUSED) != 0) {
10354 output = debugIndent(depth) + " FOCUSED";
10355 Log.d(VIEW_LOG_TAG, output);
10356 }
10357
10358 output = debugIndent(depth);
10359 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
10360 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
10361 + "} ";
10362 Log.d(VIEW_LOG_TAG, output);
10363
10364 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
10365 || mPaddingBottom != 0) {
10366 output = debugIndent(depth);
10367 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
10368 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
10369 Log.d(VIEW_LOG_TAG, output);
10370 }
10371
10372 output = debugIndent(depth);
10373 output += "mMeasureWidth=" + mMeasuredWidth +
10374 " mMeasureHeight=" + mMeasuredHeight;
10375 Log.d(VIEW_LOG_TAG, output);
10376
10377 output = debugIndent(depth);
10378 if (mLayoutParams == null) {
10379 output += "BAD! no layout params";
10380 } else {
10381 output = mLayoutParams.debug(output);
10382 }
10383 Log.d(VIEW_LOG_TAG, output);
10384
10385 output = debugIndent(depth);
10386 output += "flags={";
10387 output += View.printFlags(mViewFlags);
10388 output += "}";
10389 Log.d(VIEW_LOG_TAG, output);
10390
10391 output = debugIndent(depth);
10392 output += "privateFlags={";
10393 output += View.printPrivateFlags(mPrivateFlags);
10394 output += "}";
10395 Log.d(VIEW_LOG_TAG, output);
10396 }
10397
10398 /**
10399 * Creates an string of whitespaces used for indentation.
10400 *
10401 * @param depth the indentation level
10402 * @return a String containing (depth * 2 + 3) * 2 white spaces
10403 *
10404 * @hide
10405 */
10406 protected static String debugIndent(int depth) {
10407 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
10408 for (int i = 0; i < (depth * 2) + 3; i++) {
10409 spaces.append(' ').append(' ');
10410 }
10411 return spaces.toString();
10412 }
10413
10414 /**
10415 * <p>Return the offset of the widget's text baseline from the widget's top
10416 * boundary. If this widget does not support baseline alignment, this
10417 * method returns -1. </p>
10418 *
10419 * @return the offset of the baseline within the widget's bounds or -1
10420 * if baseline alignment is not supported
10421 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -070010422 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010423 public int getBaseline() {
10424 return -1;
10425 }
10426
10427 /**
10428 * Call this when something has changed which has invalidated the
10429 * layout of this view. This will schedule a layout pass of the view
10430 * tree.
10431 */
10432 public void requestLayout() {
10433 if (ViewDebug.TRACE_HIERARCHY) {
10434 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
10435 }
10436
10437 mPrivateFlags |= FORCE_LAYOUT;
Chet Haase5af048c2011-01-24 17:00:32 -080010438 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010439
10440 if (mParent != null && !mParent.isLayoutRequested()) {
10441 mParent.requestLayout();
10442 }
10443 }
10444
10445 /**
10446 * Forces this view to be laid out during the next layout pass.
10447 * This method does not call requestLayout() or forceLayout()
10448 * on the parent.
10449 */
10450 public void forceLayout() {
10451 mPrivateFlags |= FORCE_LAYOUT;
Chet Haase5af048c2011-01-24 17:00:32 -080010452 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010453 }
10454
10455 /**
10456 * <p>
10457 * This is called to find out how big a view should be. The parent
10458 * supplies constraint information in the width and height parameters.
10459 * </p>
10460 *
10461 * <p>
10462 * The actual mesurement work of a view is performed in
10463 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
10464 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
10465 * </p>
10466 *
10467 *
10468 * @param widthMeasureSpec Horizontal space requirements as imposed by the
10469 * parent
10470 * @param heightMeasureSpec Vertical space requirements as imposed by the
10471 * parent
10472 *
10473 * @see #onMeasure(int, int)
10474 */
10475 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
10476 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
10477 widthMeasureSpec != mOldWidthMeasureSpec ||
10478 heightMeasureSpec != mOldHeightMeasureSpec) {
10479
10480 // first clears the measured dimension flag
10481 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
10482
10483 if (ViewDebug.TRACE_HIERARCHY) {
10484 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
10485 }
10486
10487 // measure ourselves, this should set the measured dimension flag back
10488 onMeasure(widthMeasureSpec, heightMeasureSpec);
10489
10490 // flag not set, setMeasuredDimension() was not invoked, we raise
10491 // an exception to warn the developer
10492 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
10493 throw new IllegalStateException("onMeasure() did not set the"
10494 + " measured dimension by calling"
10495 + " setMeasuredDimension()");
10496 }
10497
10498 mPrivateFlags |= LAYOUT_REQUIRED;
10499 }
10500
10501 mOldWidthMeasureSpec = widthMeasureSpec;
10502 mOldHeightMeasureSpec = heightMeasureSpec;
10503 }
10504
10505 /**
10506 * <p>
10507 * Measure the view and its content to determine the measured width and the
10508 * measured height. This method is invoked by {@link #measure(int, int)} and
10509 * should be overriden by subclasses to provide accurate and efficient
10510 * measurement of their contents.
10511 * </p>
10512 *
10513 * <p>
10514 * <strong>CONTRACT:</strong> When overriding this method, you
10515 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
10516 * measured width and height of this view. Failure to do so will trigger an
10517 * <code>IllegalStateException</code>, thrown by
10518 * {@link #measure(int, int)}. Calling the superclass'
10519 * {@link #onMeasure(int, int)} is a valid use.
10520 * </p>
10521 *
10522 * <p>
10523 * The base class implementation of measure defaults to the background size,
10524 * unless a larger size is allowed by the MeasureSpec. Subclasses should
10525 * override {@link #onMeasure(int, int)} to provide better measurements of
10526 * their content.
10527 * </p>
10528 *
10529 * <p>
10530 * If this method is overridden, it is the subclass's responsibility to make
10531 * sure the measured height and width are at least the view's minimum height
10532 * and width ({@link #getSuggestedMinimumHeight()} and
10533 * {@link #getSuggestedMinimumWidth()}).
10534 * </p>
10535 *
10536 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
10537 * The requirements are encoded with
10538 * {@link android.view.View.MeasureSpec}.
10539 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
10540 * The requirements are encoded with
10541 * {@link android.view.View.MeasureSpec}.
10542 *
10543 * @see #getMeasuredWidth()
10544 * @see #getMeasuredHeight()
10545 * @see #setMeasuredDimension(int, int)
10546 * @see #getSuggestedMinimumHeight()
10547 * @see #getSuggestedMinimumWidth()
10548 * @see android.view.View.MeasureSpec#getMode(int)
10549 * @see android.view.View.MeasureSpec#getSize(int)
10550 */
10551 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10552 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
10553 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
10554 }
10555
10556 /**
10557 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
10558 * measured width and measured height. Failing to do so will trigger an
10559 * exception at measurement time.</p>
10560 *
Dianne Hackborn189ee182010-12-02 21:48:53 -080010561 * @param measuredWidth The measured width of this view. May be a complex
10562 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10563 * {@link #MEASURED_STATE_TOO_SMALL}.
10564 * @param measuredHeight The measured height of this view. May be a complex
10565 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10566 * {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010567 */
10568 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
10569 mMeasuredWidth = measuredWidth;
10570 mMeasuredHeight = measuredHeight;
10571
10572 mPrivateFlags |= MEASURED_DIMENSION_SET;
10573 }
10574
10575 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -080010576 * Merge two states as returned by {@link #getMeasuredState()}.
10577 * @param curState The current state as returned from a view or the result
10578 * of combining multiple views.
10579 * @param newState The new view state to combine.
10580 * @return Returns a new integer reflecting the combination of the two
10581 * states.
10582 */
10583 public static int combineMeasuredStates(int curState, int newState) {
10584 return curState | newState;
10585 }
10586
10587 /**
10588 * Version of {@link #resolveSizeAndState(int, int, int)}
10589 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
10590 */
10591 public static int resolveSize(int size, int measureSpec) {
10592 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
10593 }
10594
10595 /**
10596 * Utility to reconcile a desired size and state, with constraints imposed
10597 * by a MeasureSpec. Will take the desired size, unless a different size
10598 * is imposed by the constraints. The returned value is a compound integer,
10599 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
10600 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
10601 * size is smaller than the size the view wants to be.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010602 *
10603 * @param size How big the view wants to be
10604 * @param measureSpec Constraints imposed by the parent
Dianne Hackborn189ee182010-12-02 21:48:53 -080010605 * @return Size information bit mask as defined by
10606 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010607 */
Dianne Hackborn189ee182010-12-02 21:48:53 -080010608 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010609 int result = size;
10610 int specMode = MeasureSpec.getMode(measureSpec);
10611 int specSize = MeasureSpec.getSize(measureSpec);
10612 switch (specMode) {
10613 case MeasureSpec.UNSPECIFIED:
10614 result = size;
10615 break;
10616 case MeasureSpec.AT_MOST:
Dianne Hackborn189ee182010-12-02 21:48:53 -080010617 if (specSize < size) {
10618 result = specSize | MEASURED_STATE_TOO_SMALL;
10619 } else {
10620 result = size;
10621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010622 break;
10623 case MeasureSpec.EXACTLY:
10624 result = specSize;
10625 break;
10626 }
Dianne Hackborn189ee182010-12-02 21:48:53 -080010627 return result | (childMeasuredState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628 }
10629
10630 /**
10631 * Utility to return a default size. Uses the supplied size if the
10632 * MeasureSpec imposed no contraints. Will get larger if allowed
10633 * by the MeasureSpec.
10634 *
10635 * @param size Default size for this view
10636 * @param measureSpec Constraints imposed by the parent
10637 * @return The size this view should be.
10638 */
10639 public static int getDefaultSize(int size, int measureSpec) {
10640 int result = size;
10641 int specMode = MeasureSpec.getMode(measureSpec);
10642 int specSize = MeasureSpec.getSize(measureSpec);
10643
10644 switch (specMode) {
10645 case MeasureSpec.UNSPECIFIED:
10646 result = size;
10647 break;
10648 case MeasureSpec.AT_MOST:
10649 case MeasureSpec.EXACTLY:
10650 result = specSize;
10651 break;
10652 }
10653 return result;
10654 }
10655
10656 /**
10657 * Returns the suggested minimum height that the view should use. This
10658 * returns the maximum of the view's minimum height
10659 * and the background's minimum height
10660 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10661 * <p>
10662 * When being used in {@link #onMeasure(int, int)}, the caller should still
10663 * ensure the returned height is within the requirements of the parent.
10664 *
10665 * @return The suggested minimum height of the view.
10666 */
10667 protected int getSuggestedMinimumHeight() {
10668 int suggestedMinHeight = mMinHeight;
10669
10670 if (mBGDrawable != null) {
10671 final int bgMinHeight = mBGDrawable.getMinimumHeight();
10672 if (suggestedMinHeight < bgMinHeight) {
10673 suggestedMinHeight = bgMinHeight;
10674 }
10675 }
10676
10677 return suggestedMinHeight;
10678 }
10679
10680 /**
10681 * Returns the suggested minimum width that the view should use. This
10682 * returns the maximum of the view's minimum width)
10683 * and the background's minimum width
10684 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10685 * <p>
10686 * When being used in {@link #onMeasure(int, int)}, the caller should still
10687 * ensure the returned width is within the requirements of the parent.
10688 *
10689 * @return The suggested minimum width of the view.
10690 */
10691 protected int getSuggestedMinimumWidth() {
10692 int suggestedMinWidth = mMinWidth;
10693
10694 if (mBGDrawable != null) {
10695 final int bgMinWidth = mBGDrawable.getMinimumWidth();
10696 if (suggestedMinWidth < bgMinWidth) {
10697 suggestedMinWidth = bgMinWidth;
10698 }
10699 }
10700
10701 return suggestedMinWidth;
10702 }
10703
10704 /**
10705 * Sets the minimum height of the view. It is not guaranteed the view will
10706 * be able to achieve this minimum height (for example, if its parent layout
10707 * constrains it with less available height).
10708 *
10709 * @param minHeight The minimum height the view will try to be.
10710 */
10711 public void setMinimumHeight(int minHeight) {
10712 mMinHeight = minHeight;
10713 }
10714
10715 /**
10716 * Sets the minimum width of the view. It is not guaranteed the view will
10717 * be able to achieve this minimum width (for example, if its parent layout
10718 * constrains it with less available width).
10719 *
10720 * @param minWidth The minimum width the view will try to be.
10721 */
10722 public void setMinimumWidth(int minWidth) {
10723 mMinWidth = minWidth;
10724 }
10725
10726 /**
10727 * Get the animation currently associated with this view.
10728 *
10729 * @return The animation that is currently playing or
10730 * scheduled to play for this view.
10731 */
10732 public Animation getAnimation() {
10733 return mCurrentAnimation;
10734 }
10735
10736 /**
10737 * Start the specified animation now.
10738 *
10739 * @param animation the animation to start now
10740 */
10741 public void startAnimation(Animation animation) {
10742 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10743 setAnimation(animation);
Romain Guy0fd89bf2011-01-26 15:41:30 -080010744 invalidateParentCaches();
10745 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010746 }
10747
10748 /**
10749 * Cancels any animations for this view.
10750 */
10751 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -080010752 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -080010753 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -080010754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010755 mCurrentAnimation = null;
Romain Guy0fd89bf2011-01-26 15:41:30 -080010756 invalidateParentIfNeeded();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010757 }
10758
10759 /**
10760 * Sets the next animation to play for this view.
10761 * If you want the animation to play immediately, use
10762 * startAnimation. This method provides allows fine-grained
10763 * control over the start time and invalidation, but you
10764 * must make sure that 1) the animation has a start time set, and
10765 * 2) the view will be invalidated when the animation is supposed to
10766 * start.
10767 *
10768 * @param animation The next animation, or null.
10769 */
10770 public void setAnimation(Animation animation) {
10771 mCurrentAnimation = animation;
10772 if (animation != null) {
10773 animation.reset();
10774 }
10775 }
10776
10777 /**
10778 * Invoked by a parent ViewGroup to notify the start of the animation
10779 * currently associated with this view. If you override this method,
10780 * always call super.onAnimationStart();
10781 *
10782 * @see #setAnimation(android.view.animation.Animation)
10783 * @see #getAnimation()
10784 */
10785 protected void onAnimationStart() {
10786 mPrivateFlags |= ANIMATION_STARTED;
10787 }
10788
10789 /**
10790 * Invoked by a parent ViewGroup to notify the end of the animation
10791 * currently associated with this view. If you override this method,
10792 * always call super.onAnimationEnd();
10793 *
10794 * @see #setAnimation(android.view.animation.Animation)
10795 * @see #getAnimation()
10796 */
10797 protected void onAnimationEnd() {
10798 mPrivateFlags &= ~ANIMATION_STARTED;
10799 }
10800
10801 /**
10802 * Invoked if there is a Transform that involves alpha. Subclass that can
10803 * draw themselves with the specified alpha should return true, and then
10804 * respect that alpha when their onDraw() is called. If this returns false
10805 * then the view may be redirected to draw into an offscreen buffer to
10806 * fulfill the request, which will look fine, but may be slower than if the
10807 * subclass handles it internally. The default implementation returns false.
10808 *
10809 * @param alpha The alpha (0..255) to apply to the view's drawing
10810 * @return true if the view can draw with the specified alpha.
10811 */
10812 protected boolean onSetAlpha(int alpha) {
10813 return false;
10814 }
10815
10816 /**
10817 * This is used by the RootView to perform an optimization when
10818 * the view hierarchy contains one or several SurfaceView.
10819 * SurfaceView is always considered transparent, but its children are not,
10820 * therefore all View objects remove themselves from the global transparent
10821 * region (passed as a parameter to this function).
10822 *
10823 * @param region The transparent region for this ViewRoot (window).
10824 *
10825 * @return Returns true if the effective visibility of the view at this
10826 * point is opaque, regardless of the transparent region; returns false
10827 * if it is possible for underlying windows to be seen behind the view.
10828 *
10829 * {@hide}
10830 */
10831 public boolean gatherTransparentRegion(Region region) {
10832 final AttachInfo attachInfo = mAttachInfo;
10833 if (region != null && attachInfo != null) {
10834 final int pflags = mPrivateFlags;
10835 if ((pflags & SKIP_DRAW) == 0) {
10836 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10837 // remove it from the transparent region.
10838 final int[] location = attachInfo.mTransparentLocation;
10839 getLocationInWindow(location);
10840 region.op(location[0], location[1], location[0] + mRight - mLeft,
10841 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10842 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10843 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10844 // exists, so we remove the background drawable's non-transparent
10845 // parts from this transparent region.
10846 applyDrawableToTransparentRegion(mBGDrawable, region);
10847 }
10848 }
10849 return true;
10850 }
10851
10852 /**
10853 * Play a sound effect for this view.
10854 *
10855 * <p>The framework will play sound effects for some built in actions, such as
10856 * clicking, but you may wish to play these effects in your widget,
10857 * for instance, for internal navigation.
10858 *
10859 * <p>The sound effect will only be played if sound effects are enabled by the user, and
10860 * {@link #isSoundEffectsEnabled()} is true.
10861 *
10862 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10863 */
10864 public void playSoundEffect(int soundConstant) {
10865 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10866 return;
10867 }
10868 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10869 }
10870
10871 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010872 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010873 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010874 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010875 *
10876 * <p>The framework will provide haptic feedback for some built in actions,
10877 * such as long presses, but you may wish to provide feedback for your
10878 * own widget.
10879 *
10880 * <p>The feedback will only be performed if
10881 * {@link #isHapticFeedbackEnabled()} is true.
10882 *
10883 * @param feedbackConstant One of the constants defined in
10884 * {@link HapticFeedbackConstants}
10885 */
10886 public boolean performHapticFeedback(int feedbackConstant) {
10887 return performHapticFeedback(feedbackConstant, 0);
10888 }
10889
10890 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010891 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010892 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010893 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 *
10895 * @param feedbackConstant One of the constants defined in
10896 * {@link HapticFeedbackConstants}
10897 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10898 */
10899 public boolean performHapticFeedback(int feedbackConstant, int flags) {
10900 if (mAttachInfo == null) {
10901 return false;
10902 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010903 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010904 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010905 && !isHapticFeedbackEnabled()) {
10906 return false;
10907 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010908 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10909 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010910 }
10911
10912 /**
Joe Onorato664644d2011-01-23 17:53:23 -080010913 * Request that the visibility of the status bar be changed.
10914 */
10915 public void setSystemUiVisibility(int visibility) {
10916 if (visibility != mSystemUiVisibility) {
10917 mSystemUiVisibility = visibility;
10918 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10919 mParent.recomputeViewAttributes(this);
10920 }
10921 }
10922 }
10923
10924 /**
10925 * Returns the status bar visibility that this view has requested.
10926 */
Joe Onoratoe595cad2011-01-24 09:22:12 -080010927 public int getSystemUiVisibility() {
Joe Onorato664644d2011-01-23 17:53:23 -080010928 return mSystemUiVisibility;
10929 }
10930
10931 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
10932 mOnSystemUiVisibilityChangeListener = l;
10933 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10934 mParent.recomputeViewAttributes(this);
10935 }
10936 }
10937
10938 /**
10939 */
10940 public void dispatchSystemUiVisibilityChanged(int visibility) {
10941 if (mOnSystemUiVisibilityChangeListener != null) {
Joe Onorato7bb8eeb2011-01-27 16:00:58 -080010942 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
Joe Onorato6ab77bd2011-01-31 11:21:10 -080010943 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
Joe Onorato664644d2011-01-23 17:53:23 -080010944 }
10945 }
10946
10947 /**
Joe Malin32736f02011-01-19 16:14:20 -080010948 * Creates an image that the system displays during the drag and drop
10949 * operation. This is called a &quot;drag shadow&quot;. The default implementation
10950 * for a DragShadowBuilder based on a View returns an image that has exactly the same
10951 * appearance as the given View. The default also positions the center of the drag shadow
10952 * directly under the touch point. If no View is provided (the constructor with no parameters
10953 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
10954 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
10955 * default is an invisible drag shadow.
10956 * <p>
10957 * You are not required to use the View you provide to the constructor as the basis of the
10958 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
10959 * anything you want as the drag shadow.
10960 * </p>
10961 * <p>
10962 * You pass a DragShadowBuilder object to the system when you start the drag. The system
10963 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
10964 * size and position of the drag shadow. It uses this data to construct a
10965 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
10966 * so that your application can draw the shadow image in the Canvas.
10967 * </p>
Christopher Tate2c095f32010-10-04 14:13:40 -070010968 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010969 public static class DragShadowBuilder {
Christopher Tatea0374192010-10-05 13:06:41 -070010970 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010971
10972 /**
Joe Malin32736f02011-01-19 16:14:20 -080010973 * Constructs a shadow image builder based on a View. By default, the resulting drag
10974 * shadow will have the same appearance and dimensions as the View, with the touch point
10975 * over the center of the View.
10976 * @param view A View. Any View in scope can be used.
Christopher Tate2c095f32010-10-04 14:13:40 -070010977 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010978 public DragShadowBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010979 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010980 }
10981
Christopher Tate17ed60c2011-01-18 12:50:26 -080010982 /**
10983 * Construct a shadow builder object with no associated View. This
10984 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
10985 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
10986 * to supply the drag shadow's dimensions and appearance without
Joe Malin32736f02011-01-19 16:14:20 -080010987 * reference to any View object. If they are not overridden, then the result is an
10988 * invisible drag shadow.
Christopher Tate17ed60c2011-01-18 12:50:26 -080010989 */
10990 public DragShadowBuilder() {
10991 mView = new WeakReference<View>(null);
10992 }
10993
10994 /**
10995 * Returns the View object that had been passed to the
10996 * {@link #View.DragShadowBuilder(View)}
10997 * constructor. If that View parameter was {@code null} or if the
10998 * {@link #View.DragShadowBuilder()}
10999 * constructor was used to instantiate the builder object, this method will return
11000 * null.
11001 *
11002 * @return The View object associate with this builder object.
11003 */
Chris Tate6b391282010-10-14 15:48:59 -070011004 final public View getView() {
11005 return mView.get();
11006 }
11007
Christopher Tate2c095f32010-10-04 14:13:40 -070011008 /**
Joe Malin32736f02011-01-19 16:14:20 -080011009 * Provides the metrics for the shadow image. These include the dimensions of
11010 * the shadow image, and the point within that shadow that should
Christopher Tate2c095f32010-10-04 14:13:40 -070011011 * be centered under the touch location while dragging.
11012 * <p>
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011013 * The default implementation sets the dimensions of the shadow to be the
Joe Malin32736f02011-01-19 16:14:20 -080011014 * same as the dimensions of the View itself and centers the shadow under
11015 * the touch point.
11016 * </p>
Christopher Tate2c095f32010-10-04 14:13:40 -070011017 *
Joe Malin32736f02011-01-19 16:14:20 -080011018 * @param shadowSize A {@link android.graphics.Point} containing the width and height
11019 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
11020 * desired width and must set {@link android.graphics.Point#y} to the desired height of the
11021 * image.
11022 *
11023 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
11024 * shadow image that should be underneath the touch point during the drag and drop
11025 * operation. Your application must set {@link android.graphics.Point#x} to the
11026 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
Christopher Tate2c095f32010-10-04 14:13:40 -070011027 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011028 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070011029 final View view = mView.get();
11030 if (view != null) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011031 shadowSize.set(view.getWidth(), view.getHeight());
11032 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
Christopher Tatea0374192010-10-05 13:06:41 -070011033 } else {
11034 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
11035 }
Christopher Tate2c095f32010-10-04 14:13:40 -070011036 }
11037
11038 /**
Joe Malin32736f02011-01-19 16:14:20 -080011039 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
11040 * based on the dimensions it received from the
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011041 * {@link #onProvideShadowMetrics(Point, Point)} callback.
Christopher Tate2c095f32010-10-04 14:13:40 -070011042 *
Joe Malin32736f02011-01-19 16:14:20 -080011043 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
Christopher Tate2c095f32010-10-04 14:13:40 -070011044 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011045 public void onDrawShadow(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070011046 final View view = mView.get();
11047 if (view != null) {
11048 view.draw(canvas);
11049 } else {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011050 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
Christopher Tatea0374192010-10-05 13:06:41 -070011051 }
Christopher Tate2c095f32010-10-04 14:13:40 -070011052 }
11053 }
11054
11055 /**
Joe Malin32736f02011-01-19 16:14:20 -080011056 * Starts a drag and drop operation. When your application calls this method, it passes a
11057 * {@link android.view.View.DragShadowBuilder} object to the system. The
11058 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
11059 * to get metrics for the drag shadow, and then calls the object's
11060 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
11061 * <p>
11062 * Once the system has the drag shadow, it begins the drag and drop operation by sending
11063 * drag events to all the View objects in your application that are currently visible. It does
11064 * this either by calling the View object's drag listener (an implementation of
11065 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
11066 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
11067 * Both are passed a {@link android.view.DragEvent} object that has a
11068 * {@link android.view.DragEvent#getAction()} value of
11069 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
11070 * </p>
11071 * <p>
11072 * Your application can invoke startDrag() on any attached View object. The View object does not
11073 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
11074 * be related to the View the user selected for dragging.
11075 * </p>
11076 * @param data A {@link android.content.ClipData} object pointing to the data to be
11077 * transferred by the drag and drop operation.
11078 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
11079 * drag shadow.
11080 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
11081 * drop operation. This Object is put into every DragEvent object sent by the system during the
11082 * current drag.
11083 * <p>
11084 * myLocalState is a lightweight mechanism for the sending information from the dragged View
11085 * to the target Views. For example, it can contain flags that differentiate between a
11086 * a copy operation and a move operation.
11087 * </p>
11088 * @param flags Flags that control the drag and drop operation. No flags are currently defined,
11089 * so the parameter should be set to 0.
11090 * @return {@code true} if the method completes successfully, or
11091 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
11092 * do a drag, and so no drag operation is in progress.
Christopher Tatea53146c2010-09-07 11:57:52 -070011093 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011094 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080011095 Object myLocalState, int flags) {
Christopher Tate2c095f32010-10-04 14:13:40 -070011096 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate02d2b3b2011-01-10 20:43:53 -080011097 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
Christopher Tatea53146c2010-09-07 11:57:52 -070011098 }
11099 boolean okay = false;
11100
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011101 Point shadowSize = new Point();
11102 Point shadowTouchPoint = new Point();
11103 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
Christopher Tate2c095f32010-10-04 14:13:40 -070011104
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011105 if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
11106 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
11107 throw new IllegalStateException("Drag shadow dimensions must not be negative");
Christopher Tate2c095f32010-10-04 14:13:40 -070011108 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011109
Chris Tatea32dcf72010-10-14 12:13:50 -070011110 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011111 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
11112 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
Chris Tatea32dcf72010-10-14 12:13:50 -070011113 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011114 Surface surface = new Surface();
11115 try {
11116 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080011117 flags, shadowSize.x, shadowSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070011118 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070011119 + " surface=" + surface);
11120 if (token != null) {
11121 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070011122 try {
Chris Tate6b391282010-10-14 15:48:59 -070011123 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011124 shadowBuilder.onDrawShadow(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070011125 } finally {
11126 surface.unlockCanvasAndPost(canvas);
11127 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011128
Christopher Tate407b4e92010-11-30 17:14:08 -080011129 final ViewRoot root = getViewRoot();
11130
11131 // Cache the local state object for delivery with DragEvents
11132 root.setLocalDragState(myLocalState);
11133
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011134 // repurpose 'shadowSize' for the last touch point
11135 root.getLastTouchPoint(shadowSize);
Christopher Tate2c095f32010-10-04 14:13:40 -070011136
Christopher Tatea53146c2010-09-07 11:57:52 -070011137 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011138 shadowSize.x, shadowSize.y,
11139 shadowTouchPoint.x, shadowTouchPoint.y, data);
Christopher Tate2c095f32010-10-04 14:13:40 -070011140 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070011141 }
11142 } catch (Exception e) {
11143 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
11144 surface.destroy();
11145 }
11146
11147 return okay;
11148 }
11149
Christopher Tatea53146c2010-09-07 11:57:52 -070011150 /**
Joe Malin32736f02011-01-19 16:14:20 -080011151 * Handles drag events sent by the system following a call to
11152 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
11153 *<p>
11154 * When the system calls this method, it passes a
11155 * {@link android.view.DragEvent} object. A call to
11156 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
11157 * in DragEvent. The method uses these to determine what is happening in the drag and drop
11158 * operation.
11159 * @param event The {@link android.view.DragEvent} sent by the system.
11160 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
11161 * in DragEvent, indicating the type of drag event represented by this object.
11162 * @return {@code true} if the method was successful, otherwise {@code false}.
11163 * <p>
11164 * The method should return {@code true} in response to an action type of
11165 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
11166 * operation.
11167 * </p>
11168 * <p>
11169 * The method should also return {@code true} in response to an action type of
11170 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
11171 * {@code false} if it didn't.
11172 * </p>
Christopher Tatea53146c2010-09-07 11:57:52 -070011173 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070011174 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070011175 return false;
11176 }
11177
11178 /**
Joe Malin32736f02011-01-19 16:14:20 -080011179 * Detects if this View is enabled and has a drag event listener.
11180 * If both are true, then it calls the drag event listener with the
11181 * {@link android.view.DragEvent} it received. If the drag event listener returns
11182 * {@code true}, then dispatchDragEvent() returns {@code true}.
11183 * <p>
11184 * For all other cases, the method calls the
11185 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
11186 * method and returns its result.
11187 * </p>
11188 * <p>
11189 * This ensures that a drag event is always consumed, even if the View does not have a drag
11190 * event listener. However, if the View has a listener and the listener returns true, then
11191 * onDragEvent() is not called.
11192 * </p>
Christopher Tatea53146c2010-09-07 11:57:52 -070011193 */
11194 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070011195 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
11196 && mOnDragListener.onDrag(this, event)) {
11197 return true;
11198 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011199 return onDragEvent(event);
11200 }
11201
11202 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070011203 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
11204 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070011205 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070011206 */
11207 public void onCloseSystemDialogs(String reason) {
11208 }
Joe Malin32736f02011-01-19 16:14:20 -080011209
Dianne Hackbornffa42482009-09-23 22:20:11 -070011210 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 * Given a Drawable whose bounds have been set to draw into this view,
11212 * update a Region being computed for {@link #gatherTransparentRegion} so
11213 * that any non-transparent parts of the Drawable are removed from the
11214 * given transparent region.
11215 *
11216 * @param dr The Drawable whose transparency is to be applied to the region.
11217 * @param region A Region holding the current transparency information,
11218 * where any parts of the region that are set are considered to be
11219 * transparent. On return, this region will be modified to have the
11220 * transparency information reduced by the corresponding parts of the
11221 * Drawable that are not transparent.
11222 * {@hide}
11223 */
11224 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
11225 if (DBG) {
11226 Log.i("View", "Getting transparent region for: " + this);
11227 }
11228 final Region r = dr.getTransparentRegion();
11229 final Rect db = dr.getBounds();
11230 final AttachInfo attachInfo = mAttachInfo;
11231 if (r != null && attachInfo != null) {
11232 final int w = getRight()-getLeft();
11233 final int h = getBottom()-getTop();
11234 if (db.left > 0) {
11235 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
11236 r.op(0, 0, db.left, h, Region.Op.UNION);
11237 }
11238 if (db.right < w) {
11239 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
11240 r.op(db.right, 0, w, h, Region.Op.UNION);
11241 }
11242 if (db.top > 0) {
11243 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
11244 r.op(0, 0, w, db.top, Region.Op.UNION);
11245 }
11246 if (db.bottom < h) {
11247 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
11248 r.op(0, db.bottom, w, h, Region.Op.UNION);
11249 }
11250 final int[] location = attachInfo.mTransparentLocation;
11251 getLocationInWindow(location);
11252 r.translate(location[0], location[1]);
11253 region.op(r, Region.Op.INTERSECT);
11254 } else {
11255 region.op(db, Region.Op.DIFFERENCE);
11256 }
11257 }
11258
Adam Powelle14579b2009-12-16 18:39:52 -080011259 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011260 mHasPerformedLongPress = false;
11261
11262 if (mPendingCheckForLongPress == null) {
11263 mPendingCheckForLongPress = new CheckForLongPress();
11264 }
11265 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080011266 postDelayed(mPendingCheckForLongPress,
11267 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011268 }
11269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011270 /**
11271 * Inflate a view from an XML resource. This convenience method wraps the {@link
11272 * LayoutInflater} class, which provides a full range of options for view inflation.
11273 *
11274 * @param context The Context object for your activity or application.
11275 * @param resource The resource ID to inflate
11276 * @param root A view group that will be the parent. Used to properly inflate the
11277 * layout_* parameters.
11278 * @see LayoutInflater
11279 */
11280 public static View inflate(Context context, int resource, ViewGroup root) {
11281 LayoutInflater factory = LayoutInflater.from(context);
11282 return factory.inflate(resource, root);
11283 }
Romain Guy33e72ae2010-07-17 12:40:29 -070011284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011285 /**
Adam Powell637d3372010-08-25 14:37:03 -070011286 * Scroll the view with standard behavior for scrolling beyond the normal
11287 * content boundaries. Views that call this method should override
11288 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
11289 * results of an over-scroll operation.
11290 *
11291 * Views can use this method to handle any touch or fling-based scrolling.
11292 *
11293 * @param deltaX Change in X in pixels
11294 * @param deltaY Change in Y in pixels
11295 * @param scrollX Current X scroll value in pixels before applying deltaX
11296 * @param scrollY Current Y scroll value in pixels before applying deltaY
11297 * @param scrollRangeX Maximum content scroll range along the X axis
11298 * @param scrollRangeY Maximum content scroll range along the Y axis
11299 * @param maxOverScrollX Number of pixels to overscroll by in either direction
11300 * along the X axis.
11301 * @param maxOverScrollY Number of pixels to overscroll by in either direction
11302 * along the Y axis.
11303 * @param isTouchEvent true if this scroll operation is the result of a touch event.
11304 * @return true if scrolling was clamped to an over-scroll boundary along either
11305 * axis, false otherwise.
11306 */
11307 protected boolean overScrollBy(int deltaX, int deltaY,
11308 int scrollX, int scrollY,
11309 int scrollRangeX, int scrollRangeY,
11310 int maxOverScrollX, int maxOverScrollY,
11311 boolean isTouchEvent) {
11312 final int overScrollMode = mOverScrollMode;
11313 final boolean canScrollHorizontal =
11314 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
11315 final boolean canScrollVertical =
11316 computeVerticalScrollRange() > computeVerticalScrollExtent();
11317 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
11318 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
11319 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
11320 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
11321
11322 int newScrollX = scrollX + deltaX;
11323 if (!overScrollHorizontal) {
11324 maxOverScrollX = 0;
11325 }
11326
11327 int newScrollY = scrollY + deltaY;
11328 if (!overScrollVertical) {
11329 maxOverScrollY = 0;
11330 }
11331
11332 // Clamp values if at the limits and record
11333 final int left = -maxOverScrollX;
11334 final int right = maxOverScrollX + scrollRangeX;
11335 final int top = -maxOverScrollY;
11336 final int bottom = maxOverScrollY + scrollRangeY;
11337
11338 boolean clampedX = false;
11339 if (newScrollX > right) {
11340 newScrollX = right;
11341 clampedX = true;
11342 } else if (newScrollX < left) {
11343 newScrollX = left;
11344 clampedX = true;
11345 }
11346
11347 boolean clampedY = false;
11348 if (newScrollY > bottom) {
11349 newScrollY = bottom;
11350 clampedY = true;
11351 } else if (newScrollY < top) {
11352 newScrollY = top;
11353 clampedY = true;
11354 }
11355
11356 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
11357
11358 return clampedX || clampedY;
11359 }
11360
11361 /**
11362 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
11363 * respond to the results of an over-scroll operation.
11364 *
11365 * @param scrollX New X scroll value in pixels
11366 * @param scrollY New Y scroll value in pixels
11367 * @param clampedX True if scrollX was clamped to an over-scroll boundary
11368 * @param clampedY True if scrollY was clamped to an over-scroll boundary
11369 */
11370 protected void onOverScrolled(int scrollX, int scrollY,
11371 boolean clampedX, boolean clampedY) {
11372 // Intentionally empty.
11373 }
11374
11375 /**
11376 * Returns the over-scroll mode for this view. The result will be
11377 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11378 * (allow over-scrolling only if the view content is larger than the container),
11379 * or {@link #OVER_SCROLL_NEVER}.
11380 *
11381 * @return This view's over-scroll mode.
11382 */
11383 public int getOverScrollMode() {
11384 return mOverScrollMode;
11385 }
11386
11387 /**
11388 * Set the over-scroll mode for this view. Valid over-scroll modes are
11389 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11390 * (allow over-scrolling only if the view content is larger than the container),
11391 * or {@link #OVER_SCROLL_NEVER}.
11392 *
11393 * Setting the over-scroll mode of a view will have an effect only if the
11394 * view is capable of scrolling.
11395 *
11396 * @param overScrollMode The new over-scroll mode for this view.
11397 */
11398 public void setOverScrollMode(int overScrollMode) {
11399 if (overScrollMode != OVER_SCROLL_ALWAYS &&
11400 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
11401 overScrollMode != OVER_SCROLL_NEVER) {
11402 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
11403 }
11404 mOverScrollMode = overScrollMode;
11405 }
11406
11407 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011408 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
11409 * Each MeasureSpec represents a requirement for either the width or the height.
11410 * A MeasureSpec is comprised of a size and a mode. There are three possible
11411 * modes:
11412 * <dl>
11413 * <dt>UNSPECIFIED</dt>
11414 * <dd>
11415 * The parent has not imposed any constraint on the child. It can be whatever size
11416 * it wants.
11417 * </dd>
11418 *
11419 * <dt>EXACTLY</dt>
11420 * <dd>
11421 * The parent has determined an exact size for the child. The child is going to be
11422 * given those bounds regardless of how big it wants to be.
11423 * </dd>
11424 *
11425 * <dt>AT_MOST</dt>
11426 * <dd>
11427 * The child can be as large as it wants up to the specified size.
11428 * </dd>
11429 * </dl>
11430 *
11431 * MeasureSpecs are implemented as ints to reduce object allocation. This class
11432 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
11433 */
11434 public static class MeasureSpec {
11435 private static final int MODE_SHIFT = 30;
11436 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
11437
11438 /**
11439 * Measure specification mode: The parent has not imposed any constraint
11440 * on the child. It can be whatever size it wants.
11441 */
11442 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
11443
11444 /**
11445 * Measure specification mode: The parent has determined an exact size
11446 * for the child. The child is going to be given those bounds regardless
11447 * of how big it wants to be.
11448 */
11449 public static final int EXACTLY = 1 << MODE_SHIFT;
11450
11451 /**
11452 * Measure specification mode: The child can be as large as it wants up
11453 * to the specified size.
11454 */
11455 public static final int AT_MOST = 2 << MODE_SHIFT;
11456
11457 /**
11458 * Creates a measure specification based on the supplied size and mode.
11459 *
11460 * The mode must always be one of the following:
11461 * <ul>
11462 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
11463 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
11464 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
11465 * </ul>
11466 *
11467 * @param size the size of the measure specification
11468 * @param mode the mode of the measure specification
11469 * @return the measure specification based on size and mode
11470 */
11471 public static int makeMeasureSpec(int size, int mode) {
11472 return size + mode;
11473 }
11474
11475 /**
11476 * Extracts the mode from the supplied measure specification.
11477 *
11478 * @param measureSpec the measure specification to extract the mode from
11479 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
11480 * {@link android.view.View.MeasureSpec#AT_MOST} or
11481 * {@link android.view.View.MeasureSpec#EXACTLY}
11482 */
11483 public static int getMode(int measureSpec) {
11484 return (measureSpec & MODE_MASK);
11485 }
11486
11487 /**
11488 * Extracts the size from the supplied measure specification.
11489 *
11490 * @param measureSpec the measure specification to extract the size from
11491 * @return the size in pixels defined in the supplied measure specification
11492 */
11493 public static int getSize(int measureSpec) {
11494 return (measureSpec & ~MODE_MASK);
11495 }
11496
11497 /**
11498 * Returns a String representation of the specified measure
11499 * specification.
11500 *
11501 * @param measureSpec the measure specification to convert to a String
11502 * @return a String with the following format: "MeasureSpec: MODE SIZE"
11503 */
11504 public static String toString(int measureSpec) {
11505 int mode = getMode(measureSpec);
11506 int size = getSize(measureSpec);
11507
11508 StringBuilder sb = new StringBuilder("MeasureSpec: ");
11509
11510 if (mode == UNSPECIFIED)
11511 sb.append("UNSPECIFIED ");
11512 else if (mode == EXACTLY)
11513 sb.append("EXACTLY ");
11514 else if (mode == AT_MOST)
11515 sb.append("AT_MOST ");
11516 else
11517 sb.append(mode).append(" ");
11518
11519 sb.append(size);
11520 return sb.toString();
11521 }
11522 }
11523
11524 class CheckForLongPress implements Runnable {
11525
11526 private int mOriginalWindowAttachCount;
11527
11528 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011529 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011530 && mOriginalWindowAttachCount == mWindowAttachCount) {
11531 if (performLongClick()) {
11532 mHasPerformedLongPress = true;
11533 }
11534 }
11535 }
11536
11537 public void rememberWindowAttachCount() {
11538 mOriginalWindowAttachCount = mWindowAttachCount;
11539 }
11540 }
Joe Malin32736f02011-01-19 16:14:20 -080011541
Adam Powelle14579b2009-12-16 18:39:52 -080011542 private final class CheckForTap implements Runnable {
11543 public void run() {
11544 mPrivateFlags &= ~PREPRESSED;
11545 mPrivateFlags |= PRESSED;
11546 refreshDrawableState();
11547 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
11548 postCheckForLongClick(ViewConfiguration.getTapTimeout());
11549 }
11550 }
11551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011552
Adam Powella35d7682010-03-12 14:48:13 -080011553 private final class PerformClick implements Runnable {
11554 public void run() {
11555 performClick();
11556 }
11557 }
11558
Dianne Hackborn63042d62011-01-26 18:56:29 -080011559 /** @hide */
11560 public void hackTurnOffWindowResizeAnim(boolean off) {
11561 mAttachInfo.mTurnOffWindowResizeAnim = off;
11562 }
Joe Malin32736f02011-01-19 16:14:20 -080011563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011564 /**
11565 * Interface definition for a callback to be invoked when a key event is
11566 * dispatched to this view. The callback will be invoked before the key
11567 * event is given to the view.
11568 */
11569 public interface OnKeyListener {
11570 /**
11571 * Called when a key is dispatched to a view. This allows listeners to
11572 * get a chance to respond before the target view.
11573 *
11574 * @param v The view the key has been dispatched to.
11575 * @param keyCode The code for the physical key that was pressed
11576 * @param event The KeyEvent object containing full information about
11577 * the event.
11578 * @return True if the listener has consumed the event, false otherwise.
11579 */
11580 boolean onKey(View v, int keyCode, KeyEvent event);
11581 }
11582
11583 /**
11584 * Interface definition for a callback to be invoked when a touch event is
11585 * dispatched to this view. The callback will be invoked before the touch
11586 * event is given to the view.
11587 */
11588 public interface OnTouchListener {
11589 /**
11590 * Called when a touch event is dispatched to a view. This allows listeners to
11591 * get a chance to respond before the target view.
11592 *
11593 * @param v The view the touch event has been dispatched to.
11594 * @param event The MotionEvent object containing full information about
11595 * the event.
11596 * @return True if the listener has consumed the event, false otherwise.
11597 */
11598 boolean onTouch(View v, MotionEvent event);
11599 }
11600
11601 /**
11602 * Interface definition for a callback to be invoked when a view has been clicked and held.
11603 */
11604 public interface OnLongClickListener {
11605 /**
11606 * Called when a view has been clicked and held.
11607 *
11608 * @param v The view that was clicked and held.
11609 *
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -080011610 * @return true if the callback consumed the long click, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011611 */
11612 boolean onLongClick(View v);
11613 }
11614
11615 /**
Chris Tate32affef2010-10-18 15:29:21 -070011616 * Interface definition for a callback to be invoked when a drag is being dispatched
11617 * to this view. The callback will be invoked before the hosting view's own
11618 * onDrag(event) method. If the listener wants to fall back to the hosting view's
11619 * onDrag(event) behavior, it should return 'false' from this callback.
11620 */
11621 public interface OnDragListener {
11622 /**
11623 * Called when a drag event is dispatched to a view. This allows listeners
11624 * to get a chance to override base View behavior.
11625 *
Joe Malin32736f02011-01-19 16:14:20 -080011626 * @param v The View that received the drag event.
11627 * @param event The {@link android.view.DragEvent} object for the drag event.
11628 * @return {@code true} if the drag event was handled successfully, or {@code false}
11629 * if the drag event was not handled. Note that {@code false} will trigger the View
11630 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
Chris Tate32affef2010-10-18 15:29:21 -070011631 */
11632 boolean onDrag(View v, DragEvent event);
11633 }
11634
11635 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 * Interface definition for a callback to be invoked when the focus state of
11637 * a view changed.
11638 */
11639 public interface OnFocusChangeListener {
11640 /**
11641 * Called when the focus state of a view has changed.
11642 *
11643 * @param v The view whose state has changed.
11644 * @param hasFocus The new focus state of v.
11645 */
11646 void onFocusChange(View v, boolean hasFocus);
11647 }
11648
11649 /**
11650 * Interface definition for a callback to be invoked when a view is clicked.
11651 */
11652 public interface OnClickListener {
11653 /**
11654 * Called when a view has been clicked.
11655 *
11656 * @param v The view that was clicked.
11657 */
11658 void onClick(View v);
11659 }
11660
11661 /**
11662 * Interface definition for a callback to be invoked when the context menu
11663 * for this view is being built.
11664 */
11665 public interface OnCreateContextMenuListener {
11666 /**
11667 * Called when the context menu for this view is being built. It is not
11668 * safe to hold onto the menu after this method returns.
11669 *
11670 * @param menu The context menu that is being built
11671 * @param v The view for which the context menu is being built
11672 * @param menuInfo Extra information about the item for which the
11673 * context menu should be shown. This information will vary
11674 * depending on the class of v.
11675 */
11676 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
11677 }
11678
Joe Onorato664644d2011-01-23 17:53:23 -080011679 /**
11680 * Interface definition for a callback to be invoked when the status bar changes
11681 * visibility.
11682 *
11683 * @see #setOnSystemUiVisibilityChangeListener
11684 */
11685 public interface OnSystemUiVisibilityChangeListener {
11686 /**
11687 * Called when the status bar changes visibility because of a call to
11688 * {@link #setSystemUiVisibility}.
11689 *
11690 * @param visibility {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}.
11691 */
11692 public void onSystemUiVisibilityChange(int visibility);
11693 }
11694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011695 private final class UnsetPressedState implements Runnable {
11696 public void run() {
11697 setPressed(false);
11698 }
11699 }
11700
11701 /**
11702 * Base class for derived classes that want to save and restore their own
11703 * state in {@link android.view.View#onSaveInstanceState()}.
11704 */
11705 public static class BaseSavedState extends AbsSavedState {
11706 /**
11707 * Constructor used when reading from a parcel. Reads the state of the superclass.
11708 *
11709 * @param source
11710 */
11711 public BaseSavedState(Parcel source) {
11712 super(source);
11713 }
11714
11715 /**
11716 * Constructor called by derived classes when creating their SavedState objects
11717 *
11718 * @param superState The state of the superclass of this view
11719 */
11720 public BaseSavedState(Parcelable superState) {
11721 super(superState);
11722 }
11723
11724 public static final Parcelable.Creator<BaseSavedState> CREATOR =
11725 new Parcelable.Creator<BaseSavedState>() {
11726 public BaseSavedState createFromParcel(Parcel in) {
11727 return new BaseSavedState(in);
11728 }
11729
11730 public BaseSavedState[] newArray(int size) {
11731 return new BaseSavedState[size];
11732 }
11733 };
11734 }
11735
11736 /**
11737 * A set of information given to a view when it is attached to its parent
11738 * window.
11739 */
11740 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011741 interface Callbacks {
11742 void playSoundEffect(int effectId);
11743 boolean performHapticFeedback(int effectId, boolean always);
11744 }
11745
11746 /**
11747 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11748 * to a Handler. This class contains the target (View) to invalidate and
11749 * the coordinates of the dirty rectangle.
11750 *
11751 * For performance purposes, this class also implements a pool of up to
11752 * POOL_LIMIT objects that get reused. This reduces memory allocations
11753 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011754 */
Romain Guyd928d682009-03-31 17:52:16 -070011755 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011756 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070011757 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11758 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070011759 public InvalidateInfo newInstance() {
11760 return new InvalidateInfo();
11761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011762
Romain Guyd928d682009-03-31 17:52:16 -070011763 public void onAcquired(InvalidateInfo element) {
11764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011765
Romain Guyd928d682009-03-31 17:52:16 -070011766 public void onReleased(InvalidateInfo element) {
11767 }
11768 }, POOL_LIMIT)
11769 );
11770
11771 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011772
11773 View target;
11774
11775 int left;
11776 int top;
11777 int right;
11778 int bottom;
11779
Romain Guyd928d682009-03-31 17:52:16 -070011780 public void setNextPoolable(InvalidateInfo element) {
11781 mNext = element;
11782 }
11783
11784 public InvalidateInfo getNextPoolable() {
11785 return mNext;
11786 }
11787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011788 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070011789 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011790 }
11791
11792 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070011793 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011794 }
11795 }
11796
11797 final IWindowSession mSession;
11798
11799 final IWindow mWindow;
11800
11801 final IBinder mWindowToken;
11802
11803 final Callbacks mRootCallbacks;
11804
Chet Haasedaf98e92011-01-10 14:10:36 -080011805 Canvas mHardwareCanvas;
11806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011807 /**
11808 * The top view of the hierarchy.
11809 */
11810 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070011811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011812 IBinder mPanelParentWindowToken;
11813 Surface mSurface;
11814
Romain Guyb051e892010-09-28 19:09:36 -070011815 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080011816 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070011817 HardwareRenderer mHardwareRenderer;
Joe Malin32736f02011-01-19 16:14:20 -080011818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011819 /**
Romain Guy8506ab42009-06-11 17:35:47 -070011820 * Scale factor used by the compatibility mode
11821 */
11822 float mApplicationScale;
11823
11824 /**
11825 * Indicates whether the application is in compatibility mode
11826 */
11827 boolean mScalingRequired;
11828
11829 /**
Dianne Hackborn63042d62011-01-26 18:56:29 -080011830 * If set, ViewRoot doesn't use its lame animation for when the window resizes.
11831 */
11832 boolean mTurnOffWindowResizeAnim;
Joe Malin32736f02011-01-19 16:14:20 -080011833
Dianne Hackborn63042d62011-01-26 18:56:29 -080011834 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011835 * Left position of this view's window
11836 */
11837 int mWindowLeft;
11838
11839 /**
11840 * Top position of this view's window
11841 */
11842 int mWindowTop;
11843
11844 /**
Adam Powell26153a32010-11-08 15:22:27 -080011845 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070011846 */
Adam Powell26153a32010-11-08 15:22:27 -080011847 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070011848
11849 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011850 * For windows that are full-screen but using insets to layout inside
11851 * of the screen decorations, these are the current insets for the
11852 * content of the window.
11853 */
11854 final Rect mContentInsets = new Rect();
11855
11856 /**
11857 * For windows that are full-screen but using insets to layout inside
11858 * of the screen decorations, these are the current insets for the
11859 * actual visible parts of the window.
11860 */
11861 final Rect mVisibleInsets = new Rect();
11862
11863 /**
11864 * The internal insets given by this window. This value is
11865 * supplied by the client (through
11866 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11867 * be given to the window manager when changed to be used in laying
11868 * out windows behind it.
11869 */
11870 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11871 = new ViewTreeObserver.InternalInsetsInfo();
11872
11873 /**
11874 * All views in the window's hierarchy that serve as scroll containers,
11875 * used to determine if the window can be resized or must be panned
11876 * to adjust for a soft input area.
11877 */
11878 final ArrayList<View> mScrollContainers = new ArrayList<View>();
11879
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070011880 final KeyEvent.DispatcherState mKeyDispatchState
11881 = new KeyEvent.DispatcherState();
11882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011883 /**
11884 * Indicates whether the view's window currently has the focus.
11885 */
11886 boolean mHasWindowFocus;
11887
11888 /**
11889 * The current visibility of the window.
11890 */
11891 int mWindowVisibility;
11892
11893 /**
11894 * Indicates the time at which drawing started to occur.
11895 */
11896 long mDrawingTime;
11897
11898 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070011899 * Indicates whether or not ignoring the DIRTY_MASK flags.
11900 */
11901 boolean mIgnoreDirtyState;
11902
11903 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011904 * Indicates whether the view's window is currently in touch mode.
11905 */
11906 boolean mInTouchMode;
11907
11908 /**
11909 * Indicates that ViewRoot should trigger a global layout change
11910 * the next time it performs a traversal
11911 */
11912 boolean mRecomputeGlobalAttributes;
11913
11914 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011915 * Set during a traveral if any views want to keep the screen on.
11916 */
11917 boolean mKeepScreenOn;
11918
11919 /**
Joe Onorato664644d2011-01-23 17:53:23 -080011920 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
11921 */
11922 int mSystemUiVisibility;
11923
11924 /**
11925 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
11926 * attached.
11927 */
11928 boolean mHasSystemUiListeners;
11929
11930 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011931 * Set if the visibility of any views has changed.
11932 */
11933 boolean mViewVisibilityChanged;
11934
11935 /**
11936 * Set to true if a view has been scrolled.
11937 */
11938 boolean mViewScrollChanged;
11939
11940 /**
11941 * Global to the view hierarchy used as a temporary for dealing with
11942 * x/y points in the transparent region computations.
11943 */
11944 final int[] mTransparentLocation = new int[2];
11945
11946 /**
11947 * Global to the view hierarchy used as a temporary for dealing with
11948 * x/y points in the ViewGroup.invalidateChild implementation.
11949 */
11950 final int[] mInvalidateChildLocation = new int[2];
11951
Chet Haasec3aa3612010-06-17 08:50:37 -070011952
11953 /**
11954 * Global to the view hierarchy used as a temporary for dealing with
11955 * x/y location when view is transformed.
11956 */
11957 final float[] mTmpTransformLocation = new float[2];
11958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011959 /**
11960 * The view tree observer used to dispatch global events like
11961 * layout, pre-draw, touch mode change, etc.
11962 */
11963 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11964
11965 /**
11966 * A Canvas used by the view hierarchy to perform bitmap caching.
11967 */
11968 Canvas mCanvas;
11969
11970 /**
11971 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11972 * handler can be used to pump events in the UI events queue.
11973 */
11974 final Handler mHandler;
11975
11976 /**
11977 * Identifier for messages requesting the view to be invalidated.
11978 * Such messages should be sent to {@link #mHandler}.
11979 */
11980 static final int INVALIDATE_MSG = 0x1;
11981
11982 /**
11983 * Identifier for messages requesting the view to invalidate a region.
11984 * Such messages should be sent to {@link #mHandler}.
11985 */
11986 static final int INVALIDATE_RECT_MSG = 0x2;
11987
11988 /**
11989 * Temporary for use in computing invalidate rectangles while
11990 * calling up the hierarchy.
11991 */
11992 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070011993
11994 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070011995 * Temporary for use in computing hit areas with transformed views
11996 */
11997 final RectF mTmpTransformRect = new RectF();
11998
11999 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070012000 * Temporary list for use in collecting focusable descendents of a view.
12001 */
12002 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
12003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012004 /**
12005 * Creates a new set of attachment information with the specified
12006 * events handler and thread.
12007 *
12008 * @param handler the events handler the view must use
12009 */
12010 AttachInfo(IWindowSession session, IWindow window,
12011 Handler handler, Callbacks effectPlayer) {
12012 mSession = session;
12013 mWindow = window;
12014 mWindowToken = window.asBinder();
12015 mHandler = handler;
12016 mRootCallbacks = effectPlayer;
12017 }
12018 }
12019
12020 /**
12021 * <p>ScrollabilityCache holds various fields used by a View when scrolling
12022 * is supported. This avoids keeping too many unused fields in most
12023 * instances of View.</p>
12024 */
Mike Cleronf116bf82009-09-27 19:14:12 -070012025 private static class ScrollabilityCache implements Runnable {
Joe Malin32736f02011-01-19 16:14:20 -080012026
Mike Cleronf116bf82009-09-27 19:14:12 -070012027 /**
12028 * Scrollbars are not visible
12029 */
12030 public static final int OFF = 0;
12031
12032 /**
12033 * Scrollbars are visible
12034 */
12035 public static final int ON = 1;
12036
12037 /**
12038 * Scrollbars are fading away
12039 */
12040 public static final int FADING = 2;
12041
12042 public boolean fadeScrollBars;
Joe Malin32736f02011-01-19 16:14:20 -080012043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012044 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070012045 public int scrollBarDefaultDelayBeforeFade;
12046 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012047
12048 public int scrollBarSize;
12049 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070012050 public float[] interpolatorValues;
12051 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012052
12053 public final Paint paint;
12054 public final Matrix matrix;
12055 public Shader shader;
12056
Mike Cleronf116bf82009-09-27 19:14:12 -070012057 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
12058
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080012059 private static final float[] OPAQUE = { 255 };
12060 private static final float[] TRANSPARENT = { 0.0f };
Joe Malin32736f02011-01-19 16:14:20 -080012061
Mike Cleronf116bf82009-09-27 19:14:12 -070012062 /**
12063 * When fading should start. This time moves into the future every time
12064 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
12065 */
12066 public long fadeStartTime;
12067
12068
12069 /**
12070 * The current state of the scrollbars: ON, OFF, or FADING
12071 */
12072 public int state = OFF;
12073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012074 private int mLastColor;
12075
Mike Cleronf116bf82009-09-27 19:14:12 -070012076 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012077 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
12078 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070012079 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
12080 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012081
12082 paint = new Paint();
12083 matrix = new Matrix();
12084 // use use a height of 1, and then wack the matrix each time we
12085 // actually use it.
12086 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070012087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012088 paint.setShader(shader);
12089 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070012090 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012091 }
Romain Guy8506ab42009-06-11 17:35:47 -070012092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012093 public void setFadeColor(int color) {
12094 if (color != 0 && color != mLastColor) {
12095 mLastColor = color;
12096 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070012097
Romain Guye55e1a72009-08-27 10:42:26 -070012098 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
12099 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070012100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012101 paint.setShader(shader);
12102 // Restore the default transfer mode (src_over)
12103 paint.setXfermode(null);
12104 }
12105 }
Joe Malin32736f02011-01-19 16:14:20 -080012106
Mike Cleronf116bf82009-09-27 19:14:12 -070012107 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070012108 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070012109 if (now >= fadeStartTime) {
12110
12111 // the animation fades the scrollbars out by changing
12112 // the opacity (alpha) from fully opaque to fully
12113 // transparent
12114 int nextFrame = (int) now;
12115 int framesCount = 0;
12116
12117 Interpolator interpolator = scrollBarInterpolator;
12118
12119 // Start opaque
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080012120 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
Mike Cleronf116bf82009-09-27 19:14:12 -070012121
12122 // End transparent
12123 nextFrame += scrollBarFadeDuration;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080012124 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
Mike Cleronf116bf82009-09-27 19:14:12 -070012125
12126 state = FADING;
12127
12128 // Kick off the fade animation
Romain Guy0fd89bf2011-01-26 15:41:30 -080012129 host.invalidate(true);
Mike Cleronf116bf82009-09-27 19:14:12 -070012130 }
12131 }
12132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012133 }
12134}