blob: 5c6dd29c534f1fd067660e8621729a049556f43f [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;
Joe Onorato664644d2011-01-23 17:53:23 -080051import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.SystemClock;
53import android.os.SystemProperties;
54import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070056import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070057import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070058import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070059import android.util.Pools;
60import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.view.ContextMenu.ContextMenuInfo;
svetoslavganov75986cf2009-05-14 22:28:01 -070062import android.view.accessibility.AccessibilityEvent;
63import android.view.accessibility.AccessibilityEventSource;
64import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070066import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070067import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.view.inputmethod.InputConnection;
69import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.widget.ScrollBarDrawable;
71
Christopher Tatea0374192010-10-05 13:06:41 -070072import java.lang.ref.WeakReference;
svetoslavganov75986cf2009-05-14 22:28:01 -070073import java.lang.reflect.InvocationTargetException;
74import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import java.util.ArrayList;
76import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070077import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070078import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
80/**
81 * <p>
82 * This class represents the basic building block for user interface components. A View
83 * occupies a rectangular area on the screen and is responsible for drawing and
84 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070085 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
87 * are invisible containers that hold other Views (or other ViewGroups) and define
88 * their layout properties.
89 * </p>
90 *
91 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070092 * <p>For an introduction to using this class to develop your
93 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070095 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
102 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
103 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
104 * </p>
105 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700106 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 * <a name="Using"></a>
108 * <h3>Using Views</h3>
109 * <p>
110 * All of the views in a window are arranged in a single tree. You can add views
111 * either from code or by specifying a tree of views in one or more XML layout
112 * files. There are many specialized subclasses of views that act as controls or
113 * are capable of displaying text, images, or other content.
114 * </p>
115 * <p>
116 * Once you have created a tree of views, there are typically a few types of
117 * common operations you may wish to perform:
118 * <ul>
119 * <li><strong>Set properties:</strong> for example setting the text of a
120 * {@link android.widget.TextView}. The available properties and the methods
121 * that set them will vary among the different subclasses of views. Note that
122 * properties that are known at build time can be set in the XML layout
123 * files.</li>
124 * <li><strong>Set focus:</strong> The framework will handled moving focus in
125 * response to user input. To force focus to a specific view, call
126 * {@link #requestFocus}.</li>
127 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
128 * that will be notified when something interesting happens to the view. For
129 * example, all views will let you set a listener to be notified when the view
130 * gains or loses focus. You can register such a listener using
131 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
132 * specialized listeners. For example, a Button exposes a listener to notify
133 * clients when the button is clicked.</li>
134 * <li><strong>Set visibility:</strong> You can hide or show views using
135 * {@link #setVisibility}.</li>
136 * </ul>
137 * </p>
138 * <p><em>
139 * Note: The Android framework is responsible for measuring, laying out and
140 * drawing views. You should not call methods that perform these actions on
141 * views yourself unless you are actually implementing a
142 * {@link android.view.ViewGroup}.
143 * </em></p>
144 *
145 * <a name="Lifecycle"></a>
146 * <h3>Implementing a Custom View</h3>
147 *
148 * <p>
149 * To implement a custom view, you will usually begin by providing overrides for
150 * some of the standard methods that the framework calls on all views. You do
151 * not need to override all of these methods. In fact, you can start by just
152 * overriding {@link #onDraw(android.graphics.Canvas)}.
153 * <table border="2" width="85%" align="center" cellpadding="5">
154 * <thead>
155 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
156 * </thead>
157 *
158 * <tbody>
159 * <tr>
160 * <td rowspan="2">Creation</td>
161 * <td>Constructors</td>
162 * <td>There is a form of the constructor that are called when the view
163 * is created from code and a form that is called when the view is
164 * inflated from a layout file. The second form should parse and apply
165 * any attributes defined in the layout file.
166 * </td>
167 * </tr>
168 * <tr>
169 * <td><code>{@link #onFinishInflate()}</code></td>
170 * <td>Called after a view and all of its children has been inflated
171 * from XML.</td>
172 * </tr>
173 *
174 * <tr>
175 * <td rowspan="3">Layout</td>
176 * <td><code>{@link #onMeasure}</code></td>
177 * <td>Called to determine the size requirements for this view and all
178 * of its children.
179 * </td>
180 * </tr>
181 * <tr>
182 * <td><code>{@link #onLayout}</code></td>
183 * <td>Called when this view should assign a size and position to all
184 * of its children.
185 * </td>
186 * </tr>
187 * <tr>
188 * <td><code>{@link #onSizeChanged}</code></td>
189 * <td>Called when the size of this view has changed.
190 * </td>
191 * </tr>
192 *
193 * <tr>
194 * <td>Drawing</td>
195 * <td><code>{@link #onDraw}</code></td>
196 * <td>Called when the view should render its content.
197 * </td>
198 * </tr>
199 *
200 * <tr>
201 * <td rowspan="4">Event processing</td>
202 * <td><code>{@link #onKeyDown}</code></td>
203 * <td>Called when a new key event occurs.
204 * </td>
205 * </tr>
206 * <tr>
207 * <td><code>{@link #onKeyUp}</code></td>
208 * <td>Called when a key up event occurs.
209 * </td>
210 * </tr>
211 * <tr>
212 * <td><code>{@link #onTrackballEvent}</code></td>
213 * <td>Called when a trackball motion event occurs.
214 * </td>
215 * </tr>
216 * <tr>
217 * <td><code>{@link #onTouchEvent}</code></td>
218 * <td>Called when a touch screen motion event occurs.
219 * </td>
220 * </tr>
221 *
222 * <tr>
223 * <td rowspan="2">Focus</td>
224 * <td><code>{@link #onFocusChanged}</code></td>
225 * <td>Called when the view gains or loses focus.
226 * </td>
227 * </tr>
228 *
229 * <tr>
230 * <td><code>{@link #onWindowFocusChanged}</code></td>
231 * <td>Called when the window containing the view gains or loses focus.
232 * </td>
233 * </tr>
234 *
235 * <tr>
236 * <td rowspan="3">Attaching</td>
237 * <td><code>{@link #onAttachedToWindow()}</code></td>
238 * <td>Called when the view is attached to a window.
239 * </td>
240 * </tr>
241 *
242 * <tr>
243 * <td><code>{@link #onDetachedFromWindow}</code></td>
244 * <td>Called when the view is detached from its window.
245 * </td>
246 * </tr>
247 *
248 * <tr>
249 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
250 * <td>Called when the visibility of the window containing the view
251 * has changed.
252 * </td>
253 * </tr>
254 * </tbody>
255 *
256 * </table>
257 * </p>
258 *
259 * <a name="IDs"></a>
260 * <h3>IDs</h3>
261 * Views may have an integer id associated with them. These ids are typically
262 * assigned in the layout XML files, and are used to find specific views within
263 * the view tree. A common pattern is to:
264 * <ul>
265 * <li>Define a Button in the layout file and assign it a unique ID.
266 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700267 * &lt;Button
268 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 * android:layout_width="wrap_content"
270 * android:layout_height="wrap_content"
271 * android:text="@string/my_button_text"/&gt;
272 * </pre></li>
273 * <li>From the onCreate method of an Activity, find the Button
274 * <pre class="prettyprint">
275 * Button myButton = (Button) findViewById(R.id.my_button);
276 * </pre></li>
277 * </ul>
278 * <p>
279 * View IDs need not be unique throughout the tree, but it is good practice to
280 * ensure that they are at least unique within the part of the tree you are
281 * searching.
282 * </p>
283 *
284 * <a name="Position"></a>
285 * <h3>Position</h3>
286 * <p>
287 * The geometry of a view is that of a rectangle. A view has a location,
288 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
289 * two dimensions, expressed as a width and a height. The unit for location
290 * and dimensions is the pixel.
291 * </p>
292 *
293 * <p>
294 * It is possible to retrieve the location of a view by invoking the methods
295 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
296 * coordinate of the rectangle representing the view. The latter returns the
297 * top, or Y, coordinate of the rectangle representing the view. These methods
298 * both return the location of the view relative to its parent. For instance,
299 * when getLeft() returns 20, that means the view is located 20 pixels to the
300 * right of the left edge of its direct parent.
301 * </p>
302 *
303 * <p>
304 * In addition, several convenience methods are offered to avoid unnecessary
305 * computations, namely {@link #getRight()} and {@link #getBottom()}.
306 * These methods return the coordinates of the right and bottom edges of the
307 * rectangle representing the view. For instance, calling {@link #getRight()}
308 * is similar to the following computation: <code>getLeft() + getWidth()</code>
309 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
310 * </p>
311 *
312 * <a name="SizePaddingMargins"></a>
313 * <h3>Size, padding and margins</h3>
314 * <p>
315 * The size of a view is expressed with a width and a height. A view actually
316 * possess two pairs of width and height values.
317 * </p>
318 *
319 * <p>
320 * The first pair is known as <em>measured width</em> and
321 * <em>measured height</em>. These dimensions define how big a view wants to be
322 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
323 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
324 * and {@link #getMeasuredHeight()}.
325 * </p>
326 *
327 * <p>
328 * The second pair is simply known as <em>width</em> and <em>height</em>, or
329 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
330 * dimensions define the actual size of the view on screen, at drawing time and
331 * after layout. These values may, but do not have to, be different from the
332 * measured width and height. The width and height can be obtained by calling
333 * {@link #getWidth()} and {@link #getHeight()}.
334 * </p>
335 *
336 * <p>
337 * To measure its dimensions, a view takes into account its padding. The padding
338 * is expressed in pixels for the left, top, right and bottom parts of the view.
339 * Padding can be used to offset the content of the view by a specific amount of
340 * pixels. For instance, a left padding of 2 will push the view's content by
341 * 2 pixels to the right of the left edge. Padding can be set using the
342 * {@link #setPadding(int, int, int, int)} method and queried by calling
343 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
344 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
345 * </p>
346 *
347 * <p>
348 * Even though a view can define a padding, it does not provide any support for
349 * margins. However, view groups provide such a support. Refer to
350 * {@link android.view.ViewGroup} and
351 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
352 * </p>
353 *
354 * <a name="Layout"></a>
355 * <h3>Layout</h3>
356 * <p>
357 * Layout is a two pass process: a measure pass and a layout pass. The measuring
358 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
359 * of the view tree. Each view pushes dimension specifications down the tree
360 * during the recursion. At the end of the measure pass, every view has stored
361 * its measurements. The second pass happens in
362 * {@link #layout(int,int,int,int)} and is also top-down. During
363 * this pass each parent is responsible for positioning all of its children
364 * using the sizes computed in the measure pass.
365 * </p>
366 *
367 * <p>
368 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
369 * {@link #getMeasuredHeight()} values must be set, along with those for all of
370 * that view's descendants. A view's measured width and measured height values
371 * must respect the constraints imposed by the view's parents. This guarantees
372 * that at the end of the measure pass, all parents accept all of their
373 * children's measurements. A parent view may call measure() more than once on
374 * its children. For example, the parent may measure each child once with
375 * unspecified dimensions to find out how big they want to be, then call
376 * measure() on them again with actual numbers if the sum of all the children's
377 * unconstrained sizes is too big or too small.
378 * </p>
379 *
380 * <p>
381 * The measure pass uses two classes to communicate dimensions. The
382 * {@link MeasureSpec} class is used by views to tell their parents how they
383 * want to be measured and positioned. The base LayoutParams class just
384 * describes how big the view wants to be for both width and height. For each
385 * dimension, it can specify one of:
386 * <ul>
387 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800388 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 * (minus padding)
390 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
391 * enclose its content (plus padding).
392 * </ul>
393 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
394 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
395 * an X and Y value.
396 * </p>
397 *
398 * <p>
399 * MeasureSpecs are used to push requirements down the tree from parent to
400 * child. A MeasureSpec can be in one of three modes:
401 * <ul>
402 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
403 * of a child view. For example, a LinearLayout may call measure() on its child
404 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
405 * tall the child view wants to be given a width of 240 pixels.
406 * <li>EXACTLY: This is used by the parent to impose an exact size on the
407 * child. The child must use this size, and guarantee that all of its
408 * descendants will fit within this size.
409 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
410 * child. The child must gurantee that it and all of its descendants will fit
411 * within this size.
412 * </ul>
413 * </p>
414 *
415 * <p>
416 * To intiate a layout, call {@link #requestLayout}. This method is typically
417 * called by a view on itself when it believes that is can no longer fit within
418 * its current bounds.
419 * </p>
420 *
421 * <a name="Drawing"></a>
422 * <h3>Drawing</h3>
423 * <p>
424 * Drawing is handled by walking the tree and rendering each view that
425 * intersects the the invalid region. Because the tree is traversed in-order,
426 * this means that parents will draw before (i.e., behind) their children, with
427 * siblings drawn in the order they appear in the tree.
428 * If you set a background drawable for a View, then the View will draw it for you
429 * before calling back to its <code>onDraw()</code> method.
430 * </p>
431 *
432 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700433 * Note that the framework will not draw views that are not in the invalid region.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 * </p>
435 *
436 * <p>
437 * To force a view to draw, call {@link #invalidate()}.
438 * </p>
439 *
440 * <a name="EventHandlingThreading"></a>
441 * <h3>Event Handling and Threading</h3>
442 * <p>
443 * The basic cycle of a view is as follows:
444 * <ol>
445 * <li>An event comes in and is dispatched to the appropriate view. The view
446 * handles the event and notifies any listeners.</li>
447 * <li>If in the course of processing the event, the view's bounds may need
448 * to be changed, the view will call {@link #requestLayout()}.</li>
449 * <li>Similarly, if in the course of processing the event the view's appearance
450 * may need to be changed, the view will call {@link #invalidate()}.</li>
451 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
452 * the framework will take care of measuring, laying out, and drawing the tree
453 * as appropriate.</li>
454 * </ol>
455 * </p>
456 *
457 * <p><em>Note: The entire view tree is single threaded. You must always be on
458 * the UI thread when calling any method on any view.</em>
459 * If you are doing work on other threads and want to update the state of a view
460 * from that thread, you should use a {@link Handler}.
461 * </p>
462 *
463 * <a name="FocusHandling"></a>
464 * <h3>Focus Handling</h3>
465 * <p>
466 * The framework will handle routine focus movement in response to user input.
467 * This includes changing the focus as views are removed or hidden, or as new
468 * views become available. Views indicate their willingness to take focus
469 * through the {@link #isFocusable} method. To change whether a view can take
470 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
471 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
472 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
473 * </p>
474 * <p>
475 * Focus movement is based on an algorithm which finds the nearest neighbor in a
476 * given direction. In rare cases, the default algorithm may not match the
477 * intended behavior of the developer. In these situations, you can provide
478 * explicit overrides by using these XML attributes in the layout file:
479 * <pre>
480 * nextFocusDown
481 * nextFocusLeft
482 * nextFocusRight
483 * nextFocusUp
484 * </pre>
485 * </p>
486 *
487 *
488 * <p>
489 * To get a particular view to take focus, call {@link #requestFocus()}.
490 * </p>
491 *
492 * <a name="TouchMode"></a>
493 * <h3>Touch Mode</h3>
494 * <p>
495 * When a user is navigating a user interface via directional keys such as a D-pad, it is
496 * necessary to give focus to actionable items such as buttons so the user can see
497 * what will take input. If the device has touch capabilities, however, and the user
498 * begins interacting with the interface by touching it, it is no longer necessary to
499 * always highlight, or give focus to, a particular view. This motivates a mode
500 * for interaction named 'touch mode'.
501 * </p>
502 * <p>
503 * For a touch capable device, once the user touches the screen, the device
504 * will enter touch mode. From this point onward, only views for which
505 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
506 * Other views that are touchable, like buttons, will not take focus when touched; they will
507 * only fire the on click listeners.
508 * </p>
509 * <p>
510 * Any time a user hits a directional key, such as a D-pad direction, the view device will
511 * exit touch mode, and find a view to take focus, so that the user may resume interacting
512 * with the user interface without touching the screen again.
513 * </p>
514 * <p>
515 * The touch mode state is maintained across {@link android.app.Activity}s. Call
516 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
517 * </p>
518 *
519 * <a name="Scrolling"></a>
520 * <h3>Scrolling</h3>
521 * <p>
522 * The framework provides basic support for views that wish to internally
523 * scroll their content. This includes keeping track of the X and Y scroll
524 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700525 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
526 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 * </p>
528 *
529 * <a name="Tags"></a>
530 * <h3>Tags</h3>
531 * <p>
532 * Unlike IDs, tags are not used to identify views. Tags are essentially an
533 * extra piece of information that can be associated with a view. They are most
534 * often used as a convenience to store data related to views in the views
535 * themselves rather than by putting them in a separate structure.
536 * </p>
537 *
538 * <a name="Animation"></a>
539 * <h3>Animation</h3>
540 * <p>
541 * You can attach an {@link Animation} object to a view using
542 * {@link #setAnimation(Animation)} or
543 * {@link #startAnimation(Animation)}. The animation can alter the scale,
544 * rotation, translation and alpha of a view over time. If the animation is
545 * attached to a view that has children, the animation will affect the entire
546 * subtree rooted by that node. When an animation is started, the framework will
547 * take care of redrawing the appropriate views until the animation completes.
548 * </p>
Romain Guy171c5922011-01-06 10:04:23 -0800549 * <p>
550 * Starting with Android 3.0, the preferred way of animating views is to use the
551 * {@link android.animation} package APIs.
552 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 *
Jeff Brown85a31762010-09-01 17:01:00 -0700554 * <a name="Security"></a>
555 * <h3>Security</h3>
556 * <p>
557 * Sometimes it is essential that an application be able to verify that an action
558 * is being performed with the full knowledge and consent of the user, such as
559 * granting a permission request, making a purchase or clicking on an advertisement.
560 * Unfortunately, a malicious application could try to spoof the user into
561 * performing these actions, unaware, by concealing the intended purpose of the view.
562 * As a remedy, the framework offers a touch filtering mechanism that can be used to
563 * improve the security of views that provide access to sensitive functionality.
564 * </p><p>
565 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
Jeff Brown49ed71d2010-12-06 17:13:33 -0800566 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework
Jeff Brown85a31762010-09-01 17:01:00 -0700567 * will discard touches that are received whenever the view's window is obscured by
568 * another visible window. As a result, the view will not receive touches whenever a
569 * toast, dialog or other window appears above the view's window.
570 * </p><p>
571 * For more fine-grained control over security, consider overriding the
572 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
573 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
574 * </p>
575 *
Romain Guy171c5922011-01-06 10:04:23 -0800576 * @attr ref android.R.styleable#View_alpha
Romain Guyd6a463a2009-05-21 23:10:10 -0700577 * @attr ref android.R.styleable#View_background
578 * @attr ref android.R.styleable#View_clickable
579 * @attr ref android.R.styleable#View_contentDescription
580 * @attr ref android.R.styleable#View_drawingCacheQuality
581 * @attr ref android.R.styleable#View_duplicateParentState
582 * @attr ref android.R.styleable#View_id
583 * @attr ref android.R.styleable#View_fadingEdge
584 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700585 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700587 * @attr ref android.R.styleable#View_isScrollContainer
588 * @attr ref android.R.styleable#View_focusable
589 * @attr ref android.R.styleable#View_focusableInTouchMode
590 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
591 * @attr ref android.R.styleable#View_keepScreenOn
Romain Guy171c5922011-01-06 10:04:23 -0800592 * @attr ref android.R.styleable#View_layerType
Romain Guyd6a463a2009-05-21 23:10:10 -0700593 * @attr ref android.R.styleable#View_longClickable
594 * @attr ref android.R.styleable#View_minHeight
595 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 * @attr ref android.R.styleable#View_nextFocusDown
597 * @attr ref android.R.styleable#View_nextFocusLeft
598 * @attr ref android.R.styleable#View_nextFocusRight
599 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700600 * @attr ref android.R.styleable#View_onClick
601 * @attr ref android.R.styleable#View_padding
602 * @attr ref android.R.styleable#View_paddingBottom
603 * @attr ref android.R.styleable#View_paddingLeft
604 * @attr ref android.R.styleable#View_paddingRight
605 * @attr ref android.R.styleable#View_paddingTop
606 * @attr ref android.R.styleable#View_saveEnabled
Chet Haase73066682010-11-29 15:55:32 -0800607 * @attr ref android.R.styleable#View_rotation
608 * @attr ref android.R.styleable#View_rotationX
609 * @attr ref android.R.styleable#View_rotationY
610 * @attr ref android.R.styleable#View_scaleX
611 * @attr ref android.R.styleable#View_scaleY
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 * @attr ref android.R.styleable#View_scrollX
613 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700614 * @attr ref android.R.styleable#View_scrollbarSize
615 * @attr ref android.R.styleable#View_scrollbarStyle
616 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700617 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
618 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
620 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 * @attr ref android.R.styleable#View_scrollbarThumbVertical
622 * @attr ref android.R.styleable#View_scrollbarTrackVertical
623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
624 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700625 * @attr ref android.R.styleable#View_soundEffectsEnabled
626 * @attr ref android.R.styleable#View_tag
Chet Haase73066682010-11-29 15:55:32 -0800627 * @attr ref android.R.styleable#View_transformPivotX
628 * @attr ref android.R.styleable#View_transformPivotY
629 * @attr ref android.R.styleable#View_translationX
630 * @attr ref android.R.styleable#View_translationY
Romain Guyd6a463a2009-05-21 23:10:10 -0700631 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 *
633 * @see android.view.ViewGroup
634 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700635public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 private static final boolean DBG = false;
637
638 /**
639 * The logging tag used by this class with android.util.Log.
640 */
641 protected static final String VIEW_LOG_TAG = "View";
642
643 /**
644 * Used to mark a View that has no ID.
645 */
646 public static final int NO_ID = -1;
647
648 /**
649 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
650 * calling setFlags.
651 */
652 private static final int NOT_FOCUSABLE = 0x00000000;
653
654 /**
655 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
656 * setFlags.
657 */
658 private static final int FOCUSABLE = 0x00000001;
659
660 /**
661 * Mask for use with setFlags indicating bits used for focus.
662 */
663 private static final int FOCUSABLE_MASK = 0x00000001;
664
665 /**
666 * This view will adjust its padding to fit sytem windows (e.g. status bar)
667 */
668 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
669
670 /**
671 * This view is visible. Use with {@link #setVisibility}.
672 */
673 public static final int VISIBLE = 0x00000000;
674
675 /**
676 * This view is invisible, but it still takes up space for layout purposes.
677 * Use with {@link #setVisibility}.
678 */
679 public static final int INVISIBLE = 0x00000004;
680
681 /**
682 * This view is invisible, and it doesn't take any space for layout
683 * purposes. Use with {@link #setVisibility}.
684 */
685 public static final int GONE = 0x00000008;
686
687 /**
688 * Mask for use with setFlags indicating bits used for visibility.
689 * {@hide}
690 */
691 static final int VISIBILITY_MASK = 0x0000000C;
692
693 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
694
695 /**
696 * This view is enabled. Intrepretation varies by subclass.
697 * Use with ENABLED_MASK when calling setFlags.
698 * {@hide}
699 */
700 static final int ENABLED = 0x00000000;
701
702 /**
703 * This view is disabled. Intrepretation varies by subclass.
704 * Use with ENABLED_MASK when calling setFlags.
705 * {@hide}
706 */
707 static final int DISABLED = 0x00000020;
708
709 /**
710 * Mask for use with setFlags indicating bits used for indicating whether
711 * this view is enabled
712 * {@hide}
713 */
714 static final int ENABLED_MASK = 0x00000020;
715
716 /**
717 * This view won't draw. {@link #onDraw} won't be called and further
718 * optimizations
719 * will be performed. It is okay to have this flag set and a background.
720 * Use with DRAW_MASK when calling setFlags.
721 * {@hide}
722 */
723 static final int WILL_NOT_DRAW = 0x00000080;
724
725 /**
726 * Mask for use with setFlags indicating bits used for indicating whether
727 * this view is will draw
728 * {@hide}
729 */
730 static final int DRAW_MASK = 0x00000080;
731
732 /**
733 * <p>This view doesn't show scrollbars.</p>
734 * {@hide}
735 */
736 static final int SCROLLBARS_NONE = 0x00000000;
737
738 /**
739 * <p>This view shows horizontal scrollbars.</p>
740 * {@hide}
741 */
742 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
743
744 /**
745 * <p>This view shows vertical scrollbars.</p>
746 * {@hide}
747 */
748 static final int SCROLLBARS_VERTICAL = 0x00000200;
749
750 /**
751 * <p>Mask for use with setFlags indicating bits used for indicating which
752 * scrollbars are enabled.</p>
753 * {@hide}
754 */
755 static final int SCROLLBARS_MASK = 0x00000300;
756
Jeff Brown85a31762010-09-01 17:01:00 -0700757 /**
758 * Indicates that the view should filter touches when its window is obscured.
759 * Refer to the class comments for more information about this security feature.
760 * {@hide}
761 */
762 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
763
764 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765
766 /**
767 * <p>This view doesn't show fading edges.</p>
768 * {@hide}
769 */
770 static final int FADING_EDGE_NONE = 0x00000000;
771
772 /**
773 * <p>This view shows horizontal fading edges.</p>
774 * {@hide}
775 */
776 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
777
778 /**
779 * <p>This view shows vertical fading edges.</p>
780 * {@hide}
781 */
782 static final int FADING_EDGE_VERTICAL = 0x00002000;
783
784 /**
785 * <p>Mask for use with setFlags indicating bits used for indicating which
786 * fading edges are enabled.</p>
787 * {@hide}
788 */
789 static final int FADING_EDGE_MASK = 0x00003000;
790
791 /**
792 * <p>Indicates this view can be clicked. When clickable, a View reacts
793 * to clicks by notifying the OnClickListener.<p>
794 * {@hide}
795 */
796 static final int CLICKABLE = 0x00004000;
797
798 /**
799 * <p>Indicates this view is caching its drawing into a bitmap.</p>
800 * {@hide}
801 */
802 static final int DRAWING_CACHE_ENABLED = 0x00008000;
803
804 /**
805 * <p>Indicates that no icicle should be saved for this view.<p>
806 * {@hide}
807 */
808 static final int SAVE_DISABLED = 0x000010000;
809
810 /**
811 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
812 * property.</p>
813 * {@hide}
814 */
815 static final int SAVE_DISABLED_MASK = 0x000010000;
816
817 /**
818 * <p>Indicates that no drawing cache should ever be created for this view.<p>
819 * {@hide}
820 */
821 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
822
823 /**
824 * <p>Indicates this view can take / keep focus when int touch mode.</p>
825 * {@hide}
826 */
827 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
828
829 /**
830 * <p>Enables low quality mode for the drawing cache.</p>
831 */
832 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
833
834 /**
835 * <p>Enables high quality mode for the drawing cache.</p>
836 */
837 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
838
839 /**
840 * <p>Enables automatic quality mode for the drawing cache.</p>
841 */
842 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
843
844 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
845 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
846 };
847
848 /**
849 * <p>Mask for use with setFlags indicating bits used for the cache
850 * quality property.</p>
851 * {@hide}
852 */
853 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
854
855 /**
856 * <p>
857 * Indicates this view can be long clicked. When long clickable, a View
858 * reacts to long clicks by notifying the OnLongClickListener or showing a
859 * context menu.
860 * </p>
861 * {@hide}
862 */
863 static final int LONG_CLICKABLE = 0x00200000;
864
865 /**
866 * <p>Indicates that this view gets its drawable states from its direct parent
867 * and ignores its original internal states.</p>
868 *
869 * @hide
870 */
871 static final int DUPLICATE_PARENT_STATE = 0x00400000;
872
873 /**
874 * The scrollbar style to display the scrollbars inside the content area,
875 * without increasing the padding. The scrollbars will be overlaid with
876 * translucency on the view's content.
877 */
878 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
879
880 /**
881 * The scrollbar style to display the scrollbars inside the padded area,
882 * increasing the padding of the view. The scrollbars will not overlap the
883 * content area of the view.
884 */
885 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
886
887 /**
888 * The scrollbar style to display the scrollbars at the edge of the view,
889 * without increasing the padding. The scrollbars will be overlaid with
890 * translucency.
891 */
892 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
893
894 /**
895 * The scrollbar style to display the scrollbars at the edge of the view,
896 * increasing the padding of the view. The scrollbars will only overlap the
897 * background, if any.
898 */
899 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
900
901 /**
902 * Mask to check if the scrollbar style is overlay or inset.
903 * {@hide}
904 */
905 static final int SCROLLBARS_INSET_MASK = 0x01000000;
906
907 /**
908 * Mask to check if the scrollbar style is inside or outside.
909 * {@hide}
910 */
911 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
912
913 /**
914 * Mask for scrollbar style.
915 * {@hide}
916 */
917 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
918
919 /**
920 * View flag indicating that the screen should remain on while the
921 * window containing this view is visible to the user. This effectively
922 * takes care of automatically setting the WindowManager's
923 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
924 */
925 public static final int KEEP_SCREEN_ON = 0x04000000;
926
927 /**
928 * View flag indicating whether this view should have sound effects enabled
929 * for events such as clicking and touching.
930 */
931 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
932
933 /**
934 * View flag indicating whether this view should have haptic feedback
935 * enabled for events such as long presses.
936 */
937 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
938
939 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700940 * <p>Indicates that the view hierarchy should stop saving state when
941 * it reaches this view. If state saving is initiated immediately at
942 * the view, it will be allowed.
943 * {@hide}
944 */
945 static final int PARENT_SAVE_DISABLED = 0x20000000;
946
947 /**
948 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
949 * {@hide}
950 */
951 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
952
953 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700954 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
955 * should add all focusable Views regardless if they are focusable in touch mode.
956 */
957 public static final int FOCUSABLES_ALL = 0x00000000;
958
959 /**
960 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
961 * should add only Views focusable in touch mode.
962 */
963 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
964
965 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 * Use with {@link #focusSearch}. Move focus to the previous selectable
967 * item.
968 */
969 public static final int FOCUS_BACKWARD = 0x00000001;
970
971 /**
972 * Use with {@link #focusSearch}. Move focus to the next selectable
973 * item.
974 */
975 public static final int FOCUS_FORWARD = 0x00000002;
976
977 /**
978 * Use with {@link #focusSearch}. Move focus to the left.
979 */
980 public static final int FOCUS_LEFT = 0x00000011;
981
982 /**
983 * Use with {@link #focusSearch}. Move focus up.
984 */
985 public static final int FOCUS_UP = 0x00000021;
986
987 /**
988 * Use with {@link #focusSearch}. Move focus to the right.
989 */
990 public static final int FOCUS_RIGHT = 0x00000042;
991
992 /**
993 * Use with {@link #focusSearch}. Move focus down.
994 */
995 public static final int FOCUS_DOWN = 0x00000082;
996
997 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -0800998 * Bits of {@link #getMeasuredWidthAndState()} and
999 * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1000 */
1001 public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1002
1003 /**
1004 * Bits of {@link #getMeasuredWidthAndState()} and
1005 * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1006 */
1007 public static final int MEASURED_STATE_MASK = 0xff000000;
1008
1009 /**
1010 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1011 * for functions that combine both width and height into a single int,
1012 * such as {@link #getMeasuredState()} and the childState argument of
1013 * {@link #resolveSizeAndState(int, int, int)}.
1014 */
1015 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1016
1017 /**
1018 * Bit of {@link #getMeasuredWidthAndState()} and
1019 * {@link #getMeasuredWidthAndState()} that indicates the measured size
1020 * is smaller that the space the view would like to have.
1021 */
1022 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1023
1024 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 * Base View state sets
1026 */
1027 // Singles
1028 /**
1029 * Indicates the view has no states set. States are used with
1030 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1031 * view depending on its state.
1032 *
1033 * @see android.graphics.drawable.Drawable
1034 * @see #getDrawableState()
1035 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001036 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 /**
1038 * Indicates the view is enabled. States are used with
1039 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1040 * view depending on its state.
1041 *
1042 * @see android.graphics.drawable.Drawable
1043 * @see #getDrawableState()
1044 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001045 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 /**
1047 * Indicates the view is focused. States are used with
1048 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1049 * view depending on its state.
1050 *
1051 * @see android.graphics.drawable.Drawable
1052 * @see #getDrawableState()
1053 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001054 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 /**
1056 * Indicates the view is selected. States are used with
1057 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1058 * view depending on its state.
1059 *
1060 * @see android.graphics.drawable.Drawable
1061 * @see #getDrawableState()
1062 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001063 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 /**
1065 * Indicates the view is pressed. States are used with
1066 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1067 * view depending on its state.
1068 *
1069 * @see android.graphics.drawable.Drawable
1070 * @see #getDrawableState()
1071 * @hide
1072 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001073 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 /**
1075 * Indicates the view's window has focus. States are used with
1076 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1077 * view depending on its state.
1078 *
1079 * @see android.graphics.drawable.Drawable
1080 * @see #getDrawableState()
1081 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001082 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 // Doubles
1084 /**
1085 * Indicates the view is enabled and has the focus.
1086 *
1087 * @see #ENABLED_STATE_SET
1088 * @see #FOCUSED_STATE_SET
1089 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001090 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 /**
1092 * Indicates the view is enabled and selected.
1093 *
1094 * @see #ENABLED_STATE_SET
1095 * @see #SELECTED_STATE_SET
1096 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001097 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 /**
1099 * Indicates the view is enabled and that its window has focus.
1100 *
1101 * @see #ENABLED_STATE_SET
1102 * @see #WINDOW_FOCUSED_STATE_SET
1103 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001104 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 /**
1106 * Indicates the view is focused and selected.
1107 *
1108 * @see #FOCUSED_STATE_SET
1109 * @see #SELECTED_STATE_SET
1110 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001111 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 /**
1113 * Indicates the view has the focus and that its window has the focus.
1114 *
1115 * @see #FOCUSED_STATE_SET
1116 * @see #WINDOW_FOCUSED_STATE_SET
1117 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001118 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 /**
1120 * Indicates the view is selected and that its window has the focus.
1121 *
1122 * @see #SELECTED_STATE_SET
1123 * @see #WINDOW_FOCUSED_STATE_SET
1124 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001125 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 // Triples
1127 /**
1128 * Indicates the view is enabled, focused and selected.
1129 *
1130 * @see #ENABLED_STATE_SET
1131 * @see #FOCUSED_STATE_SET
1132 * @see #SELECTED_STATE_SET
1133 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001134 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 /**
1136 * Indicates the view is enabled, focused and its window has the focus.
1137 *
1138 * @see #ENABLED_STATE_SET
1139 * @see #FOCUSED_STATE_SET
1140 * @see #WINDOW_FOCUSED_STATE_SET
1141 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001142 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 /**
1144 * Indicates the view is enabled, selected and its window has the focus.
1145 *
1146 * @see #ENABLED_STATE_SET
1147 * @see #SELECTED_STATE_SET
1148 * @see #WINDOW_FOCUSED_STATE_SET
1149 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001150 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 /**
1152 * Indicates the view is focused, selected and its window has the focus.
1153 *
1154 * @see #FOCUSED_STATE_SET
1155 * @see #SELECTED_STATE_SET
1156 * @see #WINDOW_FOCUSED_STATE_SET
1157 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001158 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 /**
1160 * Indicates the view is enabled, focused, selected and its window
1161 * has the focus.
1162 *
1163 * @see #ENABLED_STATE_SET
1164 * @see #FOCUSED_STATE_SET
1165 * @see #SELECTED_STATE_SET
1166 * @see #WINDOW_FOCUSED_STATE_SET
1167 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001168 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 /**
1170 * Indicates the view is pressed and its window has the focus.
1171 *
1172 * @see #PRESSED_STATE_SET
1173 * @see #WINDOW_FOCUSED_STATE_SET
1174 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001175 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 /**
1177 * Indicates the view is pressed and selected.
1178 *
1179 * @see #PRESSED_STATE_SET
1180 * @see #SELECTED_STATE_SET
1181 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001182 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 /**
1184 * Indicates the view is pressed, selected and its window has the focus.
1185 *
1186 * @see #PRESSED_STATE_SET
1187 * @see #SELECTED_STATE_SET
1188 * @see #WINDOW_FOCUSED_STATE_SET
1189 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001190 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 /**
1192 * Indicates the view is pressed and focused.
1193 *
1194 * @see #PRESSED_STATE_SET
1195 * @see #FOCUSED_STATE_SET
1196 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001197 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 /**
1199 * Indicates the view is pressed, focused and its window has the focus.
1200 *
1201 * @see #PRESSED_STATE_SET
1202 * @see #FOCUSED_STATE_SET
1203 * @see #WINDOW_FOCUSED_STATE_SET
1204 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001205 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 /**
1207 * Indicates the view is pressed, focused and selected.
1208 *
1209 * @see #PRESSED_STATE_SET
1210 * @see #SELECTED_STATE_SET
1211 * @see #FOCUSED_STATE_SET
1212 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001213 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 /**
1215 * Indicates the view is pressed, focused, selected and its window has the focus.
1216 *
1217 * @see #PRESSED_STATE_SET
1218 * @see #FOCUSED_STATE_SET
1219 * @see #SELECTED_STATE_SET
1220 * @see #WINDOW_FOCUSED_STATE_SET
1221 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001222 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 /**
1224 * Indicates the view is pressed and enabled.
1225 *
1226 * @see #PRESSED_STATE_SET
1227 * @see #ENABLED_STATE_SET
1228 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001229 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 /**
1231 * Indicates the view is pressed, enabled and its window has the focus.
1232 *
1233 * @see #PRESSED_STATE_SET
1234 * @see #ENABLED_STATE_SET
1235 * @see #WINDOW_FOCUSED_STATE_SET
1236 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001237 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 /**
1239 * Indicates the view is pressed, enabled and selected.
1240 *
1241 * @see #PRESSED_STATE_SET
1242 * @see #ENABLED_STATE_SET
1243 * @see #SELECTED_STATE_SET
1244 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001245 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 /**
1247 * Indicates the view is pressed, enabled, selected and its window has the
1248 * focus.
1249 *
1250 * @see #PRESSED_STATE_SET
1251 * @see #ENABLED_STATE_SET
1252 * @see #SELECTED_STATE_SET
1253 * @see #WINDOW_FOCUSED_STATE_SET
1254 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001255 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 /**
1257 * Indicates the view is pressed, enabled and focused.
1258 *
1259 * @see #PRESSED_STATE_SET
1260 * @see #ENABLED_STATE_SET
1261 * @see #FOCUSED_STATE_SET
1262 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001263 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 /**
1265 * Indicates the view is pressed, enabled, focused and its window has the
1266 * focus.
1267 *
1268 * @see #PRESSED_STATE_SET
1269 * @see #ENABLED_STATE_SET
1270 * @see #FOCUSED_STATE_SET
1271 * @see #WINDOW_FOCUSED_STATE_SET
1272 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001273 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 /**
1275 * Indicates the view is pressed, enabled, focused and selected.
1276 *
1277 * @see #PRESSED_STATE_SET
1278 * @see #ENABLED_STATE_SET
1279 * @see #SELECTED_STATE_SET
1280 * @see #FOCUSED_STATE_SET
1281 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001282 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 /**
1284 * Indicates the view is pressed, enabled, focused, selected and its window
1285 * has the focus.
1286 *
1287 * @see #PRESSED_STATE_SET
1288 * @see #ENABLED_STATE_SET
1289 * @see #SELECTED_STATE_SET
1290 * @see #FOCUSED_STATE_SET
1291 * @see #WINDOW_FOCUSED_STATE_SET
1292 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001293 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294
1295 /**
1296 * The order here is very important to {@link #getDrawableState()}
1297 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001298 private static final int[][] VIEW_STATE_SETS;
1299
Romain Guyb051e892010-09-28 19:09:36 -07001300 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1301 static final int VIEW_STATE_SELECTED = 1 << 1;
1302 static final int VIEW_STATE_FOCUSED = 1 << 2;
1303 static final int VIEW_STATE_ENABLED = 1 << 3;
1304 static final int VIEW_STATE_PRESSED = 1 << 4;
1305 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001306 static final int VIEW_STATE_ACCELERATED = 1 << 6;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001307
1308 static final int[] VIEW_STATE_IDS = new int[] {
1309 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1310 R.attr.state_selected, VIEW_STATE_SELECTED,
1311 R.attr.state_focused, VIEW_STATE_FOCUSED,
1312 R.attr.state_enabled, VIEW_STATE_ENABLED,
1313 R.attr.state_pressed, VIEW_STATE_PRESSED,
1314 R.attr.state_activated, VIEW_STATE_ACTIVATED,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001315 R.attr.state_accelerated, VIEW_STATE_ACCELERATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 };
1317
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001318 static {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001319 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1320 throw new IllegalStateException(
1321 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1322 }
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001323 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001324 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001325 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001326 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001327 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001328 orderedIds[i * 2] = viewState;
1329 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001330 }
1331 }
1332 }
Romain Guyb051e892010-09-28 19:09:36 -07001333 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1334 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1335 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001336 int numBits = Integer.bitCount(i);
1337 int[] set = new int[numBits];
1338 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001339 for (int j = 0; j < orderedIds.length; j += 2) {
1340 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001341 set[pos++] = orderedIds[j];
1342 }
1343 }
1344 VIEW_STATE_SETS[i] = set;
1345 }
1346
1347 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1348 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1349 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1350 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1351 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1352 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1353 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1354 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1355 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1356 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1357 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1358 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1359 | VIEW_STATE_FOCUSED];
1360 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1361 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1362 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1363 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1364 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1365 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1366 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1367 | VIEW_STATE_ENABLED];
1368 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1369 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1370 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1371 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1372 | VIEW_STATE_ENABLED];
1373 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1374 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1375 | VIEW_STATE_ENABLED];
1376 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1377 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1378 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1379
1380 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1381 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1382 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1383 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1384 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1385 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1386 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1387 | VIEW_STATE_PRESSED];
1388 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1389 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1390 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1391 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1392 | VIEW_STATE_PRESSED];
1393 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1394 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1395 | VIEW_STATE_PRESSED];
1396 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1397 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1398 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1399 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1400 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1401 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1402 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1403 | VIEW_STATE_PRESSED];
1404 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1405 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1406 | VIEW_STATE_PRESSED];
1407 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1408 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1409 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1410 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1411 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1412 | VIEW_STATE_PRESSED];
1413 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1414 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1415 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1416 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1418 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1419 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1420 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1421 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1422 | VIEW_STATE_PRESSED];
1423 }
1424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 /**
1426 * Used by views that contain lists of items. This state indicates that
1427 * the view is showing the last item.
1428 * @hide
1429 */
1430 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1431 /**
1432 * Used by views that contain lists of items. This state indicates that
1433 * the view is showing the first item.
1434 * @hide
1435 */
1436 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1437 /**
1438 * Used by views that contain lists of items. This state indicates that
1439 * the view is showing the middle item.
1440 * @hide
1441 */
1442 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1443 /**
1444 * Used by views that contain lists of items. This state indicates that
1445 * the view is showing only one item.
1446 * @hide
1447 */
1448 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1449 /**
1450 * Used by views that contain lists of items. This state indicates that
1451 * the view is pressed and showing the last item.
1452 * @hide
1453 */
1454 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1455 /**
1456 * Used by views that contain lists of items. This state indicates that
1457 * the view is pressed and showing the first item.
1458 * @hide
1459 */
1460 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1461 /**
1462 * Used by views that contain lists of items. This state indicates that
1463 * the view is pressed and showing the middle item.
1464 * @hide
1465 */
1466 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1467 /**
1468 * Used by views that contain lists of items. This state indicates that
1469 * the view is pressed and showing only one item.
1470 * @hide
1471 */
1472 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1473
1474 /**
1475 * Temporary Rect currently for use in setBackground(). This will probably
1476 * be extended in the future to hold our own class with more than just
1477 * a Rect. :)
1478 */
1479 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001480
1481 /**
1482 * Map used to store views' tags.
1483 */
1484 private static WeakHashMap<View, SparseArray<Object>> sTags;
1485
1486 /**
1487 * Lock used to access sTags.
1488 */
1489 private static final Object sTagsLock = new Object();
1490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 /**
1492 * The animation currently associated with this view.
1493 * @hide
1494 */
1495 protected Animation mCurrentAnimation = null;
1496
1497 /**
1498 * Width as measured during measure pass.
1499 * {@hide}
1500 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001501 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001502 /*package*/ int mMeasuredWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503
1504 /**
1505 * Height as measured during measure pass.
1506 * {@hide}
1507 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001508 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001509 /*package*/ int mMeasuredHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510
1511 /**
Chet Haasedaf98e92011-01-10 14:10:36 -08001512 * Flag to indicate that this view was marked INVALIDATED, or had its display list
1513 * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1514 * its display list. This flag, used only when hw accelerated, allows us to clear the
1515 * flag while retaining this information until it's needed (at getDisplayList() time and
1516 * in drawChild(), when we decide to draw a view's children's display lists into our own).
1517 *
1518 * {@hide}
1519 */
1520 boolean mRecreateDisplayList = false;
1521
1522 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 * The view's identifier.
1524 * {@hide}
1525 *
1526 * @see #setId(int)
1527 * @see #getId()
1528 */
1529 @ViewDebug.ExportedProperty(resolveId = true)
1530 int mID = NO_ID;
1531
1532 /**
1533 * The view's tag.
1534 * {@hide}
1535 *
1536 * @see #setTag(Object)
1537 * @see #getTag()
1538 */
1539 protected Object mTag;
1540
1541 // for mPrivateFlags:
1542 /** {@hide} */
1543 static final int WANTS_FOCUS = 0x00000001;
1544 /** {@hide} */
1545 static final int FOCUSED = 0x00000002;
1546 /** {@hide} */
1547 static final int SELECTED = 0x00000004;
1548 /** {@hide} */
1549 static final int IS_ROOT_NAMESPACE = 0x00000008;
1550 /** {@hide} */
1551 static final int HAS_BOUNDS = 0x00000010;
1552 /** {@hide} */
1553 static final int DRAWN = 0x00000020;
1554 /**
1555 * When this flag is set, this view is running an animation on behalf of its
1556 * children and should therefore not cancel invalidate requests, even if they
1557 * lie outside of this view's bounds.
1558 *
1559 * {@hide}
1560 */
1561 static final int DRAW_ANIMATION = 0x00000040;
1562 /** {@hide} */
1563 static final int SKIP_DRAW = 0x00000080;
1564 /** {@hide} */
1565 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1566 /** {@hide} */
1567 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1568 /** {@hide} */
1569 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1570 /** {@hide} */
1571 static final int MEASURED_DIMENSION_SET = 0x00000800;
1572 /** {@hide} */
1573 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001574 /** {@hide} */
1575 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576
1577 private static final int PRESSED = 0x00004000;
1578
1579 /** {@hide} */
1580 static final int DRAWING_CACHE_VALID = 0x00008000;
1581 /**
1582 * Flag used to indicate that this view should be drawn once more (and only once
1583 * more) after its animation has completed.
1584 * {@hide}
1585 */
1586 static final int ANIMATION_STARTED = 0x00010000;
1587
1588 private static final int SAVE_STATE_CALLED = 0x00020000;
1589
1590 /**
1591 * Indicates that the View returned true when onSetAlpha() was called and that
1592 * the alpha must be restored.
1593 * {@hide}
1594 */
1595 static final int ALPHA_SET = 0x00040000;
1596
1597 /**
1598 * Set by {@link #setScrollContainer(boolean)}.
1599 */
1600 static final int SCROLL_CONTAINER = 0x00080000;
1601
1602 /**
1603 * Set by {@link #setScrollContainer(boolean)}.
1604 */
1605 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1606
1607 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001608 * View flag indicating whether this view was invalidated (fully or partially.)
1609 *
1610 * @hide
1611 */
1612 static final int DIRTY = 0x00200000;
1613
1614 /**
1615 * View flag indicating whether this view was invalidated by an opaque
1616 * invalidate request.
1617 *
1618 * @hide
1619 */
1620 static final int DIRTY_OPAQUE = 0x00400000;
1621
1622 /**
1623 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1624 *
1625 * @hide
1626 */
1627 static final int DIRTY_MASK = 0x00600000;
1628
1629 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001630 * Indicates whether the background is opaque.
1631 *
1632 * @hide
1633 */
1634 static final int OPAQUE_BACKGROUND = 0x00800000;
1635
1636 /**
1637 * Indicates whether the scrollbars are opaque.
1638 *
1639 * @hide
1640 */
1641 static final int OPAQUE_SCROLLBARS = 0x01000000;
1642
1643 /**
1644 * Indicates whether the view is opaque.
1645 *
1646 * @hide
1647 */
1648 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001649
1650 /**
1651 * Indicates a prepressed state;
1652 * the short time between ACTION_DOWN and recognizing
1653 * a 'real' press. Prepressed is used to recognize quick taps
1654 * even when they are shorter than ViewConfiguration.getTapTimeout().
1655 *
1656 * @hide
1657 */
1658 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001659
1660 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001661 * Indicates whether the view is temporarily detached.
1662 *
1663 * @hide
1664 */
1665 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001666
1667 /**
1668 * Indicates that we should awaken scroll bars once attached
1669 *
1670 * @hide
1671 */
1672 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001673
1674 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001675 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1676 * for transform operations
1677 *
1678 * @hide
1679 */
Adam Powellf37df072010-09-17 16:22:49 -07001680 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001681
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001682 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001683 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001684
Chet Haasefd2b0022010-08-06 13:08:56 -07001685 /**
Chet Haasedaf98e92011-01-10 14:10:36 -08001686 * Indicates that this view was specifically invalidated, not just dirtied because some
1687 * child view was invalidated. The flag is used to determine when we need to recreate
1688 * a view's display list (as opposed to just returning a reference to its existing
1689 * display list).
1690 *
1691 * @hide
1692 */
1693 static final int INVALIDATED = 0x80000000;
1694
1695 /**
Adam Powell637d3372010-08-25 14:37:03 -07001696 * Always allow a user to over-scroll this view, provided it is a
1697 * view that can scroll.
1698 *
1699 * @see #getOverScrollMode()
1700 * @see #setOverScrollMode(int)
1701 */
1702 public static final int OVER_SCROLL_ALWAYS = 0;
1703
1704 /**
1705 * Allow a user to over-scroll this view only if the content is large
1706 * enough to meaningfully scroll, provided it is a view that can scroll.
1707 *
1708 * @see #getOverScrollMode()
1709 * @see #setOverScrollMode(int)
1710 */
1711 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1712
1713 /**
1714 * Never allow a user to over-scroll this view.
1715 *
1716 * @see #getOverScrollMode()
1717 * @see #setOverScrollMode(int)
1718 */
1719 public static final int OVER_SCROLL_NEVER = 2;
1720
1721 /**
Joe Onorato664644d2011-01-23 17:53:23 -08001722 * View has requested the status bar to be visible (the default).
1723 *
1724 * @see setSystemUiVisibility
1725 */
1726 public static final int STATUS_BAR_VISIBLE = 0;
1727
1728 /**
1729 * View has requested the status bar to be visible (the default).
1730 *
1731 * @see setSystemUiVisibility
1732 */
1733 public static final int STATUS_BAR_HIDDEN = 0x00000001;
1734
1735 /**
Adam Powell637d3372010-08-25 14:37:03 -07001736 * Controls the over-scroll mode for this view.
1737 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1738 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1739 * and {@link #OVER_SCROLL_NEVER}.
1740 */
1741 private int mOverScrollMode;
1742
1743 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 * The parent this view is attached to.
1745 * {@hide}
1746 *
1747 * @see #getParent()
1748 */
1749 protected ViewParent mParent;
1750
1751 /**
1752 * {@hide}
1753 */
1754 AttachInfo mAttachInfo;
1755
1756 /**
1757 * {@hide}
1758 */
Romain Guy809a7f62009-05-14 15:44:42 -07001759 @ViewDebug.ExportedProperty(flagMapping = {
1760 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1761 name = "FORCE_LAYOUT"),
1762 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1763 name = "LAYOUT_REQUIRED"),
1764 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001765 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001766 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1767 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1768 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1769 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1770 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 int mPrivateFlags;
1772
1773 /**
Joe Onorato664644d2011-01-23 17:53:23 -08001774 * This view's request for the visibility of the status bar.
1775 * @hide
1776 */
1777 int mSystemUiVisibility;
1778
1779 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 * Count of how many windows this view has been attached to.
1781 */
1782 int mWindowAttachCount;
1783
1784 /**
1785 * The layout parameters associated with this view and used by the parent
1786 * {@link android.view.ViewGroup} to determine how this view should be
1787 * laid out.
1788 * {@hide}
1789 */
1790 protected ViewGroup.LayoutParams mLayoutParams;
1791
1792 /**
1793 * The view flags hold various views states.
1794 * {@hide}
1795 */
1796 @ViewDebug.ExportedProperty
1797 int mViewFlags;
1798
1799 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001800 * The transform matrix for the View. This transform is calculated internally
1801 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1802 * is used by default. Do *not* use this variable directly; instead call
1803 * getMatrix(), which will automatically recalculate the matrix if necessary
1804 * to get the correct matrix based on the latest rotation and scale properties.
1805 */
1806 private final Matrix mMatrix = new Matrix();
1807
1808 /**
1809 * The transform matrix for the View. This transform is calculated internally
1810 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1811 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001812 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001813 * to get the correct matrix based on the latest rotation and scale properties.
1814 */
1815 private Matrix mInverseMatrix;
1816
1817 /**
1818 * An internal variable that tracks whether we need to recalculate the
1819 * transform matrix, based on whether the rotation or scaleX/Y properties
1820 * have changed since the matrix was last calculated.
1821 */
1822 private boolean mMatrixDirty = false;
1823
1824 /**
1825 * An internal variable that tracks whether we need to recalculate the
1826 * transform matrix, based on whether the rotation or scaleX/Y properties
1827 * have changed since the matrix was last calculated.
1828 */
1829 private boolean mInverseMatrixDirty = true;
1830
1831 /**
1832 * A variable that tracks whether we need to recalculate the
1833 * transform matrix, based on whether the rotation or scaleX/Y properties
1834 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001835 * is only valid after a call to updateMatrix() or to a function that
1836 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001837 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001838 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001839
1840 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001841 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1842 */
1843 private Camera mCamera = null;
1844
1845 /**
1846 * This matrix is used when computing the matrix for 3D rotations.
1847 */
1848 private Matrix matrix3D = null;
1849
1850 /**
1851 * These prev values are used to recalculate a centered pivot point when necessary. The
1852 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1853 * set), so thes values are only used then as well.
1854 */
1855 private int mPrevWidth = -1;
1856 private int mPrevHeight = -1;
1857
Romain Guyc5d55862011-01-21 19:01:46 -08001858 private boolean mLastIsOpaque;
1859
Chet Haasefd2b0022010-08-06 13:08:56 -07001860 /**
1861 * Convenience value to check for float values that are close enough to zero to be considered
1862 * zero.
1863 */
Romain Guy2542d192010-08-18 11:47:12 -07001864 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001865
1866 /**
1867 * The degrees rotation around the vertical axis through the pivot point.
1868 */
1869 @ViewDebug.ExportedProperty
1870 private float mRotationY = 0f;
1871
1872 /**
1873 * The degrees rotation around the horizontal axis through the pivot point.
1874 */
1875 @ViewDebug.ExportedProperty
1876 private float mRotationX = 0f;
1877
1878 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001879 * The degrees rotation around the pivot point.
1880 */
1881 @ViewDebug.ExportedProperty
1882 private float mRotation = 0f;
1883
1884 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001885 * The amount of translation of the object away from its left property (post-layout).
1886 */
1887 @ViewDebug.ExportedProperty
1888 private float mTranslationX = 0f;
1889
1890 /**
1891 * The amount of translation of the object away from its top property (post-layout).
1892 */
1893 @ViewDebug.ExportedProperty
1894 private float mTranslationY = 0f;
1895
1896 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001897 * The amount of scale in the x direction around the pivot point. A
1898 * value of 1 means no scaling is applied.
1899 */
1900 @ViewDebug.ExportedProperty
1901 private float mScaleX = 1f;
1902
1903 /**
1904 * The amount of scale in the y direction around the pivot point. A
1905 * value of 1 means no scaling is applied.
1906 */
1907 @ViewDebug.ExportedProperty
1908 private float mScaleY = 1f;
1909
1910 /**
1911 * The amount of scale in the x direction around the pivot point. A
1912 * value of 1 means no scaling is applied.
1913 */
1914 @ViewDebug.ExportedProperty
1915 private float mPivotX = 0f;
1916
1917 /**
1918 * The amount of scale in the y direction around the pivot point. A
1919 * value of 1 means no scaling is applied.
1920 */
1921 @ViewDebug.ExportedProperty
1922 private float mPivotY = 0f;
1923
1924 /**
1925 * The opacity of the View. This is a value from 0 to 1, where 0 means
1926 * completely transparent and 1 means completely opaque.
1927 */
1928 @ViewDebug.ExportedProperty
1929 private float mAlpha = 1f;
1930
1931 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 * The distance in pixels from the left edge of this view's parent
1933 * to the left edge of this view.
1934 * {@hide}
1935 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001936 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 protected int mLeft;
1938 /**
1939 * The distance in pixels from the left edge of this view's parent
1940 * to the right edge of this view.
1941 * {@hide}
1942 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001943 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 protected int mRight;
1945 /**
1946 * The distance in pixels from the top edge of this view's parent
1947 * to the top edge of this view.
1948 * {@hide}
1949 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001950 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 protected int mTop;
1952 /**
1953 * The distance in pixels from the top edge of this view's parent
1954 * to the bottom edge of this view.
1955 * {@hide}
1956 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001957 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 protected int mBottom;
1959
1960 /**
1961 * The offset, in pixels, by which the content of this view is scrolled
1962 * horizontally.
1963 * {@hide}
1964 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001965 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 protected int mScrollX;
1967 /**
1968 * The offset, in pixels, by which the content of this view is scrolled
1969 * vertically.
1970 * {@hide}
1971 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001972 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 protected int mScrollY;
1974
1975 /**
1976 * The left padding in pixels, that is the distance in pixels between the
1977 * left edge of this view and the left edge of its content.
1978 * {@hide}
1979 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001980 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 protected int mPaddingLeft;
1982 /**
1983 * The right padding in pixels, that is the distance in pixels between the
1984 * right edge of this view and the right edge of its content.
1985 * {@hide}
1986 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001987 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 protected int mPaddingRight;
1989 /**
1990 * The top padding in pixels, that is the distance in pixels between the
1991 * top edge of this view and the top edge of its content.
1992 * {@hide}
1993 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001994 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 protected int mPaddingTop;
1996 /**
1997 * The bottom padding in pixels, that is the distance in pixels between the
1998 * bottom edge of this view and the bottom edge of its content.
1999 * {@hide}
2000 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002001 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 protected int mPaddingBottom;
2003
2004 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002005 * Briefly describes the view and is primarily used for accessibility support.
2006 */
2007 private CharSequence mContentDescription;
2008
2009 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 * Cache the paddingRight set by the user to append to the scrollbar's size.
2011 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002012 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 int mUserPaddingRight;
2014
2015 /**
2016 * Cache the paddingBottom set by the user to append to the scrollbar's size.
2017 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002018 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 int mUserPaddingBottom;
2020
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002021 /**
Adam Powell20232d02010-12-08 21:08:53 -08002022 * Cache the paddingLeft set by the user to append to the scrollbar's size.
2023 */
2024 @ViewDebug.ExportedProperty(category = "padding")
2025 int mUserPaddingLeft;
2026
2027 /**
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002028 * @hide
2029 */
2030 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2031 /**
2032 * @hide
2033 */
2034 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035
2036 private Resources mResources = null;
2037
2038 private Drawable mBGDrawable;
2039
2040 private int mBackgroundResource;
2041 private boolean mBackgroundSizeChanged;
2042
2043 /**
2044 * Listener used to dispatch focus change events.
2045 * This field should be made private, so it is hidden from the SDK.
2046 * {@hide}
2047 */
2048 protected OnFocusChangeListener mOnFocusChangeListener;
2049
2050 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002051 * Listeners for layout change events.
2052 */
2053 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2054
2055 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 * Listener used to dispatch click events.
2057 * This field should be made private, so it is hidden from the SDK.
2058 * {@hide}
2059 */
2060 protected OnClickListener mOnClickListener;
2061
2062 /**
2063 * Listener used to dispatch long click events.
2064 * This field should be made private, so it is hidden from the SDK.
2065 * {@hide}
2066 */
2067 protected OnLongClickListener mOnLongClickListener;
2068
2069 /**
2070 * Listener used to build the context menu.
2071 * This field should be made private, so it is hidden from the SDK.
2072 * {@hide}
2073 */
2074 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2075
2076 private OnKeyListener mOnKeyListener;
2077
2078 private OnTouchListener mOnTouchListener;
2079
Chris Tate32affef2010-10-18 15:29:21 -07002080 private OnDragListener mOnDragListener;
2081
Joe Onorato664644d2011-01-23 17:53:23 -08002082 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 /**
2085 * The application environment this view lives in.
2086 * This field should be made private, so it is hidden from the SDK.
2087 * {@hide}
2088 */
2089 protected Context mContext;
2090
2091 private ScrollabilityCache mScrollCache;
2092
2093 private int[] mDrawableState = null;
2094
Romain Guy02890fd2010-08-06 17:58:44 -07002095 private Bitmap mDrawingCache;
2096 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07002097 private DisplayList mDisplayList;
Romain Guy6c319ca2011-01-11 14:29:25 -08002098 private HardwareLayer mHardwareLayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099
2100 /**
2101 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2102 * the user may specify which view to go to next.
2103 */
2104 private int mNextFocusLeftId = View.NO_ID;
2105
2106 /**
2107 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2108 * the user may specify which view to go to next.
2109 */
2110 private int mNextFocusRightId = View.NO_ID;
2111
2112 /**
2113 * When this view has focus and the next focus is {@link #FOCUS_UP},
2114 * the user may specify which view to go to next.
2115 */
2116 private int mNextFocusUpId = View.NO_ID;
2117
2118 /**
2119 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2120 * the user may specify which view to go to next.
2121 */
2122 private int mNextFocusDownId = View.NO_ID;
2123
Jeff Brown4e6319b2010-12-13 10:36:51 -08002124 /**
2125 * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2126 * the user may specify which view to go to next.
2127 */
2128 int mNextFocusForwardId = View.NO_ID;
2129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08002131 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08002132 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08002133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 private UnsetPressedState mUnsetPressedState;
2135
2136 /**
2137 * Whether the long press's action has been invoked. The tap's action is invoked on the
2138 * up event while a long press is invoked as soon as the long press duration is reached, so
2139 * a long press could be performed before the tap is checked, in which case the tap's action
2140 * should not be invoked.
2141 */
2142 private boolean mHasPerformedLongPress;
2143
2144 /**
2145 * The minimum height of the view. We'll try our best to have the height
2146 * of this view to at least this amount.
2147 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002148 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 private int mMinHeight;
2150
2151 /**
2152 * The minimum width of the view. We'll try our best to have the width
2153 * of this view to at least this amount.
2154 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002155 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 private int mMinWidth;
2157
2158 /**
2159 * The delegate to handle touch events that are physically in this view
2160 * but should be handled by another view.
2161 */
2162 private TouchDelegate mTouchDelegate = null;
2163
2164 /**
2165 * Solid color to use as a background when creating the drawing cache. Enables
2166 * the cache to use 16 bit bitmaps instead of 32 bit.
2167 */
2168 private int mDrawingCacheBackgroundColor = 0;
2169
2170 /**
2171 * Special tree observer used when mAttachInfo is null.
2172 */
2173 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002174
2175 /**
2176 * Cache the touch slop from the context that created the view.
2177 */
2178 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002181 * Cache drag/drop state
2182 *
2183 */
2184 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002185
2186 /**
Christopher Tate02d2b3b2011-01-10 20:43:53 -08002187 * Flag indicating that a drag can cross window boundaries
2188 * @hide
2189 */
2190 public static final int DRAG_FLAG_GLOBAL = 1;
2191
2192 /**
Adam Powell20232d02010-12-08 21:08:53 -08002193 * Position of the vertical scroll bar.
2194 */
2195 private int mVerticalScrollbarPosition;
2196
2197 /**
2198 * Position the scroll bar at the default position as determined by the system.
2199 */
2200 public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2201
2202 /**
2203 * Position the scroll bar along the left edge.
2204 */
2205 public static final int SCROLLBAR_POSITION_LEFT = 1;
2206
2207 /**
2208 * Position the scroll bar along the right edge.
2209 */
2210 public static final int SCROLLBAR_POSITION_RIGHT = 2;
2211
2212 /**
Romain Guy171c5922011-01-06 10:04:23 -08002213 * Indicates that the view does not have a layer.
2214 *
2215 * @see #getLayerType()
2216 * @see #setLayerType(int, android.graphics.Paint)
2217 * @see #LAYER_TYPE_SOFTWARE
2218 * @see #LAYER_TYPE_HARDWARE
2219 */
2220 public static final int LAYER_TYPE_NONE = 0;
2221
2222 /**
2223 * <p>Indicates that the view has a software layer. A software layer is backed
2224 * by a bitmap and causes the view to be rendered using Android's software
2225 * rendering pipeline, even if hardware acceleration is enabled.</p>
2226 *
2227 * <p>Software layers have various usages:</p>
2228 * <p>When the application is not using hardware acceleration, a software layer
2229 * is useful to apply a specific color filter and/or blending mode and/or
2230 * translucency to a view and all its children.</p>
2231 * <p>When the application is using hardware acceleration, a software layer
2232 * is useful to render drawing primitives not supported by the hardware
2233 * accelerated pipeline. It can also be used to cache a complex view tree
2234 * into a texture and reduce the complexity of drawing operations. For instance,
2235 * when animating a complex view tree with a translation, a software layer can
2236 * be used to render the view tree only once.</p>
2237 * <p>Software layers should be avoided when the affected view tree updates
2238 * often. Every update will require to re-render the software layer, which can
2239 * potentially be slow (particularly when hardware acceleration is turned on
2240 * since the layer will have to be uploaded into a hardware texture after every
2241 * update.)</p>
2242 *
2243 * @see #getLayerType()
2244 * @see #setLayerType(int, android.graphics.Paint)
2245 * @see #LAYER_TYPE_NONE
2246 * @see #LAYER_TYPE_HARDWARE
2247 */
2248 public static final int LAYER_TYPE_SOFTWARE = 1;
2249
2250 /**
2251 * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2252 * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2253 * OpenGL hardware) and causes the view to be rendered using Android's hardware
2254 * rendering pipeline, but only if hardware acceleration is turned on for the
2255 * view hierarchy. When hardware acceleration is turned off, hardware layers
2256 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2257 *
2258 * <p>A hardware layer is useful to apply a specific color filter and/or
2259 * blending mode and/or translucency to a view and all its children.</p>
Romain Guy6c319ca2011-01-11 14:29:25 -08002260 * <p>A hardware layer can be used to cache a complex view tree into a
2261 * texture and reduce the complexity of drawing operations. For instance,
2262 * when animating a complex view tree with a translation, a hardware layer can
2263 * be used to render the view tree only once.</p>
Romain Guy171c5922011-01-06 10:04:23 -08002264 * <p>A hardware layer can also be used to increase the rendering quality when
2265 * rotation transformations are applied on a view. It can also be used to
2266 * prevent potential clipping issues when applying 3D transforms on a view.</p>
2267 *
2268 * @see #getLayerType()
2269 * @see #setLayerType(int, android.graphics.Paint)
2270 * @see #LAYER_TYPE_NONE
2271 * @see #LAYER_TYPE_SOFTWARE
2272 */
2273 public static final int LAYER_TYPE_HARDWARE = 2;
2274
Romain Guy3aaff3a2011-01-12 14:18:47 -08002275 @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2276 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2277 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2278 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2279 })
Romain Guy171c5922011-01-06 10:04:23 -08002280 int mLayerType = LAYER_TYPE_NONE;
2281 Paint mLayerPaint;
2282
2283 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 * Simple constructor to use when creating a view from code.
2285 *
2286 * @param context The Context the view is running in, through which it can
2287 * access the current theme, resources, etc.
2288 */
2289 public View(Context context) {
2290 mContext = context;
2291 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002292 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002293 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Adam Powell637d3372010-08-25 14:37:03 -07002294 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 }
2296
2297 /**
2298 * Constructor that is called when inflating a view from XML. This is called
2299 * when a view is being constructed from an XML file, supplying attributes
2300 * that were specified in the XML file. This version uses a default style of
2301 * 0, so the only attribute values applied are those in the Context's Theme
2302 * and the given AttributeSet.
2303 *
2304 * <p>
2305 * The method onFinishInflate() will be called after all children have been
2306 * added.
2307 *
2308 * @param context The Context the view is running in, through which it can
2309 * access the current theme, resources, etc.
2310 * @param attrs The attributes of the XML tag that is inflating the view.
2311 * @see #View(Context, AttributeSet, int)
2312 */
2313 public View(Context context, AttributeSet attrs) {
2314 this(context, attrs, 0);
2315 }
2316
2317 /**
2318 * Perform inflation from XML and apply a class-specific base style. This
2319 * constructor of View allows subclasses to use their own base style when
2320 * they are inflating. For example, a Button class's constructor would call
2321 * this version of the super class constructor and supply
2322 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2323 * the theme's button style to modify all of the base view attributes (in
2324 * particular its background) as well as the Button class's attributes.
2325 *
2326 * @param context The Context the view is running in, through which it can
2327 * access the current theme, resources, etc.
2328 * @param attrs The attributes of the XML tag that is inflating the view.
2329 * @param defStyle The default style to apply to this view. If 0, no style
2330 * will be applied (beyond what is included in the theme). This may
2331 * either be an attribute resource, whose value will be retrieved
2332 * from the current theme, or an explicit style resource.
2333 * @see #View(Context, AttributeSet)
2334 */
2335 public View(Context context, AttributeSet attrs, int defStyle) {
2336 this(context);
2337
2338 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2339 defStyle, 0);
2340
2341 Drawable background = null;
2342
2343 int leftPadding = -1;
2344 int topPadding = -1;
2345 int rightPadding = -1;
2346 int bottomPadding = -1;
2347
2348 int padding = -1;
2349
2350 int viewFlagValues = 0;
2351 int viewFlagMasks = 0;
2352
2353 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 int x = 0;
2356 int y = 0;
2357
Chet Haase73066682010-11-29 15:55:32 -08002358 float tx = 0;
2359 float ty = 0;
2360 float rotation = 0;
2361 float rotationX = 0;
2362 float rotationY = 0;
2363 float sx = 1f;
2364 float sy = 1f;
2365 boolean transformSet = false;
2366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2368
Adam Powell637d3372010-08-25 14:37:03 -07002369 int overScrollMode = mOverScrollMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 final int N = a.getIndexCount();
2371 for (int i = 0; i < N; i++) {
2372 int attr = a.getIndex(i);
2373 switch (attr) {
2374 case com.android.internal.R.styleable.View_background:
2375 background = a.getDrawable(attr);
2376 break;
2377 case com.android.internal.R.styleable.View_padding:
2378 padding = a.getDimensionPixelSize(attr, -1);
2379 break;
2380 case com.android.internal.R.styleable.View_paddingLeft:
2381 leftPadding = a.getDimensionPixelSize(attr, -1);
2382 break;
2383 case com.android.internal.R.styleable.View_paddingTop:
2384 topPadding = a.getDimensionPixelSize(attr, -1);
2385 break;
2386 case com.android.internal.R.styleable.View_paddingRight:
2387 rightPadding = a.getDimensionPixelSize(attr, -1);
2388 break;
2389 case com.android.internal.R.styleable.View_paddingBottom:
2390 bottomPadding = a.getDimensionPixelSize(attr, -1);
2391 break;
2392 case com.android.internal.R.styleable.View_scrollX:
2393 x = a.getDimensionPixelOffset(attr, 0);
2394 break;
2395 case com.android.internal.R.styleable.View_scrollY:
2396 y = a.getDimensionPixelOffset(attr, 0);
2397 break;
Chet Haase73066682010-11-29 15:55:32 -08002398 case com.android.internal.R.styleable.View_alpha:
2399 setAlpha(a.getFloat(attr, 1f));
2400 break;
2401 case com.android.internal.R.styleable.View_transformPivotX:
2402 setPivotX(a.getDimensionPixelOffset(attr, 0));
2403 break;
2404 case com.android.internal.R.styleable.View_transformPivotY:
2405 setPivotY(a.getDimensionPixelOffset(attr, 0));
2406 break;
2407 case com.android.internal.R.styleable.View_translationX:
2408 tx = a.getDimensionPixelOffset(attr, 0);
2409 transformSet = true;
2410 break;
2411 case com.android.internal.R.styleable.View_translationY:
2412 ty = a.getDimensionPixelOffset(attr, 0);
2413 transformSet = true;
2414 break;
2415 case com.android.internal.R.styleable.View_rotation:
2416 rotation = a.getFloat(attr, 0);
2417 transformSet = true;
2418 break;
2419 case com.android.internal.R.styleable.View_rotationX:
2420 rotationX = a.getFloat(attr, 0);
2421 transformSet = true;
2422 break;
2423 case com.android.internal.R.styleable.View_rotationY:
2424 rotationY = a.getFloat(attr, 0);
2425 transformSet = true;
2426 break;
2427 case com.android.internal.R.styleable.View_scaleX:
2428 sx = a.getFloat(attr, 1f);
2429 transformSet = true;
2430 break;
2431 case com.android.internal.R.styleable.View_scaleY:
2432 sy = a.getFloat(attr, 1f);
2433 transformSet = true;
2434 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 case com.android.internal.R.styleable.View_id:
2436 mID = a.getResourceId(attr, NO_ID);
2437 break;
2438 case com.android.internal.R.styleable.View_tag:
2439 mTag = a.getText(attr);
2440 break;
2441 case com.android.internal.R.styleable.View_fitsSystemWindows:
2442 if (a.getBoolean(attr, false)) {
2443 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2444 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2445 }
2446 break;
2447 case com.android.internal.R.styleable.View_focusable:
2448 if (a.getBoolean(attr, false)) {
2449 viewFlagValues |= FOCUSABLE;
2450 viewFlagMasks |= FOCUSABLE_MASK;
2451 }
2452 break;
2453 case com.android.internal.R.styleable.View_focusableInTouchMode:
2454 if (a.getBoolean(attr, false)) {
2455 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2456 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2457 }
2458 break;
2459 case com.android.internal.R.styleable.View_clickable:
2460 if (a.getBoolean(attr, false)) {
2461 viewFlagValues |= CLICKABLE;
2462 viewFlagMasks |= CLICKABLE;
2463 }
2464 break;
2465 case com.android.internal.R.styleable.View_longClickable:
2466 if (a.getBoolean(attr, false)) {
2467 viewFlagValues |= LONG_CLICKABLE;
2468 viewFlagMasks |= LONG_CLICKABLE;
2469 }
2470 break;
2471 case com.android.internal.R.styleable.View_saveEnabled:
2472 if (!a.getBoolean(attr, true)) {
2473 viewFlagValues |= SAVE_DISABLED;
2474 viewFlagMasks |= SAVE_DISABLED_MASK;
2475 }
2476 break;
2477 case com.android.internal.R.styleable.View_duplicateParentState:
2478 if (a.getBoolean(attr, false)) {
2479 viewFlagValues |= DUPLICATE_PARENT_STATE;
2480 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2481 }
2482 break;
2483 case com.android.internal.R.styleable.View_visibility:
2484 final int visibility = a.getInt(attr, 0);
2485 if (visibility != 0) {
2486 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2487 viewFlagMasks |= VISIBILITY_MASK;
2488 }
2489 break;
2490 case com.android.internal.R.styleable.View_drawingCacheQuality:
2491 final int cacheQuality = a.getInt(attr, 0);
2492 if (cacheQuality != 0) {
2493 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2494 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2495 }
2496 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002497 case com.android.internal.R.styleable.View_contentDescription:
2498 mContentDescription = a.getString(attr);
2499 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2501 if (!a.getBoolean(attr, true)) {
2502 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2503 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2504 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002505 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2507 if (!a.getBoolean(attr, true)) {
2508 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2509 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2510 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002511 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 case R.styleable.View_scrollbars:
2513 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2514 if (scrollbars != SCROLLBARS_NONE) {
2515 viewFlagValues |= scrollbars;
2516 viewFlagMasks |= SCROLLBARS_MASK;
2517 initializeScrollbars(a);
2518 }
2519 break;
2520 case R.styleable.View_fadingEdge:
2521 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2522 if (fadingEdge != FADING_EDGE_NONE) {
2523 viewFlagValues |= fadingEdge;
2524 viewFlagMasks |= FADING_EDGE_MASK;
2525 initializeFadingEdge(a);
2526 }
2527 break;
2528 case R.styleable.View_scrollbarStyle:
2529 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2530 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2531 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2532 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2533 }
2534 break;
2535 case R.styleable.View_isScrollContainer:
2536 setScrollContainer = true;
2537 if (a.getBoolean(attr, false)) {
2538 setScrollContainer(true);
2539 }
2540 break;
2541 case com.android.internal.R.styleable.View_keepScreenOn:
2542 if (a.getBoolean(attr, false)) {
2543 viewFlagValues |= KEEP_SCREEN_ON;
2544 viewFlagMasks |= KEEP_SCREEN_ON;
2545 }
2546 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002547 case R.styleable.View_filterTouchesWhenObscured:
2548 if (a.getBoolean(attr, false)) {
2549 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2550 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2551 }
2552 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 case R.styleable.View_nextFocusLeft:
2554 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2555 break;
2556 case R.styleable.View_nextFocusRight:
2557 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2558 break;
2559 case R.styleable.View_nextFocusUp:
2560 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2561 break;
2562 case R.styleable.View_nextFocusDown:
2563 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2564 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002565 case R.styleable.View_nextFocusForward:
2566 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2567 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 case R.styleable.View_minWidth:
2569 mMinWidth = a.getDimensionPixelSize(attr, 0);
2570 break;
2571 case R.styleable.View_minHeight:
2572 mMinHeight = a.getDimensionPixelSize(attr, 0);
2573 break;
Romain Guy9a817362009-05-01 10:57:14 -07002574 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002575 if (context.isRestricted()) {
2576 throw new IllegalStateException("The android:onClick attribute cannot "
2577 + "be used within a restricted context");
2578 }
2579
Romain Guy9a817362009-05-01 10:57:14 -07002580 final String handlerName = a.getString(attr);
2581 if (handlerName != null) {
2582 setOnClickListener(new OnClickListener() {
2583 private Method mHandler;
2584
2585 public void onClick(View v) {
2586 if (mHandler == null) {
2587 try {
2588 mHandler = getContext().getClass().getMethod(handlerName,
2589 View.class);
2590 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002591 int id = getId();
2592 String idText = id == NO_ID ? "" : " with id '"
2593 + getContext().getResources().getResourceEntryName(
2594 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002595 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002596 handlerName + "(View) in the activity "
2597 + getContext().getClass() + " for onClick handler"
2598 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002599 }
2600 }
2601
2602 try {
2603 mHandler.invoke(getContext(), View.this);
2604 } catch (IllegalAccessException e) {
2605 throw new IllegalStateException("Could not execute non "
2606 + "public method of the activity", e);
2607 } catch (InvocationTargetException e) {
2608 throw new IllegalStateException("Could not execute "
2609 + "method of the activity", e);
2610 }
2611 }
2612 });
2613 }
2614 break;
Adam Powell637d3372010-08-25 14:37:03 -07002615 case R.styleable.View_overScrollMode:
2616 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2617 break;
Adam Powell20232d02010-12-08 21:08:53 -08002618 case R.styleable.View_verticalScrollbarPosition:
2619 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2620 break;
Romain Guy171c5922011-01-06 10:04:23 -08002621 case R.styleable.View_layerType:
2622 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
2623 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 }
2625 }
2626
Adam Powell637d3372010-08-25 14:37:03 -07002627 setOverScrollMode(overScrollMode);
2628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 if (background != null) {
2630 setBackgroundDrawable(background);
2631 }
2632
2633 if (padding >= 0) {
2634 leftPadding = padding;
2635 topPadding = padding;
2636 rightPadding = padding;
2637 bottomPadding = padding;
2638 }
2639
2640 // If the user specified the padding (either with android:padding or
2641 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2642 // use the default padding or the padding from the background drawable
2643 // (stored at this point in mPadding*)
2644 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2645 topPadding >= 0 ? topPadding : mPaddingTop,
2646 rightPadding >= 0 ? rightPadding : mPaddingRight,
2647 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2648
2649 if (viewFlagMasks != 0) {
2650 setFlags(viewFlagValues, viewFlagMasks);
2651 }
2652
2653 // Needs to be called after mViewFlags is set
2654 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2655 recomputePadding();
2656 }
2657
2658 if (x != 0 || y != 0) {
2659 scrollTo(x, y);
2660 }
2661
Chet Haase73066682010-11-29 15:55:32 -08002662 if (transformSet) {
2663 setTranslationX(tx);
2664 setTranslationY(ty);
2665 setRotation(rotation);
2666 setRotationX(rotationX);
2667 setRotationY(rotationY);
2668 setScaleX(sx);
2669 setScaleY(sy);
2670 }
2671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2673 setScrollContainer(true);
2674 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002675
2676 computeOpaqueFlags();
2677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 a.recycle();
2679 }
2680
2681 /**
2682 * Non-public constructor for use in testing
2683 */
2684 View() {
2685 }
2686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 /**
2688 * <p>
2689 * Initializes the fading edges from a given set of styled attributes. This
2690 * method should be called by subclasses that need fading edges and when an
2691 * instance of these subclasses is created programmatically rather than
2692 * being inflated from XML. This method is automatically called when the XML
2693 * is inflated.
2694 * </p>
2695 *
2696 * @param a the styled attributes set to initialize the fading edges from
2697 */
2698 protected void initializeFadingEdge(TypedArray a) {
2699 initScrollCache();
2700
2701 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2702 R.styleable.View_fadingEdgeLength,
2703 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2704 }
2705
2706 /**
2707 * Returns the size of the vertical faded edges used to indicate that more
2708 * content in this view is visible.
2709 *
2710 * @return The size in pixels of the vertical faded edge or 0 if vertical
2711 * faded edges are not enabled for this view.
2712 * @attr ref android.R.styleable#View_fadingEdgeLength
2713 */
2714 public int getVerticalFadingEdgeLength() {
2715 if (isVerticalFadingEdgeEnabled()) {
2716 ScrollabilityCache cache = mScrollCache;
2717 if (cache != null) {
2718 return cache.fadingEdgeLength;
2719 }
2720 }
2721 return 0;
2722 }
2723
2724 /**
2725 * Set the size of the faded edge used to indicate that more content in this
2726 * view is available. Will not change whether the fading edge is enabled; use
2727 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2728 * to enable the fading edge for the vertical or horizontal fading edges.
2729 *
2730 * @param length The size in pixels of the faded edge used to indicate that more
2731 * content in this view is visible.
2732 */
2733 public void setFadingEdgeLength(int length) {
2734 initScrollCache();
2735 mScrollCache.fadingEdgeLength = length;
2736 }
2737
2738 /**
2739 * Returns the size of the horizontal faded edges used to indicate that more
2740 * content in this view is visible.
2741 *
2742 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2743 * faded edges are not enabled for this view.
2744 * @attr ref android.R.styleable#View_fadingEdgeLength
2745 */
2746 public int getHorizontalFadingEdgeLength() {
2747 if (isHorizontalFadingEdgeEnabled()) {
2748 ScrollabilityCache cache = mScrollCache;
2749 if (cache != null) {
2750 return cache.fadingEdgeLength;
2751 }
2752 }
2753 return 0;
2754 }
2755
2756 /**
2757 * Returns the width of the vertical scrollbar.
2758 *
2759 * @return The width in pixels of the vertical scrollbar or 0 if there
2760 * is no vertical scrollbar.
2761 */
2762 public int getVerticalScrollbarWidth() {
2763 ScrollabilityCache cache = mScrollCache;
2764 if (cache != null) {
2765 ScrollBarDrawable scrollBar = cache.scrollBar;
2766 if (scrollBar != null) {
2767 int size = scrollBar.getSize(true);
2768 if (size <= 0) {
2769 size = cache.scrollBarSize;
2770 }
2771 return size;
2772 }
2773 return 0;
2774 }
2775 return 0;
2776 }
2777
2778 /**
2779 * Returns the height of the horizontal scrollbar.
2780 *
2781 * @return The height in pixels of the horizontal scrollbar or 0 if
2782 * there is no horizontal scrollbar.
2783 */
2784 protected int getHorizontalScrollbarHeight() {
2785 ScrollabilityCache cache = mScrollCache;
2786 if (cache != null) {
2787 ScrollBarDrawable scrollBar = cache.scrollBar;
2788 if (scrollBar != null) {
2789 int size = scrollBar.getSize(false);
2790 if (size <= 0) {
2791 size = cache.scrollBarSize;
2792 }
2793 return size;
2794 }
2795 return 0;
2796 }
2797 return 0;
2798 }
2799
2800 /**
2801 * <p>
2802 * Initializes the scrollbars from a given set of styled attributes. This
2803 * method should be called by subclasses that need scrollbars and when an
2804 * instance of these subclasses is created programmatically rather than
2805 * being inflated from XML. This method is automatically called when the XML
2806 * is inflated.
2807 * </p>
2808 *
2809 * @param a the styled attributes set to initialize the scrollbars from
2810 */
2811 protected void initializeScrollbars(TypedArray a) {
2812 initScrollCache();
2813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002815
2816 if (scrollabilityCache.scrollBar == null) {
2817 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2818 }
2819
Romain Guy8bda2482010-03-02 11:42:11 -08002820 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821
Mike Cleronf116bf82009-09-27 19:14:12 -07002822 if (!fadeScrollbars) {
2823 scrollabilityCache.state = ScrollabilityCache.ON;
2824 }
2825 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2826
2827
2828 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2829 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2830 .getScrollBarFadeDuration());
2831 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2832 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2833 ViewConfiguration.getScrollDefaultDelay());
2834
2835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2837 com.android.internal.R.styleable.View_scrollbarSize,
2838 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2839
2840 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2841 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2842
2843 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2844 if (thumb != null) {
2845 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2846 }
2847
2848 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2849 false);
2850 if (alwaysDraw) {
2851 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2852 }
2853
2854 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2855 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2856
2857 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2858 if (thumb != null) {
2859 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2860 }
2861
2862 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2863 false);
2864 if (alwaysDraw) {
2865 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2866 }
2867
2868 // Re-apply user/background padding so that scrollbar(s) get added
2869 recomputePadding();
2870 }
2871
2872 /**
2873 * <p>
2874 * Initalizes the scrollability cache if necessary.
2875 * </p>
2876 */
2877 private void initScrollCache() {
2878 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002879 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 }
2881 }
2882
2883 /**
Adam Powell20232d02010-12-08 21:08:53 -08002884 * Set the position of the vertical scroll bar. Should be one of
2885 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
2886 * {@link #SCROLLBAR_POSITION_RIGHT}.
2887 *
2888 * @param position Where the vertical scroll bar should be positioned.
2889 */
2890 public void setVerticalScrollbarPosition(int position) {
2891 if (mVerticalScrollbarPosition != position) {
2892 mVerticalScrollbarPosition = position;
2893 computeOpaqueFlags();
2894 recomputePadding();
2895 }
2896 }
2897
2898 /**
2899 * @return The position where the vertical scroll bar will show, if applicable.
2900 * @see #setVerticalScrollbarPosition(int)
2901 */
2902 public int getVerticalScrollbarPosition() {
2903 return mVerticalScrollbarPosition;
2904 }
2905
2906 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 * Register a callback to be invoked when focus of this view changed.
2908 *
2909 * @param l The callback that will run.
2910 */
2911 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2912 mOnFocusChangeListener = l;
2913 }
2914
2915 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002916 * Add a listener that will be called when the bounds of the view change due to
2917 * layout processing.
2918 *
2919 * @param listener The listener that will be called when layout bounds change.
2920 */
2921 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2922 if (mOnLayoutChangeListeners == null) {
2923 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2924 }
2925 mOnLayoutChangeListeners.add(listener);
2926 }
2927
2928 /**
2929 * Remove a listener for layout changes.
2930 *
2931 * @param listener The listener for layout bounds change.
2932 */
2933 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2934 if (mOnLayoutChangeListeners == null) {
2935 return;
2936 }
2937 mOnLayoutChangeListeners.remove(listener);
2938 }
2939
2940 /**
2941 * Gets the current list of listeners for layout changes.
Chet Haase21cd1382010-09-01 17:42:29 -07002942 */
2943 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2944 return mOnLayoutChangeListeners;
2945 }
2946
2947 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 * Returns the focus-change callback registered for this view.
2949 *
2950 * @return The callback, or null if one is not registered.
2951 */
2952 public OnFocusChangeListener getOnFocusChangeListener() {
2953 return mOnFocusChangeListener;
2954 }
2955
2956 /**
2957 * Register a callback to be invoked when this view is clicked. If this view is not
2958 * clickable, it becomes clickable.
2959 *
2960 * @param l The callback that will run
2961 *
2962 * @see #setClickable(boolean)
2963 */
2964 public void setOnClickListener(OnClickListener l) {
2965 if (!isClickable()) {
2966 setClickable(true);
2967 }
2968 mOnClickListener = l;
2969 }
2970
2971 /**
2972 * Register a callback to be invoked when this view is clicked and held. If this view is not
2973 * long clickable, it becomes long clickable.
2974 *
2975 * @param l The callback that will run
2976 *
2977 * @see #setLongClickable(boolean)
2978 */
2979 public void setOnLongClickListener(OnLongClickListener l) {
2980 if (!isLongClickable()) {
2981 setLongClickable(true);
2982 }
2983 mOnLongClickListener = l;
2984 }
2985
2986 /**
2987 * Register a callback to be invoked when the context menu for this view is
2988 * being built. If this view is not long clickable, it becomes long clickable.
2989 *
2990 * @param l The callback that will run
2991 *
2992 */
2993 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2994 if (!isLongClickable()) {
2995 setLongClickable(true);
2996 }
2997 mOnCreateContextMenuListener = l;
2998 }
2999
3000 /**
3001 * Call this view's OnClickListener, if it is defined.
3002 *
3003 * @return True there was an assigned OnClickListener that was called, false
3004 * otherwise is returned.
3005 */
3006 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07003007 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 if (mOnClickListener != null) {
3010 playSoundEffect(SoundEffectConstants.CLICK);
3011 mOnClickListener.onClick(this);
3012 return true;
3013 }
3014
3015 return false;
3016 }
3017
3018 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07003019 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3020 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07003022 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 */
3024 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07003025 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 boolean handled = false;
3028 if (mOnLongClickListener != null) {
3029 handled = mOnLongClickListener.onLongClick(View.this);
3030 }
3031 if (!handled) {
3032 handled = showContextMenu();
3033 }
3034 if (handled) {
3035 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3036 }
3037 return handled;
3038 }
3039
3040 /**
3041 * Bring up the context menu for this view.
3042 *
3043 * @return Whether a context menu was displayed.
3044 */
3045 public boolean showContextMenu() {
3046 return getParent().showContextMenuForChild(this);
3047 }
3048
3049 /**
Adam Powell6e346362010-07-23 10:18:23 -07003050 * Start an action mode.
3051 *
3052 * @param callback Callback that will control the lifecycle of the action mode
3053 * @return The new action mode if it is started, null otherwise
3054 *
3055 * @see ActionMode
3056 */
3057 public ActionMode startActionMode(ActionMode.Callback callback) {
3058 return getParent().startActionModeForChild(this, callback);
3059 }
3060
3061 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 * Register a callback to be invoked when a key is pressed in this view.
3063 * @param l the key listener to attach to this view
3064 */
3065 public void setOnKeyListener(OnKeyListener l) {
3066 mOnKeyListener = l;
3067 }
3068
3069 /**
3070 * Register a callback to be invoked when a touch event is sent to this view.
3071 * @param l the touch listener to attach to this view
3072 */
3073 public void setOnTouchListener(OnTouchListener l) {
3074 mOnTouchListener = l;
3075 }
3076
3077 /**
Chris Tate32affef2010-10-18 15:29:21 -07003078 * Register a callback to be invoked when a drag event is sent to this view.
3079 * @param l The drag listener to attach to this view
3080 */
3081 public void setOnDragListener(OnDragListener l) {
3082 mOnDragListener = l;
3083 }
3084
3085 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
3087 *
3088 * Note: this does not check whether this {@link View} should get focus, it just
3089 * gives it focus no matter what. It should only be called internally by framework
3090 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3091 *
3092 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
3093 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
3094 * focus moved when requestFocus() is called. It may not always
3095 * apply, in which case use the default View.FOCUS_DOWN.
3096 * @param previouslyFocusedRect The rectangle of the view that had focus
3097 * prior in this View's coordinate system.
3098 */
3099 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3100 if (DBG) {
3101 System.out.println(this + " requestFocus()");
3102 }
3103
3104 if ((mPrivateFlags & FOCUSED) == 0) {
3105 mPrivateFlags |= FOCUSED;
3106
3107 if (mParent != null) {
3108 mParent.requestChildFocus(this, this);
3109 }
3110
3111 onFocusChanged(true, direction, previouslyFocusedRect);
3112 refreshDrawableState();
3113 }
3114 }
3115
3116 /**
3117 * Request that a rectangle of this view be visible on the screen,
3118 * scrolling if necessary just enough.
3119 *
3120 * <p>A View should call this if it maintains some notion of which part
3121 * of its content is interesting. For example, a text editing view
3122 * should call this when its cursor moves.
3123 *
3124 * @param rectangle The rectangle.
3125 * @return Whether any parent scrolled.
3126 */
3127 public boolean requestRectangleOnScreen(Rect rectangle) {
3128 return requestRectangleOnScreen(rectangle, false);
3129 }
3130
3131 /**
3132 * Request that a rectangle of this view be visible on the screen,
3133 * scrolling if necessary just enough.
3134 *
3135 * <p>A View should call this if it maintains some notion of which part
3136 * of its content is interesting. For example, a text editing view
3137 * should call this when its cursor moves.
3138 *
3139 * <p>When <code>immediate</code> is set to true, scrolling will not be
3140 * animated.
3141 *
3142 * @param rectangle The rectangle.
3143 * @param immediate True to forbid animated scrolling, false otherwise
3144 * @return Whether any parent scrolled.
3145 */
3146 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3147 View child = this;
3148 ViewParent parent = mParent;
3149 boolean scrolled = false;
3150 while (parent != null) {
3151 scrolled |= parent.requestChildRectangleOnScreen(child,
3152 rectangle, immediate);
3153
3154 // offset rect so next call has the rectangle in the
3155 // coordinate system of its direct child.
3156 rectangle.offset(child.getLeft(), child.getTop());
3157 rectangle.offset(-child.getScrollX(), -child.getScrollY());
3158
3159 if (!(parent instanceof View)) {
3160 break;
3161 }
Romain Guy8506ab42009-06-11 17:35:47 -07003162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163 child = (View) parent;
3164 parent = child.getParent();
3165 }
3166 return scrolled;
3167 }
3168
3169 /**
3170 * Called when this view wants to give up focus. This will cause
3171 * {@link #onFocusChanged} to be called.
3172 */
3173 public void clearFocus() {
3174 if (DBG) {
3175 System.out.println(this + " clearFocus()");
3176 }
3177
3178 if ((mPrivateFlags & FOCUSED) != 0) {
3179 mPrivateFlags &= ~FOCUSED;
3180
3181 if (mParent != null) {
3182 mParent.clearChildFocus(this);
3183 }
3184
3185 onFocusChanged(false, 0, null);
3186 refreshDrawableState();
3187 }
3188 }
3189
3190 /**
3191 * Called to clear the focus of a view that is about to be removed.
3192 * Doesn't call clearChildFocus, which prevents this view from taking
3193 * focus again before it has been removed from the parent
3194 */
3195 void clearFocusForRemoval() {
3196 if ((mPrivateFlags & FOCUSED) != 0) {
3197 mPrivateFlags &= ~FOCUSED;
3198
3199 onFocusChanged(false, 0, null);
3200 refreshDrawableState();
3201 }
3202 }
3203
3204 /**
3205 * Called internally by the view system when a new view is getting focus.
3206 * This is what clears the old focus.
3207 */
3208 void unFocus() {
3209 if (DBG) {
3210 System.out.println(this + " unFocus()");
3211 }
3212
3213 if ((mPrivateFlags & FOCUSED) != 0) {
3214 mPrivateFlags &= ~FOCUSED;
3215
3216 onFocusChanged(false, 0, null);
3217 refreshDrawableState();
3218 }
3219 }
3220
3221 /**
3222 * Returns true if this view has focus iteself, or is the ancestor of the
3223 * view that has focus.
3224 *
3225 * @return True if this view has or contains focus, false otherwise.
3226 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003227 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 public boolean hasFocus() {
3229 return (mPrivateFlags & FOCUSED) != 0;
3230 }
3231
3232 /**
3233 * Returns true if this view is focusable or if it contains a reachable View
3234 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3235 * is a View whose parents do not block descendants focus.
3236 *
3237 * Only {@link #VISIBLE} views are considered focusable.
3238 *
3239 * @return True if the view is focusable or if the view contains a focusable
3240 * View, false otherwise.
3241 *
3242 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3243 */
3244 public boolean hasFocusable() {
3245 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3246 }
3247
3248 /**
3249 * Called by the view system when the focus state of this view changes.
3250 * When the focus change event is caused by directional navigation, direction
3251 * and previouslyFocusedRect provide insight into where the focus is coming from.
3252 * When overriding, be sure to call up through to the super class so that
3253 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07003254 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 * @param gainFocus True if the View has focus; false otherwise.
3256 * @param direction The direction focus has moved when requestFocus()
3257 * is called to give this view focus. Values are
Jeff Brown4e6319b2010-12-13 10:36:51 -08003258 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3259 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3260 * It may not always apply, in which case use the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 * @param previouslyFocusedRect The rectangle, in this view's coordinate
3262 * system, of the previously focused view. If applicable, this will be
3263 * passed in as finer grained information about where the focus is coming
3264 * from (in addition to direction). Will be <code>null</code> otherwise.
3265 */
3266 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003267 if (gainFocus) {
3268 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3269 }
3270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 InputMethodManager imm = InputMethodManager.peekInstance();
3272 if (!gainFocus) {
3273 if (isPressed()) {
3274 setPressed(false);
3275 }
3276 if (imm != null && mAttachInfo != null
3277 && mAttachInfo.mHasWindowFocus) {
3278 imm.focusOut(this);
3279 }
Romain Guya2431d02009-04-30 16:30:00 -07003280 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 } else if (imm != null && mAttachInfo != null
3282 && mAttachInfo.mHasWindowFocus) {
3283 imm.focusIn(this);
3284 }
Romain Guy8506ab42009-06-11 17:35:47 -07003285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 invalidate();
3287 if (mOnFocusChangeListener != null) {
3288 mOnFocusChangeListener.onFocusChange(this, gainFocus);
3289 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003290
3291 if (mAttachInfo != null) {
3292 mAttachInfo.mKeyDispatchState.reset(this);
3293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 }
3295
3296 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07003297 * {@inheritDoc}
3298 */
3299 public void sendAccessibilityEvent(int eventType) {
3300 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3301 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3302 }
3303 }
3304
3305 /**
3306 * {@inheritDoc}
3307 */
3308 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
Svetoslav Ganov9cd1eca2011-01-13 14:24:02 -08003309 if (!isShown()) {
3310 return;
3311 }
svetoslavganov75986cf2009-05-14 22:28:01 -07003312 event.setClassName(getClass().getName());
3313 event.setPackageName(getContext().getPackageName());
3314 event.setEnabled(isEnabled());
3315 event.setContentDescription(mContentDescription);
3316
3317 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3318 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3319 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3320 event.setItemCount(focusablesTempList.size());
3321 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3322 focusablesTempList.clear();
3323 }
3324
3325 dispatchPopulateAccessibilityEvent(event);
3326
3327 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3328 }
3329
3330 /**
3331 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3332 * to be populated.
3333 *
3334 * @param event The event.
3335 *
3336 * @return True if the event population was completed.
3337 */
3338 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3339 return false;
3340 }
3341
3342 /**
3343 * Gets the {@link View} description. It briefly describes the view and is
3344 * primarily used for accessibility support. Set this property to enable
3345 * better accessibility support for your application. This is especially
3346 * true for views that do not have textual representation (For example,
3347 * ImageButton).
3348 *
3349 * @return The content descriptiopn.
3350 *
3351 * @attr ref android.R.styleable#View_contentDescription
3352 */
3353 public CharSequence getContentDescription() {
3354 return mContentDescription;
3355 }
3356
3357 /**
3358 * Sets the {@link View} description. It briefly describes the view and is
3359 * primarily used for accessibility support. Set this property to enable
3360 * better accessibility support for your application. This is especially
3361 * true for views that do not have textual representation (For example,
3362 * ImageButton).
3363 *
3364 * @param contentDescription The content description.
3365 *
3366 * @attr ref android.R.styleable#View_contentDescription
3367 */
3368 public void setContentDescription(CharSequence contentDescription) {
3369 mContentDescription = contentDescription;
3370 }
3371
3372 /**
Romain Guya2431d02009-04-30 16:30:00 -07003373 * Invoked whenever this view loses focus, either by losing window focus or by losing
3374 * focus within its window. This method can be used to clear any state tied to the
3375 * focus. For instance, if a button is held pressed with the trackball and the window
3376 * loses focus, this method can be used to cancel the press.
3377 *
3378 * Subclasses of View overriding this method should always call super.onFocusLost().
3379 *
3380 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003381 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003382 *
3383 * @hide pending API council approval
3384 */
3385 protected void onFocusLost() {
3386 resetPressedState();
3387 }
3388
3389 private void resetPressedState() {
3390 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3391 return;
3392 }
3393
3394 if (isPressed()) {
3395 setPressed(false);
3396
3397 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003398 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003399 }
3400 }
3401 }
3402
3403 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 * Returns true if this view has focus
3405 *
3406 * @return True if this view has focus, false otherwise.
3407 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003408 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 public boolean isFocused() {
3410 return (mPrivateFlags & FOCUSED) != 0;
3411 }
3412
3413 /**
3414 * Find the view in the hierarchy rooted at this view that currently has
3415 * focus.
3416 *
3417 * @return The view that currently has focus, or null if no focused view can
3418 * be found.
3419 */
3420 public View findFocus() {
3421 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3422 }
3423
3424 /**
3425 * Change whether this view is one of the set of scrollable containers in
3426 * its window. This will be used to determine whether the window can
3427 * resize or must pan when a soft input area is open -- scrollable
3428 * containers allow the window to use resize mode since the container
3429 * will appropriately shrink.
3430 */
3431 public void setScrollContainer(boolean isScrollContainer) {
3432 if (isScrollContainer) {
3433 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3434 mAttachInfo.mScrollContainers.add(this);
3435 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3436 }
3437 mPrivateFlags |= SCROLL_CONTAINER;
3438 } else {
3439 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3440 mAttachInfo.mScrollContainers.remove(this);
3441 }
3442 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3443 }
3444 }
3445
3446 /**
3447 * Returns the quality of the drawing cache.
3448 *
3449 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3450 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3451 *
3452 * @see #setDrawingCacheQuality(int)
3453 * @see #setDrawingCacheEnabled(boolean)
3454 * @see #isDrawingCacheEnabled()
3455 *
3456 * @attr ref android.R.styleable#View_drawingCacheQuality
3457 */
3458 public int getDrawingCacheQuality() {
3459 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3460 }
3461
3462 /**
3463 * Set the drawing cache quality of this view. This value is used only when the
3464 * drawing cache is enabled
3465 *
3466 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3467 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3468 *
3469 * @see #getDrawingCacheQuality()
3470 * @see #setDrawingCacheEnabled(boolean)
3471 * @see #isDrawingCacheEnabled()
3472 *
3473 * @attr ref android.R.styleable#View_drawingCacheQuality
3474 */
3475 public void setDrawingCacheQuality(int quality) {
3476 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3477 }
3478
3479 /**
3480 * Returns whether the screen should remain on, corresponding to the current
3481 * value of {@link #KEEP_SCREEN_ON}.
3482 *
3483 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3484 *
3485 * @see #setKeepScreenOn(boolean)
3486 *
3487 * @attr ref android.R.styleable#View_keepScreenOn
3488 */
3489 public boolean getKeepScreenOn() {
3490 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3491 }
3492
3493 /**
3494 * Controls whether the screen should remain on, modifying the
3495 * value of {@link #KEEP_SCREEN_ON}.
3496 *
3497 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3498 *
3499 * @see #getKeepScreenOn()
3500 *
3501 * @attr ref android.R.styleable#View_keepScreenOn
3502 */
3503 public void setKeepScreenOn(boolean keepScreenOn) {
3504 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3505 }
3506
3507 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003508 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3509 * @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 -08003510 *
3511 * @attr ref android.R.styleable#View_nextFocusLeft
3512 */
3513 public int getNextFocusLeftId() {
3514 return mNextFocusLeftId;
3515 }
3516
3517 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003518 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3519 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
3520 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 *
3522 * @attr ref android.R.styleable#View_nextFocusLeft
3523 */
3524 public void setNextFocusLeftId(int nextFocusLeftId) {
3525 mNextFocusLeftId = nextFocusLeftId;
3526 }
3527
3528 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003529 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3530 * @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 -08003531 *
3532 * @attr ref android.R.styleable#View_nextFocusRight
3533 */
3534 public int getNextFocusRightId() {
3535 return mNextFocusRightId;
3536 }
3537
3538 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003539 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3540 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
3541 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 *
3543 * @attr ref android.R.styleable#View_nextFocusRight
3544 */
3545 public void setNextFocusRightId(int nextFocusRightId) {
3546 mNextFocusRightId = nextFocusRightId;
3547 }
3548
3549 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003550 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3551 * @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 -08003552 *
3553 * @attr ref android.R.styleable#View_nextFocusUp
3554 */
3555 public int getNextFocusUpId() {
3556 return mNextFocusUpId;
3557 }
3558
3559 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003560 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3561 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
3562 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 *
3564 * @attr ref android.R.styleable#View_nextFocusUp
3565 */
3566 public void setNextFocusUpId(int nextFocusUpId) {
3567 mNextFocusUpId = nextFocusUpId;
3568 }
3569
3570 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003571 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3572 * @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 -08003573 *
3574 * @attr ref android.R.styleable#View_nextFocusDown
3575 */
3576 public int getNextFocusDownId() {
3577 return mNextFocusDownId;
3578 }
3579
3580 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003581 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3582 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
3583 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 *
3585 * @attr ref android.R.styleable#View_nextFocusDown
3586 */
3587 public void setNextFocusDownId(int nextFocusDownId) {
3588 mNextFocusDownId = nextFocusDownId;
3589 }
3590
3591 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003592 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3593 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3594 *
3595 * @attr ref android.R.styleable#View_nextFocusForward
3596 */
3597 public int getNextFocusForwardId() {
3598 return mNextFocusForwardId;
3599 }
3600
3601 /**
3602 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3603 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
3604 * decide automatically.
3605 *
3606 * @attr ref android.R.styleable#View_nextFocusForward
3607 */
3608 public void setNextFocusForwardId(int nextFocusForwardId) {
3609 mNextFocusForwardId = nextFocusForwardId;
3610 }
3611
3612 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 * Returns the visibility of this view and all of its ancestors
3614 *
3615 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3616 */
3617 public boolean isShown() {
3618 View current = this;
3619 //noinspection ConstantConditions
3620 do {
3621 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3622 return false;
3623 }
3624 ViewParent parent = current.mParent;
3625 if (parent == null) {
3626 return false; // We are not attached to the view root
3627 }
3628 if (!(parent instanceof View)) {
3629 return true;
3630 }
3631 current = (View) parent;
3632 } while (current != null);
3633
3634 return false;
3635 }
3636
3637 /**
3638 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3639 * is set
3640 *
3641 * @param insets Insets for system windows
3642 *
3643 * @return True if this view applied the insets, false otherwise
3644 */
3645 protected boolean fitSystemWindows(Rect insets) {
3646 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3647 mPaddingLeft = insets.left;
3648 mPaddingTop = insets.top;
3649 mPaddingRight = insets.right;
3650 mPaddingBottom = insets.bottom;
3651 requestLayout();
3652 return true;
3653 }
3654 return false;
3655 }
3656
3657 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003658 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3659 * @return True if window has FITS_SYSTEM_WINDOWS set
3660 *
3661 * @hide
3662 */
3663 public boolean isFitsSystemWindowsFlagSet() {
3664 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3665 }
3666
3667 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 * Returns the visibility status for this view.
3669 *
3670 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3671 * @attr ref android.R.styleable#View_visibility
3672 */
3673 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003674 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3675 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3676 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 })
3678 public int getVisibility() {
3679 return mViewFlags & VISIBILITY_MASK;
3680 }
3681
3682 /**
3683 * Set the enabled state of this view.
3684 *
3685 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3686 * @attr ref android.R.styleable#View_visibility
3687 */
3688 @RemotableViewMethod
3689 public void setVisibility(int visibility) {
3690 setFlags(visibility, VISIBILITY_MASK);
3691 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3692 }
3693
3694 /**
3695 * Returns the enabled status for this view. The interpretation of the
3696 * enabled state varies by subclass.
3697 *
3698 * @return True if this view is enabled, false otherwise.
3699 */
3700 @ViewDebug.ExportedProperty
3701 public boolean isEnabled() {
3702 return (mViewFlags & ENABLED_MASK) == ENABLED;
3703 }
3704
3705 /**
3706 * Set the enabled state of this view. The interpretation of the enabled
3707 * state varies by subclass.
3708 *
3709 * @param enabled True if this view is enabled, false otherwise.
3710 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003711 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003713 if (enabled == isEnabled()) return;
3714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3716
3717 /*
3718 * The View most likely has to change its appearance, so refresh
3719 * the drawable state.
3720 */
3721 refreshDrawableState();
3722
3723 // Invalidate too, since the default behavior for views is to be
3724 // be drawn at 50% alpha rather than to change the drawable.
3725 invalidate();
3726 }
3727
3728 /**
3729 * Set whether this view can receive the focus.
3730 *
3731 * Setting this to false will also ensure that this view is not focusable
3732 * in touch mode.
3733 *
3734 * @param focusable If true, this view can receive the focus.
3735 *
3736 * @see #setFocusableInTouchMode(boolean)
3737 * @attr ref android.R.styleable#View_focusable
3738 */
3739 public void setFocusable(boolean focusable) {
3740 if (!focusable) {
3741 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3742 }
3743 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3744 }
3745
3746 /**
3747 * Set whether this view can receive focus while in touch mode.
3748 *
3749 * Setting this to true will also ensure that this view is focusable.
3750 *
3751 * @param focusableInTouchMode If true, this view can receive the focus while
3752 * in touch mode.
3753 *
3754 * @see #setFocusable(boolean)
3755 * @attr ref android.R.styleable#View_focusableInTouchMode
3756 */
3757 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3758 // Focusable in touch mode should always be set before the focusable flag
3759 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3760 // which, in touch mode, will not successfully request focus on this view
3761 // because the focusable in touch mode flag is not set
3762 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3763 if (focusableInTouchMode) {
3764 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3765 }
3766 }
3767
3768 /**
3769 * Set whether this view should have sound effects enabled for events such as
3770 * clicking and touching.
3771 *
3772 * <p>You may wish to disable sound effects for a view if you already play sounds,
3773 * for instance, a dial key that plays dtmf tones.
3774 *
3775 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3776 * @see #isSoundEffectsEnabled()
3777 * @see #playSoundEffect(int)
3778 * @attr ref android.R.styleable#View_soundEffectsEnabled
3779 */
3780 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3781 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3782 }
3783
3784 /**
3785 * @return whether this view should have sound effects enabled for events such as
3786 * clicking and touching.
3787 *
3788 * @see #setSoundEffectsEnabled(boolean)
3789 * @see #playSoundEffect(int)
3790 * @attr ref android.R.styleable#View_soundEffectsEnabled
3791 */
3792 @ViewDebug.ExportedProperty
3793 public boolean isSoundEffectsEnabled() {
3794 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3795 }
3796
3797 /**
3798 * Set whether this view should have haptic feedback for events such as
3799 * long presses.
3800 *
3801 * <p>You may wish to disable haptic feedback if your view already controls
3802 * its own haptic feedback.
3803 *
3804 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3805 * @see #isHapticFeedbackEnabled()
3806 * @see #performHapticFeedback(int)
3807 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3808 */
3809 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3810 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3811 }
3812
3813 /**
3814 * @return whether this view should have haptic feedback enabled for events
3815 * long presses.
3816 *
3817 * @see #setHapticFeedbackEnabled(boolean)
3818 * @see #performHapticFeedback(int)
3819 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3820 */
3821 @ViewDebug.ExportedProperty
3822 public boolean isHapticFeedbackEnabled() {
3823 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3824 }
3825
3826 /**
3827 * If this view doesn't do any drawing on its own, set this flag to
3828 * allow further optimizations. By default, this flag is not set on
3829 * View, but could be set on some View subclasses such as ViewGroup.
3830 *
3831 * Typically, if you override {@link #onDraw} you should clear this flag.
3832 *
3833 * @param willNotDraw whether or not this View draw on its own
3834 */
3835 public void setWillNotDraw(boolean willNotDraw) {
3836 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3837 }
3838
3839 /**
3840 * Returns whether or not this View draws on its own.
3841 *
3842 * @return true if this view has nothing to draw, false otherwise
3843 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003844 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003845 public boolean willNotDraw() {
3846 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3847 }
3848
3849 /**
3850 * When a View's drawing cache is enabled, drawing is redirected to an
3851 * offscreen bitmap. Some views, like an ImageView, must be able to
3852 * bypass this mechanism if they already draw a single bitmap, to avoid
3853 * unnecessary usage of the memory.
3854 *
3855 * @param willNotCacheDrawing true if this view does not cache its
3856 * drawing, false otherwise
3857 */
3858 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3859 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3860 }
3861
3862 /**
3863 * Returns whether or not this View can cache its drawing or not.
3864 *
3865 * @return true if this view does not cache its drawing, false otherwise
3866 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003867 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 public boolean willNotCacheDrawing() {
3869 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3870 }
3871
3872 /**
3873 * Indicates whether this view reacts to click events or not.
3874 *
3875 * @return true if the view is clickable, false otherwise
3876 *
3877 * @see #setClickable(boolean)
3878 * @attr ref android.R.styleable#View_clickable
3879 */
3880 @ViewDebug.ExportedProperty
3881 public boolean isClickable() {
3882 return (mViewFlags & CLICKABLE) == CLICKABLE;
3883 }
3884
3885 /**
3886 * Enables or disables click events for this view. When a view
3887 * is clickable it will change its state to "pressed" on every click.
3888 * Subclasses should set the view clickable to visually react to
3889 * user's clicks.
3890 *
3891 * @param clickable true to make the view clickable, false otherwise
3892 *
3893 * @see #isClickable()
3894 * @attr ref android.R.styleable#View_clickable
3895 */
3896 public void setClickable(boolean clickable) {
3897 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3898 }
3899
3900 /**
3901 * Indicates whether this view reacts to long click events or not.
3902 *
3903 * @return true if the view is long clickable, false otherwise
3904 *
3905 * @see #setLongClickable(boolean)
3906 * @attr ref android.R.styleable#View_longClickable
3907 */
3908 public boolean isLongClickable() {
3909 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3910 }
3911
3912 /**
3913 * Enables or disables long click events for this view. When a view is long
3914 * clickable it reacts to the user holding down the button for a longer
3915 * duration than a tap. This event can either launch the listener or a
3916 * context menu.
3917 *
3918 * @param longClickable true to make the view long clickable, false otherwise
3919 * @see #isLongClickable()
3920 * @attr ref android.R.styleable#View_longClickable
3921 */
3922 public void setLongClickable(boolean longClickable) {
3923 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3924 }
3925
3926 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003927 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 *
3929 * @see #isClickable()
3930 * @see #setClickable(boolean)
3931 *
3932 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3933 * the View's internal state from a previously set "pressed" state.
3934 */
3935 public void setPressed(boolean pressed) {
3936 if (pressed) {
3937 mPrivateFlags |= PRESSED;
3938 } else {
3939 mPrivateFlags &= ~PRESSED;
3940 }
3941 refreshDrawableState();
3942 dispatchSetPressed(pressed);
3943 }
3944
3945 /**
3946 * Dispatch setPressed to all of this View's children.
3947 *
3948 * @see #setPressed(boolean)
3949 *
3950 * @param pressed The new pressed state
3951 */
3952 protected void dispatchSetPressed(boolean pressed) {
3953 }
3954
3955 /**
3956 * Indicates whether the view is currently in pressed state. Unless
3957 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3958 * the pressed state.
3959 *
3960 * @see #setPressed
3961 * @see #isClickable()
3962 * @see #setClickable(boolean)
3963 *
3964 * @return true if the view is currently pressed, false otherwise
3965 */
3966 public boolean isPressed() {
3967 return (mPrivateFlags & PRESSED) == PRESSED;
3968 }
3969
3970 /**
3971 * Indicates whether this view will save its state (that is,
3972 * whether its {@link #onSaveInstanceState} method will be called).
3973 *
3974 * @return Returns true if the view state saving is enabled, else false.
3975 *
3976 * @see #setSaveEnabled(boolean)
3977 * @attr ref android.R.styleable#View_saveEnabled
3978 */
3979 public boolean isSaveEnabled() {
3980 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3981 }
3982
3983 /**
3984 * Controls whether the saving of this view's state is
3985 * enabled (that is, whether its {@link #onSaveInstanceState} method
3986 * will be called). Note that even if freezing is enabled, the
3987 * view still must have an id assigned to it (via {@link #setId setId()})
3988 * for its state to be saved. This flag can only disable the
3989 * saving of this view; any child views may still have their state saved.
3990 *
3991 * @param enabled Set to false to <em>disable</em> state saving, or true
3992 * (the default) to allow it.
3993 *
3994 * @see #isSaveEnabled()
3995 * @see #setId(int)
3996 * @see #onSaveInstanceState()
3997 * @attr ref android.R.styleable#View_saveEnabled
3998 */
3999 public void setSaveEnabled(boolean enabled) {
4000 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
4001 }
4002
Jeff Brown85a31762010-09-01 17:01:00 -07004003 /**
4004 * Gets whether the framework should discard touches when the view's
4005 * window is obscured by another visible window.
4006 * Refer to the {@link View} security documentation for more details.
4007 *
4008 * @return True if touch filtering is enabled.
4009 *
4010 * @see #setFilterTouchesWhenObscured(boolean)
4011 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4012 */
4013 @ViewDebug.ExportedProperty
4014 public boolean getFilterTouchesWhenObscured() {
4015 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
4016 }
4017
4018 /**
4019 * Sets whether the framework should discard touches when the view's
4020 * window is obscured by another visible window.
4021 * Refer to the {@link View} security documentation for more details.
4022 *
4023 * @param enabled True if touch filtering should be enabled.
4024 *
4025 * @see #getFilterTouchesWhenObscured
4026 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4027 */
4028 public void setFilterTouchesWhenObscured(boolean enabled) {
4029 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
4030 FILTER_TOUCHES_WHEN_OBSCURED);
4031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032
4033 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004034 * Indicates whether the entire hierarchy under this view will save its
4035 * state when a state saving traversal occurs from its parent. The default
4036 * is true; if false, these views will not be saved unless
4037 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4038 *
4039 * @return Returns true if the view state saving from parent is enabled, else false.
4040 *
4041 * @see #setSaveFromParentEnabled(boolean)
4042 */
4043 public boolean isSaveFromParentEnabled() {
4044 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4045 }
4046
4047 /**
4048 * Controls whether the entire hierarchy under this view will save its
4049 * state when a state saving traversal occurs from its parent. The default
4050 * is true; if false, these views will not be saved unless
4051 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4052 *
4053 * @param enabled Set to false to <em>disable</em> state saving, or true
4054 * (the default) to allow it.
4055 *
4056 * @see #isSaveFromParentEnabled()
4057 * @see #setId(int)
4058 * @see #onSaveInstanceState()
4059 */
4060 public void setSaveFromParentEnabled(boolean enabled) {
4061 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4062 }
4063
4064
4065 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 * Returns whether this View is able to take focus.
4067 *
4068 * @return True if this view can take focus, or false otherwise.
4069 * @attr ref android.R.styleable#View_focusable
4070 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004071 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 public final boolean isFocusable() {
4073 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4074 }
4075
4076 /**
4077 * When a view is focusable, it may not want to take focus when in touch mode.
4078 * For example, a button would like focus when the user is navigating via a D-pad
4079 * so that the user can click on it, but once the user starts touching the screen,
4080 * the button shouldn't take focus
4081 * @return Whether the view is focusable in touch mode.
4082 * @attr ref android.R.styleable#View_focusableInTouchMode
4083 */
4084 @ViewDebug.ExportedProperty
4085 public final boolean isFocusableInTouchMode() {
4086 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4087 }
4088
4089 /**
4090 * Find the nearest view in the specified direction that can take focus.
4091 * This does not actually give focus to that view.
4092 *
4093 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4094 *
4095 * @return The nearest focusable in the specified direction, or null if none
4096 * can be found.
4097 */
4098 public View focusSearch(int direction) {
4099 if (mParent != null) {
4100 return mParent.focusSearch(this, direction);
4101 } else {
4102 return null;
4103 }
4104 }
4105
4106 /**
4107 * This method is the last chance for the focused view and its ancestors to
4108 * respond to an arrow key. This is called when the focused view did not
4109 * consume the key internally, nor could the view system find a new view in
4110 * the requested direction to give focus to.
4111 *
4112 * @param focused The currently focused view.
4113 * @param direction The direction focus wants to move. One of FOCUS_UP,
4114 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4115 * @return True if the this view consumed this unhandled move.
4116 */
4117 public boolean dispatchUnhandledMove(View focused, int direction) {
4118 return false;
4119 }
4120
4121 /**
4122 * If a user manually specified the next view id for a particular direction,
Jeff Brown4e6319b2010-12-13 10:36:51 -08004123 * use the root to look up the view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 * @param root The root view of the hierarchy containing this view.
Jeff Brown4e6319b2010-12-13 10:36:51 -08004125 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4126 * or FOCUS_BACKWARD.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 * @return The user specified next view, or null if there is none.
4128 */
4129 View findUserSetNextFocus(View root, int direction) {
4130 switch (direction) {
4131 case FOCUS_LEFT:
4132 if (mNextFocusLeftId == View.NO_ID) return null;
4133 return findViewShouldExist(root, mNextFocusLeftId);
4134 case FOCUS_RIGHT:
4135 if (mNextFocusRightId == View.NO_ID) return null;
4136 return findViewShouldExist(root, mNextFocusRightId);
4137 case FOCUS_UP:
4138 if (mNextFocusUpId == View.NO_ID) return null;
4139 return findViewShouldExist(root, mNextFocusUpId);
4140 case FOCUS_DOWN:
4141 if (mNextFocusDownId == View.NO_ID) return null;
4142 return findViewShouldExist(root, mNextFocusDownId);
Jeff Brown4e6319b2010-12-13 10:36:51 -08004143 case FOCUS_FORWARD:
4144 if (mNextFocusForwardId == View.NO_ID) return null;
4145 return findViewShouldExist(root, mNextFocusForwardId);
4146 case FOCUS_BACKWARD: {
4147 final int id = mID;
4148 return root.findViewByPredicate(new Predicate<View>() {
4149 @Override
4150 public boolean apply(View t) {
4151 return t.mNextFocusForwardId == id;
4152 }
4153 });
4154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 }
4156 return null;
4157 }
4158
4159 private static View findViewShouldExist(View root, int childViewId) {
4160 View result = root.findViewById(childViewId);
4161 if (result == null) {
4162 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4163 + "by user for id " + childViewId);
4164 }
4165 return result;
4166 }
4167
4168 /**
4169 * Find and return all focusable views that are descendants of this view,
4170 * possibly including this view if it is focusable itself.
4171 *
4172 * @param direction The direction of the focus
4173 * @return A list of focusable views
4174 */
4175 public ArrayList<View> getFocusables(int direction) {
4176 ArrayList<View> result = new ArrayList<View>(24);
4177 addFocusables(result, direction);
4178 return result;
4179 }
4180
4181 /**
4182 * Add any focusable views that are descendants of this view (possibly
4183 * including this view if it is focusable itself) to views. If we are in touch mode,
4184 * only add views that are also focusable in touch mode.
4185 *
4186 * @param views Focusable views found so far
4187 * @param direction The direction of the focus
4188 */
4189 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07004190 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192
svetoslavganov75986cf2009-05-14 22:28:01 -07004193 /**
4194 * Adds any focusable views that are descendants of this view (possibly
4195 * including this view if it is focusable itself) to views. This method
4196 * adds all focusable views regardless if we are in touch mode or
4197 * only views focusable in touch mode if we are in touch mode depending on
4198 * the focusable mode paramater.
4199 *
4200 * @param views Focusable views found so far or null if all we are interested is
4201 * the number of focusables.
4202 * @param direction The direction of the focus.
4203 * @param focusableMode The type of focusables to be added.
4204 *
4205 * @see #FOCUSABLES_ALL
4206 * @see #FOCUSABLES_TOUCH_MODE
4207 */
4208 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4209 if (!isFocusable()) {
4210 return;
4211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212
svetoslavganov75986cf2009-05-14 22:28:01 -07004213 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4214 isInTouchMode() && !isFocusableInTouchMode()) {
4215 return;
4216 }
4217
4218 if (views != null) {
4219 views.add(this);
4220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 }
4222
4223 /**
4224 * Find and return all touchable views that are descendants of this view,
4225 * possibly including this view if it is touchable itself.
4226 *
4227 * @return A list of touchable views
4228 */
4229 public ArrayList<View> getTouchables() {
4230 ArrayList<View> result = new ArrayList<View>();
4231 addTouchables(result);
4232 return result;
4233 }
4234
4235 /**
4236 * Add any touchable views that are descendants of this view (possibly
4237 * including this view if it is touchable itself) to views.
4238 *
4239 * @param views Touchable views found so far
4240 */
4241 public void addTouchables(ArrayList<View> views) {
4242 final int viewFlags = mViewFlags;
4243
4244 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4245 && (viewFlags & ENABLED_MASK) == ENABLED) {
4246 views.add(this);
4247 }
4248 }
4249
4250 /**
4251 * Call this to try to give focus to a specific view or to one of its
4252 * descendants.
4253 *
4254 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4255 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4256 * while the device is in touch mode.
4257 *
4258 * See also {@link #focusSearch}, which is what you call to say that you
4259 * have focus, and you want your parent to look for the next one.
4260 *
4261 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4262 * {@link #FOCUS_DOWN} and <code>null</code>.
4263 *
4264 * @return Whether this view or one of its descendants actually took focus.
4265 */
4266 public final boolean requestFocus() {
4267 return requestFocus(View.FOCUS_DOWN);
4268 }
4269
4270
4271 /**
4272 * Call this to try to give focus to a specific view or to one of its
4273 * descendants and give it a hint about what direction focus is heading.
4274 *
4275 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4276 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4277 * while the device is in touch mode.
4278 *
4279 * See also {@link #focusSearch}, which is what you call to say that you
4280 * have focus, and you want your parent to look for the next one.
4281 *
4282 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4283 * <code>null</code> set for the previously focused rectangle.
4284 *
4285 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4286 * @return Whether this view or one of its descendants actually took focus.
4287 */
4288 public final boolean requestFocus(int direction) {
4289 return requestFocus(direction, null);
4290 }
4291
4292 /**
4293 * Call this to try to give focus to a specific view or to one of its descendants
4294 * and give it hints about the direction and a specific rectangle that the focus
4295 * is coming from. The rectangle can help give larger views a finer grained hint
4296 * about where focus is coming from, and therefore, where to show selection, or
4297 * forward focus change internally.
4298 *
4299 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4300 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4301 * while the device is in touch mode.
4302 *
4303 * A View will not take focus if it is not visible.
4304 *
4305 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4306 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4307 *
4308 * See also {@link #focusSearch}, which is what you call to say that you
4309 * have focus, and you want your parent to look for the next one.
4310 *
4311 * You may wish to override this method if your custom {@link View} has an internal
4312 * {@link View} that it wishes to forward the request to.
4313 *
4314 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4315 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4316 * to give a finer grained hint about where focus is coming from. May be null
4317 * if there is no hint.
4318 * @return Whether this view or one of its descendants actually took focus.
4319 */
4320 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4321 // need to be focusable
4322 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4323 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4324 return false;
4325 }
4326
4327 // need to be focusable in touch mode if in touch mode
4328 if (isInTouchMode() &&
4329 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4330 return false;
4331 }
4332
4333 // need to not have any parents blocking us
4334 if (hasAncestorThatBlocksDescendantFocus()) {
4335 return false;
4336 }
4337
4338 handleFocusGainInternal(direction, previouslyFocusedRect);
4339 return true;
4340 }
4341
Christopher Tate2c095f32010-10-04 14:13:40 -07004342 /** Gets the ViewRoot, or null if not attached. */
4343 /*package*/ ViewRoot getViewRoot() {
4344 View root = getRootView();
4345 return root != null ? (ViewRoot)root.getParent() : null;
4346 }
4347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004348 /**
4349 * Call this to try to give focus to a specific view or to one of its descendants. This is a
4350 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4351 * touch mode to request focus when they are touched.
4352 *
4353 * @return Whether this view or one of its descendants actually took focus.
4354 *
4355 * @see #isInTouchMode()
4356 *
4357 */
4358 public final boolean requestFocusFromTouch() {
4359 // Leave touch mode if we need to
4360 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07004361 ViewRoot viewRoot = getViewRoot();
4362 if (viewRoot != null) {
4363 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 }
4365 }
4366 return requestFocus(View.FOCUS_DOWN);
4367 }
4368
4369 /**
4370 * @return Whether any ancestor of this view blocks descendant focus.
4371 */
4372 private boolean hasAncestorThatBlocksDescendantFocus() {
4373 ViewParent ancestor = mParent;
4374 while (ancestor instanceof ViewGroup) {
4375 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4376 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4377 return true;
4378 } else {
4379 ancestor = vgAncestor.getParent();
4380 }
4381 }
4382 return false;
4383 }
4384
4385 /**
Romain Guya440b002010-02-24 15:57:54 -08004386 * @hide
4387 */
4388 public void dispatchStartTemporaryDetach() {
4389 onStartTemporaryDetach();
4390 }
4391
4392 /**
4393 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4395 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004396 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 */
4398 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004399 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004400 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004401 }
4402
4403 /**
4404 * @hide
4405 */
4406 public void dispatchFinishTemporaryDetach() {
4407 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004408 }
Romain Guy8506ab42009-06-11 17:35:47 -07004409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004410 /**
4411 * Called after {@link #onStartTemporaryDetach} when the container is done
4412 * changing the view.
4413 */
4414 public void onFinishTemporaryDetach() {
4415 }
Romain Guy8506ab42009-06-11 17:35:47 -07004416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004417 /**
4418 * capture information of this view for later analysis: developement only
4419 * check dynamic switch to make sure we only dump view
4420 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4421 */
4422 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004423 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004424 return;
4425 }
4426 ViewDebug.dumpCapturedView(subTag, v);
4427 }
4428
4429 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004430 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4431 * for this view's window. Returns null if the view is not currently attached
4432 * to the window. Normally you will not need to use this directly, but
4433 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4434 */
4435 public KeyEvent.DispatcherState getKeyDispatcherState() {
4436 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4437 }
4438
4439 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440 * Dispatch a key event before it is processed by any input method
4441 * associated with the view hierarchy. This can be used to intercept
4442 * key events in special situations before the IME consumes them; a
4443 * typical example would be handling the BACK key to update the application's
4444 * UI instead of allowing the IME to see it and close itself.
4445 *
4446 * @param event The key event to be dispatched.
4447 * @return True if the event was handled, false otherwise.
4448 */
4449 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4450 return onKeyPreIme(event.getKeyCode(), event);
4451 }
4452
4453 /**
4454 * Dispatch a key event to the next view on the focus path. This path runs
4455 * from the top of the view tree down to the currently focused view. If this
4456 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4457 * the next node down the focus path. This method also fires any key
4458 * listeners.
4459 *
4460 * @param event The key event to be dispatched.
4461 * @return True if the event was handled, false otherwise.
4462 */
4463 public boolean dispatchKeyEvent(KeyEvent event) {
4464 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004465
Romain Guyf607bdc2010-09-10 19:20:06 -07004466 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004467 if (android.util.Config.LOGV) {
4468 captureViewInfo("captureViewKeyEvent", this);
4469 }
4470
Romain Guyf607bdc2010-09-10 19:20:06 -07004471 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004472 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4473 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4474 return true;
4475 }
4476
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004477 return event.dispatch(this, mAttachInfo != null
4478 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004479 }
4480
4481 /**
4482 * Dispatches a key shortcut event.
4483 *
4484 * @param event The key event to be dispatched.
4485 * @return True if the event was handled by the view, false otherwise.
4486 */
4487 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4488 return onKeyShortcut(event.getKeyCode(), event);
4489 }
4490
4491 /**
4492 * Pass the touch screen motion event down to the target view, or this
4493 * view if it is the target.
4494 *
4495 * @param event The motion event to be dispatched.
4496 * @return True if the event was handled by the view, false otherwise.
4497 */
4498 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004499 if (!onFilterTouchEventForSecurity(event)) {
4500 return false;
4501 }
4502
Romain Guyf607bdc2010-09-10 19:20:06 -07004503 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4505 mOnTouchListener.onTouch(this, event)) {
4506 return true;
4507 }
4508 return onTouchEvent(event);
4509 }
4510
4511 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004512 * Filter the touch event to apply security policies.
4513 *
4514 * @param event The motion event to be filtered.
4515 * @return True if the event should be dispatched, false if the event should be dropped.
4516 *
4517 * @see #getFilterTouchesWhenObscured
4518 */
4519 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004520 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004521 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4522 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4523 // Window is obscured, drop this touch.
4524 return false;
4525 }
4526 return true;
4527 }
4528
4529 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 * Pass a trackball motion event down to the focused view.
4531 *
4532 * @param event The motion event to be dispatched.
4533 * @return True if the event was handled by the view, false otherwise.
4534 */
4535 public boolean dispatchTrackballEvent(MotionEvent event) {
4536 //Log.i("view", "view=" + this + ", " + event.toString());
4537 return onTrackballEvent(event);
4538 }
4539
4540 /**
4541 * Called when the window containing this view gains or loses window focus.
4542 * ViewGroups should override to route to their children.
4543 *
4544 * @param hasFocus True if the window containing this view now has focus,
4545 * false otherwise.
4546 */
4547 public void dispatchWindowFocusChanged(boolean hasFocus) {
4548 onWindowFocusChanged(hasFocus);
4549 }
4550
4551 /**
4552 * Called when the window containing this view gains or loses focus. Note
4553 * that this is separate from view focus: to receive key events, both
4554 * your view and its window must have focus. If a window is displayed
4555 * on top of yours that takes input focus, then your own window will lose
4556 * focus but the view focus will remain unchanged.
4557 *
4558 * @param hasWindowFocus True if the window containing this view now has
4559 * focus, false otherwise.
4560 */
4561 public void onWindowFocusChanged(boolean hasWindowFocus) {
4562 InputMethodManager imm = InputMethodManager.peekInstance();
4563 if (!hasWindowFocus) {
4564 if (isPressed()) {
4565 setPressed(false);
4566 }
4567 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4568 imm.focusOut(this);
4569 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004570 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004571 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004572 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004573 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4574 imm.focusIn(this);
4575 }
4576 refreshDrawableState();
4577 }
4578
4579 /**
4580 * Returns true if this view is in a window that currently has window focus.
4581 * Note that this is not the same as the view itself having focus.
4582 *
4583 * @return True if this view is in a window that currently has window focus.
4584 */
4585 public boolean hasWindowFocus() {
4586 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4587 }
4588
4589 /**
Adam Powell326d8082009-12-09 15:10:07 -08004590 * Dispatch a view visibility change down the view hierarchy.
4591 * ViewGroups should override to route to their children.
4592 * @param changedView The view whose visibility changed. Could be 'this' or
4593 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004594 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4595 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004596 */
4597 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4598 onVisibilityChanged(changedView, visibility);
4599 }
4600
4601 /**
4602 * Called when the visibility of the view or an ancestor of the view is changed.
4603 * @param changedView The view whose visibility changed. Could be 'this' or
4604 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004605 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4606 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004607 */
4608 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004609 if (visibility == VISIBLE) {
4610 if (mAttachInfo != null) {
4611 initialAwakenScrollBars();
4612 } else {
4613 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4614 }
4615 }
Adam Powell326d8082009-12-09 15:10:07 -08004616 }
4617
4618 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004619 * Dispatch a hint about whether this view is displayed. For instance, when
4620 * a View moves out of the screen, it might receives a display hint indicating
4621 * the view is not displayed. Applications should not <em>rely</em> on this hint
4622 * as there is no guarantee that they will receive one.
4623 *
4624 * @param hint A hint about whether or not this view is displayed:
4625 * {@link #VISIBLE} or {@link #INVISIBLE}.
4626 */
4627 public void dispatchDisplayHint(int hint) {
4628 onDisplayHint(hint);
4629 }
4630
4631 /**
4632 * Gives this view a hint about whether is displayed or not. For instance, when
4633 * a View moves out of the screen, it might receives a display hint indicating
4634 * the view is not displayed. Applications should not <em>rely</em> on this hint
4635 * as there is no guarantee that they will receive one.
4636 *
4637 * @param hint A hint about whether or not this view is displayed:
4638 * {@link #VISIBLE} or {@link #INVISIBLE}.
4639 */
4640 protected void onDisplayHint(int hint) {
4641 }
4642
4643 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 * Dispatch a window visibility change down the view hierarchy.
4645 * ViewGroups should override to route to their children.
4646 *
4647 * @param visibility The new visibility of the window.
4648 *
4649 * @see #onWindowVisibilityChanged
4650 */
4651 public void dispatchWindowVisibilityChanged(int visibility) {
4652 onWindowVisibilityChanged(visibility);
4653 }
4654
4655 /**
4656 * Called when the window containing has change its visibility
4657 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4658 * that this tells you whether or not your window is being made visible
4659 * to the window manager; this does <em>not</em> tell you whether or not
4660 * your window is obscured by other windows on the screen, even if it
4661 * is itself visible.
4662 *
4663 * @param visibility The new visibility of the window.
4664 */
4665 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004666 if (visibility == VISIBLE) {
4667 initialAwakenScrollBars();
4668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004669 }
4670
4671 /**
4672 * Returns the current visibility of the window this view is attached to
4673 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4674 *
4675 * @return Returns the current visibility of the view's window.
4676 */
4677 public int getWindowVisibility() {
4678 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4679 }
4680
4681 /**
4682 * Retrieve the overall visible display size in which the window this view is
4683 * attached to has been positioned in. This takes into account screen
4684 * decorations above the window, for both cases where the window itself
4685 * is being position inside of them or the window is being placed under
4686 * then and covered insets are used for the window to position its content
4687 * inside. In effect, this tells you the available area where content can
4688 * be placed and remain visible to users.
4689 *
4690 * <p>This function requires an IPC back to the window manager to retrieve
4691 * the requested information, so should not be used in performance critical
4692 * code like drawing.
4693 *
4694 * @param outRect Filled in with the visible display frame. If the view
4695 * is not attached to a window, this is simply the raw display size.
4696 */
4697 public void getWindowVisibleDisplayFrame(Rect outRect) {
4698 if (mAttachInfo != null) {
4699 try {
4700 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4701 } catch (RemoteException e) {
4702 return;
4703 }
4704 // XXX This is really broken, and probably all needs to be done
4705 // in the window manager, and we need to know more about whether
4706 // we want the area behind or in front of the IME.
4707 final Rect insets = mAttachInfo.mVisibleInsets;
4708 outRect.left += insets.left;
4709 outRect.top += insets.top;
4710 outRect.right -= insets.right;
4711 outRect.bottom -= insets.bottom;
4712 return;
4713 }
4714 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4715 outRect.set(0, 0, d.getWidth(), d.getHeight());
4716 }
4717
4718 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004719 * Dispatch a notification about a resource configuration change down
4720 * the view hierarchy.
4721 * ViewGroups should override to route to their children.
4722 *
4723 * @param newConfig The new resource configuration.
4724 *
4725 * @see #onConfigurationChanged
4726 */
4727 public void dispatchConfigurationChanged(Configuration newConfig) {
4728 onConfigurationChanged(newConfig);
4729 }
4730
4731 /**
4732 * Called when the current configuration of the resources being used
4733 * by the application have changed. You can use this to decide when
4734 * to reload resources that can changed based on orientation and other
4735 * configuration characterstics. You only need to use this if you are
4736 * not relying on the normal {@link android.app.Activity} mechanism of
4737 * recreating the activity instance upon a configuration change.
4738 *
4739 * @param newConfig The new resource configuration.
4740 */
4741 protected void onConfigurationChanged(Configuration newConfig) {
4742 }
4743
4744 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 * Private function to aggregate all per-view attributes in to the view
4746 * root.
4747 */
4748 void dispatchCollectViewAttributes(int visibility) {
4749 performCollectViewAttributes(visibility);
4750 }
4751
4752 void performCollectViewAttributes(int visibility) {
Joe Onorato664644d2011-01-23 17:53:23 -08004753 if ((visibility & VISIBILITY_MASK) == VISIBLE) {
4754 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
4755 mAttachInfo.mKeepScreenOn = true;
4756 }
4757 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
4758 if (mOnSystemUiVisibilityChangeListener != null) {
4759 mAttachInfo.mHasSystemUiListeners = true;
4760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004761 }
4762 }
4763
4764 void needGlobalAttributesUpdate(boolean force) {
Joe Onorato664644d2011-01-23 17:53:23 -08004765 final AttachInfo ai = mAttachInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766 if (ai != null) {
Joe Onorato664644d2011-01-23 17:53:23 -08004767 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
4768 || ai.mHasSystemUiListeners) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 ai.mRecomputeGlobalAttributes = true;
4770 }
4771 }
4772 }
4773
4774 /**
4775 * Returns whether the device is currently in touch mode. Touch mode is entered
4776 * once the user begins interacting with the device by touch, and affects various
4777 * things like whether focus is always visible to the user.
4778 *
4779 * @return Whether the device is in touch mode.
4780 */
4781 @ViewDebug.ExportedProperty
4782 public boolean isInTouchMode() {
4783 if (mAttachInfo != null) {
4784 return mAttachInfo.mInTouchMode;
4785 } else {
4786 return ViewRoot.isInTouchMode();
4787 }
4788 }
4789
4790 /**
4791 * Returns the context the view is running in, through which it can
4792 * access the current theme, resources, etc.
4793 *
4794 * @return The view's Context.
4795 */
4796 @ViewDebug.CapturedViewProperty
4797 public final Context getContext() {
4798 return mContext;
4799 }
4800
4801 /**
4802 * Handle a key event before it is processed by any input method
4803 * associated with the view hierarchy. This can be used to intercept
4804 * key events in special situations before the IME consumes them; a
4805 * typical example would be handling the BACK key to update the application's
4806 * UI instead of allowing the IME to see it and close itself.
4807 *
4808 * @param keyCode The value in event.getKeyCode().
4809 * @param event Description of the key event.
4810 * @return If you handled the event, return true. If you want to allow the
4811 * event to be handled by the next receiver, return false.
4812 */
4813 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4814 return false;
4815 }
4816
4817 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004818 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
4819 * KeyEvent.Callback.onKeyDown()}: perform press of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004820 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4821 * is released, if the view is enabled and clickable.
4822 *
4823 * @param keyCode A key code that represents the button pressed, from
4824 * {@link android.view.KeyEvent}.
4825 * @param event The KeyEvent object that defines the button action.
4826 */
4827 public boolean onKeyDown(int keyCode, KeyEvent event) {
4828 boolean result = false;
4829
4830 switch (keyCode) {
4831 case KeyEvent.KEYCODE_DPAD_CENTER:
4832 case KeyEvent.KEYCODE_ENTER: {
4833 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4834 return true;
4835 }
4836 // Long clickable items don't necessarily have to be clickable
4837 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4838 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4839 (event.getRepeatCount() == 0)) {
4840 setPressed(true);
4841 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004842 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004843 }
4844 return true;
4845 }
4846 break;
4847 }
4848 }
4849 return result;
4850 }
4851
4852 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004853 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4854 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4855 * the event).
4856 */
4857 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4858 return false;
4859 }
4860
4861 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004862 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
4863 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004864 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4865 * {@link KeyEvent#KEYCODE_ENTER} is released.
4866 *
4867 * @param keyCode A key code that represents the button pressed, from
4868 * {@link android.view.KeyEvent}.
4869 * @param event The KeyEvent object that defines the button action.
4870 */
4871 public boolean onKeyUp(int keyCode, KeyEvent event) {
4872 boolean result = false;
4873
4874 switch (keyCode) {
4875 case KeyEvent.KEYCODE_DPAD_CENTER:
4876 case KeyEvent.KEYCODE_ENTER: {
4877 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4878 return true;
4879 }
4880 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4881 setPressed(false);
4882
4883 if (!mHasPerformedLongPress) {
4884 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004885 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004886
4887 result = performClick();
4888 }
4889 }
4890 break;
4891 }
4892 }
4893 return result;
4894 }
4895
4896 /**
4897 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4898 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4899 * the event).
4900 *
4901 * @param keyCode A key code that represents the button pressed, from
4902 * {@link android.view.KeyEvent}.
4903 * @param repeatCount The number of times the action was made.
4904 * @param event The KeyEvent object that defines the button action.
4905 */
4906 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4907 return false;
4908 }
4909
4910 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08004911 * Called on the focused view when a key shortcut event is not handled.
4912 * Override this method to implement local key shortcuts for the View.
4913 * Key shortcuts can also be implemented by setting the
4914 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004915 *
4916 * @param keyCode The value in event.getKeyCode().
4917 * @param event Description of the key event.
4918 * @return If you handled the event, return true. If you want to allow the
4919 * event to be handled by the next receiver, return false.
4920 */
4921 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4922 return false;
4923 }
4924
4925 /**
4926 * Check whether the called view is a text editor, in which case it
4927 * would make sense to automatically display a soft input window for
4928 * it. Subclasses should override this if they implement
4929 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004930 * a call on that method would return a non-null InputConnection, and
4931 * they are really a first-class editor that the user would normally
4932 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004933 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004934 * <p>The default implementation always returns false. This does
4935 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4936 * will not be called or the user can not otherwise perform edits on your
4937 * view; it is just a hint to the system that this is not the primary
4938 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004939 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004940 * @return Returns true if this view is a text editor, else false.
4941 */
4942 public boolean onCheckIsTextEditor() {
4943 return false;
4944 }
Romain Guy8506ab42009-06-11 17:35:47 -07004945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004946 /**
4947 * Create a new InputConnection for an InputMethod to interact
4948 * with the view. The default implementation returns null, since it doesn't
4949 * support input methods. You can override this to implement such support.
4950 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004951 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004952 * <p>When implementing this, you probably also want to implement
4953 * {@link #onCheckIsTextEditor()} to indicate you will return a
4954 * non-null InputConnection.
4955 *
4956 * @param outAttrs Fill in with attribute information about the connection.
4957 */
4958 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4959 return null;
4960 }
4961
4962 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004963 * Called by the {@link android.view.inputmethod.InputMethodManager}
4964 * when a view who is not the current
4965 * input connection target is trying to make a call on the manager. The
4966 * default implementation returns false; you can override this to return
4967 * true for certain views if you are performing InputConnection proxying
4968 * to them.
4969 * @param view The View that is making the InputMethodManager call.
4970 * @return Return true to allow the call, false to reject.
4971 */
4972 public boolean checkInputConnectionProxy(View view) {
4973 return false;
4974 }
Romain Guy8506ab42009-06-11 17:35:47 -07004975
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004976 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 * Show the context menu for this view. It is not safe to hold on to the
4978 * menu after returning from this method.
4979 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004980 * You should normally not overload this method. Overload
4981 * {@link #onCreateContextMenu(ContextMenu)} or define an
4982 * {@link OnCreateContextMenuListener} to add items to the context menu.
4983 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984 * @param menu The context menu to populate
4985 */
4986 public void createContextMenu(ContextMenu menu) {
4987 ContextMenuInfo menuInfo = getContextMenuInfo();
4988
4989 // Sets the current menu info so all items added to menu will have
4990 // my extra info set.
4991 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4992
4993 onCreateContextMenu(menu);
4994 if (mOnCreateContextMenuListener != null) {
4995 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4996 }
4997
4998 // Clear the extra information so subsequent items that aren't mine don't
4999 // have my extra info.
5000 ((MenuBuilder)menu).setCurrentMenuInfo(null);
5001
5002 if (mParent != null) {
5003 mParent.createContextMenu(menu);
5004 }
5005 }
5006
5007 /**
5008 * Views should implement this if they have extra information to associate
5009 * with the context menu. The return result is supplied as a parameter to
5010 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
5011 * callback.
5012 *
5013 * @return Extra information about the item for which the context menu
5014 * should be shown. This information will vary across different
5015 * subclasses of View.
5016 */
5017 protected ContextMenuInfo getContextMenuInfo() {
5018 return null;
5019 }
5020
5021 /**
5022 * Views should implement this if the view itself is going to add items to
5023 * the context menu.
5024 *
5025 * @param menu the context menu to populate
5026 */
5027 protected void onCreateContextMenu(ContextMenu menu) {
5028 }
5029
5030 /**
5031 * Implement this method to handle trackball motion events. The
5032 * <em>relative</em> movement of the trackball since the last event
5033 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
5034 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
5035 * that a movement of 1 corresponds to the user pressing one DPAD key (so
5036 * they will often be fractional values, representing the more fine-grained
5037 * movement information available from a trackball).
5038 *
5039 * @param event The motion event.
5040 * @return True if the event was handled, false otherwise.
5041 */
5042 public boolean onTrackballEvent(MotionEvent event) {
5043 return false;
5044 }
5045
5046 /**
5047 * Implement this method to handle touch screen motion events.
5048 *
5049 * @param event The motion event.
5050 * @return True if the event was handled, false otherwise.
5051 */
5052 public boolean onTouchEvent(MotionEvent event) {
5053 final int viewFlags = mViewFlags;
5054
5055 if ((viewFlags & ENABLED_MASK) == DISABLED) {
5056 // A disabled view that is clickable still consumes the touch
5057 // events, it just doesn't respond to them.
5058 return (((viewFlags & CLICKABLE) == CLICKABLE ||
5059 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
5060 }
5061
5062 if (mTouchDelegate != null) {
5063 if (mTouchDelegate.onTouchEvent(event)) {
5064 return true;
5065 }
5066 }
5067
5068 if (((viewFlags & CLICKABLE) == CLICKABLE ||
5069 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
5070 switch (event.getAction()) {
5071 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08005072 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
5073 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 // take focus if we don't have it already and we should in
5075 // touch mode.
5076 boolean focusTaken = false;
5077 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
5078 focusTaken = requestFocus();
5079 }
5080
Dianne Hackbornbe1f6222011-01-20 15:24:28 -08005081 if (prepressed) {
5082 // The button is being released before we actually
5083 // showed it as pressed. Make it show the pressed
5084 // state now (before scheduling the click) to ensure
5085 // the user sees it.
5086 mPrivateFlags |= PRESSED;
5087 refreshDrawableState();
5088 }
5089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005090 if (!mHasPerformedLongPress) {
5091 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05005092 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093
5094 // Only perform take click actions if we were in the pressed state
5095 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08005096 // Use a Runnable and post this rather than calling
5097 // performClick directly. This lets other visual state
5098 // of the view update before click actions start.
5099 if (mPerformClick == null) {
5100 mPerformClick = new PerformClick();
5101 }
5102 if (!post(mPerformClick)) {
5103 performClick();
5104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005105 }
5106 }
5107
5108 if (mUnsetPressedState == null) {
5109 mUnsetPressedState = new UnsetPressedState();
5110 }
5111
Adam Powelle14579b2009-12-16 18:39:52 -08005112 if (prepressed) {
Adam Powelle14579b2009-12-16 18:39:52 -08005113 postDelayed(mUnsetPressedState,
5114 ViewConfiguration.getPressedStateDuration());
5115 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 // If the post failed, unpress right now
5117 mUnsetPressedState.run();
5118 }
Adam Powelle14579b2009-12-16 18:39:52 -08005119 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005120 }
5121 break;
5122
5123 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08005124 if (mPendingCheckForTap == null) {
5125 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005126 }
Adam Powelle14579b2009-12-16 18:39:52 -08005127 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08005128 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08005129 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 break;
5131
5132 case MotionEvent.ACTION_CANCEL:
5133 mPrivateFlags &= ~PRESSED;
5134 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08005135 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 break;
5137
5138 case MotionEvent.ACTION_MOVE:
5139 final int x = (int) event.getX();
5140 final int y = (int) event.getY();
5141
5142 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07005143 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08005145 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005146 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08005147 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05005148 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005149
5150 // Need to switch from pressed to not pressed
5151 mPrivateFlags &= ~PRESSED;
5152 refreshDrawableState();
5153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005154 }
5155 break;
5156 }
5157 return true;
5158 }
5159
5160 return false;
5161 }
5162
5163 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05005164 * Remove the longpress detection timer.
5165 */
5166 private void removeLongPressCallback() {
5167 if (mPendingCheckForLongPress != null) {
5168 removeCallbacks(mPendingCheckForLongPress);
5169 }
5170 }
Adam Powell3cb8b632011-01-21 15:34:14 -08005171
5172 /**
5173 * Remove the pending click action
5174 */
5175 private void removePerformClickCallback() {
5176 if (mPerformClick != null) {
5177 removeCallbacks(mPerformClick);
5178 }
5179 }
5180
Adam Powelle14579b2009-12-16 18:39:52 -08005181 /**
Romain Guya440b002010-02-24 15:57:54 -08005182 * Remove the prepress detection timer.
5183 */
5184 private void removeUnsetPressCallback() {
5185 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
5186 setPressed(false);
5187 removeCallbacks(mUnsetPressedState);
5188 }
5189 }
5190
5191 /**
Adam Powelle14579b2009-12-16 18:39:52 -08005192 * Remove the tap detection timer.
5193 */
5194 private void removeTapCallback() {
5195 if (mPendingCheckForTap != null) {
5196 mPrivateFlags &= ~PREPRESSED;
5197 removeCallbacks(mPendingCheckForTap);
5198 }
5199 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05005200
5201 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005202 * Cancels a pending long press. Your subclass can use this if you
5203 * want the context menu to come up if the user presses and holds
5204 * at the same place, but you don't want it to come up if they press
5205 * and then move around enough to cause scrolling.
5206 */
5207 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05005208 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08005209
5210 /*
5211 * The prepressed state handled by the tap callback is a display
5212 * construct, but the tap callback will post a long press callback
5213 * less its own timeout. Remove it here.
5214 */
5215 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005216 }
5217
5218 /**
5219 * Sets the TouchDelegate for this View.
5220 */
5221 public void setTouchDelegate(TouchDelegate delegate) {
5222 mTouchDelegate = delegate;
5223 }
5224
5225 /**
5226 * Gets the TouchDelegate for this View.
5227 */
5228 public TouchDelegate getTouchDelegate() {
5229 return mTouchDelegate;
5230 }
5231
5232 /**
5233 * Set flags controlling behavior of this view.
5234 *
5235 * @param flags Constant indicating the value which should be set
5236 * @param mask Constant indicating the bit range that should be changed
5237 */
5238 void setFlags(int flags, int mask) {
5239 int old = mViewFlags;
5240 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
5241
5242 int changed = mViewFlags ^ old;
5243 if (changed == 0) {
5244 return;
5245 }
5246 int privateFlags = mPrivateFlags;
5247
5248 /* Check if the FOCUSABLE bit has changed */
5249 if (((changed & FOCUSABLE_MASK) != 0) &&
5250 ((privateFlags & HAS_BOUNDS) !=0)) {
5251 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
5252 && ((privateFlags & FOCUSED) != 0)) {
5253 /* Give up focus if we are no longer focusable */
5254 clearFocus();
5255 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
5256 && ((privateFlags & FOCUSED) == 0)) {
5257 /*
5258 * Tell the view system that we are now available to take focus
5259 * if no one else already has it.
5260 */
5261 if (mParent != null) mParent.focusableViewAvailable(this);
5262 }
5263 }
5264
5265 if ((flags & VISIBILITY_MASK) == VISIBLE) {
5266 if ((changed & VISIBILITY_MASK) != 0) {
5267 /*
5268 * If this view is becoming visible, set the DRAWN flag so that
5269 * the next invalidate() will not be skipped.
5270 */
5271 mPrivateFlags |= DRAWN;
5272
5273 needGlobalAttributesUpdate(true);
5274
5275 // a view becoming visible is worth notifying the parent
5276 // about in case nothing has focus. even if this specific view
5277 // isn't focusable, it may contain something that is, so let
5278 // the root view try to give this focus if nothing else does.
5279 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
5280 mParent.focusableViewAvailable(this);
5281 }
5282 }
5283 }
5284
5285 /* Check if the GONE bit has changed */
5286 if ((changed & GONE) != 0) {
5287 needGlobalAttributesUpdate(false);
5288 requestLayout();
5289 invalidate();
5290
Romain Guyecd80ee2009-12-03 17:13:02 -08005291 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5292 if (hasFocus()) clearFocus();
5293 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 }
5295 if (mAttachInfo != null) {
5296 mAttachInfo.mViewVisibilityChanged = true;
5297 }
5298 }
5299
5300 /* Check if the VISIBLE bit has changed */
5301 if ((changed & INVISIBLE) != 0) {
5302 needGlobalAttributesUpdate(false);
5303 invalidate();
5304
5305 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5306 // root view becoming invisible shouldn't clear focus
5307 if (getRootView() != this) {
5308 clearFocus();
5309 }
5310 }
5311 if (mAttachInfo != null) {
5312 mAttachInfo.mViewVisibilityChanged = true;
5313 }
5314 }
5315
Adam Powell326d8082009-12-09 15:10:07 -08005316 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07005317 if (mParent instanceof ViewGroup) {
5318 ((ViewGroup)mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
Chet Haasedaf98e92011-01-10 14:10:36 -08005319 ((View) mParent).invalidate();
Chet Haase5e25c2c2010-09-16 11:15:56 -07005320 }
Adam Powell326d8082009-12-09 15:10:07 -08005321 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5322 }
5323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005324 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5325 destroyDrawingCache();
5326 }
5327
5328 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5329 destroyDrawingCache();
5330 mPrivateFlags &= ~DRAWING_CACHE_VALID;
Chet Haasedaf98e92011-01-10 14:10:36 -08005331 invalidateParentIfAccelerated();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 }
5333
5334 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5335 destroyDrawingCache();
5336 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5337 }
5338
5339 if ((changed & DRAW_MASK) != 0) {
5340 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5341 if (mBGDrawable != null) {
5342 mPrivateFlags &= ~SKIP_DRAW;
5343 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5344 } else {
5345 mPrivateFlags |= SKIP_DRAW;
5346 }
5347 } else {
5348 mPrivateFlags &= ~SKIP_DRAW;
5349 }
5350 requestLayout();
5351 invalidate();
5352 }
5353
5354 if ((changed & KEEP_SCREEN_ON) != 0) {
Joe Onorato664644d2011-01-23 17:53:23 -08005355 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005356 mParent.recomputeViewAttributes(this);
5357 }
5358 }
5359 }
5360
5361 /**
5362 * Change the view's z order in the tree, so it's on top of other sibling
5363 * views
5364 */
5365 public void bringToFront() {
5366 if (mParent != null) {
5367 mParent.bringChildToFront(this);
5368 }
5369 }
5370
5371 /**
5372 * This is called in response to an internal scroll in this view (i.e., the
5373 * view scrolled its own contents). This is typically as a result of
5374 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5375 * called.
5376 *
5377 * @param l Current horizontal scroll origin.
5378 * @param t Current vertical scroll origin.
5379 * @param oldl Previous horizontal scroll origin.
5380 * @param oldt Previous vertical scroll origin.
5381 */
5382 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5383 mBackgroundSizeChanged = true;
5384
5385 final AttachInfo ai = mAttachInfo;
5386 if (ai != null) {
5387 ai.mViewScrollChanged = true;
5388 }
5389 }
5390
5391 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005392 * Interface definition for a callback to be invoked when the layout bounds of a view
5393 * changes due to layout processing.
5394 */
5395 public interface OnLayoutChangeListener {
5396 /**
5397 * Called when the focus state of a view has changed.
5398 *
5399 * @param v The view whose state has changed.
5400 * @param left The new value of the view's left property.
5401 * @param top The new value of the view's top property.
5402 * @param right The new value of the view's right property.
5403 * @param bottom The new value of the view's bottom property.
5404 * @param oldLeft The previous value of the view's left property.
5405 * @param oldTop The previous value of the view's top property.
5406 * @param oldRight The previous value of the view's right property.
5407 * @param oldBottom The previous value of the view's bottom property.
5408 */
5409 void onLayoutChange(View v, int left, int top, int right, int bottom,
5410 int oldLeft, int oldTop, int oldRight, int oldBottom);
5411 }
5412
5413 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005414 * This is called during layout when the size of this view has changed. If
5415 * you were just added to the view hierarchy, you're called with the old
5416 * values of 0.
5417 *
5418 * @param w Current width of this view.
5419 * @param h Current height of this view.
5420 * @param oldw Old width of this view.
5421 * @param oldh Old height of this view.
5422 */
5423 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5424 }
5425
5426 /**
5427 * Called by draw to draw the child views. This may be overridden
5428 * by derived classes to gain control just before its children are drawn
5429 * (but after its own view has been drawn).
5430 * @param canvas the canvas on which to draw the view
5431 */
5432 protected void dispatchDraw(Canvas canvas) {
5433 }
5434
5435 /**
5436 * Gets the parent of this view. Note that the parent is a
5437 * ViewParent and not necessarily a View.
5438 *
5439 * @return Parent of this view.
5440 */
5441 public final ViewParent getParent() {
5442 return mParent;
5443 }
5444
5445 /**
5446 * Return the scrolled left position of this view. This is the left edge of
5447 * the displayed part of your view. You do not need to draw any pixels
5448 * farther left, since those are outside of the frame of your view on
5449 * screen.
5450 *
5451 * @return The left edge of the displayed part of your view, in pixels.
5452 */
5453 public final int getScrollX() {
5454 return mScrollX;
5455 }
5456
5457 /**
5458 * Return the scrolled top position of this view. This is the top edge of
5459 * the displayed part of your view. You do not need to draw any pixels above
5460 * it, since those are outside of the frame of your view on screen.
5461 *
5462 * @return The top edge of the displayed part of your view, in pixels.
5463 */
5464 public final int getScrollY() {
5465 return mScrollY;
5466 }
5467
5468 /**
5469 * Return the width of the your view.
5470 *
5471 * @return The width of your view, in pixels.
5472 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005473 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 public final int getWidth() {
5475 return mRight - mLeft;
5476 }
5477
5478 /**
5479 * Return the height of your view.
5480 *
5481 * @return The height of your view, in pixels.
5482 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005483 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 public final int getHeight() {
5485 return mBottom - mTop;
5486 }
5487
5488 /**
5489 * Return the visible drawing bounds of your view. Fills in the output
5490 * rectangle with the values from getScrollX(), getScrollY(),
5491 * getWidth(), and getHeight().
5492 *
5493 * @param outRect The (scrolled) drawing bounds of the view.
5494 */
5495 public void getDrawingRect(Rect outRect) {
5496 outRect.left = mScrollX;
5497 outRect.top = mScrollY;
5498 outRect.right = mScrollX + (mRight - mLeft);
5499 outRect.bottom = mScrollY + (mBottom - mTop);
5500 }
5501
5502 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005503 * Like {@link #getMeasuredWidthAndState()}, but only returns the
5504 * raw width component (that is the result is masked by
5505 * {@link #MEASURED_SIZE_MASK}).
5506 *
5507 * @return The raw measured width of this view.
5508 */
5509 public final int getMeasuredWidth() {
5510 return mMeasuredWidth & MEASURED_SIZE_MASK;
5511 }
5512
5513 /**
5514 * Return the full width measurement information for this view as computed
5515 * by the most recent call to {@link #measure}. This result is a bit mask
5516 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 * This should be used during measurement and layout calculations only. Use
5518 * {@link #getWidth()} to see how wide a view is after layout.
5519 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005520 * @return The measured width of this view as a bit mask.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08005522 public final int getMeasuredWidthAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 return mMeasuredWidth;
5524 }
5525
5526 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005527 * Like {@link #getMeasuredHeightAndState()}, but only returns the
5528 * raw width component (that is the result is masked by
5529 * {@link #MEASURED_SIZE_MASK}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005531 * @return The raw measured height of this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 */
5533 public final int getMeasuredHeight() {
Dianne Hackborn189ee182010-12-02 21:48:53 -08005534 return mMeasuredHeight & MEASURED_SIZE_MASK;
5535 }
5536
5537 /**
5538 * Return the full height measurement information for this view as computed
5539 * by the most recent call to {@link #measure}. This result is a bit mask
5540 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5541 * This should be used during measurement and layout calculations only. Use
5542 * {@link #getHeight()} to see how wide a view is after layout.
5543 *
5544 * @return The measured width of this view as a bit mask.
5545 */
5546 public final int getMeasuredHeightAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005547 return mMeasuredHeight;
5548 }
5549
5550 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005551 * Return only the state bits of {@link #getMeasuredWidthAndState()}
5552 * and {@link #getMeasuredHeightAndState()}, combined into one integer.
5553 * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
5554 * and the height component is at the shifted bits
5555 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
5556 */
5557 public final int getMeasuredState() {
5558 return (mMeasuredWidth&MEASURED_STATE_MASK)
5559 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
5560 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
5561 }
5562
5563 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005564 * The transform matrix of this view, which is calculated based on the current
5565 * roation, scale, and pivot properties.
5566 *
5567 * @see #getRotation()
5568 * @see #getScaleX()
5569 * @see #getScaleY()
5570 * @see #getPivotX()
5571 * @see #getPivotY()
5572 * @return The current transform matrix for the view
5573 */
5574 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005575 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005576 return mMatrix;
5577 }
5578
5579 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005580 * Utility function to determine if the value is far enough away from zero to be
5581 * considered non-zero.
5582 * @param value A floating point value to check for zero-ness
5583 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5584 */
5585 private static boolean nonzero(float value) {
5586 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5587 }
5588
5589 /**
Jeff Brown86671742010-09-30 20:00:15 -07005590 * Returns true if the transform matrix is the identity matrix.
5591 * Recomputes the matrix if necessary.
Romain Guy33e72ae2010-07-17 12:40:29 -07005592 *
5593 * @return True if the transform matrix is the identity matrix, false otherwise.
5594 */
Jeff Brown86671742010-09-30 20:00:15 -07005595 final boolean hasIdentityMatrix() {
5596 updateMatrix();
5597 return mMatrixIsIdentity;
5598 }
5599
5600 /**
5601 * Recomputes the transform matrix if necessary.
5602 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005603 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005604 if (mMatrixDirty) {
5605 // transform-related properties have changed since the last time someone
5606 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005607
5608 // Figure out if we need to update the pivot point
5609 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005610 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005611 mPrevWidth = mRight - mLeft;
5612 mPrevHeight = mBottom - mTop;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -08005613 mPivotX = mPrevWidth / 2f;
5614 mPivotY = mPrevHeight / 2f;
Chet Haasefd2b0022010-08-06 13:08:56 -07005615 }
5616 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005617 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005618 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5619 mMatrix.setTranslate(mTranslationX, mTranslationY);
5620 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5621 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5622 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005623 if (mCamera == null) {
5624 mCamera = new Camera();
5625 matrix3D = new Matrix();
5626 }
5627 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005628 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005629 mCamera.rotateX(mRotationX);
5630 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005631 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005632 mCamera.getMatrix(matrix3D);
5633 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005634 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005635 mMatrix.postConcat(matrix3D);
5636 mCamera.restore();
5637 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005638 mMatrixDirty = false;
5639 mMatrixIsIdentity = mMatrix.isIdentity();
5640 mInverseMatrixDirty = true;
5641 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005642 }
5643
5644 /**
5645 * Utility method to retrieve the inverse of the current mMatrix property.
5646 * We cache the matrix to avoid recalculating it when transform properties
5647 * have not changed.
5648 *
5649 * @return The inverse of the current matrix of this view.
5650 */
Jeff Brown86671742010-09-30 20:00:15 -07005651 final Matrix getInverseMatrix() {
5652 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005653 if (mInverseMatrixDirty) {
5654 if (mInverseMatrix == null) {
5655 mInverseMatrix = new Matrix();
5656 }
5657 mMatrix.invert(mInverseMatrix);
5658 mInverseMatrixDirty = false;
5659 }
5660 return mInverseMatrix;
5661 }
5662
5663 /**
5664 * The degrees that the view is rotated around the pivot point.
5665 *
5666 * @see #getPivotX()
5667 * @see #getPivotY()
5668 * @return The degrees of rotation.
5669 */
5670 public float getRotation() {
5671 return mRotation;
5672 }
5673
5674 /**
Chet Haase897247b2010-09-09 14:54:47 -07005675 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5676 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005677 *
5678 * @param rotation The degrees of rotation.
5679 * @see #getPivotX()
5680 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005681 *
5682 * @attr ref android.R.styleable#View_rotation
Chet Haasec3aa3612010-06-17 08:50:37 -07005683 */
5684 public void setRotation(float rotation) {
5685 if (mRotation != rotation) {
5686 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005687 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005688 mRotation = rotation;
5689 mMatrixDirty = true;
5690 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005691 invalidate(false);
Chet Haasedaf98e92011-01-10 14:10:36 -08005692 invalidateParentIfAccelerated();
Chet Haasec3aa3612010-06-17 08:50:37 -07005693 }
5694 }
5695
5696 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005697 * The degrees that the view is rotated around the vertical axis through the pivot point.
5698 *
5699 * @see #getPivotX()
5700 * @see #getPivotY()
5701 * @return The degrees of Y rotation.
5702 */
5703 public float getRotationY() {
5704 return mRotationY;
5705 }
5706
5707 /**
Chet Haase897247b2010-09-09 14:54:47 -07005708 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5709 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5710 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005711 *
5712 * @param rotationY The degrees of Y rotation.
5713 * @see #getPivotX()
5714 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005715 *
5716 * @attr ref android.R.styleable#View_rotationY
Chet Haasefd2b0022010-08-06 13:08:56 -07005717 */
5718 public void setRotationY(float rotationY) {
5719 if (mRotationY != rotationY) {
5720 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005721 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005722 mRotationY = rotationY;
5723 mMatrixDirty = true;
5724 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005725 invalidate(false);
Chet Haasedaf98e92011-01-10 14:10:36 -08005726 invalidateParentIfAccelerated();
Chet Haasefd2b0022010-08-06 13:08:56 -07005727 }
5728 }
5729
5730 /**
5731 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5732 *
5733 * @see #getPivotX()
5734 * @see #getPivotY()
5735 * @return The degrees of X rotation.
5736 */
5737 public float getRotationX() {
5738 return mRotationX;
5739 }
5740
5741 /**
Chet Haase897247b2010-09-09 14:54:47 -07005742 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5743 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5744 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005745 *
5746 * @param rotationX The degrees of X rotation.
5747 * @see #getPivotX()
5748 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005749 *
5750 * @attr ref android.R.styleable#View_rotationX
Chet Haasefd2b0022010-08-06 13:08:56 -07005751 */
5752 public void setRotationX(float rotationX) {
5753 if (mRotationX != rotationX) {
5754 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005755 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005756 mRotationX = rotationX;
5757 mMatrixDirty = true;
5758 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005759 invalidate(false);
Chet Haasedaf98e92011-01-10 14:10:36 -08005760 invalidateParentIfAccelerated();
Chet Haasefd2b0022010-08-06 13:08:56 -07005761 }
5762 }
5763
5764 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005765 * The amount that the view is scaled in x around the pivot point, as a proportion of
5766 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5767 *
Joe Onorato93162322010-09-16 15:42:01 -04005768 * <p>By default, this is 1.0f.
5769 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005770 * @see #getPivotX()
5771 * @see #getPivotY()
5772 * @return The scaling factor.
5773 */
5774 public float getScaleX() {
5775 return mScaleX;
5776 }
5777
5778 /**
5779 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5780 * the view's unscaled width. A value of 1 means that no scaling is applied.
5781 *
5782 * @param scaleX The scaling factor.
5783 * @see #getPivotX()
5784 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005785 *
5786 * @attr ref android.R.styleable#View_scaleX
Chet Haasec3aa3612010-06-17 08:50:37 -07005787 */
5788 public void setScaleX(float scaleX) {
5789 if (mScaleX != scaleX) {
5790 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005791 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005792 mScaleX = scaleX;
5793 mMatrixDirty = true;
5794 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005795 invalidate(false);
Chet Haasedaf98e92011-01-10 14:10:36 -08005796 invalidateParentIfAccelerated();
Chet Haasec3aa3612010-06-17 08:50:37 -07005797 }
5798 }
5799
5800 /**
5801 * The amount that the view is scaled in y around the pivot point, as a proportion of
5802 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5803 *
Joe Onorato93162322010-09-16 15:42:01 -04005804 * <p>By default, this is 1.0f.
5805 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005806 * @see #getPivotX()
5807 * @see #getPivotY()
5808 * @return The scaling factor.
5809 */
5810 public float getScaleY() {
5811 return mScaleY;
5812 }
5813
5814 /**
5815 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5816 * the view's unscaled width. A value of 1 means that no scaling is applied.
5817 *
5818 * @param scaleY The scaling factor.
5819 * @see #getPivotX()
5820 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005821 *
5822 * @attr ref android.R.styleable#View_scaleY
Chet Haasec3aa3612010-06-17 08:50:37 -07005823 */
5824 public void setScaleY(float scaleY) {
5825 if (mScaleY != scaleY) {
5826 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005827 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005828 mScaleY = scaleY;
5829 mMatrixDirty = true;
5830 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005831 invalidate(false);
Chet Haasedaf98e92011-01-10 14:10:36 -08005832 invalidateParentIfAccelerated();
Chet Haasec3aa3612010-06-17 08:50:37 -07005833 }
5834 }
5835
5836 /**
5837 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5838 * and {@link #setScaleX(float) scaled}.
5839 *
5840 * @see #getRotation()
5841 * @see #getScaleX()
5842 * @see #getScaleY()
5843 * @see #getPivotY()
5844 * @return The x location of the pivot point.
5845 */
5846 public float getPivotX() {
5847 return mPivotX;
5848 }
5849
5850 /**
5851 * Sets the x location of the point around which the view is
5852 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005853 * By default, the pivot point is centered on the object.
5854 * Setting this property disables this behavior and causes the view to use only the
5855 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005856 *
5857 * @param pivotX The x location of the pivot point.
5858 * @see #getRotation()
5859 * @see #getScaleX()
5860 * @see #getScaleY()
5861 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005862 *
5863 * @attr ref android.R.styleable#View_transformPivotX
Chet Haasec3aa3612010-06-17 08:50:37 -07005864 */
5865 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005866 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005867 if (mPivotX != pivotX) {
5868 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005869 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005870 mPivotX = pivotX;
5871 mMatrixDirty = true;
5872 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005873 invalidate(false);
Chet Haasedaf98e92011-01-10 14:10:36 -08005874 invalidateParentIfAccelerated();
Chet Haasec3aa3612010-06-17 08:50:37 -07005875 }
5876 }
5877
5878 /**
5879 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5880 * and {@link #setScaleY(float) scaled}.
5881 *
5882 * @see #getRotation()
5883 * @see #getScaleX()
5884 * @see #getScaleY()
5885 * @see #getPivotY()
5886 * @return The y location of the pivot point.
5887 */
5888 public float getPivotY() {
5889 return mPivotY;
5890 }
5891
5892 /**
5893 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005894 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5895 * Setting this property disables this behavior and causes the view to use only the
5896 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005897 *
5898 * @param pivotY The y location of the pivot point.
5899 * @see #getRotation()
5900 * @see #getScaleX()
5901 * @see #getScaleY()
5902 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005903 *
5904 * @attr ref android.R.styleable#View_transformPivotY
Chet Haasec3aa3612010-06-17 08:50:37 -07005905 */
5906 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005907 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005908 if (mPivotY != pivotY) {
5909 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005910 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005911 mPivotY = pivotY;
5912 mMatrixDirty = true;
5913 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005914 invalidate(false);
Chet Haasedaf98e92011-01-10 14:10:36 -08005915 invalidateParentIfAccelerated();
Chet Haasec3aa3612010-06-17 08:50:37 -07005916 }
5917 }
5918
5919 /**
5920 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5921 * completely transparent and 1 means the view is completely opaque.
5922 *
Joe Onorato93162322010-09-16 15:42:01 -04005923 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005924 * @return The opacity of the view.
5925 */
5926 public float getAlpha() {
5927 return mAlpha;
5928 }
5929
5930 /**
Romain Guy171c5922011-01-06 10:04:23 -08005931 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5932 * completely transparent and 1 means the view is completely opaque.</p>
5933 *
5934 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
5935 * responsible for applying the opacity itself. Otherwise, calling this method is
5936 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
5937 * setting a hardware layer.</p>
Chet Haasec3aa3612010-06-17 08:50:37 -07005938 *
5939 * @param alpha The opacity of the view.
Chet Haase73066682010-11-29 15:55:32 -08005940 *
Romain Guy171c5922011-01-06 10:04:23 -08005941 * @see #setLayerType(int, android.graphics.Paint)
5942 *
Chet Haase73066682010-11-29 15:55:32 -08005943 * @attr ref android.R.styleable#View_alpha
Chet Haasec3aa3612010-06-17 08:50:37 -07005944 */
5945 public void setAlpha(float alpha) {
5946 mAlpha = alpha;
Chet Haaseed032702010-10-01 14:05:54 -07005947 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07005948 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005949 // subclass is handling alpha - don't optimize rendering cache invalidation
5950 invalidate();
5951 } else {
Romain Guya3496a92010-10-12 11:53:24 -07005952 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005953 invalidate(false);
5954 }
Chet Haasedaf98e92011-01-10 14:10:36 -08005955 invalidateParentIfAccelerated();
Chet Haasec3aa3612010-06-17 08:50:37 -07005956 }
5957
5958 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 * Top position of this view relative to its parent.
5960 *
5961 * @return The top of this view, in pixels.
5962 */
5963 @ViewDebug.CapturedViewProperty
5964 public final int getTop() {
5965 return mTop;
5966 }
5967
5968 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005969 * Sets the top position of this view relative to its parent. This method is meant to be called
5970 * by the layout system and should not generally be called otherwise, because the property
5971 * may be changed at any time by the layout.
5972 *
5973 * @param top The top of this view, in pixels.
5974 */
5975 public final void setTop(int top) {
5976 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07005977 updateMatrix();
5978 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005979 final ViewParent p = mParent;
5980 if (p != null && mAttachInfo != null) {
5981 final Rect r = mAttachInfo.mTmpInvalRect;
5982 int minTop;
5983 int yLoc;
5984 if (top < mTop) {
5985 minTop = top;
5986 yLoc = top - mTop;
5987 } else {
5988 minTop = mTop;
5989 yLoc = 0;
5990 }
5991 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5992 p.invalidateChild(this, r);
5993 }
5994 } else {
5995 // Double-invalidation is necessary to capture view's old and new areas
5996 invalidate();
5997 }
5998
Chet Haaseed032702010-10-01 14:05:54 -07005999 int width = mRight - mLeft;
6000 int oldHeight = mBottom - mTop;
6001
Chet Haase21cd1382010-09-01 17:42:29 -07006002 mTop = top;
6003
Chet Haaseed032702010-10-01 14:05:54 -07006004 onSizeChanged(width, mBottom - mTop, width, oldHeight);
6005
Chet Haase21cd1382010-09-01 17:42:29 -07006006 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006007 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6008 // A change in dimension means an auto-centered pivot point changes, too
6009 mMatrixDirty = true;
6010 }
Chet Haase21cd1382010-09-01 17:42:29 -07006011 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6012 invalidate();
6013 }
Chet Haase55dbb652010-12-21 20:15:08 -08006014 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006015 }
6016 }
6017
6018 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 * Bottom position of this view relative to its parent.
6020 *
6021 * @return The bottom of this view, in pixels.
6022 */
6023 @ViewDebug.CapturedViewProperty
6024 public final int getBottom() {
6025 return mBottom;
6026 }
6027
6028 /**
Michael Jurkadab559a2011-01-04 20:31:51 -08006029 * True if this view has changed since the last time being drawn.
6030 *
6031 * @return The dirty state of this view.
6032 */
6033 public boolean isDirty() {
6034 return (mPrivateFlags & DIRTY_MASK) != 0;
6035 }
6036
6037 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006038 * Sets the bottom position of this view relative to its parent. This method is meant to be
6039 * called by the layout system and should not generally be called otherwise, because the
6040 * property may be changed at any time by the layout.
6041 *
6042 * @param bottom The bottom of this view, in pixels.
6043 */
6044 public final void setBottom(int bottom) {
6045 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07006046 updateMatrix();
6047 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006048 final ViewParent p = mParent;
6049 if (p != null && mAttachInfo != null) {
6050 final Rect r = mAttachInfo.mTmpInvalRect;
6051 int maxBottom;
6052 if (bottom < mBottom) {
6053 maxBottom = mBottom;
6054 } else {
6055 maxBottom = bottom;
6056 }
6057 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
6058 p.invalidateChild(this, r);
6059 }
6060 } else {
6061 // Double-invalidation is necessary to capture view's old and new areas
6062 invalidate();
6063 }
6064
Chet Haaseed032702010-10-01 14:05:54 -07006065 int width = mRight - mLeft;
6066 int oldHeight = mBottom - mTop;
6067
Chet Haase21cd1382010-09-01 17:42:29 -07006068 mBottom = bottom;
6069
Chet Haaseed032702010-10-01 14:05:54 -07006070 onSizeChanged(width, mBottom - mTop, width, oldHeight);
6071
Chet Haase21cd1382010-09-01 17:42:29 -07006072 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006073 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6074 // A change in dimension means an auto-centered pivot point changes, too
6075 mMatrixDirty = true;
6076 }
Chet Haase21cd1382010-09-01 17:42:29 -07006077 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6078 invalidate();
6079 }
Chet Haase55dbb652010-12-21 20:15:08 -08006080 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006081 }
6082 }
6083
6084 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 * Left position of this view relative to its parent.
6086 *
6087 * @return The left edge of this view, in pixels.
6088 */
6089 @ViewDebug.CapturedViewProperty
6090 public final int getLeft() {
6091 return mLeft;
6092 }
6093
6094 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006095 * Sets the left position of this view relative to its parent. This method is meant to be called
6096 * by the layout system and should not generally be called otherwise, because the property
6097 * may be changed at any time by the layout.
6098 *
6099 * @param left The bottom of this view, in pixels.
6100 */
6101 public final void setLeft(int left) {
6102 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07006103 updateMatrix();
6104 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006105 final ViewParent p = mParent;
6106 if (p != null && mAttachInfo != null) {
6107 final Rect r = mAttachInfo.mTmpInvalRect;
6108 int minLeft;
6109 int xLoc;
6110 if (left < mLeft) {
6111 minLeft = left;
6112 xLoc = left - mLeft;
6113 } else {
6114 minLeft = mLeft;
6115 xLoc = 0;
6116 }
6117 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
6118 p.invalidateChild(this, r);
6119 }
6120 } else {
6121 // Double-invalidation is necessary to capture view's old and new areas
6122 invalidate();
6123 }
6124
Chet Haaseed032702010-10-01 14:05:54 -07006125 int oldWidth = mRight - mLeft;
6126 int height = mBottom - mTop;
6127
Chet Haase21cd1382010-09-01 17:42:29 -07006128 mLeft = left;
6129
Chet Haaseed032702010-10-01 14:05:54 -07006130 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6131
Chet Haase21cd1382010-09-01 17:42:29 -07006132 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006133 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6134 // A change in dimension means an auto-centered pivot point changes, too
6135 mMatrixDirty = true;
6136 }
Chet Haase21cd1382010-09-01 17:42:29 -07006137 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6138 invalidate();
6139 }
Chet Haase55dbb652010-12-21 20:15:08 -08006140 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006141 }
6142 }
6143
6144 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 * Right position of this view relative to its parent.
6146 *
6147 * @return The right edge of this view, in pixels.
6148 */
6149 @ViewDebug.CapturedViewProperty
6150 public final int getRight() {
6151 return mRight;
6152 }
6153
6154 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006155 * Sets the right position of this view relative to its parent. This method is meant to be called
6156 * by the layout system and should not generally be called otherwise, because the property
6157 * may be changed at any time by the layout.
6158 *
6159 * @param right The bottom of this view, in pixels.
6160 */
6161 public final void setRight(int right) {
6162 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07006163 updateMatrix();
6164 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006165 final ViewParent p = mParent;
6166 if (p != null && mAttachInfo != null) {
6167 final Rect r = mAttachInfo.mTmpInvalRect;
6168 int maxRight;
6169 if (right < mRight) {
6170 maxRight = mRight;
6171 } else {
6172 maxRight = right;
6173 }
6174 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
6175 p.invalidateChild(this, r);
6176 }
6177 } else {
6178 // Double-invalidation is necessary to capture view's old and new areas
6179 invalidate();
6180 }
6181
Chet Haaseed032702010-10-01 14:05:54 -07006182 int oldWidth = mRight - mLeft;
6183 int height = mBottom - mTop;
6184
Chet Haase21cd1382010-09-01 17:42:29 -07006185 mRight = right;
6186
Chet Haaseed032702010-10-01 14:05:54 -07006187 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6188
Chet Haase21cd1382010-09-01 17:42:29 -07006189 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006190 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6191 // A change in dimension means an auto-centered pivot point changes, too
6192 mMatrixDirty = true;
6193 }
Chet Haase21cd1382010-09-01 17:42:29 -07006194 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6195 invalidate();
6196 }
Chet Haase55dbb652010-12-21 20:15:08 -08006197 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006198 }
6199 }
6200
6201 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006202 * The visual x position of this view, in pixels. This is equivalent to the
6203 * {@link #setTranslationX(float) translationX} property plus the current
6204 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07006205 *
Chet Haasedf030d22010-07-30 17:22:38 -07006206 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006207 */
Chet Haasedf030d22010-07-30 17:22:38 -07006208 public float getX() {
6209 return mLeft + mTranslationX;
6210 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006211
Chet Haasedf030d22010-07-30 17:22:38 -07006212 /**
6213 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
6214 * {@link #setTranslationX(float) translationX} property to be the difference between
6215 * the x value passed in and the current {@link #getLeft() left} property.
6216 *
6217 * @param x The visual x position of this view, in pixels.
6218 */
6219 public void setX(float x) {
6220 setTranslationX(x - mLeft);
6221 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006222
Chet Haasedf030d22010-07-30 17:22:38 -07006223 /**
6224 * The visual y position of this view, in pixels. This is equivalent to the
6225 * {@link #setTranslationY(float) translationY} property plus the current
6226 * {@link #getTop() top} property.
6227 *
6228 * @return The visual y position of this view, in pixels.
6229 */
6230 public float getY() {
6231 return mTop + mTranslationY;
6232 }
6233
6234 /**
6235 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
6236 * {@link #setTranslationY(float) translationY} property to be the difference between
6237 * the y value passed in and the current {@link #getTop() top} property.
6238 *
6239 * @param y The visual y position of this view, in pixels.
6240 */
6241 public void setY(float y) {
6242 setTranslationY(y - mTop);
6243 }
6244
6245
6246 /**
6247 * The horizontal location of this view relative to its {@link #getLeft() left} position.
6248 * This position is post-layout, in addition to wherever the object's
6249 * layout placed it.
6250 *
6251 * @return The horizontal position of this view relative to its left position, in pixels.
6252 */
6253 public float getTranslationX() {
6254 return mTranslationX;
6255 }
6256
6257 /**
6258 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
6259 * This effectively positions the object post-layout, in addition to wherever the object's
6260 * layout placed it.
6261 *
6262 * @param translationX The horizontal position of this view relative to its left position,
6263 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006264 *
6265 * @attr ref android.R.styleable#View_translationX
Chet Haasedf030d22010-07-30 17:22:38 -07006266 */
6267 public void setTranslationX(float translationX) {
6268 if (mTranslationX != translationX) {
6269 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006270 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006271 mTranslationX = translationX;
6272 mMatrixDirty = true;
6273 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006274 invalidate(false);
Chet Haasedaf98e92011-01-10 14:10:36 -08006275 invalidateParentIfAccelerated();
Chet Haasec3aa3612010-06-17 08:50:37 -07006276 }
6277 }
6278
6279 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006280 * The horizontal location of this view relative to its {@link #getTop() top} position.
6281 * This position is post-layout, in addition to wherever the object's
6282 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006283 *
Chet Haasedf030d22010-07-30 17:22:38 -07006284 * @return The vertical position of this view relative to its top position,
6285 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006286 */
Chet Haasedf030d22010-07-30 17:22:38 -07006287 public float getTranslationY() {
6288 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07006289 }
6290
6291 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006292 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
6293 * This effectively positions the object post-layout, in addition to wherever the object's
6294 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006295 *
Chet Haasedf030d22010-07-30 17:22:38 -07006296 * @param translationY The vertical position of this view relative to its top position,
6297 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006298 *
6299 * @attr ref android.R.styleable#View_translationY
Chet Haasec3aa3612010-06-17 08:50:37 -07006300 */
Chet Haasedf030d22010-07-30 17:22:38 -07006301 public void setTranslationY(float translationY) {
6302 if (mTranslationY != translationY) {
6303 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006304 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006305 mTranslationY = translationY;
6306 mMatrixDirty = true;
6307 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006308 invalidate(false);
Chet Haasedaf98e92011-01-10 14:10:36 -08006309 invalidateParentIfAccelerated();
Chet Haasedf030d22010-07-30 17:22:38 -07006310 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006311 }
6312
6313 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 * Hit rectangle in parent's coordinates
6315 *
6316 * @param outRect The hit rectangle of the view.
6317 */
6318 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07006319 updateMatrix();
6320 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006321 outRect.set(mLeft, mTop, mRight, mBottom);
6322 } else {
6323 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07006324 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07006325 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07006326 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
6327 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07006328 }
6329 }
6330
6331 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07006332 * Determines whether the given point, in local coordinates is inside the view.
6333 */
6334 /*package*/ final boolean pointInView(float localX, float localY) {
6335 return localX >= 0 && localX < (mRight - mLeft)
6336 && localY >= 0 && localY < (mBottom - mTop);
6337 }
6338
6339 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07006340 * Utility method to determine whether the given point, in local coordinates,
6341 * is inside the view, where the area of the view is expanded by the slop factor.
6342 * This method is called while processing touch-move events to determine if the event
6343 * is still within the view.
6344 */
6345 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07006346 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07006347 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 }
6349
6350 /**
6351 * When a view has focus and the user navigates away from it, the next view is searched for
6352 * starting from the rectangle filled in by this method.
6353 *
6354 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
6355 * view maintains some idea of internal selection, such as a cursor, or a selected row
6356 * or column, you should override this method and fill in a more specific rectangle.
6357 *
6358 * @param r The rectangle to fill in, in this view's coordinates.
6359 */
6360 public void getFocusedRect(Rect r) {
6361 getDrawingRect(r);
6362 }
6363
6364 /**
6365 * If some part of this view is not clipped by any of its parents, then
6366 * return that area in r in global (root) coordinates. To convert r to local
6367 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
6368 * -globalOffset.y)) If the view is completely clipped or translated out,
6369 * return false.
6370 *
6371 * @param r If true is returned, r holds the global coordinates of the
6372 * visible portion of this view.
6373 * @param globalOffset If true is returned, globalOffset holds the dx,dy
6374 * between this view and its root. globalOffet may be null.
6375 * @return true if r is non-empty (i.e. part of the view is visible at the
6376 * root level.
6377 */
6378 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6379 int width = mRight - mLeft;
6380 int height = mBottom - mTop;
6381 if (width > 0 && height > 0) {
6382 r.set(0, 0, width, height);
6383 if (globalOffset != null) {
6384 globalOffset.set(-mScrollX, -mScrollY);
6385 }
6386 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6387 }
6388 return false;
6389 }
6390
6391 public final boolean getGlobalVisibleRect(Rect r) {
6392 return getGlobalVisibleRect(r, null);
6393 }
6394
6395 public final boolean getLocalVisibleRect(Rect r) {
6396 Point offset = new Point();
6397 if (getGlobalVisibleRect(r, offset)) {
6398 r.offset(-offset.x, -offset.y); // make r local
6399 return true;
6400 }
6401 return false;
6402 }
6403
6404 /**
6405 * Offset this view's vertical location by the specified number of pixels.
6406 *
6407 * @param offset the number of pixels to offset the view by
6408 */
6409 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006410 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006411 updateMatrix();
6412 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006413 final ViewParent p = mParent;
6414 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006415 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006416 int minTop;
6417 int maxBottom;
6418 int yLoc;
6419 if (offset < 0) {
6420 minTop = mTop + offset;
6421 maxBottom = mBottom;
6422 yLoc = offset;
6423 } else {
6424 minTop = mTop;
6425 maxBottom = mBottom + offset;
6426 yLoc = 0;
6427 }
6428 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6429 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006430 }
6431 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006432 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006433 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006434
Chet Haasec3aa3612010-06-17 08:50:37 -07006435 mTop += offset;
6436 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006437
Chet Haasec3aa3612010-06-17 08:50:37 -07006438 if (!mMatrixIsIdentity) {
6439 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006440 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006441 }
6442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 }
6444
6445 /**
6446 * Offset this view's horizontal location by the specified amount of pixels.
6447 *
6448 * @param offset the numer of pixels to offset the view by
6449 */
6450 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006451 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006452 updateMatrix();
6453 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006454 final ViewParent p = mParent;
6455 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006456 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006457 int minLeft;
6458 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006459 if (offset < 0) {
6460 minLeft = mLeft + offset;
6461 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006462 } else {
6463 minLeft = mLeft;
6464 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006465 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006466 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07006467 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006468 }
6469 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006470 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006471 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006472
Chet Haasec3aa3612010-06-17 08:50:37 -07006473 mLeft += offset;
6474 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006475
Chet Haasec3aa3612010-06-17 08:50:37 -07006476 if (!mMatrixIsIdentity) {
6477 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006478 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006479 }
6480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 }
6482
6483 /**
6484 * Get the LayoutParams associated with this view. All views should have
6485 * layout parameters. These supply parameters to the <i>parent</i> of this
6486 * view specifying how it should be arranged. There are many subclasses of
6487 * ViewGroup.LayoutParams, and these correspond to the different subclasses
6488 * of ViewGroup that are responsible for arranging their children.
6489 * @return The LayoutParams associated with this view
6490 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07006491 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 public ViewGroup.LayoutParams getLayoutParams() {
6493 return mLayoutParams;
6494 }
6495
6496 /**
6497 * Set the layout parameters associated with this view. These supply
6498 * parameters to the <i>parent</i> of this view specifying how it should be
6499 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6500 * correspond to the different subclasses of ViewGroup that are responsible
6501 * for arranging their children.
6502 *
6503 * @param params the layout parameters for this view
6504 */
6505 public void setLayoutParams(ViewGroup.LayoutParams params) {
6506 if (params == null) {
6507 throw new NullPointerException("params == null");
6508 }
6509 mLayoutParams = params;
6510 requestLayout();
6511 }
6512
6513 /**
6514 * Set the scrolled position of your view. This will cause a call to
6515 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6516 * invalidated.
6517 * @param x the x position to scroll to
6518 * @param y the y position to scroll to
6519 */
6520 public void scrollTo(int x, int y) {
6521 if (mScrollX != x || mScrollY != y) {
6522 int oldX = mScrollX;
6523 int oldY = mScrollY;
6524 mScrollX = x;
6525 mScrollY = y;
Chet Haasedaf98e92011-01-10 14:10:36 -08006526 invalidateParentIfAccelerated();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006528 if (!awakenScrollBars()) {
6529 invalidate();
6530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 }
6532 }
6533
6534 /**
6535 * Move the scrolled position of your view. This will cause a call to
6536 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6537 * invalidated.
6538 * @param x the amount of pixels to scroll by horizontally
6539 * @param y the amount of pixels to scroll by vertically
6540 */
6541 public void scrollBy(int x, int y) {
6542 scrollTo(mScrollX + x, mScrollY + y);
6543 }
6544
6545 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006546 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6547 * animation to fade the scrollbars out after a default delay. If a subclass
6548 * provides animated scrolling, the start delay should equal the duration
6549 * of the scrolling animation.</p>
6550 *
6551 * <p>The animation starts only if at least one of the scrollbars is
6552 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6553 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6554 * this method returns true, and false otherwise. If the animation is
6555 * started, this method calls {@link #invalidate()}; in that case the
6556 * caller should not call {@link #invalidate()}.</p>
6557 *
6558 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006559 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006560 *
6561 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6562 * and {@link #scrollTo(int, int)}.</p>
6563 *
6564 * @return true if the animation is played, false otherwise
6565 *
6566 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006567 * @see #scrollBy(int, int)
6568 * @see #scrollTo(int, int)
6569 * @see #isHorizontalScrollBarEnabled()
6570 * @see #isVerticalScrollBarEnabled()
6571 * @see #setHorizontalScrollBarEnabled(boolean)
6572 * @see #setVerticalScrollBarEnabled(boolean)
6573 */
6574 protected boolean awakenScrollBars() {
6575 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006576 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006577 }
6578
6579 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006580 * Trigger the scrollbars to draw.
6581 * This method differs from awakenScrollBars() only in its default duration.
6582 * initialAwakenScrollBars() will show the scroll bars for longer than
6583 * usual to give the user more of a chance to notice them.
6584 *
6585 * @return true if the animation is played, false otherwise.
6586 */
6587 private boolean initialAwakenScrollBars() {
6588 return mScrollCache != null &&
6589 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6590 }
6591
6592 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006593 * <p>
6594 * Trigger the scrollbars to draw. When invoked this method starts an
6595 * animation to fade the scrollbars out after a fixed delay. If a subclass
6596 * provides animated scrolling, the start delay should equal the duration of
6597 * the scrolling animation.
6598 * </p>
6599 *
6600 * <p>
6601 * The animation starts only if at least one of the scrollbars is enabled,
6602 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6603 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6604 * this method returns true, and false otherwise. If the animation is
6605 * started, this method calls {@link #invalidate()}; in that case the caller
6606 * should not call {@link #invalidate()}.
6607 * </p>
6608 *
6609 * <p>
6610 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006611 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006612 * </p>
6613 *
6614 * @param startDelay the delay, in milliseconds, after which the animation
6615 * should start; when the delay is 0, the animation starts
6616 * immediately
6617 * @return true if the animation is played, false otherwise
6618 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006619 * @see #scrollBy(int, int)
6620 * @see #scrollTo(int, int)
6621 * @see #isHorizontalScrollBarEnabled()
6622 * @see #isVerticalScrollBarEnabled()
6623 * @see #setHorizontalScrollBarEnabled(boolean)
6624 * @see #setVerticalScrollBarEnabled(boolean)
6625 */
6626 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006627 return awakenScrollBars(startDelay, true);
6628 }
6629
6630 /**
6631 * <p>
6632 * Trigger the scrollbars to draw. When invoked this method starts an
6633 * animation to fade the scrollbars out after a fixed delay. If a subclass
6634 * provides animated scrolling, the start delay should equal the duration of
6635 * the scrolling animation.
6636 * </p>
6637 *
6638 * <p>
6639 * The animation starts only if at least one of the scrollbars is enabled,
6640 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6641 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6642 * this method returns true, and false otherwise. If the animation is
6643 * started, this method calls {@link #invalidate()} if the invalidate parameter
6644 * is set to true; in that case the caller
6645 * should not call {@link #invalidate()}.
6646 * </p>
6647 *
6648 * <p>
6649 * This method should be invoked everytime a subclass directly updates the
6650 * scroll parameters.
6651 * </p>
6652 *
6653 * @param startDelay the delay, in milliseconds, after which the animation
6654 * should start; when the delay is 0, the animation starts
6655 * immediately
6656 *
6657 * @param invalidate Wheter this method should call invalidate
6658 *
6659 * @return true if the animation is played, false otherwise
6660 *
6661 * @see #scrollBy(int, int)
6662 * @see #scrollTo(int, int)
6663 * @see #isHorizontalScrollBarEnabled()
6664 * @see #isVerticalScrollBarEnabled()
6665 * @see #setHorizontalScrollBarEnabled(boolean)
6666 * @see #setVerticalScrollBarEnabled(boolean)
6667 */
6668 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006669 final ScrollabilityCache scrollCache = mScrollCache;
6670
6671 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6672 return false;
6673 }
6674
6675 if (scrollCache.scrollBar == null) {
6676 scrollCache.scrollBar = new ScrollBarDrawable();
6677 }
6678
6679 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6680
Mike Cleron290947b2009-09-29 18:34:32 -07006681 if (invalidate) {
6682 // Invalidate to show the scrollbars
6683 invalidate();
6684 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006685
6686 if (scrollCache.state == ScrollabilityCache.OFF) {
6687 // FIXME: this is copied from WindowManagerService.
6688 // We should get this value from the system when it
6689 // is possible to do so.
6690 final int KEY_REPEAT_FIRST_DELAY = 750;
6691 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6692 }
6693
6694 // Tell mScrollCache when we should start fading. This may
6695 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006696 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006697 scrollCache.fadeStartTime = fadeStartTime;
6698 scrollCache.state = ScrollabilityCache.ON;
6699
6700 // Schedule our fader to run, unscheduling any old ones first
6701 if (mAttachInfo != null) {
6702 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6703 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6704 }
6705
6706 return true;
6707 }
6708
6709 return false;
6710 }
6711
6712 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006713 * Mark the the area defined by dirty as needing to be drawn. If the view is
6714 * visible, {@link #onDraw} will be called at some point in the future.
6715 * This must be called from a UI thread. To call from a non-UI thread, call
6716 * {@link #postInvalidate()}.
6717 *
6718 * WARNING: This method is destructive to dirty.
6719 * @param dirty the rectangle representing the bounds of the dirty region
6720 */
6721 public void invalidate(Rect dirty) {
6722 if (ViewDebug.TRACE_HIERARCHY) {
6723 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6724 }
6725
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006726 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
Chet Haasedaf98e92011-01-10 14:10:36 -08006727 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
6728 (mPrivateFlags & INVALIDATED) != INVALIDATED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 mPrivateFlags &= ~DRAWING_CACHE_VALID;
Chet Haasedaf98e92011-01-10 14:10:36 -08006730 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 final ViewParent p = mParent;
6732 final AttachInfo ai = mAttachInfo;
Romain Guyaf636eb2010-12-09 17:47:21 -08006733 if (p != null && ai != null && ai.mHardwareAccelerated) {
6734 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6735 // with a null dirty rect, which tells the ViewRoot to redraw everything
6736 p.invalidateChild(this, null);
6737 return;
6738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006739 if (p != null && ai != null) {
6740 final int scrollX = mScrollX;
6741 final int scrollY = mScrollY;
6742 final Rect r = ai.mTmpInvalRect;
6743 r.set(dirty.left - scrollX, dirty.top - scrollY,
6744 dirty.right - scrollX, dirty.bottom - scrollY);
6745 mParent.invalidateChild(this, r);
6746 }
6747 }
6748 }
6749
6750 /**
6751 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6752 * The coordinates of the dirty rect are relative to the view.
6753 * If the view is visible, {@link #onDraw} will be called at some point
6754 * in the future. This must be called from a UI thread. To call
6755 * from a non-UI thread, call {@link #postInvalidate()}.
6756 * @param l the left position of the dirty region
6757 * @param t the top position of the dirty region
6758 * @param r the right position of the dirty region
6759 * @param b the bottom position of the dirty region
6760 */
6761 public void invalidate(int l, int t, int r, int b) {
6762 if (ViewDebug.TRACE_HIERARCHY) {
6763 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6764 }
6765
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006766 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
Chet Haasedaf98e92011-01-10 14:10:36 -08006767 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
6768 (mPrivateFlags & INVALIDATED) != INVALIDATED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 mPrivateFlags &= ~DRAWING_CACHE_VALID;
Chet Haasedaf98e92011-01-10 14:10:36 -08006770 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 final ViewParent p = mParent;
6772 final AttachInfo ai = mAttachInfo;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006773 if (p != null && ai != null && ai.mHardwareAccelerated) {
6774 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6775 // with a null dirty rect, which tells the ViewRoot to redraw everything
6776 p.invalidateChild(this, null);
6777 return;
6778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 if (p != null && ai != null && l < r && t < b) {
6780 final int scrollX = mScrollX;
6781 final int scrollY = mScrollY;
6782 final Rect tmpr = ai.mTmpInvalRect;
6783 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6784 p.invalidateChild(this, tmpr);
6785 }
6786 }
6787 }
6788
6789 /**
6790 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6791 * be called at some point in the future. This must be called from a
6792 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6793 */
6794 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006795 invalidate(true);
6796 }
Romain Guyc5d55862011-01-21 19:01:46 -08006797
Chet Haaseed032702010-10-01 14:05:54 -07006798 /**
6799 * This is where the invalidate() work actually happens. A full invalidate()
6800 * causes the drawing cache to be invalidated, but this function can be called with
6801 * invalidateCache set to false to skip that invalidation step for cases that do not
6802 * need it (for example, a component that remains at the same dimensions with the same
6803 * content).
6804 *
6805 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6806 * well. This is usually true for a full invalidate, but may be set to false if the
6807 * View's contents or dimensions have not changed.
6808 */
6809 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006810 if (ViewDebug.TRACE_HIERARCHY) {
6811 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6812 }
6813
Romain Guyc5d55862011-01-21 19:01:46 -08006814 boolean opaque = isOpaque();
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006815 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
Romain Guyc5d55862011-01-21 19:01:46 -08006816 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
Chet Haasedaf98e92011-01-10 14:10:36 -08006817 opaque != mLastIsOpaque || (mPrivateFlags & INVALIDATED) != INVALIDATED) {
Romain Guyc5d55862011-01-21 19:01:46 -08006818 mLastIsOpaque = opaque;
Chet Haaseed032702010-10-01 14:05:54 -07006819 mPrivateFlags &= ~DRAWN;
6820 if (invalidateCache) {
Chet Haasedaf98e92011-01-10 14:10:36 -08006821 mPrivateFlags |= INVALIDATED;
Chet Haaseed032702010-10-01 14:05:54 -07006822 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006824 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006825 final ViewParent p = mParent;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006826 if (p != null && ai != null && ai.mHardwareAccelerated) {
6827 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6828 // with a null dirty rect, which tells the ViewRoot to redraw everything
6829 p.invalidateChild(this, null);
6830 return;
6831 }
Michael Jurkaebefea42010-11-15 16:04:01 -08006832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006833 if (p != null && ai != null) {
6834 final Rect r = ai.mTmpInvalRect;
6835 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6836 // Don't call invalidate -- we don't want to internally scroll
6837 // our own bounds
6838 p.invalidateChild(this, r);
6839 }
6840 }
6841 }
6842
6843 /**
Chet Haasedaf98e92011-01-10 14:10:36 -08006844 * Used to indicate that the parent of this view should be invalidated. This functionality
6845 * is used to force the parent to rebuild its display list (when hardware-accelerated),
6846 * which is necessary when various parent-managed properties of the view change, such as
6847 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y.
6848 *
6849 * @hide
6850 */
6851 protected void invalidateParentIfAccelerated() {
6852 if (isHardwareAccelerated() && mParent instanceof View) {
6853 ((View) mParent).invalidate();
6854 }
6855 }
6856
6857 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006858 * Indicates whether this View is opaque. An opaque View guarantees that it will
6859 * draw all the pixels overlapping its bounds using a fully opaque color.
6860 *
6861 * Subclasses of View should override this method whenever possible to indicate
6862 * whether an instance is opaque. Opaque Views are treated in a special way by
6863 * the View hierarchy, possibly allowing it to perform optimizations during
6864 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006865 *
Romain Guy24443ea2009-05-11 11:56:30 -07006866 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006867 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006868 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006869 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006870 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6871 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006872 }
6873
Adam Powell20232d02010-12-08 21:08:53 -08006874 /**
6875 * @hide
6876 */
6877 protected void computeOpaqueFlags() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006878 // Opaque if:
6879 // - Has a background
6880 // - Background is opaque
6881 // - Doesn't have scrollbars or scrollbars are inside overlay
6882
6883 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6884 mPrivateFlags |= OPAQUE_BACKGROUND;
6885 } else {
6886 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6887 }
6888
6889 final int flags = mViewFlags;
6890 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6891 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6892 mPrivateFlags |= OPAQUE_SCROLLBARS;
6893 } else {
6894 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6895 }
6896 }
6897
6898 /**
6899 * @hide
6900 */
6901 protected boolean hasOpaqueScrollbars() {
6902 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006903 }
6904
6905 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006906 * @return A handler associated with the thread running the View. This
6907 * handler can be used to pump events in the UI events queue.
6908 */
6909 public Handler getHandler() {
6910 if (mAttachInfo != null) {
6911 return mAttachInfo.mHandler;
6912 }
6913 return null;
6914 }
6915
6916 /**
6917 * Causes the Runnable to be added to the message queue.
6918 * The runnable will be run on the user interface thread.
6919 *
6920 * @param action The Runnable that will be executed.
6921 *
6922 * @return Returns true if the Runnable was successfully placed in to the
6923 * message queue. Returns false on failure, usually because the
6924 * looper processing the message queue is exiting.
6925 */
6926 public boolean post(Runnable action) {
6927 Handler handler;
6928 if (mAttachInfo != null) {
6929 handler = mAttachInfo.mHandler;
6930 } else {
6931 // Assume that post will succeed later
6932 ViewRoot.getRunQueue().post(action);
6933 return true;
6934 }
6935
6936 return handler.post(action);
6937 }
6938
6939 /**
6940 * Causes the Runnable to be added to the message queue, to be run
6941 * after the specified amount of time elapses.
6942 * The runnable will be run on the user interface thread.
6943 *
6944 * @param action The Runnable that will be executed.
6945 * @param delayMillis The delay (in milliseconds) until the Runnable
6946 * will be executed.
6947 *
6948 * @return true if the Runnable was successfully placed in to the
6949 * message queue. Returns false on failure, usually because the
6950 * looper processing the message queue is exiting. Note that a
6951 * result of true does not mean the Runnable will be processed --
6952 * if the looper is quit before the delivery time of the message
6953 * occurs then the message will be dropped.
6954 */
6955 public boolean postDelayed(Runnable action, long delayMillis) {
6956 Handler handler;
6957 if (mAttachInfo != null) {
6958 handler = mAttachInfo.mHandler;
6959 } else {
6960 // Assume that post will succeed later
6961 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6962 return true;
6963 }
6964
6965 return handler.postDelayed(action, delayMillis);
6966 }
6967
6968 /**
6969 * Removes the specified Runnable from the message queue.
6970 *
6971 * @param action The Runnable to remove from the message handling queue
6972 *
6973 * @return true if this view could ask the Handler to remove the Runnable,
6974 * false otherwise. When the returned value is true, the Runnable
6975 * may or may not have been actually removed from the message queue
6976 * (for instance, if the Runnable was not in the queue already.)
6977 */
6978 public boolean removeCallbacks(Runnable action) {
6979 Handler handler;
6980 if (mAttachInfo != null) {
6981 handler = mAttachInfo.mHandler;
6982 } else {
6983 // Assume that post will succeed later
6984 ViewRoot.getRunQueue().removeCallbacks(action);
6985 return true;
6986 }
6987
6988 handler.removeCallbacks(action);
6989 return true;
6990 }
6991
6992 /**
6993 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6994 * Use this to invalidate the View from a non-UI thread.
6995 *
6996 * @see #invalidate()
6997 */
6998 public void postInvalidate() {
6999 postInvalidateDelayed(0);
7000 }
7001
7002 /**
7003 * Cause an invalidate of the specified area to happen on a subsequent cycle
7004 * through the event loop. Use this to invalidate the View from a non-UI thread.
7005 *
7006 * @param left The left coordinate of the rectangle to invalidate.
7007 * @param top The top coordinate of the rectangle to invalidate.
7008 * @param right The right coordinate of the rectangle to invalidate.
7009 * @param bottom The bottom coordinate of the rectangle to invalidate.
7010 *
7011 * @see #invalidate(int, int, int, int)
7012 * @see #invalidate(Rect)
7013 */
7014 public void postInvalidate(int left, int top, int right, int bottom) {
7015 postInvalidateDelayed(0, left, top, right, bottom);
7016 }
7017
7018 /**
7019 * Cause an invalidate to happen on a subsequent cycle through the event
7020 * loop. Waits for the specified amount of time.
7021 *
7022 * @param delayMilliseconds the duration in milliseconds to delay the
7023 * invalidation by
7024 */
7025 public void postInvalidateDelayed(long delayMilliseconds) {
7026 // We try only with the AttachInfo because there's no point in invalidating
7027 // if we are not attached to our window
7028 if (mAttachInfo != null) {
7029 Message msg = Message.obtain();
7030 msg.what = AttachInfo.INVALIDATE_MSG;
7031 msg.obj = this;
7032 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
7033 }
7034 }
7035
7036 /**
7037 * Cause an invalidate of the specified area to happen on a subsequent cycle
7038 * through the event loop. Waits for the specified amount of time.
7039 *
7040 * @param delayMilliseconds the duration in milliseconds to delay the
7041 * invalidation by
7042 * @param left The left coordinate of the rectangle to invalidate.
7043 * @param top The top coordinate of the rectangle to invalidate.
7044 * @param right The right coordinate of the rectangle to invalidate.
7045 * @param bottom The bottom coordinate of the rectangle to invalidate.
7046 */
7047 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
7048 int right, int bottom) {
7049
7050 // We try only with the AttachInfo because there's no point in invalidating
7051 // if we are not attached to our window
7052 if (mAttachInfo != null) {
7053 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
7054 info.target = this;
7055 info.left = left;
7056 info.top = top;
7057 info.right = right;
7058 info.bottom = bottom;
7059
7060 final Message msg = Message.obtain();
7061 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
7062 msg.obj = info;
7063 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
7064 }
7065 }
7066
7067 /**
7068 * Called by a parent to request that a child update its values for mScrollX
7069 * and mScrollY if necessary. This will typically be done if the child is
7070 * animating a scroll using a {@link android.widget.Scroller Scroller}
7071 * object.
7072 */
7073 public void computeScroll() {
7074 }
7075
7076 /**
7077 * <p>Indicate whether the horizontal edges are faded when the view is
7078 * scrolled horizontally.</p>
7079 *
7080 * @return true if the horizontal edges should are faded on scroll, false
7081 * otherwise
7082 *
7083 * @see #setHorizontalFadingEdgeEnabled(boolean)
7084 * @attr ref android.R.styleable#View_fadingEdge
7085 */
7086 public boolean isHorizontalFadingEdgeEnabled() {
7087 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
7088 }
7089
7090 /**
7091 * <p>Define whether the horizontal edges should be faded when this view
7092 * is scrolled horizontally.</p>
7093 *
7094 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
7095 * be faded when the view is scrolled
7096 * horizontally
7097 *
7098 * @see #isHorizontalFadingEdgeEnabled()
7099 * @attr ref android.R.styleable#View_fadingEdge
7100 */
7101 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
7102 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
7103 if (horizontalFadingEdgeEnabled) {
7104 initScrollCache();
7105 }
7106
7107 mViewFlags ^= FADING_EDGE_HORIZONTAL;
7108 }
7109 }
7110
7111 /**
7112 * <p>Indicate whether the vertical edges are faded when the view is
7113 * scrolled horizontally.</p>
7114 *
7115 * @return true if the vertical edges should are faded on scroll, false
7116 * otherwise
7117 *
7118 * @see #setVerticalFadingEdgeEnabled(boolean)
7119 * @attr ref android.R.styleable#View_fadingEdge
7120 */
7121 public boolean isVerticalFadingEdgeEnabled() {
7122 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
7123 }
7124
7125 /**
7126 * <p>Define whether the vertical edges should be faded when this view
7127 * is scrolled vertically.</p>
7128 *
7129 * @param verticalFadingEdgeEnabled true if the vertical edges should
7130 * be faded when the view is scrolled
7131 * vertically
7132 *
7133 * @see #isVerticalFadingEdgeEnabled()
7134 * @attr ref android.R.styleable#View_fadingEdge
7135 */
7136 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
7137 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
7138 if (verticalFadingEdgeEnabled) {
7139 initScrollCache();
7140 }
7141
7142 mViewFlags ^= FADING_EDGE_VERTICAL;
7143 }
7144 }
7145
7146 /**
7147 * Returns the strength, or intensity, of the top faded edge. The strength is
7148 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7149 * returns 0.0 or 1.0 but no value in between.
7150 *
7151 * Subclasses should override this method to provide a smoother fade transition
7152 * when scrolling occurs.
7153 *
7154 * @return the intensity of the top fade as a float between 0.0f and 1.0f
7155 */
7156 protected float getTopFadingEdgeStrength() {
7157 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
7158 }
7159
7160 /**
7161 * Returns the strength, or intensity, of the bottom faded edge. The strength is
7162 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7163 * returns 0.0 or 1.0 but no value in between.
7164 *
7165 * Subclasses should override this method to provide a smoother fade transition
7166 * when scrolling occurs.
7167 *
7168 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
7169 */
7170 protected float getBottomFadingEdgeStrength() {
7171 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
7172 computeVerticalScrollRange() ? 1.0f : 0.0f;
7173 }
7174
7175 /**
7176 * Returns the strength, or intensity, of the left faded edge. The strength is
7177 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7178 * returns 0.0 or 1.0 but no value in between.
7179 *
7180 * Subclasses should override this method to provide a smoother fade transition
7181 * when scrolling occurs.
7182 *
7183 * @return the intensity of the left fade as a float between 0.0f and 1.0f
7184 */
7185 protected float getLeftFadingEdgeStrength() {
7186 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
7187 }
7188
7189 /**
7190 * Returns the strength, or intensity, of the right faded edge. The strength is
7191 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7192 * returns 0.0 or 1.0 but no value in between.
7193 *
7194 * Subclasses should override this method to provide a smoother fade transition
7195 * when scrolling occurs.
7196 *
7197 * @return the intensity of the right fade as a float between 0.0f and 1.0f
7198 */
7199 protected float getRightFadingEdgeStrength() {
7200 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
7201 computeHorizontalScrollRange() ? 1.0f : 0.0f;
7202 }
7203
7204 /**
7205 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
7206 * scrollbar is not drawn by default.</p>
7207 *
7208 * @return true if the horizontal scrollbar should be painted, false
7209 * otherwise
7210 *
7211 * @see #setHorizontalScrollBarEnabled(boolean)
7212 */
7213 public boolean isHorizontalScrollBarEnabled() {
7214 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7215 }
7216
7217 /**
7218 * <p>Define whether the horizontal scrollbar should be drawn or not. The
7219 * scrollbar is not drawn by default.</p>
7220 *
7221 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
7222 * be painted
7223 *
7224 * @see #isHorizontalScrollBarEnabled()
7225 */
7226 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
7227 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
7228 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007229 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007230 recomputePadding();
7231 }
7232 }
7233
7234 /**
7235 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
7236 * scrollbar is not drawn by default.</p>
7237 *
7238 * @return true if the vertical scrollbar should be painted, false
7239 * otherwise
7240 *
7241 * @see #setVerticalScrollBarEnabled(boolean)
7242 */
7243 public boolean isVerticalScrollBarEnabled() {
7244 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
7245 }
7246
7247 /**
7248 * <p>Define whether the vertical scrollbar should be drawn or not. The
7249 * scrollbar is not drawn by default.</p>
7250 *
7251 * @param verticalScrollBarEnabled true if the vertical scrollbar should
7252 * be painted
7253 *
7254 * @see #isVerticalScrollBarEnabled()
7255 */
7256 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
7257 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
7258 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007259 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007260 recomputePadding();
7261 }
7262 }
7263
Adam Powell20232d02010-12-08 21:08:53 -08007264 /**
7265 * @hide
7266 */
7267 protected void recomputePadding() {
7268 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007269 }
Mike Cleronfe81d382009-09-28 14:22:16 -07007270
7271 /**
7272 * Define whether scrollbars will fade when the view is not scrolling.
7273 *
7274 * @param fadeScrollbars wheter to enable fading
7275 *
7276 */
7277 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
7278 initScrollCache();
7279 final ScrollabilityCache scrollabilityCache = mScrollCache;
7280 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07007281 if (fadeScrollbars) {
7282 scrollabilityCache.state = ScrollabilityCache.OFF;
7283 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07007284 scrollabilityCache.state = ScrollabilityCache.ON;
7285 }
7286 }
7287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07007289 *
7290 * Returns true if scrollbars will fade when this view is not scrolling
7291 *
7292 * @return true if scrollbar fading is enabled
7293 */
7294 public boolean isScrollbarFadingEnabled() {
7295 return mScrollCache != null && mScrollCache.fadeScrollBars;
7296 }
7297
7298 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007299 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
7300 * inset. When inset, they add to the padding of the view. And the scrollbars
7301 * can be drawn inside the padding area or on the edge of the view. For example,
7302 * if a view has a background drawable and you want to draw the scrollbars
7303 * inside the padding specified by the drawable, you can use
7304 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
7305 * appear at the edge of the view, ignoring the padding, then you can use
7306 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
7307 * @param style the style of the scrollbars. Should be one of
7308 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
7309 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
7310 * @see #SCROLLBARS_INSIDE_OVERLAY
7311 * @see #SCROLLBARS_INSIDE_INSET
7312 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7313 * @see #SCROLLBARS_OUTSIDE_INSET
7314 */
7315 public void setScrollBarStyle(int style) {
7316 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
7317 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07007318 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007319 recomputePadding();
7320 }
7321 }
7322
7323 /**
7324 * <p>Returns the current scrollbar style.</p>
7325 * @return the current scrollbar style
7326 * @see #SCROLLBARS_INSIDE_OVERLAY
7327 * @see #SCROLLBARS_INSIDE_INSET
7328 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7329 * @see #SCROLLBARS_OUTSIDE_INSET
7330 */
7331 public int getScrollBarStyle() {
7332 return mViewFlags & SCROLLBARS_STYLE_MASK;
7333 }
7334
7335 /**
7336 * <p>Compute the horizontal range that the horizontal scrollbar
7337 * represents.</p>
7338 *
7339 * <p>The range is expressed in arbitrary units that must be the same as the
7340 * units used by {@link #computeHorizontalScrollExtent()} and
7341 * {@link #computeHorizontalScrollOffset()}.</p>
7342 *
7343 * <p>The default range is the drawing width of this view.</p>
7344 *
7345 * @return the total horizontal range represented by the horizontal
7346 * scrollbar
7347 *
7348 * @see #computeHorizontalScrollExtent()
7349 * @see #computeHorizontalScrollOffset()
7350 * @see android.widget.ScrollBarDrawable
7351 */
7352 protected int computeHorizontalScrollRange() {
7353 return getWidth();
7354 }
7355
7356 /**
7357 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7358 * within the horizontal range. This value is used to compute the position
7359 * of the thumb within the scrollbar's track.</p>
7360 *
7361 * <p>The range is expressed in arbitrary units that must be the same as the
7362 * units used by {@link #computeHorizontalScrollRange()} and
7363 * {@link #computeHorizontalScrollExtent()}.</p>
7364 *
7365 * <p>The default offset is the scroll offset of this view.</p>
7366 *
7367 * @return the horizontal offset of the scrollbar's thumb
7368 *
7369 * @see #computeHorizontalScrollRange()
7370 * @see #computeHorizontalScrollExtent()
7371 * @see android.widget.ScrollBarDrawable
7372 */
7373 protected int computeHorizontalScrollOffset() {
7374 return mScrollX;
7375 }
7376
7377 /**
7378 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7379 * within the horizontal range. This value is used to compute the length
7380 * of the thumb within the scrollbar's track.</p>
7381 *
7382 * <p>The range is expressed in arbitrary units that must be the same as the
7383 * units used by {@link #computeHorizontalScrollRange()} and
7384 * {@link #computeHorizontalScrollOffset()}.</p>
7385 *
7386 * <p>The default extent is the drawing width of this view.</p>
7387 *
7388 * @return the horizontal extent of the scrollbar's thumb
7389 *
7390 * @see #computeHorizontalScrollRange()
7391 * @see #computeHorizontalScrollOffset()
7392 * @see android.widget.ScrollBarDrawable
7393 */
7394 protected int computeHorizontalScrollExtent() {
7395 return getWidth();
7396 }
7397
7398 /**
7399 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7400 *
7401 * <p>The range is expressed in arbitrary units that must be the same as the
7402 * units used by {@link #computeVerticalScrollExtent()} and
7403 * {@link #computeVerticalScrollOffset()}.</p>
7404 *
7405 * @return the total vertical range represented by the vertical scrollbar
7406 *
7407 * <p>The default range is the drawing height of this view.</p>
7408 *
7409 * @see #computeVerticalScrollExtent()
7410 * @see #computeVerticalScrollOffset()
7411 * @see android.widget.ScrollBarDrawable
7412 */
7413 protected int computeVerticalScrollRange() {
7414 return getHeight();
7415 }
7416
7417 /**
7418 * <p>Compute the vertical offset of the vertical scrollbar's thumb
7419 * within the horizontal range. This value is used to compute the position
7420 * of the thumb within the scrollbar's track.</p>
7421 *
7422 * <p>The range is expressed in arbitrary units that must be the same as the
7423 * units used by {@link #computeVerticalScrollRange()} and
7424 * {@link #computeVerticalScrollExtent()}.</p>
7425 *
7426 * <p>The default offset is the scroll offset of this view.</p>
7427 *
7428 * @return the vertical offset of the scrollbar's thumb
7429 *
7430 * @see #computeVerticalScrollRange()
7431 * @see #computeVerticalScrollExtent()
7432 * @see android.widget.ScrollBarDrawable
7433 */
7434 protected int computeVerticalScrollOffset() {
7435 return mScrollY;
7436 }
7437
7438 /**
7439 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7440 * within the vertical range. This value is used to compute the length
7441 * of the thumb within the scrollbar's track.</p>
7442 *
7443 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08007444 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007445 * {@link #computeVerticalScrollOffset()}.</p>
7446 *
7447 * <p>The default extent is the drawing height of this view.</p>
7448 *
7449 * @return the vertical extent of the scrollbar's thumb
7450 *
7451 * @see #computeVerticalScrollRange()
7452 * @see #computeVerticalScrollOffset()
7453 * @see android.widget.ScrollBarDrawable
7454 */
7455 protected int computeVerticalScrollExtent() {
7456 return getHeight();
7457 }
7458
7459 /**
7460 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7461 * scrollbars are painted only if they have been awakened first.</p>
7462 *
7463 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07007464 *
7465 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007466 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08007467 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007468 // scrollbars are drawn only when the animation is running
7469 final ScrollabilityCache cache = mScrollCache;
7470 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007471
7472 int state = cache.state;
7473
7474 if (state == ScrollabilityCache.OFF) {
7475 return;
7476 }
7477
7478 boolean invalidate = false;
7479
7480 if (state == ScrollabilityCache.FADING) {
7481 // We're fading -- get our fade interpolation
7482 if (cache.interpolatorValues == null) {
7483 cache.interpolatorValues = new float[1];
7484 }
7485
7486 float[] values = cache.interpolatorValues;
7487
7488 // Stops the animation if we're done
7489 if (cache.scrollBarInterpolator.timeToValues(values) ==
7490 Interpolator.Result.FREEZE_END) {
7491 cache.state = ScrollabilityCache.OFF;
7492 } else {
7493 cache.scrollBar.setAlpha(Math.round(values[0]));
7494 }
7495
7496 // This will make the scroll bars inval themselves after
7497 // drawing. We only want this when we're fading so that
7498 // we prevent excessive redraws
7499 invalidate = true;
7500 } else {
7501 // We're just on -- but we may have been fading before so
7502 // reset alpha
7503 cache.scrollBar.setAlpha(255);
7504 }
7505
7506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507 final int viewFlags = mViewFlags;
7508
7509 final boolean drawHorizontalScrollBar =
7510 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7511 final boolean drawVerticalScrollBar =
7512 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7513 && !isVerticalScrollBarHidden();
7514
7515 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7516 final int width = mRight - mLeft;
7517 final int height = mBottom - mTop;
7518
7519 final ScrollBarDrawable scrollBar = cache.scrollBar;
7520 int size = scrollBar.getSize(false);
7521 if (size <= 0) {
7522 size = cache.scrollBarSize;
7523 }
7524
Mike Reede8853fc2009-09-04 14:01:48 -04007525 final int scrollX = mScrollX;
7526 final int scrollY = mScrollY;
7527 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7528
Mike Cleronf116bf82009-09-27 19:14:12 -07007529 int left, top, right, bottom;
7530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007531 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007532 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04007533 computeHorizontalScrollOffset(),
7534 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04007535 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07007536 getVerticalScrollbarWidth() : 0;
7537 top = scrollY + height - size - (mUserPaddingBottom & inside);
7538 left = scrollX + (mPaddingLeft & inside);
7539 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7540 bottom = top + size;
7541 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7542 if (invalidate) {
7543 invalidate(left, top, right, bottom);
7544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007545 }
7546
7547 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04007548 scrollBar.setParameters(computeVerticalScrollRange(),
7549 computeVerticalScrollOffset(),
7550 computeVerticalScrollExtent(), true);
Adam Powell20232d02010-12-08 21:08:53 -08007551 switch (mVerticalScrollbarPosition) {
7552 default:
7553 case SCROLLBAR_POSITION_DEFAULT:
7554 case SCROLLBAR_POSITION_RIGHT:
7555 left = scrollX + width - size - (mUserPaddingRight & inside);
7556 break;
7557 case SCROLLBAR_POSITION_LEFT:
7558 left = scrollX + (mUserPaddingLeft & inside);
7559 break;
7560 }
Mike Cleronf116bf82009-09-27 19:14:12 -07007561 top = scrollY + (mPaddingTop & inside);
7562 right = left + size;
7563 bottom = scrollY + height - (mUserPaddingBottom & inside);
7564 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7565 if (invalidate) {
7566 invalidate(left, top, right, bottom);
7567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568 }
7569 }
7570 }
7571 }
Romain Guy8506ab42009-06-11 17:35:47 -07007572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007574 * 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 -08007575 * FastScroller is visible.
7576 * @return whether to temporarily hide the vertical scrollbar
7577 * @hide
7578 */
7579 protected boolean isVerticalScrollBarHidden() {
7580 return false;
7581 }
7582
7583 /**
7584 * <p>Draw the horizontal scrollbar if
7585 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7586 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 * @param canvas the canvas on which to draw the scrollbar
7588 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007589 *
7590 * @see #isHorizontalScrollBarEnabled()
7591 * @see #computeHorizontalScrollRange()
7592 * @see #computeHorizontalScrollExtent()
7593 * @see #computeHorizontalScrollOffset()
7594 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007595 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007596 */
Romain Guy8fb95422010-08-17 18:38:51 -07007597 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7598 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007599 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007600 scrollBar.draw(canvas);
7601 }
Mike Reede8853fc2009-09-04 14:01:48 -04007602
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007603 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007604 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7605 * returns true.</p>
7606 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007607 * @param canvas the canvas on which to draw the scrollbar
7608 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007609 *
7610 * @see #isVerticalScrollBarEnabled()
7611 * @see #computeVerticalScrollRange()
7612 * @see #computeVerticalScrollExtent()
7613 * @see #computeVerticalScrollOffset()
7614 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007615 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 */
Romain Guy8fb95422010-08-17 18:38:51 -07007617 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7618 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007619 scrollBar.setBounds(l, t, r, b);
7620 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007621 }
7622
7623 /**
7624 * Implement this to do your drawing.
7625 *
7626 * @param canvas the canvas on which the background will be drawn
7627 */
7628 protected void onDraw(Canvas canvas) {
7629 }
7630
7631 /*
7632 * Caller is responsible for calling requestLayout if necessary.
7633 * (This allows addViewInLayout to not request a new layout.)
7634 */
7635 void assignParent(ViewParent parent) {
7636 if (mParent == null) {
7637 mParent = parent;
7638 } else if (parent == null) {
7639 mParent = null;
7640 } else {
7641 throw new RuntimeException("view " + this + " being added, but"
7642 + " it already has a parent");
7643 }
7644 }
7645
7646 /**
7647 * This is called when the view is attached to a window. At this point it
7648 * has a Surface and will start drawing. Note that this function is
7649 * guaranteed to be called before {@link #onDraw}, however it may be called
7650 * any time before the first onDraw -- including before or after
7651 * {@link #onMeasure}.
7652 *
7653 * @see #onDetachedFromWindow()
7654 */
7655 protected void onAttachedToWindow() {
7656 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7657 mParent.requestTransparentRegion(this);
7658 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007659 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7660 initialAwakenScrollBars();
7661 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7662 }
Chet Haasea9b61ac2010-12-20 07:40:25 -08007663 jumpDrawablesToCurrentState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007664 }
7665
7666 /**
7667 * This is called when the view is detached from a window. At this point it
7668 * no longer has a surface for drawing.
7669 *
7670 * @see #onAttachedToWindow()
7671 */
7672 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007673 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guy6c319ca2011-01-11 14:29:25 -08007674
Romain Guya440b002010-02-24 15:57:54 -08007675 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007676 removeLongPressCallback();
Adam Powell3cb8b632011-01-21 15:34:14 -08007677 removePerformClickCallback();
Romain Guy6c319ca2011-01-11 14:29:25 -08007678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 destroyDrawingCache();
Romain Guy6c319ca2011-01-11 14:29:25 -08007680
7681 if (mHardwareLayer != null) {
7682 mHardwareLayer.destroy();
7683 mHardwareLayer = null;
7684 }
Romain Guy8dd5b1e2011-01-14 17:28:51 -08007685
Chet Haasedaf98e92011-01-10 14:10:36 -08007686 if (mDisplayList != null) {
7687 mDisplayList.invalidate();
7688 }
7689
Romain Guy8dd5b1e2011-01-14 17:28:51 -08007690 if (mAttachInfo != null) {
7691 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
7692 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this);
7693 }
7694
Patrick Dubroyec84c3a2011-01-13 17:55:37 -08007695 mCurrentAnimation = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007696 }
7697
7698 /**
7699 * @return The number of times this view has been attached to a window
7700 */
7701 protected int getWindowAttachCount() {
7702 return mWindowAttachCount;
7703 }
7704
7705 /**
7706 * Retrieve a unique token identifying the window this view is attached to.
7707 * @return Return the window's token for use in
7708 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7709 */
7710 public IBinder getWindowToken() {
7711 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7712 }
7713
7714 /**
7715 * Retrieve a unique token identifying the top-level "real" window of
7716 * the window that this view is attached to. That is, this is like
7717 * {@link #getWindowToken}, except if the window this view in is a panel
7718 * window (attached to another containing window), then the token of
7719 * the containing window is returned instead.
7720 *
7721 * @return Returns the associated window token, either
7722 * {@link #getWindowToken()} or the containing window's token.
7723 */
7724 public IBinder getApplicationWindowToken() {
7725 AttachInfo ai = mAttachInfo;
7726 if (ai != null) {
7727 IBinder appWindowToken = ai.mPanelParentWindowToken;
7728 if (appWindowToken == null) {
7729 appWindowToken = ai.mWindowToken;
7730 }
7731 return appWindowToken;
7732 }
7733 return null;
7734 }
7735
7736 /**
7737 * Retrieve private session object this view hierarchy is using to
7738 * communicate with the window manager.
7739 * @return the session object to communicate with the window manager
7740 */
7741 /*package*/ IWindowSession getWindowSession() {
7742 return mAttachInfo != null ? mAttachInfo.mSession : null;
7743 }
7744
7745 /**
7746 * @param info the {@link android.view.View.AttachInfo} to associated with
7747 * this view
7748 */
7749 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7750 //System.out.println("Attached! " + this);
7751 mAttachInfo = info;
7752 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007753 // We will need to evaluate the drawable state at least once.
7754 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007755 if (mFloatingTreeObserver != null) {
7756 info.mTreeObserver.merge(mFloatingTreeObserver);
7757 mFloatingTreeObserver = null;
7758 }
7759 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7760 mAttachInfo.mScrollContainers.add(this);
7761 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7762 }
7763 performCollectViewAttributes(visibility);
7764 onAttachedToWindow();
7765 int vis = info.mWindowVisibility;
7766 if (vis != GONE) {
7767 onWindowVisibilityChanged(vis);
7768 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007769 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7770 // If nobody has evaluated the drawable state yet, then do it now.
7771 refreshDrawableState();
7772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 }
7774
7775 void dispatchDetachedFromWindow() {
7776 //System.out.println("Detached! " + this);
7777 AttachInfo info = mAttachInfo;
7778 if (info != null) {
7779 int vis = info.mWindowVisibility;
7780 if (vis != GONE) {
7781 onWindowVisibilityChanged(GONE);
7782 }
7783 }
7784
7785 onDetachedFromWindow();
7786 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7787 mAttachInfo.mScrollContainers.remove(this);
7788 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7789 }
7790 mAttachInfo = null;
7791 }
7792
7793 /**
7794 * Store this view hierarchy's frozen state into the given container.
7795 *
7796 * @param container The SparseArray in which to save the view's state.
7797 *
7798 * @see #restoreHierarchyState
7799 * @see #dispatchSaveInstanceState
7800 * @see #onSaveInstanceState
7801 */
7802 public void saveHierarchyState(SparseArray<Parcelable> container) {
7803 dispatchSaveInstanceState(container);
7804 }
7805
7806 /**
7807 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7808 * May be overridden to modify how freezing happens to a view's children; for example, some
7809 * views may want to not store state for their children.
7810 *
7811 * @param container The SparseArray in which to save the view's state.
7812 *
7813 * @see #dispatchRestoreInstanceState
7814 * @see #saveHierarchyState
7815 * @see #onSaveInstanceState
7816 */
7817 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7818 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7819 mPrivateFlags &= ~SAVE_STATE_CALLED;
7820 Parcelable state = onSaveInstanceState();
7821 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7822 throw new IllegalStateException(
7823 "Derived class did not call super.onSaveInstanceState()");
7824 }
7825 if (state != null) {
7826 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7827 // + ": " + state);
7828 container.put(mID, state);
7829 }
7830 }
7831 }
7832
7833 /**
7834 * Hook allowing a view to generate a representation of its internal state
7835 * that can later be used to create a new instance with that same state.
7836 * This state should only contain information that is not persistent or can
7837 * not be reconstructed later. For example, you will never store your
7838 * current position on screen because that will be computed again when a
7839 * new instance of the view is placed in its view hierarchy.
7840 * <p>
7841 * Some examples of things you may store here: the current cursor position
7842 * in a text view (but usually not the text itself since that is stored in a
7843 * content provider or other persistent storage), the currently selected
7844 * item in a list view.
7845 *
7846 * @return Returns a Parcelable object containing the view's current dynamic
7847 * state, or null if there is nothing interesting to save. The
7848 * default implementation returns null.
7849 * @see #onRestoreInstanceState
7850 * @see #saveHierarchyState
7851 * @see #dispatchSaveInstanceState
7852 * @see #setSaveEnabled(boolean)
7853 */
7854 protected Parcelable onSaveInstanceState() {
7855 mPrivateFlags |= SAVE_STATE_CALLED;
7856 return BaseSavedState.EMPTY_STATE;
7857 }
7858
7859 /**
7860 * Restore this view hierarchy's frozen state from the given container.
7861 *
7862 * @param container The SparseArray which holds previously frozen states.
7863 *
7864 * @see #saveHierarchyState
7865 * @see #dispatchRestoreInstanceState
7866 * @see #onRestoreInstanceState
7867 */
7868 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7869 dispatchRestoreInstanceState(container);
7870 }
7871
7872 /**
7873 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7874 * children. May be overridden to modify how restoreing happens to a view's children; for
7875 * example, some views may want to not store state for their children.
7876 *
7877 * @param container The SparseArray which holds previously saved state.
7878 *
7879 * @see #dispatchSaveInstanceState
7880 * @see #restoreHierarchyState
7881 * @see #onRestoreInstanceState
7882 */
7883 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7884 if (mID != NO_ID) {
7885 Parcelable state = container.get(mID);
7886 if (state != null) {
7887 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7888 // + ": " + state);
7889 mPrivateFlags &= ~SAVE_STATE_CALLED;
7890 onRestoreInstanceState(state);
7891 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7892 throw new IllegalStateException(
7893 "Derived class did not call super.onRestoreInstanceState()");
7894 }
7895 }
7896 }
7897 }
7898
7899 /**
7900 * Hook allowing a view to re-apply a representation of its internal state that had previously
7901 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7902 * null state.
7903 *
7904 * @param state The frozen state that had previously been returned by
7905 * {@link #onSaveInstanceState}.
7906 *
7907 * @see #onSaveInstanceState
7908 * @see #restoreHierarchyState
7909 * @see #dispatchRestoreInstanceState
7910 */
7911 protected void onRestoreInstanceState(Parcelable state) {
7912 mPrivateFlags |= SAVE_STATE_CALLED;
7913 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007914 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7915 + "received " + state.getClass().toString() + " instead. This usually happens "
7916 + "when two views of different type have the same id in the same hierarchy. "
7917 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7918 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 }
7920 }
7921
7922 /**
7923 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7924 *
7925 * @return the drawing start time in milliseconds
7926 */
7927 public long getDrawingTime() {
7928 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7929 }
7930
7931 /**
7932 * <p>Enables or disables the duplication of the parent's state into this view. When
7933 * duplication is enabled, this view gets its drawable state from its parent rather
7934 * than from its own internal properties.</p>
7935 *
7936 * <p>Note: in the current implementation, setting this property to true after the
7937 * view was added to a ViewGroup might have no effect at all. This property should
7938 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7939 *
7940 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7941 * property is enabled, an exception will be thrown.</p>
Gilles Debunnefb817032011-01-13 13:52:49 -08007942 *
7943 * <p>Note: if the child view uses and updates additionnal states which are unknown to the
7944 * parent, these states should not be affected by this method.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007945 *
7946 * @param enabled True to enable duplication of the parent's drawable state, false
7947 * to disable it.
7948 *
7949 * @see #getDrawableState()
7950 * @see #isDuplicateParentStateEnabled()
7951 */
7952 public void setDuplicateParentStateEnabled(boolean enabled) {
7953 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7954 }
7955
7956 /**
7957 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7958 *
7959 * @return True if this view's drawable state is duplicated from the parent,
7960 * false otherwise
7961 *
7962 * @see #getDrawableState()
7963 * @see #setDuplicateParentStateEnabled(boolean)
7964 */
7965 public boolean isDuplicateParentStateEnabled() {
7966 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7967 }
7968
7969 /**
Romain Guy171c5922011-01-06 10:04:23 -08007970 * <p>Specifies the type of layer backing this view. The layer can be
7971 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
7972 * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
7973 *
7974 * <p>A layer is associated with an optional {@link android.graphics.Paint}
7975 * instance that controls how the layer is composed on screen. The following
7976 * properties of the paint are taken into account when composing the layer:</p>
7977 * <ul>
7978 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
7979 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
7980 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
7981 * </ul>
7982 *
7983 * <p>If this view has an alpha value set to < 1.0 by calling
7984 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
7985 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
7986 * equivalent to setting a hardware layer on this view and providing a paint with
7987 * the desired alpha value.<p>
7988 *
7989 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
7990 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
7991 * for more information on when and how to use layers.</p>
7992 *
7993 * @param layerType The ype of layer to use with this view, must be one of
7994 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
7995 * {@link #LAYER_TYPE_HARDWARE}
7996 * @param paint The paint used to compose the layer. This argument is optional
7997 * and can be null. It is ignored when the layer type is
7998 * {@link #LAYER_TYPE_NONE}
7999 *
8000 * @see #getLayerType()
8001 * @see #LAYER_TYPE_NONE
8002 * @see #LAYER_TYPE_SOFTWARE
8003 * @see #LAYER_TYPE_HARDWARE
8004 * @see #setAlpha(float)
8005 *
8006 * @attr ref android.R.styleable#View_layerType
8007 */
8008 public void setLayerType(int layerType, Paint paint) {
8009 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
8010 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
8011 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
8012 }
Chet Haasedaf98e92011-01-10 14:10:36 -08008013
Romain Guyd6cd5722011-01-17 14:42:41 -08008014 if (layerType == mLayerType) {
8015 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
8016 mLayerPaint = paint == null ? new Paint() : paint;
8017 if (mParent instanceof ViewGroup) {
8018 ((ViewGroup) mParent).invalidate();
8019 }
8020 invalidate();
8021 }
8022 return;
8023 }
Romain Guy171c5922011-01-06 10:04:23 -08008024
8025 // Destroy any previous software drawing cache if needed
Romain Guy6c319ca2011-01-11 14:29:25 -08008026 switch (mLayerType) {
8027 case LAYER_TYPE_SOFTWARE:
8028 if (mDrawingCache != null) {
8029 mDrawingCache.recycle();
8030 mDrawingCache = null;
8031 }
8032
8033 if (mUnscaledDrawingCache != null) {
8034 mUnscaledDrawingCache.recycle();
8035 mUnscaledDrawingCache = null;
8036 }
8037 break;
8038 case LAYER_TYPE_HARDWARE:
8039 if (mHardwareLayer != null) {
8040 mHardwareLayer.destroy();
8041 mHardwareLayer = null;
8042 }
8043 break;
8044 default:
8045 break;
Romain Guy171c5922011-01-06 10:04:23 -08008046 }
8047
8048 mLayerType = layerType;
Romain Guyd6cd5722011-01-17 14:42:41 -08008049 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : (paint == null ? new Paint() : paint);
Romain Guy171c5922011-01-06 10:04:23 -08008050
Romain Guyd6cd5722011-01-17 14:42:41 -08008051 if (mParent instanceof ViewGroup) {
8052 ((ViewGroup) mParent).invalidate();
8053 }
Romain Guy171c5922011-01-06 10:04:23 -08008054 invalidate();
8055 }
8056
8057 /**
8058 * Indicates what type of layer is currently associated with this view. By default
8059 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
8060 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
8061 * for more information on the different types of layers.
8062 *
8063 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
8064 * {@link #LAYER_TYPE_HARDWARE}
8065 *
8066 * @see #setLayerType(int, android.graphics.Paint)
8067 * @see #LAYER_TYPE_NONE
8068 * @see #LAYER_TYPE_SOFTWARE
8069 * @see #LAYER_TYPE_HARDWARE
8070 */
8071 public int getLayerType() {
8072 return mLayerType;
8073 }
Romain Guy6c319ca2011-01-11 14:29:25 -08008074
8075 /**
8076 * <p>Returns a hardware layer that can be used to draw this view again
8077 * without executing its draw method.</p>
8078 *
8079 * @return A HardwareLayer ready to render, or null if an error occurred.
8080 */
8081 HardwareLayer getHardwareLayer(Canvas currentCanvas) {
8082 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8083 return null;
8084 }
8085
8086 final int width = mRight - mLeft;
8087 final int height = mBottom - mTop;
8088
8089 if (width == 0 || height == 0) {
8090 return null;
8091 }
8092
8093 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
8094 if (mHardwareLayer == null) {
8095 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
8096 width, height, isOpaque());
8097 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
8098 mHardwareLayer.resize(width, height);
8099 }
8100
Chet Haasedaf98e92011-01-10 14:10:36 -08008101 final HardwareCanvas canvas = mHardwareLayer.start(mAttachInfo.mHardwareCanvas);
Romain Guy6c319ca2011-01-11 14:29:25 -08008102 try {
8103 canvas.setViewport(width, height);
8104 canvas.onPreDraw();
8105
8106 computeScroll();
8107 canvas.translate(-mScrollX, -mScrollY);
8108
8109 final int restoreCount = canvas.save();
8110
8111 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8112
8113 // Fast path for layouts with no backgrounds
8114 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8115 mPrivateFlags &= ~DIRTY_MASK;
8116 dispatchDraw(canvas);
8117 } else {
8118 draw(canvas);
8119 }
8120
8121 canvas.restoreToCount(restoreCount);
8122 } finally {
8123 canvas.onPostDraw();
Chet Haasedaf98e92011-01-10 14:10:36 -08008124 mHardwareLayer.end(mAttachInfo.mHardwareCanvas);
Romain Guy6c319ca2011-01-11 14:29:25 -08008125 }
8126 }
8127
8128 return mHardwareLayer;
8129 }
Romain Guy171c5922011-01-06 10:04:23 -08008130
8131 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008132 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
8133 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
8134 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
8135 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
8136 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
8137 * null.</p>
Romain Guy171c5922011-01-06 10:04:23 -08008138 *
8139 * <p>Enabling the drawing cache is similar to
8140 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
Chet Haasedaf98e92011-01-10 14:10:36 -08008141 * acceleration is turned off. When hardware acceleration is turned on, enabling the
8142 * drawing cache has no effect on rendering because the system uses a different mechanism
8143 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
8144 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
8145 * for information on how to enable software and hardware layers.</p>
8146 *
8147 * <p>This API can be used to manually generate
8148 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
8149 * {@link #getDrawingCache()}.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 *
8151 * @param enabled true to enable the drawing cache, false otherwise
8152 *
8153 * @see #isDrawingCacheEnabled()
8154 * @see #getDrawingCache()
8155 * @see #buildDrawingCache()
Romain Guy171c5922011-01-06 10:04:23 -08008156 * @see #setLayerType(int, android.graphics.Paint)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 */
8158 public void setDrawingCacheEnabled(boolean enabled) {
8159 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
8160 }
8161
8162 /**
8163 * <p>Indicates whether the drawing cache is enabled for this view.</p>
8164 *
8165 * @return true if the drawing cache is enabled
8166 *
8167 * @see #setDrawingCacheEnabled(boolean)
8168 * @see #getDrawingCache()
8169 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07008170 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008171 public boolean isDrawingCacheEnabled() {
8172 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
8173 }
8174
8175 /**
Chet Haasedaf98e92011-01-10 14:10:36 -08008176 * Debugging utility which recursively outputs the dirty state of a view and its
8177 * descendants.
8178 *
8179 * @hide
8180 */
8181 public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
8182 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
8183 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
8184 (mPrivateFlags & View.DRAWING_CACHE_VALID) +
8185 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
8186 if (clear) {
8187 mPrivateFlags &= clearMask;
8188 }
8189 if (this instanceof ViewGroup) {
8190 ViewGroup parent = (ViewGroup) this;
8191 final int count = parent.getChildCount();
8192 for (int i = 0; i < count; i++) {
8193 final View child = (View) parent.getChildAt(i);
8194 child.outputDirtyFlags(indent + " ", clear, clearMask);
8195 }
8196 }
8197 }
8198
8199 /**
8200 * This method is used by ViewGroup to cause its children to restore or recreate their
8201 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
8202 * to recreate its own display list, which would happen if it went through the normal
8203 * draw/dispatchDraw mechanisms.
8204 *
8205 * @hide
8206 */
8207 protected void dispatchGetDisplayList() {}
8208
8209 /**
Romain Guyb051e892010-09-28 19:09:36 -07008210 * <p>Returns a display list that can be used to draw this view again
8211 * without executing its draw method.</p>
8212 *
8213 * @return A DisplayList ready to replay, or null if caching is not enabled.
Chet Haasedaf98e92011-01-10 14:10:36 -08008214 *
8215 * @hide
Romain Guyb051e892010-09-28 19:09:36 -07008216 */
Chet Haasedaf98e92011-01-10 14:10:36 -08008217 public DisplayList getDisplayList() {
Romain Guyb051e892010-09-28 19:09:36 -07008218 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8219 return null;
8220 }
8221
Chet Haasedaf98e92011-01-10 14:10:36 -08008222 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
8223 mDisplayList == null || !mDisplayList.isValid() ||
8224 mRecreateDisplayList)) {
8225 // Don't need to recreate the display list, just need to tell our
8226 // children to restore/recreate theirs
8227 if (mDisplayList != null && mDisplayList.isValid() &&
8228 !mRecreateDisplayList) {
8229 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8230 mPrivateFlags &= ~DIRTY_MASK;
8231 dispatchGetDisplayList();
8232
8233 return mDisplayList;
8234 }
8235
8236 // If we got here, we're recreating it. Mark it as such to ensure that
8237 // we copy in child display lists into ours in drawChild()
8238 mRecreateDisplayList = true;
Romain Guyb051e892010-09-28 19:09:36 -07008239
Chet Haase9e90a992011-01-04 16:23:21 -08008240 if (mDisplayList == null) {
Chet Haasedaf98e92011-01-10 14:10:36 -08008241 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this);
8242 // If we're creating a new display list, make sure our parent gets invalidated
8243 // since they will need to recreate their display list to account for this
8244 // new child display list.
8245 invalidateParentIfAccelerated();
Chet Haase9e90a992011-01-04 16:23:21 -08008246 }
Romain Guyb051e892010-09-28 19:09:36 -07008247
8248 final HardwareCanvas canvas = mDisplayList.start();
8249 try {
8250 int width = mRight - mLeft;
8251 int height = mBottom - mTop;
8252
8253 canvas.setViewport(width, height);
8254 canvas.onPreDraw();
8255
8256 final int restoreCount = canvas.save();
8257
Chet Haasedaf98e92011-01-10 14:10:36 -08008258 computeScroll();
8259 canvas.translate(-mScrollX, -mScrollY);
Romain Guy2fe9a8f2010-10-04 20:17:01 -07008260 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07008261
8262 // Fast path for layouts with no backgrounds
8263 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8264 mPrivateFlags &= ~DIRTY_MASK;
8265 dispatchDraw(canvas);
8266 } else {
8267 draw(canvas);
8268 }
8269
8270 canvas.restoreToCount(restoreCount);
8271 } finally {
8272 canvas.onPostDraw();
8273
8274 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07008275 }
8276 }
8277
8278 return mDisplayList;
8279 }
8280
8281 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008282 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
8283 *
8284 * @return A non-scaled bitmap representing this view or null if cache is disabled.
8285 *
8286 * @see #getDrawingCache(boolean)
8287 */
8288 public Bitmap getDrawingCache() {
8289 return getDrawingCache(false);
8290 }
8291
8292 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008293 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
8294 * is null when caching is disabled. If caching is enabled and the cache is not ready,
8295 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
8296 * draw from the cache when the cache is enabled. To benefit from the cache, you must
8297 * request the drawing cache by calling this method and draw it on screen if the
8298 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008299 *
8300 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8301 * this method will create a bitmap of the same size as this view. Because this bitmap
8302 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8303 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8304 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8305 * size than the view. This implies that your application must be able to handle this
8306 * size.</p>
8307 *
8308 * @param autoScale Indicates whether the generated bitmap should be scaled based on
8309 * the current density of the screen when the application is in compatibility
8310 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008311 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008312 * @return A bitmap representing this view or null if cache is disabled.
8313 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008314 * @see #setDrawingCacheEnabled(boolean)
8315 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07008316 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008317 * @see #destroyDrawingCache()
8318 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008319 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8321 return null;
8322 }
8323 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008324 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008325 }
Romain Guy02890fd2010-08-06 17:58:44 -07008326 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008327 }
8328
8329 /**
8330 * <p>Frees the resources used by the drawing cache. If you call
8331 * {@link #buildDrawingCache()} manually without calling
8332 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8333 * should cleanup the cache with this method afterwards.</p>
8334 *
8335 * @see #setDrawingCacheEnabled(boolean)
8336 * @see #buildDrawingCache()
8337 * @see #getDrawingCache()
8338 */
8339 public void destroyDrawingCache() {
8340 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008341 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008342 mDrawingCache = null;
8343 }
Romain Guyfbd8f692009-06-26 14:51:58 -07008344 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008345 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07008346 mUnscaledDrawingCache = null;
8347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008348 }
8349
8350 /**
8351 * Setting a solid background color for the drawing cache's bitmaps will improve
8352 * perfromance and memory usage. Note, though that this should only be used if this
8353 * view will always be drawn on top of a solid color.
8354 *
8355 * @param color The background color to use for the drawing cache's bitmap
8356 *
8357 * @see #setDrawingCacheEnabled(boolean)
8358 * @see #buildDrawingCache()
8359 * @see #getDrawingCache()
8360 */
8361 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08008362 if (color != mDrawingCacheBackgroundColor) {
8363 mDrawingCacheBackgroundColor = color;
8364 mPrivateFlags &= ~DRAWING_CACHE_VALID;
8365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008366 }
8367
8368 /**
8369 * @see #setDrawingCacheBackgroundColor(int)
8370 *
8371 * @return The background color to used for the drawing cache's bitmap
8372 */
8373 public int getDrawingCacheBackgroundColor() {
8374 return mDrawingCacheBackgroundColor;
8375 }
8376
8377 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008378 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
8379 *
8380 * @see #buildDrawingCache(boolean)
8381 */
8382 public void buildDrawingCache() {
8383 buildDrawingCache(false);
8384 }
8385
8386 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008387 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
8388 *
8389 * <p>If you call {@link #buildDrawingCache()} manually without calling
8390 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8391 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008392 *
8393 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8394 * this method will create a bitmap of the same size as this view. Because this bitmap
8395 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8396 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8397 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8398 * size than the view. This implies that your application must be able to handle this
8399 * size.</p>
Romain Guy0d9275e2010-10-26 14:22:30 -07008400 *
8401 * <p>You should avoid calling this method when hardware acceleration is enabled. If
8402 * you do not need the drawing cache bitmap, calling this method will increase memory
8403 * usage and cause the view to be rendered in software once, thus negatively impacting
8404 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008405 *
8406 * @see #getDrawingCache()
8407 * @see #destroyDrawingCache()
8408 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008409 public void buildDrawingCache(boolean autoScale) {
8410 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07008411 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008412
8413 if (ViewDebug.TRACE_HIERARCHY) {
8414 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
8415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008416
Romain Guy8506ab42009-06-11 17:35:47 -07008417 int width = mRight - mLeft;
8418 int height = mBottom - mTop;
8419
8420 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07008421 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07008422
Romain Guye1123222009-06-29 14:24:56 -07008423 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008424 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
8425 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07008426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008427
8428 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07008429 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08008430 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008431
8432 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07008433 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08008434 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008435 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
8436 destroyDrawingCache();
8437 return;
8438 }
8439
8440 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07008441 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008442
8443 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008444 Bitmap.Config quality;
8445 if (!opaque) {
8446 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
8447 case DRAWING_CACHE_QUALITY_AUTO:
8448 quality = Bitmap.Config.ARGB_8888;
8449 break;
8450 case DRAWING_CACHE_QUALITY_LOW:
8451 quality = Bitmap.Config.ARGB_4444;
8452 break;
8453 case DRAWING_CACHE_QUALITY_HIGH:
8454 quality = Bitmap.Config.ARGB_8888;
8455 break;
8456 default:
8457 quality = Bitmap.Config.ARGB_8888;
8458 break;
8459 }
8460 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07008461 // Optimization for translucent windows
8462 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08008463 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008464 }
8465
8466 // Try to cleanup memory
8467 if (bitmap != null) bitmap.recycle();
8468
8469 try {
8470 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07008471 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07008472 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07008473 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008474 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07008475 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008476 }
Adam Powell26153a32010-11-08 15:22:27 -08008477 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008478 } catch (OutOfMemoryError e) {
8479 // If there is not enough memory to create the bitmap cache, just
8480 // ignore the issue as bitmap caches are not required to draw the
8481 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07008482 if (autoScale) {
8483 mDrawingCache = null;
8484 } else {
8485 mUnscaledDrawingCache = null;
8486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008487 return;
8488 }
8489
8490 clear = drawingCacheBackgroundColor != 0;
8491 }
8492
8493 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 if (attachInfo != null) {
8495 canvas = attachInfo.mCanvas;
8496 if (canvas == null) {
8497 canvas = new Canvas();
8498 }
8499 canvas.setBitmap(bitmap);
8500 // Temporarily clobber the cached Canvas in case one of our children
8501 // is also using a drawing cache. Without this, the children would
8502 // steal the canvas by attaching their own bitmap to it and bad, bad
8503 // thing would happen (invisible views, corrupted drawings, etc.)
8504 attachInfo.mCanvas = null;
8505 } else {
8506 // This case should hopefully never or seldom happen
8507 canvas = new Canvas(bitmap);
8508 }
8509
8510 if (clear) {
8511 bitmap.eraseColor(drawingCacheBackgroundColor);
8512 }
8513
8514 computeScroll();
8515 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07008516
Romain Guye1123222009-06-29 14:24:56 -07008517 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008518 final float scale = attachInfo.mApplicationScale;
8519 canvas.scale(scale, scale);
8520 }
8521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008522 canvas.translate(-mScrollX, -mScrollY);
8523
Romain Guy5bcdff42009-05-14 21:27:18 -07008524 mPrivateFlags |= DRAWN;
Romain Guy171c5922011-01-06 10:04:23 -08008525 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
8526 mLayerType != LAYER_TYPE_NONE) {
Romain Guy0d9275e2010-10-26 14:22:30 -07008527 mPrivateFlags |= DRAWING_CACHE_VALID;
8528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008529
8530 // Fast path for layouts with no backgrounds
8531 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8532 if (ViewDebug.TRACE_HIERARCHY) {
8533 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8534 }
Romain Guy5bcdff42009-05-14 21:27:18 -07008535 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008536 dispatchDraw(canvas);
8537 } else {
8538 draw(canvas);
8539 }
8540
8541 canvas.restoreToCount(restoreCount);
8542
8543 if (attachInfo != null) {
8544 // Restore the cached Canvas for our siblings
8545 attachInfo.mCanvas = canvas;
8546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547 }
8548 }
8549
8550 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008551 * Create a snapshot of the view into a bitmap. We should probably make
8552 * some form of this public, but should think about the API.
8553 */
Romain Guy223ff5c2010-03-02 17:07:47 -08008554 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008555 int width = mRight - mLeft;
8556 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008557
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008558 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07008559 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008560 width = (int) ((width * scale) + 0.5f);
8561 height = (int) ((height * scale) + 0.5f);
8562
Romain Guy8c11e312009-09-14 15:15:30 -07008563 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008564 if (bitmap == null) {
8565 throw new OutOfMemoryError();
8566 }
8567
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008568 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8569
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008570 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008571 if (attachInfo != null) {
8572 canvas = attachInfo.mCanvas;
8573 if (canvas == null) {
8574 canvas = new Canvas();
8575 }
8576 canvas.setBitmap(bitmap);
8577 // Temporarily clobber the cached Canvas in case one of our children
8578 // is also using a drawing cache. Without this, the children would
8579 // steal the canvas by attaching their own bitmap to it and bad, bad
8580 // things would happen (invisible views, corrupted drawings, etc.)
8581 attachInfo.mCanvas = null;
8582 } else {
8583 // This case should hopefully never or seldom happen
8584 canvas = new Canvas(bitmap);
8585 }
8586
Romain Guy5bcdff42009-05-14 21:27:18 -07008587 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008588 bitmap.eraseColor(backgroundColor);
8589 }
8590
8591 computeScroll();
8592 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008593 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008594 canvas.translate(-mScrollX, -mScrollY);
8595
Romain Guy5bcdff42009-05-14 21:27:18 -07008596 // Temporarily remove the dirty mask
8597 int flags = mPrivateFlags;
8598 mPrivateFlags &= ~DIRTY_MASK;
8599
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008600 // Fast path for layouts with no backgrounds
8601 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8602 dispatchDraw(canvas);
8603 } else {
8604 draw(canvas);
8605 }
8606
Romain Guy5bcdff42009-05-14 21:27:18 -07008607 mPrivateFlags = flags;
8608
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008609 canvas.restoreToCount(restoreCount);
8610
8611 if (attachInfo != null) {
8612 // Restore the cached Canvas for our siblings
8613 attachInfo.mCanvas = canvas;
8614 }
Romain Guy8506ab42009-06-11 17:35:47 -07008615
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008616 return bitmap;
8617 }
8618
8619 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008620 * Indicates whether this View is currently in edit mode. A View is usually
8621 * in edit mode when displayed within a developer tool. For instance, if
8622 * this View is being drawn by a visual user interface builder, this method
8623 * should return true.
8624 *
8625 * Subclasses should check the return value of this method to provide
8626 * different behaviors if their normal behavior might interfere with the
8627 * host environment. For instance: the class spawns a thread in its
8628 * constructor, the drawing code relies on device-specific features, etc.
8629 *
8630 * This method is usually checked in the drawing code of custom widgets.
8631 *
8632 * @return True if this View is in edit mode, false otherwise.
8633 */
8634 public boolean isInEditMode() {
8635 return false;
8636 }
8637
8638 /**
8639 * If the View draws content inside its padding and enables fading edges,
8640 * it needs to support padding offsets. Padding offsets are added to the
8641 * fading edges to extend the length of the fade so that it covers pixels
8642 * drawn inside the padding.
8643 *
8644 * Subclasses of this class should override this method if they need
8645 * to draw content inside the padding.
8646 *
8647 * @return True if padding offset must be applied, false otherwise.
8648 *
8649 * @see #getLeftPaddingOffset()
8650 * @see #getRightPaddingOffset()
8651 * @see #getTopPaddingOffset()
8652 * @see #getBottomPaddingOffset()
8653 *
8654 * @since CURRENT
8655 */
8656 protected boolean isPaddingOffsetRequired() {
8657 return false;
8658 }
8659
8660 /**
8661 * Amount by which to extend the left fading region. Called only when
8662 * {@link #isPaddingOffsetRequired()} returns true.
8663 *
8664 * @return The left padding offset in pixels.
8665 *
8666 * @see #isPaddingOffsetRequired()
8667 *
8668 * @since CURRENT
8669 */
8670 protected int getLeftPaddingOffset() {
8671 return 0;
8672 }
8673
8674 /**
8675 * Amount by which to extend the right fading region. Called only when
8676 * {@link #isPaddingOffsetRequired()} returns true.
8677 *
8678 * @return The right padding offset in pixels.
8679 *
8680 * @see #isPaddingOffsetRequired()
8681 *
8682 * @since CURRENT
8683 */
8684 protected int getRightPaddingOffset() {
8685 return 0;
8686 }
8687
8688 /**
8689 * Amount by which to extend the top fading region. Called only when
8690 * {@link #isPaddingOffsetRequired()} returns true.
8691 *
8692 * @return The top padding offset in pixels.
8693 *
8694 * @see #isPaddingOffsetRequired()
8695 *
8696 * @since CURRENT
8697 */
8698 protected int getTopPaddingOffset() {
8699 return 0;
8700 }
8701
8702 /**
8703 * Amount by which to extend the bottom fading region. Called only when
8704 * {@link #isPaddingOffsetRequired()} returns true.
8705 *
8706 * @return The bottom padding offset in pixels.
8707 *
8708 * @see #isPaddingOffsetRequired()
8709 *
8710 * @since CURRENT
8711 */
8712 protected int getBottomPaddingOffset() {
8713 return 0;
8714 }
8715
8716 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008717 * <p>Indicates whether this view is attached to an hardware accelerated
8718 * window or not.</p>
8719 *
8720 * <p>Even if this method returns true, it does not mean that every call
8721 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8722 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8723 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8724 * window is hardware accelerated,
8725 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8726 * return false, and this method will return true.</p>
8727 *
8728 * @return True if the view is attached to a window and the window is
8729 * hardware accelerated; false in any other case.
8730 */
8731 public boolean isHardwareAccelerated() {
8732 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8733 }
8734
8735 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008736 * Manually render this view (and all of its children) to the given Canvas.
8737 * The view must have already done a full layout before this function is
Chet Haasec75ec332010-12-17 07:44:30 -08008738 * called. When implementing a view, implement {@link #onDraw} instead of
8739 * overriding this method. If you do need to override this method, call
8740 * the superclass version.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008741 *
8742 * @param canvas The Canvas to which the View is rendered.
8743 */
8744 public void draw(Canvas canvas) {
8745 if (ViewDebug.TRACE_HIERARCHY) {
8746 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8747 }
8748
Romain Guy5bcdff42009-05-14 21:27:18 -07008749 final int privateFlags = mPrivateFlags;
8750 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8751 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8752 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008754 /*
8755 * Draw traversal performs several drawing steps which must be executed
8756 * in the appropriate order:
8757 *
8758 * 1. Draw the background
8759 * 2. If necessary, save the canvas' layers to prepare for fading
8760 * 3. Draw view's content
8761 * 4. Draw children
8762 * 5. If necessary, draw the fading edges and restore layers
8763 * 6. Draw decorations (scrollbars for instance)
8764 */
8765
8766 // Step 1, draw the background, if needed
8767 int saveCount;
8768
Romain Guy24443ea2009-05-11 11:56:30 -07008769 if (!dirtyOpaque) {
8770 final Drawable background = mBGDrawable;
8771 if (background != null) {
8772 final int scrollX = mScrollX;
8773 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774
Romain Guy24443ea2009-05-11 11:56:30 -07008775 if (mBackgroundSizeChanged) {
8776 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8777 mBackgroundSizeChanged = false;
8778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779
Romain Guy24443ea2009-05-11 11:56:30 -07008780 if ((scrollX | scrollY) == 0) {
8781 background.draw(canvas);
8782 } else {
8783 canvas.translate(scrollX, scrollY);
8784 background.draw(canvas);
8785 canvas.translate(-scrollX, -scrollY);
8786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 }
8788 }
8789
8790 // skip step 2 & 5 if possible (common case)
8791 final int viewFlags = mViewFlags;
8792 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8793 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8794 if (!verticalEdges && !horizontalEdges) {
8795 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008796 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008797
8798 // Step 4, draw the children
8799 dispatchDraw(canvas);
8800
8801 // Step 6, draw decorations (scrollbars)
8802 onDrawScrollBars(canvas);
8803
8804 // we're done...
8805 return;
8806 }
8807
8808 /*
8809 * Here we do the full fledged routine...
8810 * (this is an uncommon case where speed matters less,
8811 * this is why we repeat some of the tests that have been
8812 * done above)
8813 */
8814
8815 boolean drawTop = false;
8816 boolean drawBottom = false;
8817 boolean drawLeft = false;
8818 boolean drawRight = false;
8819
8820 float topFadeStrength = 0.0f;
8821 float bottomFadeStrength = 0.0f;
8822 float leftFadeStrength = 0.0f;
8823 float rightFadeStrength = 0.0f;
8824
8825 // Step 2, save the canvas' layers
8826 int paddingLeft = mPaddingLeft;
8827 int paddingTop = mPaddingTop;
8828
8829 final boolean offsetRequired = isPaddingOffsetRequired();
8830 if (offsetRequired) {
8831 paddingLeft += getLeftPaddingOffset();
8832 paddingTop += getTopPaddingOffset();
8833 }
8834
8835 int left = mScrollX + paddingLeft;
8836 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8837 int top = mScrollY + paddingTop;
8838 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8839
8840 if (offsetRequired) {
8841 right += getRightPaddingOffset();
8842 bottom += getBottomPaddingOffset();
8843 }
8844
8845 final ScrollabilityCache scrollabilityCache = mScrollCache;
8846 int length = scrollabilityCache.fadingEdgeLength;
8847
8848 // clip the fade length if top and bottom fades overlap
8849 // overlapping fades produce odd-looking artifacts
8850 if (verticalEdges && (top + length > bottom - length)) {
8851 length = (bottom - top) / 2;
8852 }
8853
8854 // also clip horizontal fades if necessary
8855 if (horizontalEdges && (left + length > right - length)) {
8856 length = (right - left) / 2;
8857 }
8858
8859 if (verticalEdges) {
8860 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008861 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008862 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008863 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 }
8865
8866 if (horizontalEdges) {
8867 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008868 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008869 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008870 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008871 }
8872
8873 saveCount = canvas.getSaveCount();
8874
8875 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008876 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008877 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8878
8879 if (drawTop) {
8880 canvas.saveLayer(left, top, right, top + length, null, flags);
8881 }
8882
8883 if (drawBottom) {
8884 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8885 }
8886
8887 if (drawLeft) {
8888 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8889 }
8890
8891 if (drawRight) {
8892 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8893 }
8894 } else {
8895 scrollabilityCache.setFadeColor(solidColor);
8896 }
8897
8898 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008899 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008900
8901 // Step 4, draw the children
8902 dispatchDraw(canvas);
8903
8904 // Step 5, draw the fade effect and restore layers
8905 final Paint p = scrollabilityCache.paint;
8906 final Matrix matrix = scrollabilityCache.matrix;
8907 final Shader fade = scrollabilityCache.shader;
8908 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8909
8910 if (drawTop) {
8911 matrix.setScale(1, fadeHeight * topFadeStrength);
8912 matrix.postTranslate(left, top);
8913 fade.setLocalMatrix(matrix);
8914 canvas.drawRect(left, top, right, top + length, p);
8915 }
8916
8917 if (drawBottom) {
8918 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8919 matrix.postRotate(180);
8920 matrix.postTranslate(left, bottom);
8921 fade.setLocalMatrix(matrix);
8922 canvas.drawRect(left, bottom - length, right, bottom, p);
8923 }
8924
8925 if (drawLeft) {
8926 matrix.setScale(1, fadeHeight * leftFadeStrength);
8927 matrix.postRotate(-90);
8928 matrix.postTranslate(left, top);
8929 fade.setLocalMatrix(matrix);
8930 canvas.drawRect(left, top, left + length, bottom, p);
8931 }
8932
8933 if (drawRight) {
8934 matrix.setScale(1, fadeHeight * rightFadeStrength);
8935 matrix.postRotate(90);
8936 matrix.postTranslate(right, top);
8937 fade.setLocalMatrix(matrix);
8938 canvas.drawRect(right - length, top, right, bottom, p);
8939 }
8940
8941 canvas.restoreToCount(saveCount);
8942
8943 // Step 6, draw decorations (scrollbars)
8944 onDrawScrollBars(canvas);
8945 }
8946
8947 /**
8948 * Override this if your view is known to always be drawn on top of a solid color background,
8949 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8950 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8951 * should be set to 0xFF.
8952 *
8953 * @see #setVerticalFadingEdgeEnabled
8954 * @see #setHorizontalFadingEdgeEnabled
8955 *
8956 * @return The known solid color background for this view, or 0 if the color may vary
8957 */
8958 public int getSolidColor() {
8959 return 0;
8960 }
8961
8962 /**
8963 * Build a human readable string representation of the specified view flags.
8964 *
8965 * @param flags the view flags to convert to a string
8966 * @return a String representing the supplied flags
8967 */
8968 private static String printFlags(int flags) {
8969 String output = "";
8970 int numFlags = 0;
8971 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8972 output += "TAKES_FOCUS";
8973 numFlags++;
8974 }
8975
8976 switch (flags & VISIBILITY_MASK) {
8977 case INVISIBLE:
8978 if (numFlags > 0) {
8979 output += " ";
8980 }
8981 output += "INVISIBLE";
8982 // USELESS HERE numFlags++;
8983 break;
8984 case GONE:
8985 if (numFlags > 0) {
8986 output += " ";
8987 }
8988 output += "GONE";
8989 // USELESS HERE numFlags++;
8990 break;
8991 default:
8992 break;
8993 }
8994 return output;
8995 }
8996
8997 /**
8998 * Build a human readable string representation of the specified private
8999 * view flags.
9000 *
9001 * @param privateFlags the private view flags to convert to a string
9002 * @return a String representing the supplied flags
9003 */
9004 private static String printPrivateFlags(int privateFlags) {
9005 String output = "";
9006 int numFlags = 0;
9007
9008 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
9009 output += "WANTS_FOCUS";
9010 numFlags++;
9011 }
9012
9013 if ((privateFlags & FOCUSED) == FOCUSED) {
9014 if (numFlags > 0) {
9015 output += " ";
9016 }
9017 output += "FOCUSED";
9018 numFlags++;
9019 }
9020
9021 if ((privateFlags & SELECTED) == SELECTED) {
9022 if (numFlags > 0) {
9023 output += " ";
9024 }
9025 output += "SELECTED";
9026 numFlags++;
9027 }
9028
9029 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
9030 if (numFlags > 0) {
9031 output += " ";
9032 }
9033 output += "IS_ROOT_NAMESPACE";
9034 numFlags++;
9035 }
9036
9037 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
9038 if (numFlags > 0) {
9039 output += " ";
9040 }
9041 output += "HAS_BOUNDS";
9042 numFlags++;
9043 }
9044
9045 if ((privateFlags & DRAWN) == DRAWN) {
9046 if (numFlags > 0) {
9047 output += " ";
9048 }
9049 output += "DRAWN";
9050 // USELESS HERE numFlags++;
9051 }
9052 return output;
9053 }
9054
9055 /**
9056 * <p>Indicates whether or not this view's layout will be requested during
9057 * the next hierarchy layout pass.</p>
9058 *
9059 * @return true if the layout will be forced during next layout pass
9060 */
9061 public boolean isLayoutRequested() {
9062 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
9063 }
9064
9065 /**
9066 * Assign a size and position to a view and all of its
9067 * descendants
9068 *
9069 * <p>This is the second phase of the layout mechanism.
9070 * (The first is measuring). In this phase, each parent calls
9071 * layout on all of its children to position them.
9072 * This is typically done using the child measurements
Chet Haase9c087442011-01-12 16:20:16 -08009073 * that were stored in the measure pass().</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009074 *
Chet Haase9c087442011-01-12 16:20:16 -08009075 * <p>Derived classes should not override this method.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009076 * Derived classes with children should override
9077 * onLayout. In that method, they should
Chet Haase9c087442011-01-12 16:20:16 -08009078 * call layout on each of their children.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009079 *
9080 * @param l Left position, relative to parent
9081 * @param t Top position, relative to parent
9082 * @param r Right position, relative to parent
9083 * @param b Bottom position, relative to parent
9084 */
Romain Guy5429e1d2010-09-07 12:38:00 -07009085 @SuppressWarnings({"unchecked"})
Chet Haase9c087442011-01-12 16:20:16 -08009086 public void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07009087 int oldL = mLeft;
9088 int oldT = mTop;
9089 int oldB = mBottom;
9090 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 boolean changed = setFrame(l, t, r, b);
9092 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
9093 if (ViewDebug.TRACE_HIERARCHY) {
9094 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
9095 }
9096
9097 onLayout(changed, l, t, r, b);
9098 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07009099
9100 if (mOnLayoutChangeListeners != null) {
9101 ArrayList<OnLayoutChangeListener> listenersCopy =
9102 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
9103 int numListeners = listenersCopy.size();
9104 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07009105 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07009106 }
9107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108 }
9109 mPrivateFlags &= ~FORCE_LAYOUT;
9110 }
9111
9112 /**
9113 * Called from layout when this view should
9114 * assign a size and position to each of its children.
9115 *
9116 * Derived classes with children should override
9117 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07009118 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009119 * @param changed This is a new size or position for this view
9120 * @param left Left position, relative to parent
9121 * @param top Top position, relative to parent
9122 * @param right Right position, relative to parent
9123 * @param bottom Bottom position, relative to parent
9124 */
9125 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
9126 }
9127
9128 /**
9129 * Assign a size and position to this view.
9130 *
9131 * This is called from layout.
9132 *
9133 * @param left Left position, relative to parent
9134 * @param top Top position, relative to parent
9135 * @param right Right position, relative to parent
9136 * @param bottom Bottom position, relative to parent
9137 * @return true if the new size and position are different than the
9138 * previous ones
9139 * {@hide}
9140 */
9141 protected boolean setFrame(int left, int top, int right, int bottom) {
9142 boolean changed = false;
9143
9144 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07009145 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009146 + right + "," + bottom + ")");
9147 }
9148
9149 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
9150 changed = true;
9151
9152 // Remember our drawn bit
9153 int drawn = mPrivateFlags & DRAWN;
9154
9155 // Invalidate our old position
9156 invalidate();
9157
9158
9159 int oldWidth = mRight - mLeft;
9160 int oldHeight = mBottom - mTop;
9161
9162 mLeft = left;
9163 mTop = top;
9164 mRight = right;
9165 mBottom = bottom;
9166
9167 mPrivateFlags |= HAS_BOUNDS;
9168
9169 int newWidth = right - left;
9170 int newHeight = bottom - top;
9171
9172 if (newWidth != oldWidth || newHeight != oldHeight) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009173 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9174 // A change in dimension means an auto-centered pivot point changes, too
9175 mMatrixDirty = true;
9176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009177 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
9178 }
9179
9180 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
9181 // If we are visible, force the DRAWN bit to on so that
9182 // this invalidate will go through (at least to our parent).
9183 // This is because someone may have invalidated this view
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009184 // before this call to setFrame came in, thereby clearing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009185 // the DRAWN bit.
9186 mPrivateFlags |= DRAWN;
9187 invalidate();
9188 }
9189
9190 // Reset drawn bit to original value (invalidate turns it off)
9191 mPrivateFlags |= drawn;
9192
9193 mBackgroundSizeChanged = true;
9194 }
9195 return changed;
9196 }
9197
9198 /**
9199 * Finalize inflating a view from XML. This is called as the last phase
9200 * of inflation, after all child views have been added.
9201 *
9202 * <p>Even if the subclass overrides onFinishInflate, they should always be
9203 * sure to call the super method, so that we get called.
9204 */
9205 protected void onFinishInflate() {
9206 }
9207
9208 /**
9209 * Returns the resources associated with this view.
9210 *
9211 * @return Resources object.
9212 */
9213 public Resources getResources() {
9214 return mResources;
9215 }
9216
9217 /**
9218 * Invalidates the specified Drawable.
9219 *
9220 * @param drawable the drawable to invalidate
9221 */
9222 public void invalidateDrawable(Drawable drawable) {
9223 if (verifyDrawable(drawable)) {
9224 final Rect dirty = drawable.getBounds();
9225 final int scrollX = mScrollX;
9226 final int scrollY = mScrollY;
9227
9228 invalidate(dirty.left + scrollX, dirty.top + scrollY,
9229 dirty.right + scrollX, dirty.bottom + scrollY);
9230 }
9231 }
9232
9233 /**
9234 * Schedules an action on a drawable to occur at a specified time.
9235 *
9236 * @param who the recipient of the action
9237 * @param what the action to run on the drawable
9238 * @param when the time at which the action must occur. Uses the
9239 * {@link SystemClock#uptimeMillis} timebase.
9240 */
9241 public void scheduleDrawable(Drawable who, Runnable what, long when) {
9242 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9243 mAttachInfo.mHandler.postAtTime(what, who, when);
9244 }
9245 }
9246
9247 /**
9248 * Cancels a scheduled action on a drawable.
9249 *
9250 * @param who the recipient of the action
9251 * @param what the action to cancel
9252 */
9253 public void unscheduleDrawable(Drawable who, Runnable what) {
9254 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9255 mAttachInfo.mHandler.removeCallbacks(what, who);
9256 }
9257 }
9258
9259 /**
9260 * Unschedule any events associated with the given Drawable. This can be
9261 * used when selecting a new Drawable into a view, so that the previous
9262 * one is completely unscheduled.
9263 *
9264 * @param who The Drawable to unschedule.
9265 *
9266 * @see #drawableStateChanged
9267 */
9268 public void unscheduleDrawable(Drawable who) {
9269 if (mAttachInfo != null) {
9270 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
9271 }
9272 }
9273
9274 /**
9275 * If your view subclass is displaying its own Drawable objects, it should
9276 * override this function and return true for any Drawable it is
9277 * displaying. This allows animations for those drawables to be
9278 * scheduled.
9279 *
9280 * <p>Be sure to call through to the super class when overriding this
9281 * function.
9282 *
9283 * @param who The Drawable to verify. Return true if it is one you are
9284 * displaying, else return the result of calling through to the
9285 * super class.
9286 *
9287 * @return boolean If true than the Drawable is being displayed in the
9288 * view; else false and it is not allowed to animate.
9289 *
9290 * @see #unscheduleDrawable
9291 * @see #drawableStateChanged
9292 */
9293 protected boolean verifyDrawable(Drawable who) {
9294 return who == mBGDrawable;
9295 }
9296
9297 /**
9298 * This function is called whenever the state of the view changes in such
9299 * a way that it impacts the state of drawables being shown.
9300 *
9301 * <p>Be sure to call through to the superclass when overriding this
9302 * function.
9303 *
9304 * @see Drawable#setState
9305 */
9306 protected void drawableStateChanged() {
9307 Drawable d = mBGDrawable;
9308 if (d != null && d.isStateful()) {
9309 d.setState(getDrawableState());
9310 }
9311 }
9312
9313 /**
9314 * Call this to force a view to update its drawable state. This will cause
9315 * drawableStateChanged to be called on this view. Views that are interested
9316 * in the new state should call getDrawableState.
9317 *
9318 * @see #drawableStateChanged
9319 * @see #getDrawableState
9320 */
9321 public void refreshDrawableState() {
9322 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9323 drawableStateChanged();
9324
9325 ViewParent parent = mParent;
9326 if (parent != null) {
9327 parent.childDrawableStateChanged(this);
9328 }
9329 }
9330
9331 /**
9332 * Return an array of resource IDs of the drawable states representing the
9333 * current state of the view.
9334 *
9335 * @return The current drawable state
9336 *
9337 * @see Drawable#setState
9338 * @see #drawableStateChanged
9339 * @see #onCreateDrawableState
9340 */
9341 public final int[] getDrawableState() {
9342 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
9343 return mDrawableState;
9344 } else {
9345 mDrawableState = onCreateDrawableState(0);
9346 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
9347 return mDrawableState;
9348 }
9349 }
9350
9351 /**
9352 * Generate the new {@link android.graphics.drawable.Drawable} state for
9353 * this view. This is called by the view
9354 * system when the cached Drawable state is determined to be invalid. To
9355 * retrieve the current state, you should use {@link #getDrawableState}.
9356 *
9357 * @param extraSpace if non-zero, this is the number of extra entries you
9358 * would like in the returned array in which you can place your own
9359 * states.
9360 *
9361 * @return Returns an array holding the current {@link Drawable} state of
9362 * the view.
9363 *
9364 * @see #mergeDrawableStates
9365 */
9366 protected int[] onCreateDrawableState(int extraSpace) {
9367 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
9368 mParent instanceof View) {
9369 return ((View) mParent).onCreateDrawableState(extraSpace);
9370 }
9371
9372 int[] drawableState;
9373
9374 int privateFlags = mPrivateFlags;
9375
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009376 int viewStateIndex = 0;
9377 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
9378 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
9379 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07009380 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009381 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
9382 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08009383 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
9384 // This is set if HW acceleration is requested, even if the current
9385 // process doesn't allow it. This is just to allow app preview
9386 // windows to better match their app.
9387 viewStateIndex |= VIEW_STATE_ACCELERATED;
9388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009389
9390 drawableState = VIEW_STATE_SETS[viewStateIndex];
9391
9392 //noinspection ConstantIfStatement
9393 if (false) {
9394 Log.i("View", "drawableStateIndex=" + viewStateIndex);
9395 Log.i("View", toString()
9396 + " pressed=" + ((privateFlags & PRESSED) != 0)
9397 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
9398 + " fo=" + hasFocus()
9399 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009400 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 + ": " + Arrays.toString(drawableState));
9402 }
9403
9404 if (extraSpace == 0) {
9405 return drawableState;
9406 }
9407
9408 final int[] fullState;
9409 if (drawableState != null) {
9410 fullState = new int[drawableState.length + extraSpace];
9411 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
9412 } else {
9413 fullState = new int[extraSpace];
9414 }
9415
9416 return fullState;
9417 }
9418
9419 /**
9420 * Merge your own state values in <var>additionalState</var> into the base
9421 * state values <var>baseState</var> that were returned by
9422 * {@link #onCreateDrawableState}.
9423 *
9424 * @param baseState The base state values returned by
9425 * {@link #onCreateDrawableState}, which will be modified to also hold your
9426 * own additional state values.
9427 *
9428 * @param additionalState The additional state values you would like
9429 * added to <var>baseState</var>; this array is not modified.
9430 *
9431 * @return As a convenience, the <var>baseState</var> array you originally
9432 * passed into the function is returned.
9433 *
9434 * @see #onCreateDrawableState
9435 */
9436 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
9437 final int N = baseState.length;
9438 int i = N - 1;
9439 while (i >= 0 && baseState[i] == 0) {
9440 i--;
9441 }
9442 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
9443 return baseState;
9444 }
9445
9446 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07009447 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
9448 * on all Drawable objects associated with this view.
9449 */
9450 public void jumpDrawablesToCurrentState() {
9451 if (mBGDrawable != null) {
9452 mBGDrawable.jumpToCurrentState();
9453 }
9454 }
9455
9456 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009457 * Sets the background color for this view.
9458 * @param color the color of the background
9459 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009460 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009461 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07009462 if (mBGDrawable instanceof ColorDrawable) {
9463 ((ColorDrawable) mBGDrawable).setColor(color);
9464 } else {
9465 setBackgroundDrawable(new ColorDrawable(color));
9466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009467 }
9468
9469 /**
9470 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07009471 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009472 * @param resid The identifier of the resource.
9473 * @attr ref android.R.styleable#View_background
9474 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009475 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476 public void setBackgroundResource(int resid) {
9477 if (resid != 0 && resid == mBackgroundResource) {
9478 return;
9479 }
9480
9481 Drawable d= null;
9482 if (resid != 0) {
9483 d = mResources.getDrawable(resid);
9484 }
9485 setBackgroundDrawable(d);
9486
9487 mBackgroundResource = resid;
9488 }
9489
9490 /**
9491 * Set the background to a given Drawable, or remove the background. If the
9492 * background has padding, this View's padding is set to the background's
9493 * padding. However, when a background is removed, this View's padding isn't
9494 * touched. If setting the padding is desired, please use
9495 * {@link #setPadding(int, int, int, int)}.
9496 *
9497 * @param d The Drawable to use as the background, or null to remove the
9498 * background
9499 */
9500 public void setBackgroundDrawable(Drawable d) {
9501 boolean requestLayout = false;
9502
9503 mBackgroundResource = 0;
9504
9505 /*
9506 * Regardless of whether we're setting a new background or not, we want
9507 * to clear the previous drawable.
9508 */
9509 if (mBGDrawable != null) {
9510 mBGDrawable.setCallback(null);
9511 unscheduleDrawable(mBGDrawable);
9512 }
9513
9514 if (d != null) {
9515 Rect padding = sThreadLocal.get();
9516 if (padding == null) {
9517 padding = new Rect();
9518 sThreadLocal.set(padding);
9519 }
9520 if (d.getPadding(padding)) {
9521 setPadding(padding.left, padding.top, padding.right, padding.bottom);
9522 }
9523
9524 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
9525 // if it has a different minimum size, we should layout again
9526 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9527 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9528 requestLayout = true;
9529 }
9530
9531 d.setCallback(this);
9532 if (d.isStateful()) {
9533 d.setState(getDrawableState());
9534 }
9535 d.setVisible(getVisibility() == VISIBLE, false);
9536 mBGDrawable = d;
9537
9538 if ((mPrivateFlags & SKIP_DRAW) != 0) {
9539 mPrivateFlags &= ~SKIP_DRAW;
9540 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9541 requestLayout = true;
9542 }
9543 } else {
9544 /* Remove the background */
9545 mBGDrawable = null;
9546
9547 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9548 /*
9549 * This view ONLY drew the background before and we're removing
9550 * the background, so now it won't draw anything
9551 * (hence we SKIP_DRAW)
9552 */
9553 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9554 mPrivateFlags |= SKIP_DRAW;
9555 }
9556
9557 /*
9558 * When the background is set, we try to apply its padding to this
9559 * View. When the background is removed, we don't touch this View's
9560 * padding. This is noted in the Javadocs. Hence, we don't need to
9561 * requestLayout(), the invalidate() below is sufficient.
9562 */
9563
9564 // The old background's minimum size could have affected this
9565 // View's layout, so let's requestLayout
9566 requestLayout = true;
9567 }
9568
Romain Guy8f1344f52009-05-15 16:03:59 -07009569 computeOpaqueFlags();
9570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009571 if (requestLayout) {
9572 requestLayout();
9573 }
9574
9575 mBackgroundSizeChanged = true;
9576 invalidate();
9577 }
9578
9579 /**
9580 * Gets the background drawable
9581 * @return The drawable used as the background for this view, if any.
9582 */
9583 public Drawable getBackground() {
9584 return mBGDrawable;
9585 }
9586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009587 /**
9588 * Sets the padding. The view may add on the space required to display
9589 * the scrollbars, depending on the style and visibility of the scrollbars.
9590 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9591 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9592 * from the values set in this call.
9593 *
9594 * @attr ref android.R.styleable#View_padding
9595 * @attr ref android.R.styleable#View_paddingBottom
9596 * @attr ref android.R.styleable#View_paddingLeft
9597 * @attr ref android.R.styleable#View_paddingRight
9598 * @attr ref android.R.styleable#View_paddingTop
9599 * @param left the left padding in pixels
9600 * @param top the top padding in pixels
9601 * @param right the right padding in pixels
9602 * @param bottom the bottom padding in pixels
9603 */
9604 public void setPadding(int left, int top, int right, int bottom) {
9605 boolean changed = false;
9606
Adam Powell20232d02010-12-08 21:08:53 -08009607 mUserPaddingLeft = left;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009608 mUserPaddingRight = right;
9609 mUserPaddingBottom = bottom;
9610
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009611 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07009612
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009613 // Common case is there are no scroll bars.
9614 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009615 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
Adam Powell20232d02010-12-08 21:08:53 -08009616 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9617 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009618 ? 0 : getVerticalScrollbarWidth();
Adam Powell20232d02010-12-08 21:08:53 -08009619 switch (mVerticalScrollbarPosition) {
9620 case SCROLLBAR_POSITION_DEFAULT:
9621 case SCROLLBAR_POSITION_RIGHT:
9622 right += offset;
9623 break;
9624 case SCROLLBAR_POSITION_LEFT:
9625 left += offset;
9626 break;
9627 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009628 }
Adam Powell20232d02010-12-08 21:08:53 -08009629 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009630 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9631 ? 0 : getHorizontalScrollbarHeight();
9632 }
9633 }
Romain Guy8506ab42009-06-11 17:35:47 -07009634
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009635 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009636 changed = true;
9637 mPaddingLeft = left;
9638 }
9639 if (mPaddingTop != top) {
9640 changed = true;
9641 mPaddingTop = top;
9642 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009643 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009644 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009645 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009646 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009647 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009648 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009649 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009650 }
9651
9652 if (changed) {
9653 requestLayout();
9654 }
9655 }
9656
9657 /**
9658 * Returns the top padding of this view.
9659 *
9660 * @return the top padding in pixels
9661 */
9662 public int getPaddingTop() {
9663 return mPaddingTop;
9664 }
9665
9666 /**
9667 * Returns the bottom padding of this view. If there are inset and enabled
9668 * scrollbars, this value may include the space required to display the
9669 * scrollbars as well.
9670 *
9671 * @return the bottom padding in pixels
9672 */
9673 public int getPaddingBottom() {
9674 return mPaddingBottom;
9675 }
9676
9677 /**
9678 * Returns the left padding of this view. If there are inset and enabled
9679 * scrollbars, this value may include the space required to display the
9680 * scrollbars as well.
9681 *
9682 * @return the left padding in pixels
9683 */
9684 public int getPaddingLeft() {
9685 return mPaddingLeft;
9686 }
9687
9688 /**
9689 * Returns the right padding of this view. If there are inset and enabled
9690 * scrollbars, this value may include the space required to display the
9691 * scrollbars as well.
9692 *
9693 * @return the right padding in pixels
9694 */
9695 public int getPaddingRight() {
9696 return mPaddingRight;
9697 }
9698
9699 /**
9700 * Changes the selection state of this view. A view can be selected or not.
9701 * Note that selection is not the same as focus. Views are typically
9702 * selected in the context of an AdapterView like ListView or GridView;
9703 * the selected view is the view that is highlighted.
9704 *
9705 * @param selected true if the view must be selected, false otherwise
9706 */
9707 public void setSelected(boolean selected) {
9708 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9709 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009710 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009711 invalidate();
9712 refreshDrawableState();
9713 dispatchSetSelected(selected);
9714 }
9715 }
9716
9717 /**
9718 * Dispatch setSelected to all of this View's children.
9719 *
9720 * @see #setSelected(boolean)
9721 *
9722 * @param selected The new selected state
9723 */
9724 protected void dispatchSetSelected(boolean selected) {
9725 }
9726
9727 /**
9728 * Indicates the selection state of this view.
9729 *
9730 * @return true if the view is selected, false otherwise
9731 */
9732 @ViewDebug.ExportedProperty
9733 public boolean isSelected() {
9734 return (mPrivateFlags & SELECTED) != 0;
9735 }
9736
9737 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009738 * Changes the activated state of this view. A view can be activated or not.
9739 * Note that activation is not the same as selection. Selection is
9740 * a transient property, representing the view (hierarchy) the user is
9741 * currently interacting with. Activation is a longer-term state that the
9742 * user can move views in and out of. For example, in a list view with
9743 * single or multiple selection enabled, the views in the current selection
9744 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9745 * here.) The activated state is propagated down to children of the view it
9746 * is set on.
9747 *
9748 * @param activated true if the view must be activated, false otherwise
9749 */
9750 public void setActivated(boolean activated) {
9751 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9752 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
9753 invalidate();
9754 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009755 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009756 }
9757 }
9758
9759 /**
9760 * Dispatch setActivated to all of this View's children.
9761 *
9762 * @see #setActivated(boolean)
9763 *
9764 * @param activated The new activated state
9765 */
9766 protected void dispatchSetActivated(boolean activated) {
9767 }
9768
9769 /**
9770 * Indicates the activation state of this view.
9771 *
9772 * @return true if the view is activated, false otherwise
9773 */
9774 @ViewDebug.ExportedProperty
9775 public boolean isActivated() {
9776 return (mPrivateFlags & ACTIVATED) != 0;
9777 }
9778
9779 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009780 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9781 * observer can be used to get notifications when global events, like
9782 * layout, happen.
9783 *
9784 * The returned ViewTreeObserver observer is not guaranteed to remain
9785 * valid for the lifetime of this View. If the caller of this method keeps
9786 * a long-lived reference to ViewTreeObserver, it should always check for
9787 * the return value of {@link ViewTreeObserver#isAlive()}.
9788 *
9789 * @return The ViewTreeObserver for this view's hierarchy.
9790 */
9791 public ViewTreeObserver getViewTreeObserver() {
9792 if (mAttachInfo != null) {
9793 return mAttachInfo.mTreeObserver;
9794 }
9795 if (mFloatingTreeObserver == null) {
9796 mFloatingTreeObserver = new ViewTreeObserver();
9797 }
9798 return mFloatingTreeObserver;
9799 }
9800
9801 /**
9802 * <p>Finds the topmost view in the current view hierarchy.</p>
9803 *
9804 * @return the topmost view containing this view
9805 */
9806 public View getRootView() {
9807 if (mAttachInfo != null) {
9808 final View v = mAttachInfo.mRootView;
9809 if (v != null) {
9810 return v;
9811 }
9812 }
Romain Guy8506ab42009-06-11 17:35:47 -07009813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009814 View parent = this;
9815
9816 while (parent.mParent != null && parent.mParent instanceof View) {
9817 parent = (View) parent.mParent;
9818 }
9819
9820 return parent;
9821 }
9822
9823 /**
9824 * <p>Computes the coordinates of this view on the screen. The argument
9825 * must be an array of two integers. After the method returns, the array
9826 * contains the x and y location in that order.</p>
9827 *
9828 * @param location an array of two integers in which to hold the coordinates
9829 */
9830 public void getLocationOnScreen(int[] location) {
9831 getLocationInWindow(location);
9832
9833 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009834 if (info != null) {
9835 location[0] += info.mWindowLeft;
9836 location[1] += info.mWindowTop;
9837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009838 }
9839
9840 /**
9841 * <p>Computes the coordinates of this view in its window. The argument
9842 * must be an array of two integers. After the method returns, the array
9843 * contains the x and y location in that order.</p>
9844 *
9845 * @param location an array of two integers in which to hold the coordinates
9846 */
9847 public void getLocationInWindow(int[] location) {
9848 if (location == null || location.length < 2) {
9849 throw new IllegalArgumentException("location must be an array of "
9850 + "two integers");
9851 }
9852
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009853 location[0] = mLeft + (int) (mTranslationX + 0.5f);
9854 location[1] = mTop + (int) (mTranslationY + 0.5f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009855
9856 ViewParent viewParent = mParent;
9857 while (viewParent instanceof View) {
9858 final View view = (View)viewParent;
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009859 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
9860 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009861 viewParent = view.mParent;
9862 }
Romain Guy8506ab42009-06-11 17:35:47 -07009863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009864 if (viewParent instanceof ViewRoot) {
9865 // *cough*
9866 final ViewRoot vr = (ViewRoot)viewParent;
9867 location[1] -= vr.mCurScrollY;
9868 }
9869 }
9870
9871 /**
9872 * {@hide}
9873 * @param id the id of the view to be found
9874 * @return the view of the specified id, null if cannot be found
9875 */
9876 protected View findViewTraversal(int id) {
9877 if (id == mID) {
9878 return this;
9879 }
9880 return null;
9881 }
9882
9883 /**
9884 * {@hide}
9885 * @param tag the tag of the view to be found
9886 * @return the view of specified tag, null if cannot be found
9887 */
9888 protected View findViewWithTagTraversal(Object tag) {
9889 if (tag != null && tag.equals(mTag)) {
9890 return this;
9891 }
9892 return null;
9893 }
9894
9895 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009896 * {@hide}
9897 * @param predicate The predicate to evaluate.
9898 * @return The first view that matches the predicate or null.
9899 */
9900 protected View findViewByPredicateTraversal(Predicate<View> predicate) {
9901 if (predicate.apply(this)) {
9902 return this;
9903 }
9904 return null;
9905 }
9906
9907 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009908 * Look for a child view with the given id. If this view has the given
9909 * id, return this view.
9910 *
9911 * @param id The id to search for.
9912 * @return The view that has the given id in the hierarchy or null
9913 */
9914 public final View findViewById(int id) {
9915 if (id < 0) {
9916 return null;
9917 }
9918 return findViewTraversal(id);
9919 }
9920
9921 /**
9922 * Look for a child view with the given tag. If this view has the given
9923 * tag, return this view.
9924 *
9925 * @param tag The tag to search for, using "tag.equals(getTag())".
9926 * @return The View that has the given tag in the hierarchy or null
9927 */
9928 public final View findViewWithTag(Object tag) {
9929 if (tag == null) {
9930 return null;
9931 }
9932 return findViewWithTagTraversal(tag);
9933 }
9934
9935 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009936 * {@hide}
9937 * Look for a child view that matches the specified predicate.
9938 * If this view matches the predicate, return this view.
9939 *
9940 * @param predicate The predicate to evaluate.
9941 * @return The first view that matches the predicate or null.
9942 */
9943 public final View findViewByPredicate(Predicate<View> predicate) {
9944 return findViewByPredicateTraversal(predicate);
9945 }
9946
9947 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009948 * Sets the identifier for this view. The identifier does not have to be
9949 * unique in this view's hierarchy. The identifier should be a positive
9950 * number.
9951 *
9952 * @see #NO_ID
9953 * @see #getId
9954 * @see #findViewById
9955 *
9956 * @param id a number used to identify the view
9957 *
9958 * @attr ref android.R.styleable#View_id
9959 */
9960 public void setId(int id) {
9961 mID = id;
9962 }
9963
9964 /**
9965 * {@hide}
9966 *
9967 * @param isRoot true if the view belongs to the root namespace, false
9968 * otherwise
9969 */
9970 public void setIsRootNamespace(boolean isRoot) {
9971 if (isRoot) {
9972 mPrivateFlags |= IS_ROOT_NAMESPACE;
9973 } else {
9974 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9975 }
9976 }
9977
9978 /**
9979 * {@hide}
9980 *
9981 * @return true if the view belongs to the root namespace, false otherwise
9982 */
9983 public boolean isRootNamespace() {
9984 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9985 }
9986
9987 /**
9988 * Returns this view's identifier.
9989 *
9990 * @return a positive integer used to identify the view or {@link #NO_ID}
9991 * if the view has no ID
9992 *
9993 * @see #setId
9994 * @see #findViewById
9995 * @attr ref android.R.styleable#View_id
9996 */
9997 @ViewDebug.CapturedViewProperty
9998 public int getId() {
9999 return mID;
10000 }
10001
10002 /**
10003 * Returns this view's tag.
10004 *
10005 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -070010006 *
10007 * @see #setTag(Object)
10008 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010009 */
10010 @ViewDebug.ExportedProperty
10011 public Object getTag() {
10012 return mTag;
10013 }
10014
10015 /**
10016 * Sets the tag associated with this view. A tag can be used to mark
10017 * a view in its hierarchy and does not have to be unique within the
10018 * hierarchy. Tags can also be used to store data within a view without
10019 * resorting to another data structure.
10020 *
10021 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -070010022 *
10023 * @see #getTag()
10024 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010025 */
10026 public void setTag(final Object tag) {
10027 mTag = tag;
10028 }
10029
10030 /**
Romain Guyd90a3312009-05-06 14:54:28 -070010031 * Returns the tag associated with this view and the specified key.
10032 *
10033 * @param key The key identifying the tag
10034 *
10035 * @return the Object stored in this view as a tag
10036 *
10037 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -070010038 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -070010039 */
10040 public Object getTag(int key) {
10041 SparseArray<Object> tags = null;
10042 synchronized (sTagsLock) {
10043 if (sTags != null) {
10044 tags = sTags.get(this);
10045 }
10046 }
10047
10048 if (tags != null) return tags.get(key);
10049 return null;
10050 }
10051
10052 /**
10053 * Sets a tag associated with this view and a key. A tag can be used
10054 * to mark a view in its hierarchy and does not have to be unique within
10055 * the hierarchy. Tags can also be used to store data within a view
10056 * without resorting to another data structure.
10057 *
10058 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -070010059 * application to ensure it is unique (see the <a
10060 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
10061 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -070010062 * the Android framework or not associated with any package will cause
10063 * an {@link IllegalArgumentException} to be thrown.
10064 *
10065 * @param key The key identifying the tag
10066 * @param tag An Object to tag the view with
10067 *
10068 * @throws IllegalArgumentException If they specified key is not valid
10069 *
10070 * @see #setTag(Object)
10071 * @see #getTag(int)
10072 */
10073 public void setTag(int key, final Object tag) {
10074 // If the package id is 0x00 or 0x01, it's either an undefined package
10075 // or a framework id
10076 if ((key >>> 24) < 2) {
10077 throw new IllegalArgumentException("The key must be an application-specific "
10078 + "resource id.");
10079 }
10080
10081 setTagInternal(this, key, tag);
10082 }
10083
10084 /**
10085 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
10086 * framework id.
10087 *
10088 * @hide
10089 */
10090 public void setTagInternal(int key, Object tag) {
10091 if ((key >>> 24) != 0x1) {
10092 throw new IllegalArgumentException("The key must be a framework-specific "
10093 + "resource id.");
10094 }
10095
Romain Guy8506ab42009-06-11 17:35:47 -070010096 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -070010097 }
10098
10099 private static void setTagInternal(View view, int key, Object tag) {
10100 SparseArray<Object> tags = null;
10101 synchronized (sTagsLock) {
10102 if (sTags == null) {
10103 sTags = new WeakHashMap<View, SparseArray<Object>>();
10104 } else {
10105 tags = sTags.get(view);
10106 }
10107 }
10108
10109 if (tags == null) {
10110 tags = new SparseArray<Object>(2);
10111 synchronized (sTagsLock) {
10112 sTags.put(view, tags);
10113 }
10114 }
10115
10116 tags.put(key, tag);
10117 }
10118
10119 /**
Romain Guy13922e02009-05-12 17:56:14 -070010120 * @param consistency The type of consistency. See ViewDebug for more information.
10121 *
10122 * @hide
10123 */
10124 protected boolean dispatchConsistencyCheck(int consistency) {
10125 return onConsistencyCheck(consistency);
10126 }
10127
10128 /**
10129 * Method that subclasses should implement to check their consistency. The type of
10130 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -070010131 *
Romain Guy13922e02009-05-12 17:56:14 -070010132 * @param consistency The type of consistency. See ViewDebug for more information.
10133 *
10134 * @throws IllegalStateException if the view is in an inconsistent state.
10135 *
10136 * @hide
10137 */
10138 protected boolean onConsistencyCheck(int consistency) {
10139 boolean result = true;
10140
10141 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
10142 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
10143
10144 if (checkLayout) {
10145 if (getParent() == null) {
10146 result = false;
10147 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10148 "View " + this + " does not have a parent.");
10149 }
10150
10151 if (mAttachInfo == null) {
10152 result = false;
10153 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10154 "View " + this + " is not attached to a window.");
10155 }
10156 }
10157
10158 if (checkDrawing) {
10159 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
10160 // from their draw() method
10161
10162 if ((mPrivateFlags & DRAWN) != DRAWN &&
10163 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
10164 result = false;
10165 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10166 "View " + this + " was invalidated but its drawing cache is valid.");
10167 }
10168 }
10169
10170 return result;
10171 }
10172
10173 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010174 * Prints information about this view in the log output, with the tag
10175 * {@link #VIEW_LOG_TAG}.
10176 *
10177 * @hide
10178 */
10179 public void debug() {
10180 debug(0);
10181 }
10182
10183 /**
10184 * Prints information about this view in the log output, with the tag
10185 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
10186 * indentation defined by the <code>depth</code>.
10187 *
10188 * @param depth the indentation level
10189 *
10190 * @hide
10191 */
10192 protected void debug(int depth) {
10193 String output = debugIndent(depth - 1);
10194
10195 output += "+ " + this;
10196 int id = getId();
10197 if (id != -1) {
10198 output += " (id=" + id + ")";
10199 }
10200 Object tag = getTag();
10201 if (tag != null) {
10202 output += " (tag=" + tag + ")";
10203 }
10204 Log.d(VIEW_LOG_TAG, output);
10205
10206 if ((mPrivateFlags & FOCUSED) != 0) {
10207 output = debugIndent(depth) + " FOCUSED";
10208 Log.d(VIEW_LOG_TAG, output);
10209 }
10210
10211 output = debugIndent(depth);
10212 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
10213 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
10214 + "} ";
10215 Log.d(VIEW_LOG_TAG, output);
10216
10217 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
10218 || mPaddingBottom != 0) {
10219 output = debugIndent(depth);
10220 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
10221 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
10222 Log.d(VIEW_LOG_TAG, output);
10223 }
10224
10225 output = debugIndent(depth);
10226 output += "mMeasureWidth=" + mMeasuredWidth +
10227 " mMeasureHeight=" + mMeasuredHeight;
10228 Log.d(VIEW_LOG_TAG, output);
10229
10230 output = debugIndent(depth);
10231 if (mLayoutParams == null) {
10232 output += "BAD! no layout params";
10233 } else {
10234 output = mLayoutParams.debug(output);
10235 }
10236 Log.d(VIEW_LOG_TAG, output);
10237
10238 output = debugIndent(depth);
10239 output += "flags={";
10240 output += View.printFlags(mViewFlags);
10241 output += "}";
10242 Log.d(VIEW_LOG_TAG, output);
10243
10244 output = debugIndent(depth);
10245 output += "privateFlags={";
10246 output += View.printPrivateFlags(mPrivateFlags);
10247 output += "}";
10248 Log.d(VIEW_LOG_TAG, output);
10249 }
10250
10251 /**
10252 * Creates an string of whitespaces used for indentation.
10253 *
10254 * @param depth the indentation level
10255 * @return a String containing (depth * 2 + 3) * 2 white spaces
10256 *
10257 * @hide
10258 */
10259 protected static String debugIndent(int depth) {
10260 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
10261 for (int i = 0; i < (depth * 2) + 3; i++) {
10262 spaces.append(' ').append(' ');
10263 }
10264 return spaces.toString();
10265 }
10266
10267 /**
10268 * <p>Return the offset of the widget's text baseline from the widget's top
10269 * boundary. If this widget does not support baseline alignment, this
10270 * method returns -1. </p>
10271 *
10272 * @return the offset of the baseline within the widget's bounds or -1
10273 * if baseline alignment is not supported
10274 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -070010275 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010276 public int getBaseline() {
10277 return -1;
10278 }
10279
10280 /**
10281 * Call this when something has changed which has invalidated the
10282 * layout of this view. This will schedule a layout pass of the view
10283 * tree.
10284 */
10285 public void requestLayout() {
10286 if (ViewDebug.TRACE_HIERARCHY) {
10287 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
10288 }
10289
10290 mPrivateFlags |= FORCE_LAYOUT;
10291
10292 if (mParent != null && !mParent.isLayoutRequested()) {
10293 mParent.requestLayout();
10294 }
10295 }
10296
10297 /**
10298 * Forces this view to be laid out during the next layout pass.
10299 * This method does not call requestLayout() or forceLayout()
10300 * on the parent.
10301 */
10302 public void forceLayout() {
10303 mPrivateFlags |= FORCE_LAYOUT;
10304 }
10305
10306 /**
10307 * <p>
10308 * This is called to find out how big a view should be. The parent
10309 * supplies constraint information in the width and height parameters.
10310 * </p>
10311 *
10312 * <p>
10313 * The actual mesurement work of a view is performed in
10314 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
10315 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
10316 * </p>
10317 *
10318 *
10319 * @param widthMeasureSpec Horizontal space requirements as imposed by the
10320 * parent
10321 * @param heightMeasureSpec Vertical space requirements as imposed by the
10322 * parent
10323 *
10324 * @see #onMeasure(int, int)
10325 */
10326 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
10327 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
10328 widthMeasureSpec != mOldWidthMeasureSpec ||
10329 heightMeasureSpec != mOldHeightMeasureSpec) {
10330
10331 // first clears the measured dimension flag
10332 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
10333
10334 if (ViewDebug.TRACE_HIERARCHY) {
10335 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
10336 }
10337
10338 // measure ourselves, this should set the measured dimension flag back
10339 onMeasure(widthMeasureSpec, heightMeasureSpec);
10340
10341 // flag not set, setMeasuredDimension() was not invoked, we raise
10342 // an exception to warn the developer
10343 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
10344 throw new IllegalStateException("onMeasure() did not set the"
10345 + " measured dimension by calling"
10346 + " setMeasuredDimension()");
10347 }
10348
10349 mPrivateFlags |= LAYOUT_REQUIRED;
10350 }
10351
10352 mOldWidthMeasureSpec = widthMeasureSpec;
10353 mOldHeightMeasureSpec = heightMeasureSpec;
10354 }
10355
10356 /**
10357 * <p>
10358 * Measure the view and its content to determine the measured width and the
10359 * measured height. This method is invoked by {@link #measure(int, int)} and
10360 * should be overriden by subclasses to provide accurate and efficient
10361 * measurement of their contents.
10362 * </p>
10363 *
10364 * <p>
10365 * <strong>CONTRACT:</strong> When overriding this method, you
10366 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
10367 * measured width and height of this view. Failure to do so will trigger an
10368 * <code>IllegalStateException</code>, thrown by
10369 * {@link #measure(int, int)}. Calling the superclass'
10370 * {@link #onMeasure(int, int)} is a valid use.
10371 * </p>
10372 *
10373 * <p>
10374 * The base class implementation of measure defaults to the background size,
10375 * unless a larger size is allowed by the MeasureSpec. Subclasses should
10376 * override {@link #onMeasure(int, int)} to provide better measurements of
10377 * their content.
10378 * </p>
10379 *
10380 * <p>
10381 * If this method is overridden, it is the subclass's responsibility to make
10382 * sure the measured height and width are at least the view's minimum height
10383 * and width ({@link #getSuggestedMinimumHeight()} and
10384 * {@link #getSuggestedMinimumWidth()}).
10385 * </p>
10386 *
10387 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
10388 * The requirements are encoded with
10389 * {@link android.view.View.MeasureSpec}.
10390 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
10391 * The requirements are encoded with
10392 * {@link android.view.View.MeasureSpec}.
10393 *
10394 * @see #getMeasuredWidth()
10395 * @see #getMeasuredHeight()
10396 * @see #setMeasuredDimension(int, int)
10397 * @see #getSuggestedMinimumHeight()
10398 * @see #getSuggestedMinimumWidth()
10399 * @see android.view.View.MeasureSpec#getMode(int)
10400 * @see android.view.View.MeasureSpec#getSize(int)
10401 */
10402 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10403 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
10404 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
10405 }
10406
10407 /**
10408 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
10409 * measured width and measured height. Failing to do so will trigger an
10410 * exception at measurement time.</p>
10411 *
Dianne Hackborn189ee182010-12-02 21:48:53 -080010412 * @param measuredWidth The measured width of this view. May be a complex
10413 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10414 * {@link #MEASURED_STATE_TOO_SMALL}.
10415 * @param measuredHeight The measured height of this view. May be a complex
10416 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10417 * {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010418 */
10419 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
10420 mMeasuredWidth = measuredWidth;
10421 mMeasuredHeight = measuredHeight;
10422
10423 mPrivateFlags |= MEASURED_DIMENSION_SET;
10424 }
10425
10426 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -080010427 * Merge two states as returned by {@link #getMeasuredState()}.
10428 * @param curState The current state as returned from a view or the result
10429 * of combining multiple views.
10430 * @param newState The new view state to combine.
10431 * @return Returns a new integer reflecting the combination of the two
10432 * states.
10433 */
10434 public static int combineMeasuredStates(int curState, int newState) {
10435 return curState | newState;
10436 }
10437
10438 /**
10439 * Version of {@link #resolveSizeAndState(int, int, int)}
10440 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
10441 */
10442 public static int resolveSize(int size, int measureSpec) {
10443 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
10444 }
10445
10446 /**
10447 * Utility to reconcile a desired size and state, with constraints imposed
10448 * by a MeasureSpec. Will take the desired size, unless a different size
10449 * is imposed by the constraints. The returned value is a compound integer,
10450 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
10451 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
10452 * size is smaller than the size the view wants to be.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010453 *
10454 * @param size How big the view wants to be
10455 * @param measureSpec Constraints imposed by the parent
Dianne Hackborn189ee182010-12-02 21:48:53 -080010456 * @return Size information bit mask as defined by
10457 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010458 */
Dianne Hackborn189ee182010-12-02 21:48:53 -080010459 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010460 int result = size;
10461 int specMode = MeasureSpec.getMode(measureSpec);
10462 int specSize = MeasureSpec.getSize(measureSpec);
10463 switch (specMode) {
10464 case MeasureSpec.UNSPECIFIED:
10465 result = size;
10466 break;
10467 case MeasureSpec.AT_MOST:
Dianne Hackborn189ee182010-12-02 21:48:53 -080010468 if (specSize < size) {
10469 result = specSize | MEASURED_STATE_TOO_SMALL;
10470 } else {
10471 result = size;
10472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010473 break;
10474 case MeasureSpec.EXACTLY:
10475 result = specSize;
10476 break;
10477 }
Dianne Hackborn189ee182010-12-02 21:48:53 -080010478 return result | (childMeasuredState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010479 }
10480
10481 /**
10482 * Utility to return a default size. Uses the supplied size if the
10483 * MeasureSpec imposed no contraints. Will get larger if allowed
10484 * by the MeasureSpec.
10485 *
10486 * @param size Default size for this view
10487 * @param measureSpec Constraints imposed by the parent
10488 * @return The size this view should be.
10489 */
10490 public static int getDefaultSize(int size, int measureSpec) {
10491 int result = size;
10492 int specMode = MeasureSpec.getMode(measureSpec);
10493 int specSize = MeasureSpec.getSize(measureSpec);
10494
10495 switch (specMode) {
10496 case MeasureSpec.UNSPECIFIED:
10497 result = size;
10498 break;
10499 case MeasureSpec.AT_MOST:
10500 case MeasureSpec.EXACTLY:
10501 result = specSize;
10502 break;
10503 }
10504 return result;
10505 }
10506
10507 /**
10508 * Returns the suggested minimum height that the view should use. This
10509 * returns the maximum of the view's minimum height
10510 * and the background's minimum height
10511 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10512 * <p>
10513 * When being used in {@link #onMeasure(int, int)}, the caller should still
10514 * ensure the returned height is within the requirements of the parent.
10515 *
10516 * @return The suggested minimum height of the view.
10517 */
10518 protected int getSuggestedMinimumHeight() {
10519 int suggestedMinHeight = mMinHeight;
10520
10521 if (mBGDrawable != null) {
10522 final int bgMinHeight = mBGDrawable.getMinimumHeight();
10523 if (suggestedMinHeight < bgMinHeight) {
10524 suggestedMinHeight = bgMinHeight;
10525 }
10526 }
10527
10528 return suggestedMinHeight;
10529 }
10530
10531 /**
10532 * Returns the suggested minimum width that the view should use. This
10533 * returns the maximum of the view's minimum width)
10534 * and the background's minimum width
10535 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10536 * <p>
10537 * When being used in {@link #onMeasure(int, int)}, the caller should still
10538 * ensure the returned width is within the requirements of the parent.
10539 *
10540 * @return The suggested minimum width of the view.
10541 */
10542 protected int getSuggestedMinimumWidth() {
10543 int suggestedMinWidth = mMinWidth;
10544
10545 if (mBGDrawable != null) {
10546 final int bgMinWidth = mBGDrawable.getMinimumWidth();
10547 if (suggestedMinWidth < bgMinWidth) {
10548 suggestedMinWidth = bgMinWidth;
10549 }
10550 }
10551
10552 return suggestedMinWidth;
10553 }
10554
10555 /**
10556 * Sets the minimum height of the view. It is not guaranteed the view will
10557 * be able to achieve this minimum height (for example, if its parent layout
10558 * constrains it with less available height).
10559 *
10560 * @param minHeight The minimum height the view will try to be.
10561 */
10562 public void setMinimumHeight(int minHeight) {
10563 mMinHeight = minHeight;
10564 }
10565
10566 /**
10567 * Sets the minimum width of the view. It is not guaranteed the view will
10568 * be able to achieve this minimum width (for example, if its parent layout
10569 * constrains it with less available width).
10570 *
10571 * @param minWidth The minimum width the view will try to be.
10572 */
10573 public void setMinimumWidth(int minWidth) {
10574 mMinWidth = minWidth;
10575 }
10576
10577 /**
10578 * Get the animation currently associated with this view.
10579 *
10580 * @return The animation that is currently playing or
10581 * scheduled to play for this view.
10582 */
10583 public Animation getAnimation() {
10584 return mCurrentAnimation;
10585 }
10586
10587 /**
10588 * Start the specified animation now.
10589 *
10590 * @param animation the animation to start now
10591 */
10592 public void startAnimation(Animation animation) {
10593 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10594 setAnimation(animation);
10595 invalidate();
Chet Haasedaf98e92011-01-10 14:10:36 -080010596 invalidateParentIfAccelerated();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010597 }
10598
10599 /**
10600 * Cancels any animations for this view.
10601 */
10602 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -080010603 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -080010604 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -080010605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010606 mCurrentAnimation = null;
Chet Haasedaf98e92011-01-10 14:10:36 -080010607 invalidateParentIfAccelerated();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010608 }
10609
10610 /**
10611 * Sets the next animation to play for this view.
10612 * If you want the animation to play immediately, use
10613 * startAnimation. This method provides allows fine-grained
10614 * control over the start time and invalidation, but you
10615 * must make sure that 1) the animation has a start time set, and
10616 * 2) the view will be invalidated when the animation is supposed to
10617 * start.
10618 *
10619 * @param animation The next animation, or null.
10620 */
10621 public void setAnimation(Animation animation) {
10622 mCurrentAnimation = animation;
10623 if (animation != null) {
10624 animation.reset();
10625 }
10626 }
10627
10628 /**
10629 * Invoked by a parent ViewGroup to notify the start of the animation
10630 * currently associated with this view. If you override this method,
10631 * always call super.onAnimationStart();
10632 *
10633 * @see #setAnimation(android.view.animation.Animation)
10634 * @see #getAnimation()
10635 */
10636 protected void onAnimationStart() {
10637 mPrivateFlags |= ANIMATION_STARTED;
10638 }
10639
10640 /**
10641 * Invoked by a parent ViewGroup to notify the end of the animation
10642 * currently associated with this view. If you override this method,
10643 * always call super.onAnimationEnd();
10644 *
10645 * @see #setAnimation(android.view.animation.Animation)
10646 * @see #getAnimation()
10647 */
10648 protected void onAnimationEnd() {
10649 mPrivateFlags &= ~ANIMATION_STARTED;
10650 }
10651
10652 /**
10653 * Invoked if there is a Transform that involves alpha. Subclass that can
10654 * draw themselves with the specified alpha should return true, and then
10655 * respect that alpha when their onDraw() is called. If this returns false
10656 * then the view may be redirected to draw into an offscreen buffer to
10657 * fulfill the request, which will look fine, but may be slower than if the
10658 * subclass handles it internally. The default implementation returns false.
10659 *
10660 * @param alpha The alpha (0..255) to apply to the view's drawing
10661 * @return true if the view can draw with the specified alpha.
10662 */
10663 protected boolean onSetAlpha(int alpha) {
10664 return false;
10665 }
10666
10667 /**
10668 * This is used by the RootView to perform an optimization when
10669 * the view hierarchy contains one or several SurfaceView.
10670 * SurfaceView is always considered transparent, but its children are not,
10671 * therefore all View objects remove themselves from the global transparent
10672 * region (passed as a parameter to this function).
10673 *
10674 * @param region The transparent region for this ViewRoot (window).
10675 *
10676 * @return Returns true if the effective visibility of the view at this
10677 * point is opaque, regardless of the transparent region; returns false
10678 * if it is possible for underlying windows to be seen behind the view.
10679 *
10680 * {@hide}
10681 */
10682 public boolean gatherTransparentRegion(Region region) {
10683 final AttachInfo attachInfo = mAttachInfo;
10684 if (region != null && attachInfo != null) {
10685 final int pflags = mPrivateFlags;
10686 if ((pflags & SKIP_DRAW) == 0) {
10687 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10688 // remove it from the transparent region.
10689 final int[] location = attachInfo.mTransparentLocation;
10690 getLocationInWindow(location);
10691 region.op(location[0], location[1], location[0] + mRight - mLeft,
10692 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10693 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10694 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10695 // exists, so we remove the background drawable's non-transparent
10696 // parts from this transparent region.
10697 applyDrawableToTransparentRegion(mBGDrawable, region);
10698 }
10699 }
10700 return true;
10701 }
10702
10703 /**
10704 * Play a sound effect for this view.
10705 *
10706 * <p>The framework will play sound effects for some built in actions, such as
10707 * clicking, but you may wish to play these effects in your widget,
10708 * for instance, for internal navigation.
10709 *
10710 * <p>The sound effect will only be played if sound effects are enabled by the user, and
10711 * {@link #isSoundEffectsEnabled()} is true.
10712 *
10713 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10714 */
10715 public void playSoundEffect(int soundConstant) {
10716 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10717 return;
10718 }
10719 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10720 }
10721
10722 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010723 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010724 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010725 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010726 *
10727 * <p>The framework will provide haptic feedback for some built in actions,
10728 * such as long presses, but you may wish to provide feedback for your
10729 * own widget.
10730 *
10731 * <p>The feedback will only be performed if
10732 * {@link #isHapticFeedbackEnabled()} is true.
10733 *
10734 * @param feedbackConstant One of the constants defined in
10735 * {@link HapticFeedbackConstants}
10736 */
10737 public boolean performHapticFeedback(int feedbackConstant) {
10738 return performHapticFeedback(feedbackConstant, 0);
10739 }
10740
10741 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010742 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010743 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010744 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010745 *
10746 * @param feedbackConstant One of the constants defined in
10747 * {@link HapticFeedbackConstants}
10748 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10749 */
10750 public boolean performHapticFeedback(int feedbackConstant, int flags) {
10751 if (mAttachInfo == null) {
10752 return false;
10753 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010754 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010755 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010756 && !isHapticFeedbackEnabled()) {
10757 return false;
10758 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010759 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10760 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010761 }
10762
10763 /**
Joe Onorato664644d2011-01-23 17:53:23 -080010764 * Request that the visibility of the status bar be changed.
10765 */
10766 public void setSystemUiVisibility(int visibility) {
10767 if (visibility != mSystemUiVisibility) {
10768 mSystemUiVisibility = visibility;
10769 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10770 mParent.recomputeViewAttributes(this);
10771 }
10772 }
10773 }
10774
10775 /**
10776 * Returns the status bar visibility that this view has requested.
10777 */
10778 public int getSystemUiVisibility(int visibility) {
10779 return mSystemUiVisibility;
10780 }
10781
10782 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
10783 mOnSystemUiVisibilityChangeListener = l;
10784 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10785 mParent.recomputeViewAttributes(this);
10786 }
10787 }
10788
10789 /**
10790 */
10791 public void dispatchSystemUiVisibilityChanged(int visibility) {
10792 if (mOnSystemUiVisibilityChangeListener != null) {
10793 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(visibility);
10794 }
10795 }
10796
10797 /**
Christopher Tate2c095f32010-10-04 14:13:40 -070010798 * !!! TODO: real docs
10799 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010800 * The base class implementation makes the shadow the same size and appearance
Christopher Tate2c095f32010-10-04 14:13:40 -070010801 * as the view itself, and positions it with its center at the touch point.
10802 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010803 public static class DragShadowBuilder {
Christopher Tatea0374192010-10-05 13:06:41 -070010804 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010805
10806 /**
Christopher Tate17ed60c2011-01-18 12:50:26 -080010807 * Construct a shadow builder object for use with the given View object. The
10808 * default implementation will construct a drag shadow the same size and
10809 * appearance as the supplied View.
10810 *
10811 * @param view A view within the application's layout whose appearance
10812 * should be replicated as the drag shadow.
Christopher Tate2c095f32010-10-04 14:13:40 -070010813 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010814 public DragShadowBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010815 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010816 }
10817
Christopher Tate17ed60c2011-01-18 12:50:26 -080010818 /**
10819 * Construct a shadow builder object with no associated View. This
10820 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
10821 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
10822 * to supply the drag shadow's dimensions and appearance without
10823 * reference to any View object.
10824 */
10825 public DragShadowBuilder() {
10826 mView = new WeakReference<View>(null);
10827 }
10828
10829 /**
10830 * Returns the View object that had been passed to the
10831 * {@link #View.DragShadowBuilder(View)}
10832 * constructor. If that View parameter was {@code null} or if the
10833 * {@link #View.DragShadowBuilder()}
10834 * constructor was used to instantiate the builder object, this method will return
10835 * null.
10836 *
10837 * @return The View object associate with this builder object.
10838 */
Chris Tate6b391282010-10-14 15:48:59 -070010839 final public View getView() {
10840 return mView.get();
10841 }
10842
Christopher Tate2c095f32010-10-04 14:13:40 -070010843 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010844 * Provide the draggable-shadow metrics for the operation: the dimensions of
10845 * the shadow image itself, and the point within that shadow that should
Christopher Tate2c095f32010-10-04 14:13:40 -070010846 * be centered under the touch location while dragging.
10847 * <p>
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010848 * The default implementation sets the dimensions of the shadow to be the
Christopher Tate17ed60c2011-01-18 12:50:26 -080010849 * same as the dimensions of the View object that had been supplied to the
10850 * {@link #View.DragShadowBuilder(View)} constructor
10851 * when the builder object was instantiated, and centers the shadow under the touch
10852 * point.
Christopher Tate2c095f32010-10-04 14:13:40 -070010853 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010854 * @param shadowSize The application should set the {@code x} member of this
10855 * parameter to the desired shadow width, and the {@code y} member to
Christopher Tate2c095f32010-10-04 14:13:40 -070010856 * the desired height.
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010857 * @param shadowTouchPoint The application should set this point to be the
10858 * location within the shadow that should track directly underneath
Christopher Tate2c095f32010-10-04 14:13:40 -070010859 * the touch point on the screen during a drag.
10860 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010861 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070010862 final View view = mView.get();
10863 if (view != null) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010864 shadowSize.set(view.getWidth(), view.getHeight());
10865 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
Christopher Tatea0374192010-10-05 13:06:41 -070010866 } else {
10867 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10868 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010869 }
10870
10871 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010872 * Draw the shadow image for the upcoming drag. The shadow canvas was
10873 * created with the dimensions supplied by the
10874 * {@link #onProvideShadowMetrics(Point, Point)} callback.
Christopher Tate17ed60c2011-01-18 12:50:26 -080010875 * <p>
10876 * The default implementation replicates the appearance of the View object
10877 * that had been supplied to the
10878 * {@link #View.DragShadowBuilder(View)}
10879 * constructor when the builder object was instantiated.
Christopher Tate2c095f32010-10-04 14:13:40 -070010880 *
10881 * @param canvas
10882 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010883 public void onDrawShadow(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070010884 final View view = mView.get();
10885 if (view != null) {
10886 view.draw(canvas);
10887 } else {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010888 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
Christopher Tatea0374192010-10-05 13:06:41 -070010889 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010890 }
10891 }
10892
10893 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010894 * Drag and drop. App calls startDrag(), then callbacks to the shadow builder's
10895 * {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} and
10896 * {@link DragShadowBuilder#onDrawShadow(Canvas)} methods happen, then the drag
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010897 * operation is handed over to the OS.
Christopher Tatea53146c2010-09-07 11:57:52 -070010898 * !!! TODO: real docs
Christopher Tate407b4e92010-11-30 17:14:08 -080010899 *
10900 * @param data !!! TODO
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010901 * @param shadowBuilder !!! TODO
Christopher Tate407b4e92010-11-30 17:14:08 -080010902 * @param myLocalState An arbitrary object that will be passed as part of every DragEvent
10903 * delivered to the calling application during the course of the current drag operation.
10904 * This object is private to the application that called startDrag(), and is not
10905 * visible to other applications. It provides a lightweight way for the application to
10906 * propagate information from the initiator to the recipient of a drag within its own
10907 * application; for example, to help disambiguate between 'copy' and 'move' semantics.
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010908 * @param flags Flags affecting the drag operation. At present no flags are defined;
10909 * pass 0 for this parameter.
Christopher Tate407b4e92010-11-30 17:14:08 -080010910 * @return {@code true} if the drag operation was initiated successfully; {@code false} if
10911 * an error prevented the drag from taking place.
Christopher Tatea53146c2010-09-07 11:57:52 -070010912 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010913 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010914 Object myLocalState, int flags) {
Christopher Tate2c095f32010-10-04 14:13:40 -070010915 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010916 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
Christopher Tatea53146c2010-09-07 11:57:52 -070010917 }
10918 boolean okay = false;
10919
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010920 Point shadowSize = new Point();
10921 Point shadowTouchPoint = new Point();
10922 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
Christopher Tate2c095f32010-10-04 14:13:40 -070010923
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010924 if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
10925 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
10926 throw new IllegalStateException("Drag shadow dimensions must not be negative");
Christopher Tate2c095f32010-10-04 14:13:40 -070010927 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010928
Chris Tatea32dcf72010-10-14 12:13:50 -070010929 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010930 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
10931 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
Chris Tatea32dcf72010-10-14 12:13:50 -070010932 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010933 Surface surface = new Surface();
10934 try {
10935 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010936 flags, shadowSize.x, shadowSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070010937 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070010938 + " surface=" + surface);
10939 if (token != null) {
10940 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070010941 try {
Chris Tate6b391282010-10-14 15:48:59 -070010942 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010943 shadowBuilder.onDrawShadow(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070010944 } finally {
10945 surface.unlockCanvasAndPost(canvas);
10946 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010947
Christopher Tate407b4e92010-11-30 17:14:08 -080010948 final ViewRoot root = getViewRoot();
10949
10950 // Cache the local state object for delivery with DragEvents
10951 root.setLocalDragState(myLocalState);
10952
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010953 // repurpose 'shadowSize' for the last touch point
10954 root.getLastTouchPoint(shadowSize);
Christopher Tate2c095f32010-10-04 14:13:40 -070010955
Christopher Tatea53146c2010-09-07 11:57:52 -070010956 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010957 shadowSize.x, shadowSize.y,
10958 shadowTouchPoint.x, shadowTouchPoint.y, data);
Christopher Tate2c095f32010-10-04 14:13:40 -070010959 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070010960 }
10961 } catch (Exception e) {
10962 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
10963 surface.destroy();
10964 }
10965
10966 return okay;
10967 }
10968
Christopher Tatea53146c2010-09-07 11:57:52 -070010969 /**
10970 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
10971 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
10972 *
10973 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
10974 * being dragged. onDragEvent() should return 'true' if the view can handle
10975 * a drop of that content. A view that returns 'false' here will receive no
10976 * further calls to onDragEvent() about the drag/drop operation.
10977 *
10978 * For DRAG_ENTERED, event.getClipDescription() describes the content being
10979 * dragged. This will be the same content description passed in the
10980 * DRAG_STARTED_EVENT invocation.
10981 *
10982 * For DRAG_EXITED, event.getClipDescription() describes the content being
10983 * dragged. This will be the same content description passed in the
10984 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
10985 * drag-acceptance visual state.
10986 *
10987 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10988 * coordinates of the current drag point. The view must return 'true' if it
10989 * can accept a drop of the current drag content, false otherwise.
10990 *
10991 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10992 * within the view; also, event.getClipData() returns the full data payload
10993 * being dropped. The view should return 'true' if it consumed the dropped
10994 * content, 'false' if it did not.
10995 *
10996 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
10997 * to its normal visual state.
10998 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010999 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070011000 return false;
11001 }
11002
11003 /**
11004 * Views typically don't need to override dispatchDragEvent(); it just calls
Chris Tate32affef2010-10-18 15:29:21 -070011005 * onDragEvent(event) and passes the result up appropriately.
Christopher Tatea53146c2010-09-07 11:57:52 -070011006 */
11007 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070011008 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
11009 && mOnDragListener.onDrag(this, event)) {
11010 return true;
11011 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011012 return onDragEvent(event);
11013 }
11014
11015 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070011016 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
11017 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070011018 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070011019 */
11020 public void onCloseSystemDialogs(String reason) {
11021 }
11022
11023 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011024 * Given a Drawable whose bounds have been set to draw into this view,
11025 * update a Region being computed for {@link #gatherTransparentRegion} so
11026 * that any non-transparent parts of the Drawable are removed from the
11027 * given transparent region.
11028 *
11029 * @param dr The Drawable whose transparency is to be applied to the region.
11030 * @param region A Region holding the current transparency information,
11031 * where any parts of the region that are set are considered to be
11032 * transparent. On return, this region will be modified to have the
11033 * transparency information reduced by the corresponding parts of the
11034 * Drawable that are not transparent.
11035 * {@hide}
11036 */
11037 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
11038 if (DBG) {
11039 Log.i("View", "Getting transparent region for: " + this);
11040 }
11041 final Region r = dr.getTransparentRegion();
11042 final Rect db = dr.getBounds();
11043 final AttachInfo attachInfo = mAttachInfo;
11044 if (r != null && attachInfo != null) {
11045 final int w = getRight()-getLeft();
11046 final int h = getBottom()-getTop();
11047 if (db.left > 0) {
11048 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
11049 r.op(0, 0, db.left, h, Region.Op.UNION);
11050 }
11051 if (db.right < w) {
11052 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
11053 r.op(db.right, 0, w, h, Region.Op.UNION);
11054 }
11055 if (db.top > 0) {
11056 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
11057 r.op(0, 0, w, db.top, Region.Op.UNION);
11058 }
11059 if (db.bottom < h) {
11060 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
11061 r.op(0, db.bottom, w, h, Region.Op.UNION);
11062 }
11063 final int[] location = attachInfo.mTransparentLocation;
11064 getLocationInWindow(location);
11065 r.translate(location[0], location[1]);
11066 region.op(r, Region.Op.INTERSECT);
11067 } else {
11068 region.op(db, Region.Op.DIFFERENCE);
11069 }
11070 }
11071
Adam Powelle14579b2009-12-16 18:39:52 -080011072 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011073 mHasPerformedLongPress = false;
11074
11075 if (mPendingCheckForLongPress == null) {
11076 mPendingCheckForLongPress = new CheckForLongPress();
11077 }
11078 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080011079 postDelayed(mPendingCheckForLongPress,
11080 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011081 }
11082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011083 /**
11084 * Inflate a view from an XML resource. This convenience method wraps the {@link
11085 * LayoutInflater} class, which provides a full range of options for view inflation.
11086 *
11087 * @param context The Context object for your activity or application.
11088 * @param resource The resource ID to inflate
11089 * @param root A view group that will be the parent. Used to properly inflate the
11090 * layout_* parameters.
11091 * @see LayoutInflater
11092 */
11093 public static View inflate(Context context, int resource, ViewGroup root) {
11094 LayoutInflater factory = LayoutInflater.from(context);
11095 return factory.inflate(resource, root);
11096 }
Romain Guy33e72ae2010-07-17 12:40:29 -070011097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011098 /**
Adam Powell637d3372010-08-25 14:37:03 -070011099 * Scroll the view with standard behavior for scrolling beyond the normal
11100 * content boundaries. Views that call this method should override
11101 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
11102 * results of an over-scroll operation.
11103 *
11104 * Views can use this method to handle any touch or fling-based scrolling.
11105 *
11106 * @param deltaX Change in X in pixels
11107 * @param deltaY Change in Y in pixels
11108 * @param scrollX Current X scroll value in pixels before applying deltaX
11109 * @param scrollY Current Y scroll value in pixels before applying deltaY
11110 * @param scrollRangeX Maximum content scroll range along the X axis
11111 * @param scrollRangeY Maximum content scroll range along the Y axis
11112 * @param maxOverScrollX Number of pixels to overscroll by in either direction
11113 * along the X axis.
11114 * @param maxOverScrollY Number of pixels to overscroll by in either direction
11115 * along the Y axis.
11116 * @param isTouchEvent true if this scroll operation is the result of a touch event.
11117 * @return true if scrolling was clamped to an over-scroll boundary along either
11118 * axis, false otherwise.
11119 */
11120 protected boolean overScrollBy(int deltaX, int deltaY,
11121 int scrollX, int scrollY,
11122 int scrollRangeX, int scrollRangeY,
11123 int maxOverScrollX, int maxOverScrollY,
11124 boolean isTouchEvent) {
11125 final int overScrollMode = mOverScrollMode;
11126 final boolean canScrollHorizontal =
11127 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
11128 final boolean canScrollVertical =
11129 computeVerticalScrollRange() > computeVerticalScrollExtent();
11130 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
11131 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
11132 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
11133 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
11134
11135 int newScrollX = scrollX + deltaX;
11136 if (!overScrollHorizontal) {
11137 maxOverScrollX = 0;
11138 }
11139
11140 int newScrollY = scrollY + deltaY;
11141 if (!overScrollVertical) {
11142 maxOverScrollY = 0;
11143 }
11144
11145 // Clamp values if at the limits and record
11146 final int left = -maxOverScrollX;
11147 final int right = maxOverScrollX + scrollRangeX;
11148 final int top = -maxOverScrollY;
11149 final int bottom = maxOverScrollY + scrollRangeY;
11150
11151 boolean clampedX = false;
11152 if (newScrollX > right) {
11153 newScrollX = right;
11154 clampedX = true;
11155 } else if (newScrollX < left) {
11156 newScrollX = left;
11157 clampedX = true;
11158 }
11159
11160 boolean clampedY = false;
11161 if (newScrollY > bottom) {
11162 newScrollY = bottom;
11163 clampedY = true;
11164 } else if (newScrollY < top) {
11165 newScrollY = top;
11166 clampedY = true;
11167 }
11168
11169 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
11170
11171 return clampedX || clampedY;
11172 }
11173
11174 /**
11175 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
11176 * respond to the results of an over-scroll operation.
11177 *
11178 * @param scrollX New X scroll value in pixels
11179 * @param scrollY New Y scroll value in pixels
11180 * @param clampedX True if scrollX was clamped to an over-scroll boundary
11181 * @param clampedY True if scrollY was clamped to an over-scroll boundary
11182 */
11183 protected void onOverScrolled(int scrollX, int scrollY,
11184 boolean clampedX, boolean clampedY) {
11185 // Intentionally empty.
11186 }
11187
11188 /**
11189 * Returns the over-scroll mode for this view. The result will be
11190 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11191 * (allow over-scrolling only if the view content is larger than the container),
11192 * or {@link #OVER_SCROLL_NEVER}.
11193 *
11194 * @return This view's over-scroll mode.
11195 */
11196 public int getOverScrollMode() {
11197 return mOverScrollMode;
11198 }
11199
11200 /**
11201 * Set the over-scroll mode for this view. Valid over-scroll modes are
11202 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11203 * (allow over-scrolling only if the view content is larger than the container),
11204 * or {@link #OVER_SCROLL_NEVER}.
11205 *
11206 * Setting the over-scroll mode of a view will have an effect only if the
11207 * view is capable of scrolling.
11208 *
11209 * @param overScrollMode The new over-scroll mode for this view.
11210 */
11211 public void setOverScrollMode(int overScrollMode) {
11212 if (overScrollMode != OVER_SCROLL_ALWAYS &&
11213 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
11214 overScrollMode != OVER_SCROLL_NEVER) {
11215 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
11216 }
11217 mOverScrollMode = overScrollMode;
11218 }
11219
11220 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011221 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
11222 * Each MeasureSpec represents a requirement for either the width or the height.
11223 * A MeasureSpec is comprised of a size and a mode. There are three possible
11224 * modes:
11225 * <dl>
11226 * <dt>UNSPECIFIED</dt>
11227 * <dd>
11228 * The parent has not imposed any constraint on the child. It can be whatever size
11229 * it wants.
11230 * </dd>
11231 *
11232 * <dt>EXACTLY</dt>
11233 * <dd>
11234 * The parent has determined an exact size for the child. The child is going to be
11235 * given those bounds regardless of how big it wants to be.
11236 * </dd>
11237 *
11238 * <dt>AT_MOST</dt>
11239 * <dd>
11240 * The child can be as large as it wants up to the specified size.
11241 * </dd>
11242 * </dl>
11243 *
11244 * MeasureSpecs are implemented as ints to reduce object allocation. This class
11245 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
11246 */
11247 public static class MeasureSpec {
11248 private static final int MODE_SHIFT = 30;
11249 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
11250
11251 /**
11252 * Measure specification mode: The parent has not imposed any constraint
11253 * on the child. It can be whatever size it wants.
11254 */
11255 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
11256
11257 /**
11258 * Measure specification mode: The parent has determined an exact size
11259 * for the child. The child is going to be given those bounds regardless
11260 * of how big it wants to be.
11261 */
11262 public static final int EXACTLY = 1 << MODE_SHIFT;
11263
11264 /**
11265 * Measure specification mode: The child can be as large as it wants up
11266 * to the specified size.
11267 */
11268 public static final int AT_MOST = 2 << MODE_SHIFT;
11269
11270 /**
11271 * Creates a measure specification based on the supplied size and mode.
11272 *
11273 * The mode must always be one of the following:
11274 * <ul>
11275 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
11276 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
11277 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
11278 * </ul>
11279 *
11280 * @param size the size of the measure specification
11281 * @param mode the mode of the measure specification
11282 * @return the measure specification based on size and mode
11283 */
11284 public static int makeMeasureSpec(int size, int mode) {
11285 return size + mode;
11286 }
11287
11288 /**
11289 * Extracts the mode from the supplied measure specification.
11290 *
11291 * @param measureSpec the measure specification to extract the mode from
11292 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
11293 * {@link android.view.View.MeasureSpec#AT_MOST} or
11294 * {@link android.view.View.MeasureSpec#EXACTLY}
11295 */
11296 public static int getMode(int measureSpec) {
11297 return (measureSpec & MODE_MASK);
11298 }
11299
11300 /**
11301 * Extracts the size from the supplied measure specification.
11302 *
11303 * @param measureSpec the measure specification to extract the size from
11304 * @return the size in pixels defined in the supplied measure specification
11305 */
11306 public static int getSize(int measureSpec) {
11307 return (measureSpec & ~MODE_MASK);
11308 }
11309
11310 /**
11311 * Returns a String representation of the specified measure
11312 * specification.
11313 *
11314 * @param measureSpec the measure specification to convert to a String
11315 * @return a String with the following format: "MeasureSpec: MODE SIZE"
11316 */
11317 public static String toString(int measureSpec) {
11318 int mode = getMode(measureSpec);
11319 int size = getSize(measureSpec);
11320
11321 StringBuilder sb = new StringBuilder("MeasureSpec: ");
11322
11323 if (mode == UNSPECIFIED)
11324 sb.append("UNSPECIFIED ");
11325 else if (mode == EXACTLY)
11326 sb.append("EXACTLY ");
11327 else if (mode == AT_MOST)
11328 sb.append("AT_MOST ");
11329 else
11330 sb.append(mode).append(" ");
11331
11332 sb.append(size);
11333 return sb.toString();
11334 }
11335 }
11336
11337 class CheckForLongPress implements Runnable {
11338
11339 private int mOriginalWindowAttachCount;
11340
11341 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011342 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011343 && mOriginalWindowAttachCount == mWindowAttachCount) {
11344 if (performLongClick()) {
11345 mHasPerformedLongPress = true;
11346 }
11347 }
11348 }
11349
11350 public void rememberWindowAttachCount() {
11351 mOriginalWindowAttachCount = mWindowAttachCount;
11352 }
11353 }
Adam Powelle14579b2009-12-16 18:39:52 -080011354
11355 private final class CheckForTap implements Runnable {
11356 public void run() {
11357 mPrivateFlags &= ~PREPRESSED;
11358 mPrivateFlags |= PRESSED;
11359 refreshDrawableState();
11360 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
11361 postCheckForLongClick(ViewConfiguration.getTapTimeout());
11362 }
11363 }
11364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011365
Adam Powella35d7682010-03-12 14:48:13 -080011366 private final class PerformClick implements Runnable {
11367 public void run() {
11368 performClick();
11369 }
11370 }
11371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011372 /**
11373 * Interface definition for a callback to be invoked when a key event is
11374 * dispatched to this view. The callback will be invoked before the key
11375 * event is given to the view.
11376 */
11377 public interface OnKeyListener {
11378 /**
11379 * Called when a key is dispatched to a view. This allows listeners to
11380 * get a chance to respond before the target view.
11381 *
11382 * @param v The view the key has been dispatched to.
11383 * @param keyCode The code for the physical key that was pressed
11384 * @param event The KeyEvent object containing full information about
11385 * the event.
11386 * @return True if the listener has consumed the event, false otherwise.
11387 */
11388 boolean onKey(View v, int keyCode, KeyEvent event);
11389 }
11390
11391 /**
11392 * Interface definition for a callback to be invoked when a touch event is
11393 * dispatched to this view. The callback will be invoked before the touch
11394 * event is given to the view.
11395 */
11396 public interface OnTouchListener {
11397 /**
11398 * Called when a touch event is dispatched to a view. This allows listeners to
11399 * get a chance to respond before the target view.
11400 *
11401 * @param v The view the touch event has been dispatched to.
11402 * @param event The MotionEvent object containing full information about
11403 * the event.
11404 * @return True if the listener has consumed the event, false otherwise.
11405 */
11406 boolean onTouch(View v, MotionEvent event);
11407 }
11408
11409 /**
11410 * Interface definition for a callback to be invoked when a view has been clicked and held.
11411 */
11412 public interface OnLongClickListener {
11413 /**
11414 * Called when a view has been clicked and held.
11415 *
11416 * @param v The view that was clicked and held.
11417 *
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -080011418 * @return true if the callback consumed the long click, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011419 */
11420 boolean onLongClick(View v);
11421 }
11422
11423 /**
Chris Tate32affef2010-10-18 15:29:21 -070011424 * Interface definition for a callback to be invoked when a drag is being dispatched
11425 * to this view. The callback will be invoked before the hosting view's own
11426 * onDrag(event) method. If the listener wants to fall back to the hosting view's
11427 * onDrag(event) behavior, it should return 'false' from this callback.
11428 */
11429 public interface OnDragListener {
11430 /**
11431 * Called when a drag event is dispatched to a view. This allows listeners
11432 * to get a chance to override base View behavior.
11433 *
11434 * @param v The view the drag has been dispatched to.
11435 * @param event The DragEvent object containing full information
11436 * about the event.
11437 * @return true if the listener consumed the DragEvent, false in order to fall
11438 * back to the view's default handling.
11439 */
11440 boolean onDrag(View v, DragEvent event);
11441 }
11442
11443 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011444 * Interface definition for a callback to be invoked when the focus state of
11445 * a view changed.
11446 */
11447 public interface OnFocusChangeListener {
11448 /**
11449 * Called when the focus state of a view has changed.
11450 *
11451 * @param v The view whose state has changed.
11452 * @param hasFocus The new focus state of v.
11453 */
11454 void onFocusChange(View v, boolean hasFocus);
11455 }
11456
11457 /**
11458 * Interface definition for a callback to be invoked when a view is clicked.
11459 */
11460 public interface OnClickListener {
11461 /**
11462 * Called when a view has been clicked.
11463 *
11464 * @param v The view that was clicked.
11465 */
11466 void onClick(View v);
11467 }
11468
11469 /**
11470 * Interface definition for a callback to be invoked when the context menu
11471 * for this view is being built.
11472 */
11473 public interface OnCreateContextMenuListener {
11474 /**
11475 * Called when the context menu for this view is being built. It is not
11476 * safe to hold onto the menu after this method returns.
11477 *
11478 * @param menu The context menu that is being built
11479 * @param v The view for which the context menu is being built
11480 * @param menuInfo Extra information about the item for which the
11481 * context menu should be shown. This information will vary
11482 * depending on the class of v.
11483 */
11484 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
11485 }
11486
Joe Onorato664644d2011-01-23 17:53:23 -080011487 /**
11488 * Interface definition for a callback to be invoked when the status bar changes
11489 * visibility.
11490 *
11491 * @see #setOnSystemUiVisibilityChangeListener
11492 */
11493 public interface OnSystemUiVisibilityChangeListener {
11494 /**
11495 * Called when the status bar changes visibility because of a call to
11496 * {@link #setSystemUiVisibility}.
11497 *
11498 * @param visibility {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}.
11499 */
11500 public void onSystemUiVisibilityChange(int visibility);
11501 }
11502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011503 private final class UnsetPressedState implements Runnable {
11504 public void run() {
11505 setPressed(false);
11506 }
11507 }
11508
11509 /**
11510 * Base class for derived classes that want to save and restore their own
11511 * state in {@link android.view.View#onSaveInstanceState()}.
11512 */
11513 public static class BaseSavedState extends AbsSavedState {
11514 /**
11515 * Constructor used when reading from a parcel. Reads the state of the superclass.
11516 *
11517 * @param source
11518 */
11519 public BaseSavedState(Parcel source) {
11520 super(source);
11521 }
11522
11523 /**
11524 * Constructor called by derived classes when creating their SavedState objects
11525 *
11526 * @param superState The state of the superclass of this view
11527 */
11528 public BaseSavedState(Parcelable superState) {
11529 super(superState);
11530 }
11531
11532 public static final Parcelable.Creator<BaseSavedState> CREATOR =
11533 new Parcelable.Creator<BaseSavedState>() {
11534 public BaseSavedState createFromParcel(Parcel in) {
11535 return new BaseSavedState(in);
11536 }
11537
11538 public BaseSavedState[] newArray(int size) {
11539 return new BaseSavedState[size];
11540 }
11541 };
11542 }
11543
11544 /**
11545 * A set of information given to a view when it is attached to its parent
11546 * window.
11547 */
11548 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011549 interface Callbacks {
11550 void playSoundEffect(int effectId);
11551 boolean performHapticFeedback(int effectId, boolean always);
11552 }
11553
11554 /**
11555 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11556 * to a Handler. This class contains the target (View) to invalidate and
11557 * the coordinates of the dirty rectangle.
11558 *
11559 * For performance purposes, this class also implements a pool of up to
11560 * POOL_LIMIT objects that get reused. This reduces memory allocations
11561 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011562 */
Romain Guyd928d682009-03-31 17:52:16 -070011563 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011564 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070011565 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11566 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070011567 public InvalidateInfo newInstance() {
11568 return new InvalidateInfo();
11569 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011570
Romain Guyd928d682009-03-31 17:52:16 -070011571 public void onAcquired(InvalidateInfo element) {
11572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011573
Romain Guyd928d682009-03-31 17:52:16 -070011574 public void onReleased(InvalidateInfo element) {
11575 }
11576 }, POOL_LIMIT)
11577 );
11578
11579 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011580
11581 View target;
11582
11583 int left;
11584 int top;
11585 int right;
11586 int bottom;
11587
Romain Guyd928d682009-03-31 17:52:16 -070011588 public void setNextPoolable(InvalidateInfo element) {
11589 mNext = element;
11590 }
11591
11592 public InvalidateInfo getNextPoolable() {
11593 return mNext;
11594 }
11595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011596 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070011597 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011598 }
11599
11600 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070011601 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011602 }
11603 }
11604
11605 final IWindowSession mSession;
11606
11607 final IWindow mWindow;
11608
11609 final IBinder mWindowToken;
11610
11611 final Callbacks mRootCallbacks;
11612
Chet Haasedaf98e92011-01-10 14:10:36 -080011613 Canvas mHardwareCanvas;
11614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011615 /**
11616 * The top view of the hierarchy.
11617 */
11618 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070011619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011620 IBinder mPanelParentWindowToken;
11621 Surface mSurface;
11622
Romain Guyb051e892010-09-28 19:09:36 -070011623 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080011624 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070011625 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070011626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011627 /**
Romain Guy8506ab42009-06-11 17:35:47 -070011628 * Scale factor used by the compatibility mode
11629 */
11630 float mApplicationScale;
11631
11632 /**
11633 * Indicates whether the application is in compatibility mode
11634 */
11635 boolean mScalingRequired;
11636
11637 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011638 * Left position of this view's window
11639 */
11640 int mWindowLeft;
11641
11642 /**
11643 * Top position of this view's window
11644 */
11645 int mWindowTop;
11646
11647 /**
Adam Powell26153a32010-11-08 15:22:27 -080011648 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070011649 */
Adam Powell26153a32010-11-08 15:22:27 -080011650 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070011651
11652 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011653 * For windows that are full-screen but using insets to layout inside
11654 * of the screen decorations, these are the current insets for the
11655 * content of the window.
11656 */
11657 final Rect mContentInsets = new Rect();
11658
11659 /**
11660 * For windows that are full-screen but using insets to layout inside
11661 * of the screen decorations, these are the current insets for the
11662 * actual visible parts of the window.
11663 */
11664 final Rect mVisibleInsets = new Rect();
11665
11666 /**
11667 * The internal insets given by this window. This value is
11668 * supplied by the client (through
11669 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11670 * be given to the window manager when changed to be used in laying
11671 * out windows behind it.
11672 */
11673 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11674 = new ViewTreeObserver.InternalInsetsInfo();
11675
11676 /**
11677 * All views in the window's hierarchy that serve as scroll containers,
11678 * used to determine if the window can be resized or must be panned
11679 * to adjust for a soft input area.
11680 */
11681 final ArrayList<View> mScrollContainers = new ArrayList<View>();
11682
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070011683 final KeyEvent.DispatcherState mKeyDispatchState
11684 = new KeyEvent.DispatcherState();
11685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011686 /**
11687 * Indicates whether the view's window currently has the focus.
11688 */
11689 boolean mHasWindowFocus;
11690
11691 /**
11692 * The current visibility of the window.
11693 */
11694 int mWindowVisibility;
11695
11696 /**
11697 * Indicates the time at which drawing started to occur.
11698 */
11699 long mDrawingTime;
11700
11701 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070011702 * Indicates whether or not ignoring the DIRTY_MASK flags.
11703 */
11704 boolean mIgnoreDirtyState;
11705
11706 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011707 * Indicates whether the view's window is currently in touch mode.
11708 */
11709 boolean mInTouchMode;
11710
11711 /**
11712 * Indicates that ViewRoot should trigger a global layout change
11713 * the next time it performs a traversal
11714 */
11715 boolean mRecomputeGlobalAttributes;
11716
11717 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718 * Set during a traveral if any views want to keep the screen on.
11719 */
11720 boolean mKeepScreenOn;
11721
11722 /**
Joe Onorato664644d2011-01-23 17:53:23 -080011723 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
11724 */
11725 int mSystemUiVisibility;
11726
11727 /**
11728 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
11729 * attached.
11730 */
11731 boolean mHasSystemUiListeners;
11732
11733 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011734 * Set if the visibility of any views has changed.
11735 */
11736 boolean mViewVisibilityChanged;
11737
11738 /**
11739 * Set to true if a view has been scrolled.
11740 */
11741 boolean mViewScrollChanged;
11742
11743 /**
11744 * Global to the view hierarchy used as a temporary for dealing with
11745 * x/y points in the transparent region computations.
11746 */
11747 final int[] mTransparentLocation = new int[2];
11748
11749 /**
11750 * Global to the view hierarchy used as a temporary for dealing with
11751 * x/y points in the ViewGroup.invalidateChild implementation.
11752 */
11753 final int[] mInvalidateChildLocation = new int[2];
11754
Chet Haasec3aa3612010-06-17 08:50:37 -070011755
11756 /**
11757 * Global to the view hierarchy used as a temporary for dealing with
11758 * x/y location when view is transformed.
11759 */
11760 final float[] mTmpTransformLocation = new float[2];
11761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011762 /**
11763 * The view tree observer used to dispatch global events like
11764 * layout, pre-draw, touch mode change, etc.
11765 */
11766 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11767
11768 /**
11769 * A Canvas used by the view hierarchy to perform bitmap caching.
11770 */
11771 Canvas mCanvas;
11772
11773 /**
11774 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11775 * handler can be used to pump events in the UI events queue.
11776 */
11777 final Handler mHandler;
11778
11779 /**
11780 * Identifier for messages requesting the view to be invalidated.
11781 * Such messages should be sent to {@link #mHandler}.
11782 */
11783 static final int INVALIDATE_MSG = 0x1;
11784
11785 /**
11786 * Identifier for messages requesting the view to invalidate a region.
11787 * Such messages should be sent to {@link #mHandler}.
11788 */
11789 static final int INVALIDATE_RECT_MSG = 0x2;
11790
11791 /**
11792 * Temporary for use in computing invalidate rectangles while
11793 * calling up the hierarchy.
11794 */
11795 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070011796
11797 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070011798 * Temporary for use in computing hit areas with transformed views
11799 */
11800 final RectF mTmpTransformRect = new RectF();
11801
11802 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070011803 * Temporary list for use in collecting focusable descendents of a view.
11804 */
11805 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011807 /**
11808 * Creates a new set of attachment information with the specified
11809 * events handler and thread.
11810 *
11811 * @param handler the events handler the view must use
11812 */
11813 AttachInfo(IWindowSession session, IWindow window,
11814 Handler handler, Callbacks effectPlayer) {
11815 mSession = session;
11816 mWindow = window;
11817 mWindowToken = window.asBinder();
11818 mHandler = handler;
11819 mRootCallbacks = effectPlayer;
11820 }
11821 }
11822
11823 /**
11824 * <p>ScrollabilityCache holds various fields used by a View when scrolling
11825 * is supported. This avoids keeping too many unused fields in most
11826 * instances of View.</p>
11827 */
Mike Cleronf116bf82009-09-27 19:14:12 -070011828 private static class ScrollabilityCache implements Runnable {
11829
11830 /**
11831 * Scrollbars are not visible
11832 */
11833 public static final int OFF = 0;
11834
11835 /**
11836 * Scrollbars are visible
11837 */
11838 public static final int ON = 1;
11839
11840 /**
11841 * Scrollbars are fading away
11842 */
11843 public static final int FADING = 2;
11844
11845 public boolean fadeScrollBars;
11846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011847 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070011848 public int scrollBarDefaultDelayBeforeFade;
11849 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011850
11851 public int scrollBarSize;
11852 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070011853 public float[] interpolatorValues;
11854 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011855
11856 public final Paint paint;
11857 public final Matrix matrix;
11858 public Shader shader;
11859
Mike Cleronf116bf82009-09-27 19:14:12 -070011860 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11861
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011862 private static final float[] OPAQUE = { 255 };
11863 private static final float[] TRANSPARENT = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070011864
11865 /**
11866 * When fading should start. This time moves into the future every time
11867 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11868 */
11869 public long fadeStartTime;
11870
11871
11872 /**
11873 * The current state of the scrollbars: ON, OFF, or FADING
11874 */
11875 public int state = OFF;
11876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011877 private int mLastColor;
11878
Mike Cleronf116bf82009-09-27 19:14:12 -070011879 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011880 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11881 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070011882 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11883 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011884
11885 paint = new Paint();
11886 matrix = new Matrix();
11887 // use use a height of 1, and then wack the matrix each time we
11888 // actually use it.
11889 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011891 paint.setShader(shader);
11892 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070011893 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011894 }
Romain Guy8506ab42009-06-11 17:35:47 -070011895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 public void setFadeColor(int color) {
11897 if (color != 0 && color != mLastColor) {
11898 mLastColor = color;
11899 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070011900
Romain Guye55e1a72009-08-27 10:42:26 -070011901 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11902 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011904 paint.setShader(shader);
11905 // Restore the default transfer mode (src_over)
11906 paint.setXfermode(null);
11907 }
11908 }
Mike Cleronf116bf82009-09-27 19:14:12 -070011909
11910 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070011911 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070011912 if (now >= fadeStartTime) {
11913
11914 // the animation fades the scrollbars out by changing
11915 // the opacity (alpha) from fully opaque to fully
11916 // transparent
11917 int nextFrame = (int) now;
11918 int framesCount = 0;
11919
11920 Interpolator interpolator = scrollBarInterpolator;
11921
11922 // Start opaque
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011923 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
Mike Cleronf116bf82009-09-27 19:14:12 -070011924
11925 // End transparent
11926 nextFrame += scrollBarFadeDuration;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011927 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
Mike Cleronf116bf82009-09-27 19:14:12 -070011928
11929 state = FADING;
11930
11931 // Kick off the fade animation
11932 host.invalidate();
11933 }
11934 }
11935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011936 }
11937}