blob: 39ec26d24ecaf91893b2406eb8860bba919e5284 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080019import com.android.internal.R;
20import com.android.internal.util.Predicate;
21import com.android.internal.view.menu.MenuBuilder;
22
Christopher Tatea53146c2010-09-07 11:57:52 -070023import android.content.ClipData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080025import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.res.Resources;
27import android.content.res.TypedArray;
28import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070029import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070031import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.graphics.LinearGradient;
33import android.graphics.Matrix;
34import android.graphics.Paint;
35import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070036import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.graphics.PorterDuff;
38import android.graphics.PorterDuffXfermode;
39import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070040import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.graphics.Region;
42import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.graphics.drawable.ColorDrawable;
44import android.graphics.drawable.Drawable;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Message;
48import android.os.Parcel;
49import android.os.Parcelable;
50import android.os.RemoteException;
51import android.os.SystemClock;
52import android.os.SystemProperties;
53import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070055import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070056import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070057import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070058import android.util.Pools;
59import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.ContextMenu.ContextMenuInfo;
svetoslavganov75986cf2009-05-14 22:28:01 -070061import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070065import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070066import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.view.inputmethod.InputConnection;
68import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.widget.ScrollBarDrawable;
70
Christopher Tatea0374192010-10-05 13:06:41 -070071import java.lang.ref.WeakReference;
svetoslavganov75986cf2009-05-14 22:28:01 -070072import java.lang.reflect.InvocationTargetException;
73import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import java.util.ArrayList;
75import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070076import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070077import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
79/**
80 * <p>
81 * This class represents the basic building block for user interface components. A View
82 * occupies a rectangular area on the screen and is responsible for drawing and
83 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070084 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
86 * are invisible containers that hold other Views (or other ViewGroups) and define
87 * their layout properties.
88 * </p>
89 *
90 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070091 * <p>For an introduction to using this class to develop your
92 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070094 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
102 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
103 * </p>
104 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700105 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 * <a name="Using"></a>
107 * <h3>Using Views</h3>
108 * <p>
109 * All of the views in a window are arranged in a single tree. You can add views
110 * either from code or by specifying a tree of views in one or more XML layout
111 * files. There are many specialized subclasses of views that act as controls or
112 * are capable of displaying text, images, or other content.
113 * </p>
114 * <p>
115 * Once you have created a tree of views, there are typically a few types of
116 * common operations you may wish to perform:
117 * <ul>
118 * <li><strong>Set properties:</strong> for example setting the text of a
119 * {@link android.widget.TextView}. The available properties and the methods
120 * that set them will vary among the different subclasses of views. Note that
121 * properties that are known at build time can be set in the XML layout
122 * files.</li>
123 * <li><strong>Set focus:</strong> The framework will handled moving focus in
124 * response to user input. To force focus to a specific view, call
125 * {@link #requestFocus}.</li>
126 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
127 * that will be notified when something interesting happens to the view. For
128 * example, all views will let you set a listener to be notified when the view
129 * gains or loses focus. You can register such a listener using
130 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
131 * specialized listeners. For example, a Button exposes a listener to notify
132 * clients when the button is clicked.</li>
133 * <li><strong>Set visibility:</strong> You can hide or show views using
134 * {@link #setVisibility}.</li>
135 * </ul>
136 * </p>
137 * <p><em>
138 * Note: The Android framework is responsible for measuring, laying out and
139 * drawing views. You should not call methods that perform these actions on
140 * views yourself unless you are actually implementing a
141 * {@link android.view.ViewGroup}.
142 * </em></p>
143 *
144 * <a name="Lifecycle"></a>
145 * <h3>Implementing a Custom View</h3>
146 *
147 * <p>
148 * To implement a custom view, you will usually begin by providing overrides for
149 * some of the standard methods that the framework calls on all views. You do
150 * not need to override all of these methods. In fact, you can start by just
151 * overriding {@link #onDraw(android.graphics.Canvas)}.
152 * <table border="2" width="85%" align="center" cellpadding="5">
153 * <thead>
154 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
155 * </thead>
156 *
157 * <tbody>
158 * <tr>
159 * <td rowspan="2">Creation</td>
160 * <td>Constructors</td>
161 * <td>There is a form of the constructor that are called when the view
162 * is created from code and a form that is called when the view is
163 * inflated from a layout file. The second form should parse and apply
164 * any attributes defined in the layout file.
165 * </td>
166 * </tr>
167 * <tr>
168 * <td><code>{@link #onFinishInflate()}</code></td>
169 * <td>Called after a view and all of its children has been inflated
170 * from XML.</td>
171 * </tr>
172 *
173 * <tr>
174 * <td rowspan="3">Layout</td>
175 * <td><code>{@link #onMeasure}</code></td>
176 * <td>Called to determine the size requirements for this view and all
177 * of its children.
178 * </td>
179 * </tr>
180 * <tr>
181 * <td><code>{@link #onLayout}</code></td>
182 * <td>Called when this view should assign a size and position to all
183 * of its children.
184 * </td>
185 * </tr>
186 * <tr>
187 * <td><code>{@link #onSizeChanged}</code></td>
188 * <td>Called when the size of this view has changed.
189 * </td>
190 * </tr>
191 *
192 * <tr>
193 * <td>Drawing</td>
194 * <td><code>{@link #onDraw}</code></td>
195 * <td>Called when the view should render its content.
196 * </td>
197 * </tr>
198 *
199 * <tr>
200 * <td rowspan="4">Event processing</td>
201 * <td><code>{@link #onKeyDown}</code></td>
202 * <td>Called when a new key event occurs.
203 * </td>
204 * </tr>
205 * <tr>
206 * <td><code>{@link #onKeyUp}</code></td>
207 * <td>Called when a key up event occurs.
208 * </td>
209 * </tr>
210 * <tr>
211 * <td><code>{@link #onTrackballEvent}</code></td>
212 * <td>Called when a trackball motion event occurs.
213 * </td>
214 * </tr>
215 * <tr>
216 * <td><code>{@link #onTouchEvent}</code></td>
217 * <td>Called when a touch screen motion event occurs.
218 * </td>
219 * </tr>
220 *
221 * <tr>
222 * <td rowspan="2">Focus</td>
223 * <td><code>{@link #onFocusChanged}</code></td>
224 * <td>Called when the view gains or loses focus.
225 * </td>
226 * </tr>
227 *
228 * <tr>
229 * <td><code>{@link #onWindowFocusChanged}</code></td>
230 * <td>Called when the window containing the view gains or loses focus.
231 * </td>
232 * </tr>
233 *
234 * <tr>
235 * <td rowspan="3">Attaching</td>
236 * <td><code>{@link #onAttachedToWindow()}</code></td>
237 * <td>Called when the view is attached to a window.
238 * </td>
239 * </tr>
240 *
241 * <tr>
242 * <td><code>{@link #onDetachedFromWindow}</code></td>
243 * <td>Called when the view is detached from its window.
244 * </td>
245 * </tr>
246 *
247 * <tr>
248 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
249 * <td>Called when the visibility of the window containing the view
250 * has changed.
251 * </td>
252 * </tr>
253 * </tbody>
254 *
255 * </table>
256 * </p>
257 *
258 * <a name="IDs"></a>
259 * <h3>IDs</h3>
260 * Views may have an integer id associated with them. These ids are typically
261 * assigned in the layout XML files, and are used to find specific views within
262 * the view tree. A common pattern is to:
263 * <ul>
264 * <li>Define a Button in the layout file and assign it a unique ID.
265 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700266 * &lt;Button
267 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 * android:layout_width="wrap_content"
269 * android:layout_height="wrap_content"
270 * android:text="@string/my_button_text"/&gt;
271 * </pre></li>
272 * <li>From the onCreate method of an Activity, find the Button
273 * <pre class="prettyprint">
274 * Button myButton = (Button) findViewById(R.id.my_button);
275 * </pre></li>
276 * </ul>
277 * <p>
278 * View IDs need not be unique throughout the tree, but it is good practice to
279 * ensure that they are at least unique within the part of the tree you are
280 * searching.
281 * </p>
282 *
283 * <a name="Position"></a>
284 * <h3>Position</h3>
285 * <p>
286 * The geometry of a view is that of a rectangle. A view has a location,
287 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
288 * two dimensions, expressed as a width and a height. The unit for location
289 * and dimensions is the pixel.
290 * </p>
291 *
292 * <p>
293 * It is possible to retrieve the location of a view by invoking the methods
294 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
295 * coordinate of the rectangle representing the view. The latter returns the
296 * top, or Y, coordinate of the rectangle representing the view. These methods
297 * both return the location of the view relative to its parent. For instance,
298 * when getLeft() returns 20, that means the view is located 20 pixels to the
299 * right of the left edge of its direct parent.
300 * </p>
301 *
302 * <p>
303 * In addition, several convenience methods are offered to avoid unnecessary
304 * computations, namely {@link #getRight()} and {@link #getBottom()}.
305 * These methods return the coordinates of the right and bottom edges of the
306 * rectangle representing the view. For instance, calling {@link #getRight()}
307 * is similar to the following computation: <code>getLeft() + getWidth()</code>
308 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
309 * </p>
310 *
311 * <a name="SizePaddingMargins"></a>
312 * <h3>Size, padding and margins</h3>
313 * <p>
314 * The size of a view is expressed with a width and a height. A view actually
315 * possess two pairs of width and height values.
316 * </p>
317 *
318 * <p>
319 * The first pair is known as <em>measured width</em> and
320 * <em>measured height</em>. These dimensions define how big a view wants to be
321 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
322 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
323 * and {@link #getMeasuredHeight()}.
324 * </p>
325 *
326 * <p>
327 * The second pair is simply known as <em>width</em> and <em>height</em>, or
328 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
329 * dimensions define the actual size of the view on screen, at drawing time and
330 * after layout. These values may, but do not have to, be different from the
331 * measured width and height. The width and height can be obtained by calling
332 * {@link #getWidth()} and {@link #getHeight()}.
333 * </p>
334 *
335 * <p>
336 * To measure its dimensions, a view takes into account its padding. The padding
337 * is expressed in pixels for the left, top, right and bottom parts of the view.
338 * Padding can be used to offset the content of the view by a specific amount of
339 * pixels. For instance, a left padding of 2 will push the view's content by
340 * 2 pixels to the right of the left edge. Padding can be set using the
341 * {@link #setPadding(int, int, int, int)} method and queried by calling
342 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
343 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
344 * </p>
345 *
346 * <p>
347 * Even though a view can define a padding, it does not provide any support for
348 * margins. However, view groups provide such a support. Refer to
349 * {@link android.view.ViewGroup} and
350 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
351 * </p>
352 *
353 * <a name="Layout"></a>
354 * <h3>Layout</h3>
355 * <p>
356 * Layout is a two pass process: a measure pass and a layout pass. The measuring
357 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
358 * of the view tree. Each view pushes dimension specifications down the tree
359 * during the recursion. At the end of the measure pass, every view has stored
360 * its measurements. The second pass happens in
361 * {@link #layout(int,int,int,int)} and is also top-down. During
362 * this pass each parent is responsible for positioning all of its children
363 * using the sizes computed in the measure pass.
364 * </p>
365 *
366 * <p>
367 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
368 * {@link #getMeasuredHeight()} values must be set, along with those for all of
369 * that view's descendants. A view's measured width and measured height values
370 * must respect the constraints imposed by the view's parents. This guarantees
371 * that at the end of the measure pass, all parents accept all of their
372 * children's measurements. A parent view may call measure() more than once on
373 * its children. For example, the parent may measure each child once with
374 * unspecified dimensions to find out how big they want to be, then call
375 * measure() on them again with actual numbers if the sum of all the children's
376 * unconstrained sizes is too big or too small.
377 * </p>
378 *
379 * <p>
380 * The measure pass uses two classes to communicate dimensions. The
381 * {@link MeasureSpec} class is used by views to tell their parents how they
382 * want to be measured and positioned. The base LayoutParams class just
383 * describes how big the view wants to be for both width and height. For each
384 * dimension, it can specify one of:
385 * <ul>
386 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800387 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 * (minus padding)
389 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
390 * enclose its content (plus padding).
391 * </ul>
392 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
393 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
394 * an X and Y value.
395 * </p>
396 *
397 * <p>
398 * MeasureSpecs are used to push requirements down the tree from parent to
399 * child. A MeasureSpec can be in one of three modes:
400 * <ul>
401 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
402 * of a child view. For example, a LinearLayout may call measure() on its child
403 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
404 * tall the child view wants to be given a width of 240 pixels.
405 * <li>EXACTLY: This is used by the parent to impose an exact size on the
406 * child. The child must use this size, and guarantee that all of its
407 * descendants will fit within this size.
408 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
409 * child. The child must gurantee that it and all of its descendants will fit
410 * within this size.
411 * </ul>
412 * </p>
413 *
414 * <p>
415 * To intiate a layout, call {@link #requestLayout}. This method is typically
416 * called by a view on itself when it believes that is can no longer fit within
417 * its current bounds.
418 * </p>
419 *
420 * <a name="Drawing"></a>
421 * <h3>Drawing</h3>
422 * <p>
423 * Drawing is handled by walking the tree and rendering each view that
424 * intersects the the invalid region. Because the tree is traversed in-order,
425 * this means that parents will draw before (i.e., behind) their children, with
426 * siblings drawn in the order they appear in the tree.
427 * If you set a background drawable for a View, then the View will draw it for you
428 * before calling back to its <code>onDraw()</code> method.
429 * </p>
430 *
431 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700432 * Note that the framework will not draw views that are not in the invalid region.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 * </p>
434 *
435 * <p>
436 * To force a view to draw, call {@link #invalidate()}.
437 * </p>
438 *
439 * <a name="EventHandlingThreading"></a>
440 * <h3>Event Handling and Threading</h3>
441 * <p>
442 * The basic cycle of a view is as follows:
443 * <ol>
444 * <li>An event comes in and is dispatched to the appropriate view. The view
445 * handles the event and notifies any listeners.</li>
446 * <li>If in the course of processing the event, the view's bounds may need
447 * to be changed, the view will call {@link #requestLayout()}.</li>
448 * <li>Similarly, if in the course of processing the event the view's appearance
449 * may need to be changed, the view will call {@link #invalidate()}.</li>
450 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
451 * the framework will take care of measuring, laying out, and drawing the tree
452 * as appropriate.</li>
453 * </ol>
454 * </p>
455 *
456 * <p><em>Note: The entire view tree is single threaded. You must always be on
457 * the UI thread when calling any method on any view.</em>
458 * If you are doing work on other threads and want to update the state of a view
459 * from that thread, you should use a {@link Handler}.
460 * </p>
461 *
462 * <a name="FocusHandling"></a>
463 * <h3>Focus Handling</h3>
464 * <p>
465 * The framework will handle routine focus movement in response to user input.
466 * This includes changing the focus as views are removed or hidden, or as new
467 * views become available. Views indicate their willingness to take focus
468 * through the {@link #isFocusable} method. To change whether a view can take
469 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
470 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
471 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
472 * </p>
473 * <p>
474 * Focus movement is based on an algorithm which finds the nearest neighbor in a
475 * given direction. In rare cases, the default algorithm may not match the
476 * intended behavior of the developer. In these situations, you can provide
477 * explicit overrides by using these XML attributes in the layout file:
478 * <pre>
479 * nextFocusDown
480 * nextFocusLeft
481 * nextFocusRight
482 * nextFocusUp
483 * </pre>
484 * </p>
485 *
486 *
487 * <p>
488 * To get a particular view to take focus, call {@link #requestFocus()}.
489 * </p>
490 *
491 * <a name="TouchMode"></a>
492 * <h3>Touch Mode</h3>
493 * <p>
494 * When a user is navigating a user interface via directional keys such as a D-pad, it is
495 * necessary to give focus to actionable items such as buttons so the user can see
496 * what will take input. If the device has touch capabilities, however, and the user
497 * begins interacting with the interface by touching it, it is no longer necessary to
498 * always highlight, or give focus to, a particular view. This motivates a mode
499 * for interaction named 'touch mode'.
500 * </p>
501 * <p>
502 * For a touch capable device, once the user touches the screen, the device
503 * will enter touch mode. From this point onward, only views for which
504 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
505 * Other views that are touchable, like buttons, will not take focus when touched; they will
506 * only fire the on click listeners.
507 * </p>
508 * <p>
509 * Any time a user hits a directional key, such as a D-pad direction, the view device will
510 * exit touch mode, and find a view to take focus, so that the user may resume interacting
511 * with the user interface without touching the screen again.
512 * </p>
513 * <p>
514 * The touch mode state is maintained across {@link android.app.Activity}s. Call
515 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
516 * </p>
517 *
518 * <a name="Scrolling"></a>
519 * <h3>Scrolling</h3>
520 * <p>
521 * The framework provides basic support for views that wish to internally
522 * scroll their content. This includes keeping track of the X and Y scroll
523 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700524 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
525 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 * </p>
527 *
528 * <a name="Tags"></a>
529 * <h3>Tags</h3>
530 * <p>
531 * Unlike IDs, tags are not used to identify views. Tags are essentially an
532 * extra piece of information that can be associated with a view. They are most
533 * often used as a convenience to store data related to views in the views
534 * themselves rather than by putting them in a separate structure.
535 * </p>
536 *
537 * <a name="Animation"></a>
538 * <h3>Animation</h3>
539 * <p>
540 * You can attach an {@link Animation} object to a view using
541 * {@link #setAnimation(Animation)} or
542 * {@link #startAnimation(Animation)}. The animation can alter the scale,
543 * rotation, translation and alpha of a view over time. If the animation is
544 * attached to a view that has children, the animation will affect the entire
545 * subtree rooted by that node. When an animation is started, the framework will
546 * take care of redrawing the appropriate views until the animation completes.
547 * </p>
Romain Guy171c5922011-01-06 10:04:23 -0800548 * <p>
549 * Starting with Android 3.0, the preferred way of animating views is to use the
550 * {@link android.animation} package APIs.
551 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 *
Jeff Brown85a31762010-09-01 17:01:00 -0700553 * <a name="Security"></a>
554 * <h3>Security</h3>
555 * <p>
556 * Sometimes it is essential that an application be able to verify that an action
557 * is being performed with the full knowledge and consent of the user, such as
558 * granting a permission request, making a purchase or clicking on an advertisement.
559 * Unfortunately, a malicious application could try to spoof the user into
560 * performing these actions, unaware, by concealing the intended purpose of the view.
561 * As a remedy, the framework offers a touch filtering mechanism that can be used to
562 * improve the security of views that provide access to sensitive functionality.
563 * </p><p>
564 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
Jeff Brown49ed71d2010-12-06 17:13:33 -0800565 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework
Jeff Brown85a31762010-09-01 17:01:00 -0700566 * will discard touches that are received whenever the view's window is obscured by
567 * another visible window. As a result, the view will not receive touches whenever a
568 * toast, dialog or other window appears above the view's window.
569 * </p><p>
570 * For more fine-grained control over security, consider overriding the
571 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
572 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
573 * </p>
574 *
Romain Guy171c5922011-01-06 10:04:23 -0800575 * @attr ref android.R.styleable#View_alpha
Romain Guyd6a463a2009-05-21 23:10:10 -0700576 * @attr ref android.R.styleable#View_background
577 * @attr ref android.R.styleable#View_clickable
578 * @attr ref android.R.styleable#View_contentDescription
579 * @attr ref android.R.styleable#View_drawingCacheQuality
580 * @attr ref android.R.styleable#View_duplicateParentState
581 * @attr ref android.R.styleable#View_id
582 * @attr ref android.R.styleable#View_fadingEdge
583 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700584 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700586 * @attr ref android.R.styleable#View_isScrollContainer
587 * @attr ref android.R.styleable#View_focusable
588 * @attr ref android.R.styleable#View_focusableInTouchMode
589 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
590 * @attr ref android.R.styleable#View_keepScreenOn
Romain Guy171c5922011-01-06 10:04:23 -0800591 * @attr ref android.R.styleable#View_layerType
Romain Guyd6a463a2009-05-21 23:10:10 -0700592 * @attr ref android.R.styleable#View_longClickable
593 * @attr ref android.R.styleable#View_minHeight
594 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 * @attr ref android.R.styleable#View_nextFocusDown
596 * @attr ref android.R.styleable#View_nextFocusLeft
597 * @attr ref android.R.styleable#View_nextFocusRight
598 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700599 * @attr ref android.R.styleable#View_onClick
600 * @attr ref android.R.styleable#View_padding
601 * @attr ref android.R.styleable#View_paddingBottom
602 * @attr ref android.R.styleable#View_paddingLeft
603 * @attr ref android.R.styleable#View_paddingRight
604 * @attr ref android.R.styleable#View_paddingTop
605 * @attr ref android.R.styleable#View_saveEnabled
Chet Haase73066682010-11-29 15:55:32 -0800606 * @attr ref android.R.styleable#View_rotation
607 * @attr ref android.R.styleable#View_rotationX
608 * @attr ref android.R.styleable#View_rotationY
609 * @attr ref android.R.styleable#View_scaleX
610 * @attr ref android.R.styleable#View_scaleY
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 * @attr ref android.R.styleable#View_scrollX
612 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700613 * @attr ref android.R.styleable#View_scrollbarSize
614 * @attr ref android.R.styleable#View_scrollbarStyle
615 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700616 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
617 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
619 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 * @attr ref android.R.styleable#View_scrollbarThumbVertical
621 * @attr ref android.R.styleable#View_scrollbarTrackVertical
622 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700624 * @attr ref android.R.styleable#View_soundEffectsEnabled
625 * @attr ref android.R.styleable#View_tag
Chet Haase73066682010-11-29 15:55:32 -0800626 * @attr ref android.R.styleable#View_transformPivotX
627 * @attr ref android.R.styleable#View_transformPivotY
628 * @attr ref android.R.styleable#View_translationX
629 * @attr ref android.R.styleable#View_translationY
Romain Guyd6a463a2009-05-21 23:10:10 -0700630 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 *
632 * @see android.view.ViewGroup
633 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700634public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 private static final boolean DBG = false;
636
637 /**
638 * The logging tag used by this class with android.util.Log.
639 */
640 protected static final String VIEW_LOG_TAG = "View";
641
642 /**
643 * Used to mark a View that has no ID.
644 */
645 public static final int NO_ID = -1;
646
647 /**
648 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
649 * calling setFlags.
650 */
651 private static final int NOT_FOCUSABLE = 0x00000000;
652
653 /**
654 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
655 * setFlags.
656 */
657 private static final int FOCUSABLE = 0x00000001;
658
659 /**
660 * Mask for use with setFlags indicating bits used for focus.
661 */
662 private static final int FOCUSABLE_MASK = 0x00000001;
663
664 /**
665 * This view will adjust its padding to fit sytem windows (e.g. status bar)
666 */
667 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
668
669 /**
670 * This view is visible. Use with {@link #setVisibility}.
671 */
672 public static final int VISIBLE = 0x00000000;
673
674 /**
675 * This view is invisible, but it still takes up space for layout purposes.
676 * Use with {@link #setVisibility}.
677 */
678 public static final int INVISIBLE = 0x00000004;
679
680 /**
681 * This view is invisible, and it doesn't take any space for layout
682 * purposes. Use with {@link #setVisibility}.
683 */
684 public static final int GONE = 0x00000008;
685
686 /**
687 * Mask for use with setFlags indicating bits used for visibility.
688 * {@hide}
689 */
690 static final int VISIBILITY_MASK = 0x0000000C;
691
692 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
693
694 /**
695 * This view is enabled. Intrepretation varies by subclass.
696 * Use with ENABLED_MASK when calling setFlags.
697 * {@hide}
698 */
699 static final int ENABLED = 0x00000000;
700
701 /**
702 * This view is disabled. Intrepretation varies by subclass.
703 * Use with ENABLED_MASK when calling setFlags.
704 * {@hide}
705 */
706 static final int DISABLED = 0x00000020;
707
708 /**
709 * Mask for use with setFlags indicating bits used for indicating whether
710 * this view is enabled
711 * {@hide}
712 */
713 static final int ENABLED_MASK = 0x00000020;
714
715 /**
716 * This view won't draw. {@link #onDraw} won't be called and further
717 * optimizations
718 * will be performed. It is okay to have this flag set and a background.
719 * Use with DRAW_MASK when calling setFlags.
720 * {@hide}
721 */
722 static final int WILL_NOT_DRAW = 0x00000080;
723
724 /**
725 * Mask for use with setFlags indicating bits used for indicating whether
726 * this view is will draw
727 * {@hide}
728 */
729 static final int DRAW_MASK = 0x00000080;
730
731 /**
732 * <p>This view doesn't show scrollbars.</p>
733 * {@hide}
734 */
735 static final int SCROLLBARS_NONE = 0x00000000;
736
737 /**
738 * <p>This view shows horizontal scrollbars.</p>
739 * {@hide}
740 */
741 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
742
743 /**
744 * <p>This view shows vertical scrollbars.</p>
745 * {@hide}
746 */
747 static final int SCROLLBARS_VERTICAL = 0x00000200;
748
749 /**
750 * <p>Mask for use with setFlags indicating bits used for indicating which
751 * scrollbars are enabled.</p>
752 * {@hide}
753 */
754 static final int SCROLLBARS_MASK = 0x00000300;
755
Jeff Brown85a31762010-09-01 17:01:00 -0700756 /**
757 * Indicates that the view should filter touches when its window is obscured.
758 * Refer to the class comments for more information about this security feature.
759 * {@hide}
760 */
761 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
762
763 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764
765 /**
766 * <p>This view doesn't show fading edges.</p>
767 * {@hide}
768 */
769 static final int FADING_EDGE_NONE = 0x00000000;
770
771 /**
772 * <p>This view shows horizontal fading edges.</p>
773 * {@hide}
774 */
775 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
776
777 /**
778 * <p>This view shows vertical fading edges.</p>
779 * {@hide}
780 */
781 static final int FADING_EDGE_VERTICAL = 0x00002000;
782
783 /**
784 * <p>Mask for use with setFlags indicating bits used for indicating which
785 * fading edges are enabled.</p>
786 * {@hide}
787 */
788 static final int FADING_EDGE_MASK = 0x00003000;
789
790 /**
791 * <p>Indicates this view can be clicked. When clickable, a View reacts
792 * to clicks by notifying the OnClickListener.<p>
793 * {@hide}
794 */
795 static final int CLICKABLE = 0x00004000;
796
797 /**
798 * <p>Indicates this view is caching its drawing into a bitmap.</p>
799 * {@hide}
800 */
801 static final int DRAWING_CACHE_ENABLED = 0x00008000;
802
803 /**
804 * <p>Indicates that no icicle should be saved for this view.<p>
805 * {@hide}
806 */
807 static final int SAVE_DISABLED = 0x000010000;
808
809 /**
810 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
811 * property.</p>
812 * {@hide}
813 */
814 static final int SAVE_DISABLED_MASK = 0x000010000;
815
816 /**
817 * <p>Indicates that no drawing cache should ever be created for this view.<p>
818 * {@hide}
819 */
820 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
821
822 /**
823 * <p>Indicates this view can take / keep focus when int touch mode.</p>
824 * {@hide}
825 */
826 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
827
828 /**
829 * <p>Enables low quality mode for the drawing cache.</p>
830 */
831 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
832
833 /**
834 * <p>Enables high quality mode for the drawing cache.</p>
835 */
836 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
837
838 /**
839 * <p>Enables automatic quality mode for the drawing cache.</p>
840 */
841 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
842
843 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
844 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
845 };
846
847 /**
848 * <p>Mask for use with setFlags indicating bits used for the cache
849 * quality property.</p>
850 * {@hide}
851 */
852 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
853
854 /**
855 * <p>
856 * Indicates this view can be long clicked. When long clickable, a View
857 * reacts to long clicks by notifying the OnLongClickListener or showing a
858 * context menu.
859 * </p>
860 * {@hide}
861 */
862 static final int LONG_CLICKABLE = 0x00200000;
863
864 /**
865 * <p>Indicates that this view gets its drawable states from its direct parent
866 * and ignores its original internal states.</p>
867 *
868 * @hide
869 */
870 static final int DUPLICATE_PARENT_STATE = 0x00400000;
871
872 /**
873 * The scrollbar style to display the scrollbars inside the content area,
874 * without increasing the padding. The scrollbars will be overlaid with
875 * translucency on the view's content.
876 */
877 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
878
879 /**
880 * The scrollbar style to display the scrollbars inside the padded area,
881 * increasing the padding of the view. The scrollbars will not overlap the
882 * content area of the view.
883 */
884 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
885
886 /**
887 * The scrollbar style to display the scrollbars at the edge of the view,
888 * without increasing the padding. The scrollbars will be overlaid with
889 * translucency.
890 */
891 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
892
893 /**
894 * The scrollbar style to display the scrollbars at the edge of the view,
895 * increasing the padding of the view. The scrollbars will only overlap the
896 * background, if any.
897 */
898 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
899
900 /**
901 * Mask to check if the scrollbar style is overlay or inset.
902 * {@hide}
903 */
904 static final int SCROLLBARS_INSET_MASK = 0x01000000;
905
906 /**
907 * Mask to check if the scrollbar style is inside or outside.
908 * {@hide}
909 */
910 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
911
912 /**
913 * Mask for scrollbar style.
914 * {@hide}
915 */
916 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
917
918 /**
919 * View flag indicating that the screen should remain on while the
920 * window containing this view is visible to the user. This effectively
921 * takes care of automatically setting the WindowManager's
922 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
923 */
924 public static final int KEEP_SCREEN_ON = 0x04000000;
925
926 /**
927 * View flag indicating whether this view should have sound effects enabled
928 * for events such as clicking and touching.
929 */
930 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
931
932 /**
933 * View flag indicating whether this view should have haptic feedback
934 * enabled for events such as long presses.
935 */
936 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
937
938 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700939 * <p>Indicates that the view hierarchy should stop saving state when
940 * it reaches this view. If state saving is initiated immediately at
941 * the view, it will be allowed.
942 * {@hide}
943 */
944 static final int PARENT_SAVE_DISABLED = 0x20000000;
945
946 /**
947 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
948 * {@hide}
949 */
950 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
951
952 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700953 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
954 * should add all focusable Views regardless if they are focusable in touch mode.
955 */
956 public static final int FOCUSABLES_ALL = 0x00000000;
957
958 /**
959 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
960 * should add only Views focusable in touch mode.
961 */
962 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
963
964 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 * Use with {@link #focusSearch}. Move focus to the previous selectable
966 * item.
967 */
968 public static final int FOCUS_BACKWARD = 0x00000001;
969
970 /**
971 * Use with {@link #focusSearch}. Move focus to the next selectable
972 * item.
973 */
974 public static final int FOCUS_FORWARD = 0x00000002;
975
976 /**
977 * Use with {@link #focusSearch}. Move focus to the left.
978 */
979 public static final int FOCUS_LEFT = 0x00000011;
980
981 /**
982 * Use with {@link #focusSearch}. Move focus up.
983 */
984 public static final int FOCUS_UP = 0x00000021;
985
986 /**
987 * Use with {@link #focusSearch}. Move focus to the right.
988 */
989 public static final int FOCUS_RIGHT = 0x00000042;
990
991 /**
992 * Use with {@link #focusSearch}. Move focus down.
993 */
994 public static final int FOCUS_DOWN = 0x00000082;
995
996 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -0800997 * Bits of {@link #getMeasuredWidthAndState()} and
998 * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
999 */
1000 public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1001
1002 /**
1003 * Bits of {@link #getMeasuredWidthAndState()} and
1004 * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1005 */
1006 public static final int MEASURED_STATE_MASK = 0xff000000;
1007
1008 /**
1009 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1010 * for functions that combine both width and height into a single int,
1011 * such as {@link #getMeasuredState()} and the childState argument of
1012 * {@link #resolveSizeAndState(int, int, int)}.
1013 */
1014 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1015
1016 /**
1017 * Bit of {@link #getMeasuredWidthAndState()} and
1018 * {@link #getMeasuredWidthAndState()} that indicates the measured size
1019 * is smaller that the space the view would like to have.
1020 */
1021 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1022
1023 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 * Base View state sets
1025 */
1026 // Singles
1027 /**
1028 * Indicates the view has no states set. States are used with
1029 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1030 * view depending on its state.
1031 *
1032 * @see android.graphics.drawable.Drawable
1033 * @see #getDrawableState()
1034 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001035 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 /**
1037 * Indicates the view is enabled. States are used with
1038 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1039 * view depending on its state.
1040 *
1041 * @see android.graphics.drawable.Drawable
1042 * @see #getDrawableState()
1043 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001044 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 /**
1046 * Indicates the view is focused. States are used with
1047 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1048 * view depending on its state.
1049 *
1050 * @see android.graphics.drawable.Drawable
1051 * @see #getDrawableState()
1052 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001053 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 /**
1055 * Indicates the view is selected. States are used with
1056 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1057 * view depending on its state.
1058 *
1059 * @see android.graphics.drawable.Drawable
1060 * @see #getDrawableState()
1061 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001062 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 /**
1064 * Indicates the view is pressed. States are used with
1065 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1066 * view depending on its state.
1067 *
1068 * @see android.graphics.drawable.Drawable
1069 * @see #getDrawableState()
1070 * @hide
1071 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001072 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 /**
1074 * Indicates the view's window has focus. States are used with
1075 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1076 * view depending on its state.
1077 *
1078 * @see android.graphics.drawable.Drawable
1079 * @see #getDrawableState()
1080 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001081 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 // Doubles
1083 /**
1084 * Indicates the view is enabled and has the focus.
1085 *
1086 * @see #ENABLED_STATE_SET
1087 * @see #FOCUSED_STATE_SET
1088 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001089 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 /**
1091 * Indicates the view is enabled and selected.
1092 *
1093 * @see #ENABLED_STATE_SET
1094 * @see #SELECTED_STATE_SET
1095 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001096 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 /**
1098 * Indicates the view is enabled and that its window has focus.
1099 *
1100 * @see #ENABLED_STATE_SET
1101 * @see #WINDOW_FOCUSED_STATE_SET
1102 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001103 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 /**
1105 * Indicates the view is focused and selected.
1106 *
1107 * @see #FOCUSED_STATE_SET
1108 * @see #SELECTED_STATE_SET
1109 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001110 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 /**
1112 * Indicates the view has the focus and that its window has the focus.
1113 *
1114 * @see #FOCUSED_STATE_SET
1115 * @see #WINDOW_FOCUSED_STATE_SET
1116 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001117 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 /**
1119 * Indicates the view is selected and that its window has the focus.
1120 *
1121 * @see #SELECTED_STATE_SET
1122 * @see #WINDOW_FOCUSED_STATE_SET
1123 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001124 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 // Triples
1126 /**
1127 * Indicates the view is enabled, focused and selected.
1128 *
1129 * @see #ENABLED_STATE_SET
1130 * @see #FOCUSED_STATE_SET
1131 * @see #SELECTED_STATE_SET
1132 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001133 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 /**
1135 * Indicates the view is enabled, focused and its window has the focus.
1136 *
1137 * @see #ENABLED_STATE_SET
1138 * @see #FOCUSED_STATE_SET
1139 * @see #WINDOW_FOCUSED_STATE_SET
1140 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001141 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 /**
1143 * Indicates the view is enabled, selected and its window has the focus.
1144 *
1145 * @see #ENABLED_STATE_SET
1146 * @see #SELECTED_STATE_SET
1147 * @see #WINDOW_FOCUSED_STATE_SET
1148 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001149 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 /**
1151 * Indicates the view is focused, selected and its window has the focus.
1152 *
1153 * @see #FOCUSED_STATE_SET
1154 * @see #SELECTED_STATE_SET
1155 * @see #WINDOW_FOCUSED_STATE_SET
1156 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001157 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 /**
1159 * Indicates the view is enabled, focused, selected and its window
1160 * has the focus.
1161 *
1162 * @see #ENABLED_STATE_SET
1163 * @see #FOCUSED_STATE_SET
1164 * @see #SELECTED_STATE_SET
1165 * @see #WINDOW_FOCUSED_STATE_SET
1166 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001167 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 /**
1169 * Indicates the view is pressed and its window has the focus.
1170 *
1171 * @see #PRESSED_STATE_SET
1172 * @see #WINDOW_FOCUSED_STATE_SET
1173 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001174 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 /**
1176 * Indicates the view is pressed and selected.
1177 *
1178 * @see #PRESSED_STATE_SET
1179 * @see #SELECTED_STATE_SET
1180 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001181 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 /**
1183 * Indicates the view is pressed, selected and its window has the focus.
1184 *
1185 * @see #PRESSED_STATE_SET
1186 * @see #SELECTED_STATE_SET
1187 * @see #WINDOW_FOCUSED_STATE_SET
1188 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001189 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 /**
1191 * Indicates the view is pressed and focused.
1192 *
1193 * @see #PRESSED_STATE_SET
1194 * @see #FOCUSED_STATE_SET
1195 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001196 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 /**
1198 * Indicates the view is pressed, focused and its window has the focus.
1199 *
1200 * @see #PRESSED_STATE_SET
1201 * @see #FOCUSED_STATE_SET
1202 * @see #WINDOW_FOCUSED_STATE_SET
1203 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001204 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 /**
1206 * Indicates the view is pressed, focused and selected.
1207 *
1208 * @see #PRESSED_STATE_SET
1209 * @see #SELECTED_STATE_SET
1210 * @see #FOCUSED_STATE_SET
1211 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001212 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 /**
1214 * Indicates the view is pressed, focused, selected and its window has the focus.
1215 *
1216 * @see #PRESSED_STATE_SET
1217 * @see #FOCUSED_STATE_SET
1218 * @see #SELECTED_STATE_SET
1219 * @see #WINDOW_FOCUSED_STATE_SET
1220 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001221 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 /**
1223 * Indicates the view is pressed and enabled.
1224 *
1225 * @see #PRESSED_STATE_SET
1226 * @see #ENABLED_STATE_SET
1227 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001228 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 /**
1230 * Indicates the view is pressed, enabled and its window has the focus.
1231 *
1232 * @see #PRESSED_STATE_SET
1233 * @see #ENABLED_STATE_SET
1234 * @see #WINDOW_FOCUSED_STATE_SET
1235 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001236 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 /**
1238 * Indicates the view is pressed, enabled and selected.
1239 *
1240 * @see #PRESSED_STATE_SET
1241 * @see #ENABLED_STATE_SET
1242 * @see #SELECTED_STATE_SET
1243 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001244 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 /**
1246 * Indicates the view is pressed, enabled, selected and its window has the
1247 * focus.
1248 *
1249 * @see #PRESSED_STATE_SET
1250 * @see #ENABLED_STATE_SET
1251 * @see #SELECTED_STATE_SET
1252 * @see #WINDOW_FOCUSED_STATE_SET
1253 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001254 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 /**
1256 * Indicates the view is pressed, enabled and focused.
1257 *
1258 * @see #PRESSED_STATE_SET
1259 * @see #ENABLED_STATE_SET
1260 * @see #FOCUSED_STATE_SET
1261 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001262 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 /**
1264 * Indicates the view is pressed, enabled, focused and its window has the
1265 * focus.
1266 *
1267 * @see #PRESSED_STATE_SET
1268 * @see #ENABLED_STATE_SET
1269 * @see #FOCUSED_STATE_SET
1270 * @see #WINDOW_FOCUSED_STATE_SET
1271 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001272 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 /**
1274 * Indicates the view is pressed, enabled, focused and selected.
1275 *
1276 * @see #PRESSED_STATE_SET
1277 * @see #ENABLED_STATE_SET
1278 * @see #SELECTED_STATE_SET
1279 * @see #FOCUSED_STATE_SET
1280 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001281 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 /**
1283 * Indicates the view is pressed, enabled, focused, selected and its window
1284 * has the focus.
1285 *
1286 * @see #PRESSED_STATE_SET
1287 * @see #ENABLED_STATE_SET
1288 * @see #SELECTED_STATE_SET
1289 * @see #FOCUSED_STATE_SET
1290 * @see #WINDOW_FOCUSED_STATE_SET
1291 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001292 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293
1294 /**
1295 * The order here is very important to {@link #getDrawableState()}
1296 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001297 private static final int[][] VIEW_STATE_SETS;
1298
Romain Guyb051e892010-09-28 19:09:36 -07001299 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1300 static final int VIEW_STATE_SELECTED = 1 << 1;
1301 static final int VIEW_STATE_FOCUSED = 1 << 2;
1302 static final int VIEW_STATE_ENABLED = 1 << 3;
1303 static final int VIEW_STATE_PRESSED = 1 << 4;
1304 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001305 static final int VIEW_STATE_ACCELERATED = 1 << 6;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001306
1307 static final int[] VIEW_STATE_IDS = new int[] {
1308 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1309 R.attr.state_selected, VIEW_STATE_SELECTED,
1310 R.attr.state_focused, VIEW_STATE_FOCUSED,
1311 R.attr.state_enabled, VIEW_STATE_ENABLED,
1312 R.attr.state_pressed, VIEW_STATE_PRESSED,
1313 R.attr.state_activated, VIEW_STATE_ACTIVATED,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001314 R.attr.state_accelerated, VIEW_STATE_ACCELERATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 };
1316
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001317 static {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001318 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1319 throw new IllegalStateException(
1320 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1321 }
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001322 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001323 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001324 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001325 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001326 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001327 orderedIds[i * 2] = viewState;
1328 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001329 }
1330 }
1331 }
Romain Guyb051e892010-09-28 19:09:36 -07001332 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1333 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1334 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001335 int numBits = Integer.bitCount(i);
1336 int[] set = new int[numBits];
1337 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001338 for (int j = 0; j < orderedIds.length; j += 2) {
1339 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001340 set[pos++] = orderedIds[j];
1341 }
1342 }
1343 VIEW_STATE_SETS[i] = set;
1344 }
1345
1346 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1347 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1348 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1349 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1350 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1351 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1352 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1353 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1354 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1355 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1356 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1357 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1358 | VIEW_STATE_FOCUSED];
1359 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1360 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1361 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1362 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1363 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1364 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1365 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1366 | VIEW_STATE_ENABLED];
1367 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1368 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1369 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1370 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1371 | VIEW_STATE_ENABLED];
1372 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1373 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1374 | VIEW_STATE_ENABLED];
1375 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1376 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1377 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1378
1379 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1380 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1381 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1382 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1383 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1384 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1385 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1386 | VIEW_STATE_PRESSED];
1387 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1388 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1389 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1390 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1391 | VIEW_STATE_PRESSED];
1392 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1393 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1394 | VIEW_STATE_PRESSED];
1395 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1396 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1397 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1398 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1399 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1400 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1401 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1402 | VIEW_STATE_PRESSED];
1403 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1404 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1405 | VIEW_STATE_PRESSED];
1406 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1407 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1408 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1409 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1410 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1411 | VIEW_STATE_PRESSED];
1412 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1413 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1414 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1415 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1416 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1417 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1418 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1421 | VIEW_STATE_PRESSED];
1422 }
1423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 /**
1425 * Used by views that contain lists of items. This state indicates that
1426 * the view is showing the last item.
1427 * @hide
1428 */
1429 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1430 /**
1431 * Used by views that contain lists of items. This state indicates that
1432 * the view is showing the first item.
1433 * @hide
1434 */
1435 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1436 /**
1437 * Used by views that contain lists of items. This state indicates that
1438 * the view is showing the middle item.
1439 * @hide
1440 */
1441 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1442 /**
1443 * Used by views that contain lists of items. This state indicates that
1444 * the view is showing only one item.
1445 * @hide
1446 */
1447 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1448 /**
1449 * Used by views that contain lists of items. This state indicates that
1450 * the view is pressed and showing the last item.
1451 * @hide
1452 */
1453 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1454 /**
1455 * Used by views that contain lists of items. This state indicates that
1456 * the view is pressed and showing the first item.
1457 * @hide
1458 */
1459 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1460 /**
1461 * Used by views that contain lists of items. This state indicates that
1462 * the view is pressed and showing the middle item.
1463 * @hide
1464 */
1465 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1466 /**
1467 * Used by views that contain lists of items. This state indicates that
1468 * the view is pressed and showing only one item.
1469 * @hide
1470 */
1471 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1472
1473 /**
1474 * Temporary Rect currently for use in setBackground(). This will probably
1475 * be extended in the future to hold our own class with more than just
1476 * a Rect. :)
1477 */
1478 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001479
1480 /**
1481 * Map used to store views' tags.
1482 */
1483 private static WeakHashMap<View, SparseArray<Object>> sTags;
1484
1485 /**
1486 * Lock used to access sTags.
1487 */
1488 private static final Object sTagsLock = new Object();
1489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 /**
1491 * The animation currently associated with this view.
1492 * @hide
1493 */
1494 protected Animation mCurrentAnimation = null;
1495
1496 /**
1497 * Width as measured during measure pass.
1498 * {@hide}
1499 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001500 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001501 /*package*/ int mMeasuredWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502
1503 /**
1504 * Height as measured during measure pass.
1505 * {@hide}
1506 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001507 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001508 /*package*/ int mMeasuredHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509
1510 /**
1511 * The view's identifier.
1512 * {@hide}
1513 *
1514 * @see #setId(int)
1515 * @see #getId()
1516 */
1517 @ViewDebug.ExportedProperty(resolveId = true)
1518 int mID = NO_ID;
1519
1520 /**
1521 * The view's tag.
1522 * {@hide}
1523 *
1524 * @see #setTag(Object)
1525 * @see #getTag()
1526 */
1527 protected Object mTag;
1528
1529 // for mPrivateFlags:
1530 /** {@hide} */
1531 static final int WANTS_FOCUS = 0x00000001;
1532 /** {@hide} */
1533 static final int FOCUSED = 0x00000002;
1534 /** {@hide} */
1535 static final int SELECTED = 0x00000004;
1536 /** {@hide} */
1537 static final int IS_ROOT_NAMESPACE = 0x00000008;
1538 /** {@hide} */
1539 static final int HAS_BOUNDS = 0x00000010;
1540 /** {@hide} */
1541 static final int DRAWN = 0x00000020;
1542 /**
1543 * When this flag is set, this view is running an animation on behalf of its
1544 * children and should therefore not cancel invalidate requests, even if they
1545 * lie outside of this view's bounds.
1546 *
1547 * {@hide}
1548 */
1549 static final int DRAW_ANIMATION = 0x00000040;
1550 /** {@hide} */
1551 static final int SKIP_DRAW = 0x00000080;
1552 /** {@hide} */
1553 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1554 /** {@hide} */
1555 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1556 /** {@hide} */
1557 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1558 /** {@hide} */
1559 static final int MEASURED_DIMENSION_SET = 0x00000800;
1560 /** {@hide} */
1561 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001562 /** {@hide} */
1563 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564
1565 private static final int PRESSED = 0x00004000;
1566
1567 /** {@hide} */
1568 static final int DRAWING_CACHE_VALID = 0x00008000;
1569 /**
1570 * Flag used to indicate that this view should be drawn once more (and only once
1571 * more) after its animation has completed.
1572 * {@hide}
1573 */
1574 static final int ANIMATION_STARTED = 0x00010000;
1575
1576 private static final int SAVE_STATE_CALLED = 0x00020000;
1577
1578 /**
1579 * Indicates that the View returned true when onSetAlpha() was called and that
1580 * the alpha must be restored.
1581 * {@hide}
1582 */
1583 static final int ALPHA_SET = 0x00040000;
1584
1585 /**
1586 * Set by {@link #setScrollContainer(boolean)}.
1587 */
1588 static final int SCROLL_CONTAINER = 0x00080000;
1589
1590 /**
1591 * Set by {@link #setScrollContainer(boolean)}.
1592 */
1593 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1594
1595 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001596 * View flag indicating whether this view was invalidated (fully or partially.)
1597 *
1598 * @hide
1599 */
1600 static final int DIRTY = 0x00200000;
1601
1602 /**
1603 * View flag indicating whether this view was invalidated by an opaque
1604 * invalidate request.
1605 *
1606 * @hide
1607 */
1608 static final int DIRTY_OPAQUE = 0x00400000;
1609
1610 /**
1611 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1612 *
1613 * @hide
1614 */
1615 static final int DIRTY_MASK = 0x00600000;
1616
1617 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001618 * Indicates whether the background is opaque.
1619 *
1620 * @hide
1621 */
1622 static final int OPAQUE_BACKGROUND = 0x00800000;
1623
1624 /**
1625 * Indicates whether the scrollbars are opaque.
1626 *
1627 * @hide
1628 */
1629 static final int OPAQUE_SCROLLBARS = 0x01000000;
1630
1631 /**
1632 * Indicates whether the view is opaque.
1633 *
1634 * @hide
1635 */
1636 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001637
1638 /**
1639 * Indicates a prepressed state;
1640 * the short time between ACTION_DOWN and recognizing
1641 * a 'real' press. Prepressed is used to recognize quick taps
1642 * even when they are shorter than ViewConfiguration.getTapTimeout().
1643 *
1644 * @hide
1645 */
1646 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001647
1648 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001649 * Indicates whether the view is temporarily detached.
1650 *
1651 * @hide
1652 */
1653 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001654
1655 /**
1656 * Indicates that we should awaken scroll bars once attached
1657 *
1658 * @hide
1659 */
1660 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001661
1662 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001663 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1664 * for transform operations
1665 *
1666 * @hide
1667 */
Adam Powellf37df072010-09-17 16:22:49 -07001668 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001669
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001670 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001671 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001672
Chet Haasefd2b0022010-08-06 13:08:56 -07001673 /**
Adam Powell637d3372010-08-25 14:37:03 -07001674 * Always allow a user to over-scroll this view, provided it is a
1675 * view that can scroll.
1676 *
1677 * @see #getOverScrollMode()
1678 * @see #setOverScrollMode(int)
1679 */
1680 public static final int OVER_SCROLL_ALWAYS = 0;
1681
1682 /**
1683 * Allow a user to over-scroll this view only if the content is large
1684 * enough to meaningfully scroll, provided it is a view that can scroll.
1685 *
1686 * @see #getOverScrollMode()
1687 * @see #setOverScrollMode(int)
1688 */
1689 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1690
1691 /**
1692 * Never allow a user to over-scroll this view.
1693 *
1694 * @see #getOverScrollMode()
1695 * @see #setOverScrollMode(int)
1696 */
1697 public static final int OVER_SCROLL_NEVER = 2;
1698
1699 /**
1700 * Controls the over-scroll mode for this view.
1701 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1702 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1703 * and {@link #OVER_SCROLL_NEVER}.
1704 */
1705 private int mOverScrollMode;
1706
1707 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 * The parent this view is attached to.
1709 * {@hide}
1710 *
1711 * @see #getParent()
1712 */
1713 protected ViewParent mParent;
1714
1715 /**
1716 * {@hide}
1717 */
1718 AttachInfo mAttachInfo;
1719
1720 /**
1721 * {@hide}
1722 */
Romain Guy809a7f62009-05-14 15:44:42 -07001723 @ViewDebug.ExportedProperty(flagMapping = {
1724 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1725 name = "FORCE_LAYOUT"),
1726 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1727 name = "LAYOUT_REQUIRED"),
1728 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001729 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001730 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1731 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1732 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1733 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1734 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 int mPrivateFlags;
1736
1737 /**
1738 * Count of how many windows this view has been attached to.
1739 */
1740 int mWindowAttachCount;
1741
1742 /**
1743 * The layout parameters associated with this view and used by the parent
1744 * {@link android.view.ViewGroup} to determine how this view should be
1745 * laid out.
1746 * {@hide}
1747 */
1748 protected ViewGroup.LayoutParams mLayoutParams;
1749
1750 /**
1751 * The view flags hold various views states.
1752 * {@hide}
1753 */
1754 @ViewDebug.ExportedProperty
1755 int mViewFlags;
1756
1757 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001758 * The transform matrix for the View. This transform is calculated internally
1759 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1760 * is used by default. Do *not* use this variable directly; instead call
1761 * getMatrix(), which will automatically recalculate the matrix if necessary
1762 * to get the correct matrix based on the latest rotation and scale properties.
1763 */
1764 private final Matrix mMatrix = new Matrix();
1765
1766 /**
1767 * The transform matrix for the View. This transform is calculated internally
1768 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1769 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001770 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001771 * to get the correct matrix based on the latest rotation and scale properties.
1772 */
1773 private Matrix mInverseMatrix;
1774
1775 /**
1776 * An internal variable that tracks whether we need to recalculate the
1777 * transform matrix, based on whether the rotation or scaleX/Y properties
1778 * have changed since the matrix was last calculated.
1779 */
1780 private boolean mMatrixDirty = false;
1781
1782 /**
1783 * An internal variable that tracks whether we need to recalculate the
1784 * transform matrix, based on whether the rotation or scaleX/Y properties
1785 * have changed since the matrix was last calculated.
1786 */
1787 private boolean mInverseMatrixDirty = true;
1788
1789 /**
1790 * A variable that tracks whether we need to recalculate the
1791 * transform matrix, based on whether the rotation or scaleX/Y properties
1792 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001793 * is only valid after a call to updateMatrix() or to a function that
1794 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001795 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001796 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001797
1798 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001799 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1800 */
1801 private Camera mCamera = null;
1802
1803 /**
1804 * This matrix is used when computing the matrix for 3D rotations.
1805 */
1806 private Matrix matrix3D = null;
1807
1808 /**
1809 * These prev values are used to recalculate a centered pivot point when necessary. The
1810 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1811 * set), so thes values are only used then as well.
1812 */
1813 private int mPrevWidth = -1;
1814 private int mPrevHeight = -1;
1815
1816 /**
1817 * Convenience value to check for float values that are close enough to zero to be considered
1818 * zero.
1819 */
Romain Guy2542d192010-08-18 11:47:12 -07001820 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001821
1822 /**
1823 * The degrees rotation around the vertical axis through the pivot point.
1824 */
1825 @ViewDebug.ExportedProperty
1826 private float mRotationY = 0f;
1827
1828 /**
1829 * The degrees rotation around the horizontal axis through the pivot point.
1830 */
1831 @ViewDebug.ExportedProperty
1832 private float mRotationX = 0f;
1833
1834 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001835 * The degrees rotation around the pivot point.
1836 */
1837 @ViewDebug.ExportedProperty
1838 private float mRotation = 0f;
1839
1840 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001841 * The amount of translation of the object away from its left property (post-layout).
1842 */
1843 @ViewDebug.ExportedProperty
1844 private float mTranslationX = 0f;
1845
1846 /**
1847 * The amount of translation of the object away from its top property (post-layout).
1848 */
1849 @ViewDebug.ExportedProperty
1850 private float mTranslationY = 0f;
1851
1852 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001853 * The amount of scale in the x direction around the pivot point. A
1854 * value of 1 means no scaling is applied.
1855 */
1856 @ViewDebug.ExportedProperty
1857 private float mScaleX = 1f;
1858
1859 /**
1860 * The amount of scale in the y direction around the pivot point. A
1861 * value of 1 means no scaling is applied.
1862 */
1863 @ViewDebug.ExportedProperty
1864 private float mScaleY = 1f;
1865
1866 /**
1867 * The amount of scale in the x direction around the pivot point. A
1868 * value of 1 means no scaling is applied.
1869 */
1870 @ViewDebug.ExportedProperty
1871 private float mPivotX = 0f;
1872
1873 /**
1874 * The amount of scale in the y direction around the pivot point. A
1875 * value of 1 means no scaling is applied.
1876 */
1877 @ViewDebug.ExportedProperty
1878 private float mPivotY = 0f;
1879
1880 /**
1881 * The opacity of the View. This is a value from 0 to 1, where 0 means
1882 * completely transparent and 1 means completely opaque.
1883 */
1884 @ViewDebug.ExportedProperty
1885 private float mAlpha = 1f;
1886
1887 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 * The distance in pixels from the left edge of this view's parent
1889 * to the left edge of this view.
1890 * {@hide}
1891 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001892 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 protected int mLeft;
1894 /**
1895 * The distance in pixels from the left edge of this view's parent
1896 * to the right edge of this view.
1897 * {@hide}
1898 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001899 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 protected int mRight;
1901 /**
1902 * The distance in pixels from the top edge of this view's parent
1903 * to the top edge of this view.
1904 * {@hide}
1905 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001906 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 protected int mTop;
1908 /**
1909 * The distance in pixels from the top edge of this view's parent
1910 * to the bottom edge of this view.
1911 * {@hide}
1912 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001913 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 protected int mBottom;
1915
1916 /**
1917 * The offset, in pixels, by which the content of this view is scrolled
1918 * horizontally.
1919 * {@hide}
1920 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001921 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 protected int mScrollX;
1923 /**
1924 * The offset, in pixels, by which the content of this view is scrolled
1925 * vertically.
1926 * {@hide}
1927 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001928 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 protected int mScrollY;
1930
1931 /**
1932 * The left padding in pixels, that is the distance in pixels between the
1933 * left edge of this view and the left edge of its content.
1934 * {@hide}
1935 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001936 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 protected int mPaddingLeft;
1938 /**
1939 * The right padding in pixels, that is the distance in pixels between the
1940 * right edge of this view and the right edge of its content.
1941 * {@hide}
1942 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001943 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 protected int mPaddingRight;
1945 /**
1946 * The top padding in pixels, that is the distance in pixels between the
1947 * top edge of this view and the top edge of its content.
1948 * {@hide}
1949 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001950 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 protected int mPaddingTop;
1952 /**
1953 * The bottom padding in pixels, that is the distance in pixels between the
1954 * bottom edge of this view and the bottom edge of its content.
1955 * {@hide}
1956 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001957 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 protected int mPaddingBottom;
1959
1960 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001961 * Briefly describes the view and is primarily used for accessibility support.
1962 */
1963 private CharSequence mContentDescription;
1964
1965 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 * Cache the paddingRight set by the user to append to the scrollbar's size.
1967 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001968 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 int mUserPaddingRight;
1970
1971 /**
1972 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1973 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001974 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 int mUserPaddingBottom;
1976
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001977 /**
Adam Powell20232d02010-12-08 21:08:53 -08001978 * Cache the paddingLeft set by the user to append to the scrollbar's size.
1979 */
1980 @ViewDebug.ExportedProperty(category = "padding")
1981 int mUserPaddingLeft;
1982
1983 /**
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001984 * @hide
1985 */
1986 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1987 /**
1988 * @hide
1989 */
1990 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991
1992 private Resources mResources = null;
1993
1994 private Drawable mBGDrawable;
1995
1996 private int mBackgroundResource;
1997 private boolean mBackgroundSizeChanged;
1998
1999 /**
2000 * Listener used to dispatch focus change events.
2001 * This field should be made private, so it is hidden from the SDK.
2002 * {@hide}
2003 */
2004 protected OnFocusChangeListener mOnFocusChangeListener;
2005
2006 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002007 * Listeners for layout change events.
2008 */
2009 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2010
2011 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 * Listener used to dispatch click events.
2013 * This field should be made private, so it is hidden from the SDK.
2014 * {@hide}
2015 */
2016 protected OnClickListener mOnClickListener;
2017
2018 /**
2019 * Listener used to dispatch long click events.
2020 * This field should be made private, so it is hidden from the SDK.
2021 * {@hide}
2022 */
2023 protected OnLongClickListener mOnLongClickListener;
2024
2025 /**
2026 * Listener used to build the context menu.
2027 * This field should be made private, so it is hidden from the SDK.
2028 * {@hide}
2029 */
2030 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2031
2032 private OnKeyListener mOnKeyListener;
2033
2034 private OnTouchListener mOnTouchListener;
2035
Chris Tate32affef2010-10-18 15:29:21 -07002036 private OnDragListener mOnDragListener;
2037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 /**
2039 * The application environment this view lives in.
2040 * This field should be made private, so it is hidden from the SDK.
2041 * {@hide}
2042 */
2043 protected Context mContext;
2044
2045 private ScrollabilityCache mScrollCache;
2046
2047 private int[] mDrawableState = null;
2048
Romain Guy02890fd2010-08-06 17:58:44 -07002049 private Bitmap mDrawingCache;
2050 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07002051 private DisplayList mDisplayList;
Romain Guy6c319ca2011-01-11 14:29:25 -08002052 private HardwareLayer mHardwareLayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053
2054 /**
2055 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2056 * the user may specify which view to go to next.
2057 */
2058 private int mNextFocusLeftId = View.NO_ID;
2059
2060 /**
2061 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2062 * the user may specify which view to go to next.
2063 */
2064 private int mNextFocusRightId = View.NO_ID;
2065
2066 /**
2067 * When this view has focus and the next focus is {@link #FOCUS_UP},
2068 * the user may specify which view to go to next.
2069 */
2070 private int mNextFocusUpId = View.NO_ID;
2071
2072 /**
2073 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2074 * the user may specify which view to go to next.
2075 */
2076 private int mNextFocusDownId = View.NO_ID;
2077
Jeff Brown4e6319b2010-12-13 10:36:51 -08002078 /**
2079 * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2080 * the user may specify which view to go to next.
2081 */
2082 int mNextFocusForwardId = View.NO_ID;
2083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08002085 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08002086 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08002087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 private UnsetPressedState mUnsetPressedState;
2089
2090 /**
2091 * Whether the long press's action has been invoked. The tap's action is invoked on the
2092 * up event while a long press is invoked as soon as the long press duration is reached, so
2093 * a long press could be performed before the tap is checked, in which case the tap's action
2094 * should not be invoked.
2095 */
2096 private boolean mHasPerformedLongPress;
2097
2098 /**
2099 * The minimum height of the view. We'll try our best to have the height
2100 * of this view to at least this amount.
2101 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002102 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 private int mMinHeight;
2104
2105 /**
2106 * The minimum width of the view. We'll try our best to have the width
2107 * of this view to at least this amount.
2108 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002109 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 private int mMinWidth;
2111
2112 /**
2113 * The delegate to handle touch events that are physically in this view
2114 * but should be handled by another view.
2115 */
2116 private TouchDelegate mTouchDelegate = null;
2117
2118 /**
2119 * Solid color to use as a background when creating the drawing cache. Enables
2120 * the cache to use 16 bit bitmaps instead of 32 bit.
2121 */
2122 private int mDrawingCacheBackgroundColor = 0;
2123
2124 /**
2125 * Special tree observer used when mAttachInfo is null.
2126 */
2127 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002128
2129 /**
2130 * Cache the touch slop from the context that created the view.
2131 */
2132 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002135 * Cache drag/drop state
2136 *
2137 */
2138 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002139
2140 /**
Christopher Tate02d2b3b2011-01-10 20:43:53 -08002141 * Flag indicating that a drag can cross window boundaries
2142 * @hide
2143 */
2144 public static final int DRAG_FLAG_GLOBAL = 1;
2145
2146 /**
Adam Powell20232d02010-12-08 21:08:53 -08002147 * Position of the vertical scroll bar.
2148 */
2149 private int mVerticalScrollbarPosition;
2150
2151 /**
2152 * Position the scroll bar at the default position as determined by the system.
2153 */
2154 public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2155
2156 /**
2157 * Position the scroll bar along the left edge.
2158 */
2159 public static final int SCROLLBAR_POSITION_LEFT = 1;
2160
2161 /**
2162 * Position the scroll bar along the right edge.
2163 */
2164 public static final int SCROLLBAR_POSITION_RIGHT = 2;
2165
2166 /**
Romain Guy171c5922011-01-06 10:04:23 -08002167 * Indicates that the view does not have a layer.
2168 *
2169 * @see #getLayerType()
2170 * @see #setLayerType(int, android.graphics.Paint)
2171 * @see #LAYER_TYPE_SOFTWARE
2172 * @see #LAYER_TYPE_HARDWARE
2173 */
2174 public static final int LAYER_TYPE_NONE = 0;
2175
2176 /**
2177 * <p>Indicates that the view has a software layer. A software layer is backed
2178 * by a bitmap and causes the view to be rendered using Android's software
2179 * rendering pipeline, even if hardware acceleration is enabled.</p>
2180 *
2181 * <p>Software layers have various usages:</p>
2182 * <p>When the application is not using hardware acceleration, a software layer
2183 * is useful to apply a specific color filter and/or blending mode and/or
2184 * translucency to a view and all its children.</p>
2185 * <p>When the application is using hardware acceleration, a software layer
2186 * is useful to render drawing primitives not supported by the hardware
2187 * accelerated pipeline. It can also be used to cache a complex view tree
2188 * into a texture and reduce the complexity of drawing operations. For instance,
2189 * when animating a complex view tree with a translation, a software layer can
2190 * be used to render the view tree only once.</p>
2191 * <p>Software layers should be avoided when the affected view tree updates
2192 * often. Every update will require to re-render the software layer, which can
2193 * potentially be slow (particularly when hardware acceleration is turned on
2194 * since the layer will have to be uploaded into a hardware texture after every
2195 * update.)</p>
2196 *
2197 * @see #getLayerType()
2198 * @see #setLayerType(int, android.graphics.Paint)
2199 * @see #LAYER_TYPE_NONE
2200 * @see #LAYER_TYPE_HARDWARE
2201 */
2202 public static final int LAYER_TYPE_SOFTWARE = 1;
2203
2204 /**
2205 * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2206 * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2207 * OpenGL hardware) and causes the view to be rendered using Android's hardware
2208 * rendering pipeline, but only if hardware acceleration is turned on for the
2209 * view hierarchy. When hardware acceleration is turned off, hardware layers
2210 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2211 *
2212 * <p>A hardware layer is useful to apply a specific color filter and/or
2213 * blending mode and/or translucency to a view and all its children.</p>
Romain Guy6c319ca2011-01-11 14:29:25 -08002214 * <p>A hardware layer can be used to cache a complex view tree into a
2215 * texture and reduce the complexity of drawing operations. For instance,
2216 * when animating a complex view tree with a translation, a hardware layer can
2217 * be used to render the view tree only once.</p>
Romain Guy171c5922011-01-06 10:04:23 -08002218 * <p>A hardware layer can also be used to increase the rendering quality when
2219 * rotation transformations are applied on a view. It can also be used to
2220 * prevent potential clipping issues when applying 3D transforms on a view.</p>
2221 *
2222 * @see #getLayerType()
2223 * @see #setLayerType(int, android.graphics.Paint)
2224 * @see #LAYER_TYPE_NONE
2225 * @see #LAYER_TYPE_SOFTWARE
2226 */
2227 public static final int LAYER_TYPE_HARDWARE = 2;
2228
2229 @ViewDebug.ExportedProperty(category = "drawing")
2230 int mLayerType = LAYER_TYPE_NONE;
2231 Paint mLayerPaint;
2232
2233 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 * Simple constructor to use when creating a view from code.
2235 *
2236 * @param context The Context the view is running in, through which it can
2237 * access the current theme, resources, etc.
2238 */
2239 public View(Context context) {
2240 mContext = context;
2241 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002242 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002243 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Adam Powell637d3372010-08-25 14:37:03 -07002244 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 }
2246
2247 /**
2248 * Constructor that is called when inflating a view from XML. This is called
2249 * when a view is being constructed from an XML file, supplying attributes
2250 * that were specified in the XML file. This version uses a default style of
2251 * 0, so the only attribute values applied are those in the Context's Theme
2252 * and the given AttributeSet.
2253 *
2254 * <p>
2255 * The method onFinishInflate() will be called after all children have been
2256 * added.
2257 *
2258 * @param context The Context the view is running in, through which it can
2259 * access the current theme, resources, etc.
2260 * @param attrs The attributes of the XML tag that is inflating the view.
2261 * @see #View(Context, AttributeSet, int)
2262 */
2263 public View(Context context, AttributeSet attrs) {
2264 this(context, attrs, 0);
2265 }
2266
2267 /**
2268 * Perform inflation from XML and apply a class-specific base style. This
2269 * constructor of View allows subclasses to use their own base style when
2270 * they are inflating. For example, a Button class's constructor would call
2271 * this version of the super class constructor and supply
2272 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2273 * the theme's button style to modify all of the base view attributes (in
2274 * particular its background) as well as the Button class's attributes.
2275 *
2276 * @param context The Context the view is running in, through which it can
2277 * access the current theme, resources, etc.
2278 * @param attrs The attributes of the XML tag that is inflating the view.
2279 * @param defStyle The default style to apply to this view. If 0, no style
2280 * will be applied (beyond what is included in the theme). This may
2281 * either be an attribute resource, whose value will be retrieved
2282 * from the current theme, or an explicit style resource.
2283 * @see #View(Context, AttributeSet)
2284 */
2285 public View(Context context, AttributeSet attrs, int defStyle) {
2286 this(context);
2287
2288 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2289 defStyle, 0);
2290
2291 Drawable background = null;
2292
2293 int leftPadding = -1;
2294 int topPadding = -1;
2295 int rightPadding = -1;
2296 int bottomPadding = -1;
2297
2298 int padding = -1;
2299
2300 int viewFlagValues = 0;
2301 int viewFlagMasks = 0;
2302
2303 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 int x = 0;
2306 int y = 0;
2307
Chet Haase73066682010-11-29 15:55:32 -08002308 float tx = 0;
2309 float ty = 0;
2310 float rotation = 0;
2311 float rotationX = 0;
2312 float rotationY = 0;
2313 float sx = 1f;
2314 float sy = 1f;
2315 boolean transformSet = false;
2316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2318
Adam Powell637d3372010-08-25 14:37:03 -07002319 int overScrollMode = mOverScrollMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320 final int N = a.getIndexCount();
2321 for (int i = 0; i < N; i++) {
2322 int attr = a.getIndex(i);
2323 switch (attr) {
2324 case com.android.internal.R.styleable.View_background:
2325 background = a.getDrawable(attr);
2326 break;
2327 case com.android.internal.R.styleable.View_padding:
2328 padding = a.getDimensionPixelSize(attr, -1);
2329 break;
2330 case com.android.internal.R.styleable.View_paddingLeft:
2331 leftPadding = a.getDimensionPixelSize(attr, -1);
2332 break;
2333 case com.android.internal.R.styleable.View_paddingTop:
2334 topPadding = a.getDimensionPixelSize(attr, -1);
2335 break;
2336 case com.android.internal.R.styleable.View_paddingRight:
2337 rightPadding = a.getDimensionPixelSize(attr, -1);
2338 break;
2339 case com.android.internal.R.styleable.View_paddingBottom:
2340 bottomPadding = a.getDimensionPixelSize(attr, -1);
2341 break;
2342 case com.android.internal.R.styleable.View_scrollX:
2343 x = a.getDimensionPixelOffset(attr, 0);
2344 break;
2345 case com.android.internal.R.styleable.View_scrollY:
2346 y = a.getDimensionPixelOffset(attr, 0);
2347 break;
Chet Haase73066682010-11-29 15:55:32 -08002348 case com.android.internal.R.styleable.View_alpha:
2349 setAlpha(a.getFloat(attr, 1f));
2350 break;
2351 case com.android.internal.R.styleable.View_transformPivotX:
2352 setPivotX(a.getDimensionPixelOffset(attr, 0));
2353 break;
2354 case com.android.internal.R.styleable.View_transformPivotY:
2355 setPivotY(a.getDimensionPixelOffset(attr, 0));
2356 break;
2357 case com.android.internal.R.styleable.View_translationX:
2358 tx = a.getDimensionPixelOffset(attr, 0);
2359 transformSet = true;
2360 break;
2361 case com.android.internal.R.styleable.View_translationY:
2362 ty = a.getDimensionPixelOffset(attr, 0);
2363 transformSet = true;
2364 break;
2365 case com.android.internal.R.styleable.View_rotation:
2366 rotation = a.getFloat(attr, 0);
2367 transformSet = true;
2368 break;
2369 case com.android.internal.R.styleable.View_rotationX:
2370 rotationX = a.getFloat(attr, 0);
2371 transformSet = true;
2372 break;
2373 case com.android.internal.R.styleable.View_rotationY:
2374 rotationY = a.getFloat(attr, 0);
2375 transformSet = true;
2376 break;
2377 case com.android.internal.R.styleable.View_scaleX:
2378 sx = a.getFloat(attr, 1f);
2379 transformSet = true;
2380 break;
2381 case com.android.internal.R.styleable.View_scaleY:
2382 sy = a.getFloat(attr, 1f);
2383 transformSet = true;
2384 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 case com.android.internal.R.styleable.View_id:
2386 mID = a.getResourceId(attr, NO_ID);
2387 break;
2388 case com.android.internal.R.styleable.View_tag:
2389 mTag = a.getText(attr);
2390 break;
2391 case com.android.internal.R.styleable.View_fitsSystemWindows:
2392 if (a.getBoolean(attr, false)) {
2393 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2394 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2395 }
2396 break;
2397 case com.android.internal.R.styleable.View_focusable:
2398 if (a.getBoolean(attr, false)) {
2399 viewFlagValues |= FOCUSABLE;
2400 viewFlagMasks |= FOCUSABLE_MASK;
2401 }
2402 break;
2403 case com.android.internal.R.styleable.View_focusableInTouchMode:
2404 if (a.getBoolean(attr, false)) {
2405 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2406 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2407 }
2408 break;
2409 case com.android.internal.R.styleable.View_clickable:
2410 if (a.getBoolean(attr, false)) {
2411 viewFlagValues |= CLICKABLE;
2412 viewFlagMasks |= CLICKABLE;
2413 }
2414 break;
2415 case com.android.internal.R.styleable.View_longClickable:
2416 if (a.getBoolean(attr, false)) {
2417 viewFlagValues |= LONG_CLICKABLE;
2418 viewFlagMasks |= LONG_CLICKABLE;
2419 }
2420 break;
2421 case com.android.internal.R.styleable.View_saveEnabled:
2422 if (!a.getBoolean(attr, true)) {
2423 viewFlagValues |= SAVE_DISABLED;
2424 viewFlagMasks |= SAVE_DISABLED_MASK;
2425 }
2426 break;
2427 case com.android.internal.R.styleable.View_duplicateParentState:
2428 if (a.getBoolean(attr, false)) {
2429 viewFlagValues |= DUPLICATE_PARENT_STATE;
2430 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2431 }
2432 break;
2433 case com.android.internal.R.styleable.View_visibility:
2434 final int visibility = a.getInt(attr, 0);
2435 if (visibility != 0) {
2436 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2437 viewFlagMasks |= VISIBILITY_MASK;
2438 }
2439 break;
2440 case com.android.internal.R.styleable.View_drawingCacheQuality:
2441 final int cacheQuality = a.getInt(attr, 0);
2442 if (cacheQuality != 0) {
2443 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2444 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2445 }
2446 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002447 case com.android.internal.R.styleable.View_contentDescription:
2448 mContentDescription = a.getString(attr);
2449 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2451 if (!a.getBoolean(attr, true)) {
2452 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2453 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2454 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002455 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2457 if (!a.getBoolean(attr, true)) {
2458 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2459 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2460 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002461 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462 case R.styleable.View_scrollbars:
2463 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2464 if (scrollbars != SCROLLBARS_NONE) {
2465 viewFlagValues |= scrollbars;
2466 viewFlagMasks |= SCROLLBARS_MASK;
2467 initializeScrollbars(a);
2468 }
2469 break;
2470 case R.styleable.View_fadingEdge:
2471 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2472 if (fadingEdge != FADING_EDGE_NONE) {
2473 viewFlagValues |= fadingEdge;
2474 viewFlagMasks |= FADING_EDGE_MASK;
2475 initializeFadingEdge(a);
2476 }
2477 break;
2478 case R.styleable.View_scrollbarStyle:
2479 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2480 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2481 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2482 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2483 }
2484 break;
2485 case R.styleable.View_isScrollContainer:
2486 setScrollContainer = true;
2487 if (a.getBoolean(attr, false)) {
2488 setScrollContainer(true);
2489 }
2490 break;
2491 case com.android.internal.R.styleable.View_keepScreenOn:
2492 if (a.getBoolean(attr, false)) {
2493 viewFlagValues |= KEEP_SCREEN_ON;
2494 viewFlagMasks |= KEEP_SCREEN_ON;
2495 }
2496 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002497 case R.styleable.View_filterTouchesWhenObscured:
2498 if (a.getBoolean(attr, false)) {
2499 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2500 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2501 }
2502 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 case R.styleable.View_nextFocusLeft:
2504 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2505 break;
2506 case R.styleable.View_nextFocusRight:
2507 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2508 break;
2509 case R.styleable.View_nextFocusUp:
2510 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2511 break;
2512 case R.styleable.View_nextFocusDown:
2513 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2514 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002515 case R.styleable.View_nextFocusForward:
2516 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2517 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 case R.styleable.View_minWidth:
2519 mMinWidth = a.getDimensionPixelSize(attr, 0);
2520 break;
2521 case R.styleable.View_minHeight:
2522 mMinHeight = a.getDimensionPixelSize(attr, 0);
2523 break;
Romain Guy9a817362009-05-01 10:57:14 -07002524 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002525 if (context.isRestricted()) {
2526 throw new IllegalStateException("The android:onClick attribute cannot "
2527 + "be used within a restricted context");
2528 }
2529
Romain Guy9a817362009-05-01 10:57:14 -07002530 final String handlerName = a.getString(attr);
2531 if (handlerName != null) {
2532 setOnClickListener(new OnClickListener() {
2533 private Method mHandler;
2534
2535 public void onClick(View v) {
2536 if (mHandler == null) {
2537 try {
2538 mHandler = getContext().getClass().getMethod(handlerName,
2539 View.class);
2540 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002541 int id = getId();
2542 String idText = id == NO_ID ? "" : " with id '"
2543 + getContext().getResources().getResourceEntryName(
2544 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002545 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002546 handlerName + "(View) in the activity "
2547 + getContext().getClass() + " for onClick handler"
2548 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002549 }
2550 }
2551
2552 try {
2553 mHandler.invoke(getContext(), View.this);
2554 } catch (IllegalAccessException e) {
2555 throw new IllegalStateException("Could not execute non "
2556 + "public method of the activity", e);
2557 } catch (InvocationTargetException e) {
2558 throw new IllegalStateException("Could not execute "
2559 + "method of the activity", e);
2560 }
2561 }
2562 });
2563 }
2564 break;
Adam Powell637d3372010-08-25 14:37:03 -07002565 case R.styleable.View_overScrollMode:
2566 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2567 break;
Adam Powell20232d02010-12-08 21:08:53 -08002568 case R.styleable.View_verticalScrollbarPosition:
2569 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2570 break;
Romain Guy171c5922011-01-06 10:04:23 -08002571 case R.styleable.View_layerType:
2572 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
2573 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575 }
2576
Adam Powell637d3372010-08-25 14:37:03 -07002577 setOverScrollMode(overScrollMode);
2578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 if (background != null) {
2580 setBackgroundDrawable(background);
2581 }
2582
2583 if (padding >= 0) {
2584 leftPadding = padding;
2585 topPadding = padding;
2586 rightPadding = padding;
2587 bottomPadding = padding;
2588 }
2589
2590 // If the user specified the padding (either with android:padding or
2591 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2592 // use the default padding or the padding from the background drawable
2593 // (stored at this point in mPadding*)
2594 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2595 topPadding >= 0 ? topPadding : mPaddingTop,
2596 rightPadding >= 0 ? rightPadding : mPaddingRight,
2597 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2598
2599 if (viewFlagMasks != 0) {
2600 setFlags(viewFlagValues, viewFlagMasks);
2601 }
2602
2603 // Needs to be called after mViewFlags is set
2604 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2605 recomputePadding();
2606 }
2607
2608 if (x != 0 || y != 0) {
2609 scrollTo(x, y);
2610 }
2611
Chet Haase73066682010-11-29 15:55:32 -08002612 if (transformSet) {
2613 setTranslationX(tx);
2614 setTranslationY(ty);
2615 setRotation(rotation);
2616 setRotationX(rotationX);
2617 setRotationY(rotationY);
2618 setScaleX(sx);
2619 setScaleY(sy);
2620 }
2621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2623 setScrollContainer(true);
2624 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002625
2626 computeOpaqueFlags();
2627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 a.recycle();
2629 }
2630
2631 /**
2632 * Non-public constructor for use in testing
2633 */
2634 View() {
2635 }
2636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 /**
2638 * <p>
2639 * Initializes the fading edges from a given set of styled attributes. This
2640 * method should be called by subclasses that need fading edges and when an
2641 * instance of these subclasses is created programmatically rather than
2642 * being inflated from XML. This method is automatically called when the XML
2643 * is inflated.
2644 * </p>
2645 *
2646 * @param a the styled attributes set to initialize the fading edges from
2647 */
2648 protected void initializeFadingEdge(TypedArray a) {
2649 initScrollCache();
2650
2651 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2652 R.styleable.View_fadingEdgeLength,
2653 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2654 }
2655
2656 /**
2657 * Returns the size of the vertical faded edges used to indicate that more
2658 * content in this view is visible.
2659 *
2660 * @return The size in pixels of the vertical faded edge or 0 if vertical
2661 * faded edges are not enabled for this view.
2662 * @attr ref android.R.styleable#View_fadingEdgeLength
2663 */
2664 public int getVerticalFadingEdgeLength() {
2665 if (isVerticalFadingEdgeEnabled()) {
2666 ScrollabilityCache cache = mScrollCache;
2667 if (cache != null) {
2668 return cache.fadingEdgeLength;
2669 }
2670 }
2671 return 0;
2672 }
2673
2674 /**
2675 * Set the size of the faded edge used to indicate that more content in this
2676 * view is available. Will not change whether the fading edge is enabled; use
2677 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2678 * to enable the fading edge for the vertical or horizontal fading edges.
2679 *
2680 * @param length The size in pixels of the faded edge used to indicate that more
2681 * content in this view is visible.
2682 */
2683 public void setFadingEdgeLength(int length) {
2684 initScrollCache();
2685 mScrollCache.fadingEdgeLength = length;
2686 }
2687
2688 /**
2689 * Returns the size of the horizontal faded edges used to indicate that more
2690 * content in this view is visible.
2691 *
2692 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2693 * faded edges are not enabled for this view.
2694 * @attr ref android.R.styleable#View_fadingEdgeLength
2695 */
2696 public int getHorizontalFadingEdgeLength() {
2697 if (isHorizontalFadingEdgeEnabled()) {
2698 ScrollabilityCache cache = mScrollCache;
2699 if (cache != null) {
2700 return cache.fadingEdgeLength;
2701 }
2702 }
2703 return 0;
2704 }
2705
2706 /**
2707 * Returns the width of the vertical scrollbar.
2708 *
2709 * @return The width in pixels of the vertical scrollbar or 0 if there
2710 * is no vertical scrollbar.
2711 */
2712 public int getVerticalScrollbarWidth() {
2713 ScrollabilityCache cache = mScrollCache;
2714 if (cache != null) {
2715 ScrollBarDrawable scrollBar = cache.scrollBar;
2716 if (scrollBar != null) {
2717 int size = scrollBar.getSize(true);
2718 if (size <= 0) {
2719 size = cache.scrollBarSize;
2720 }
2721 return size;
2722 }
2723 return 0;
2724 }
2725 return 0;
2726 }
2727
2728 /**
2729 * Returns the height of the horizontal scrollbar.
2730 *
2731 * @return The height in pixels of the horizontal scrollbar or 0 if
2732 * there is no horizontal scrollbar.
2733 */
2734 protected int getHorizontalScrollbarHeight() {
2735 ScrollabilityCache cache = mScrollCache;
2736 if (cache != null) {
2737 ScrollBarDrawable scrollBar = cache.scrollBar;
2738 if (scrollBar != null) {
2739 int size = scrollBar.getSize(false);
2740 if (size <= 0) {
2741 size = cache.scrollBarSize;
2742 }
2743 return size;
2744 }
2745 return 0;
2746 }
2747 return 0;
2748 }
2749
2750 /**
2751 * <p>
2752 * Initializes the scrollbars from a given set of styled attributes. This
2753 * method should be called by subclasses that need scrollbars and when an
2754 * instance of these subclasses is created programmatically rather than
2755 * being inflated from XML. This method is automatically called when the XML
2756 * is inflated.
2757 * </p>
2758 *
2759 * @param a the styled attributes set to initialize the scrollbars from
2760 */
2761 protected void initializeScrollbars(TypedArray a) {
2762 initScrollCache();
2763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002765
2766 if (scrollabilityCache.scrollBar == null) {
2767 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2768 }
2769
Romain Guy8bda2482010-03-02 11:42:11 -08002770 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771
Mike Cleronf116bf82009-09-27 19:14:12 -07002772 if (!fadeScrollbars) {
2773 scrollabilityCache.state = ScrollabilityCache.ON;
2774 }
2775 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2776
2777
2778 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2779 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2780 .getScrollBarFadeDuration());
2781 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2782 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2783 ViewConfiguration.getScrollDefaultDelay());
2784
2785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2787 com.android.internal.R.styleable.View_scrollbarSize,
2788 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2789
2790 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2791 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2792
2793 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2794 if (thumb != null) {
2795 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2796 }
2797
2798 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2799 false);
2800 if (alwaysDraw) {
2801 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2802 }
2803
2804 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2805 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2806
2807 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2808 if (thumb != null) {
2809 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2810 }
2811
2812 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2813 false);
2814 if (alwaysDraw) {
2815 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2816 }
2817
2818 // Re-apply user/background padding so that scrollbar(s) get added
2819 recomputePadding();
2820 }
2821
2822 /**
2823 * <p>
2824 * Initalizes the scrollability cache if necessary.
2825 * </p>
2826 */
2827 private void initScrollCache() {
2828 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002829 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 }
2831 }
2832
2833 /**
Adam Powell20232d02010-12-08 21:08:53 -08002834 * Set the position of the vertical scroll bar. Should be one of
2835 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
2836 * {@link #SCROLLBAR_POSITION_RIGHT}.
2837 *
2838 * @param position Where the vertical scroll bar should be positioned.
2839 */
2840 public void setVerticalScrollbarPosition(int position) {
2841 if (mVerticalScrollbarPosition != position) {
2842 mVerticalScrollbarPosition = position;
2843 computeOpaqueFlags();
2844 recomputePadding();
2845 }
2846 }
2847
2848 /**
2849 * @return The position where the vertical scroll bar will show, if applicable.
2850 * @see #setVerticalScrollbarPosition(int)
2851 */
2852 public int getVerticalScrollbarPosition() {
2853 return mVerticalScrollbarPosition;
2854 }
2855
2856 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 * Register a callback to be invoked when focus of this view changed.
2858 *
2859 * @param l The callback that will run.
2860 */
2861 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2862 mOnFocusChangeListener = l;
2863 }
2864
2865 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002866 * Add a listener that will be called when the bounds of the view change due to
2867 * layout processing.
2868 *
2869 * @param listener The listener that will be called when layout bounds change.
2870 */
2871 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2872 if (mOnLayoutChangeListeners == null) {
2873 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2874 }
2875 mOnLayoutChangeListeners.add(listener);
2876 }
2877
2878 /**
2879 * Remove a listener for layout changes.
2880 *
2881 * @param listener The listener for layout bounds change.
2882 */
2883 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2884 if (mOnLayoutChangeListeners == null) {
2885 return;
2886 }
2887 mOnLayoutChangeListeners.remove(listener);
2888 }
2889
2890 /**
2891 * Gets the current list of listeners for layout changes.
Chet Haase21cd1382010-09-01 17:42:29 -07002892 */
2893 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2894 return mOnLayoutChangeListeners;
2895 }
2896
2897 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 * Returns the focus-change callback registered for this view.
2899 *
2900 * @return The callback, or null if one is not registered.
2901 */
2902 public OnFocusChangeListener getOnFocusChangeListener() {
2903 return mOnFocusChangeListener;
2904 }
2905
2906 /**
2907 * Register a callback to be invoked when this view is clicked. If this view is not
2908 * clickable, it becomes clickable.
2909 *
2910 * @param l The callback that will run
2911 *
2912 * @see #setClickable(boolean)
2913 */
2914 public void setOnClickListener(OnClickListener l) {
2915 if (!isClickable()) {
2916 setClickable(true);
2917 }
2918 mOnClickListener = l;
2919 }
2920
2921 /**
2922 * Register a callback to be invoked when this view is clicked and held. If this view is not
2923 * long clickable, it becomes long clickable.
2924 *
2925 * @param l The callback that will run
2926 *
2927 * @see #setLongClickable(boolean)
2928 */
2929 public void setOnLongClickListener(OnLongClickListener l) {
2930 if (!isLongClickable()) {
2931 setLongClickable(true);
2932 }
2933 mOnLongClickListener = l;
2934 }
2935
2936 /**
2937 * Register a callback to be invoked when the context menu for this view is
2938 * being built. If this view is not long clickable, it becomes long clickable.
2939 *
2940 * @param l The callback that will run
2941 *
2942 */
2943 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2944 if (!isLongClickable()) {
2945 setLongClickable(true);
2946 }
2947 mOnCreateContextMenuListener = l;
2948 }
2949
2950 /**
2951 * Call this view's OnClickListener, if it is defined.
2952 *
2953 * @return True there was an assigned OnClickListener that was called, false
2954 * otherwise is returned.
2955 */
2956 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002957 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 if (mOnClickListener != null) {
2960 playSoundEffect(SoundEffectConstants.CLICK);
2961 mOnClickListener.onClick(this);
2962 return true;
2963 }
2964
2965 return false;
2966 }
2967
2968 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002969 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2970 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002972 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 */
2974 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002975 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 boolean handled = false;
2978 if (mOnLongClickListener != null) {
2979 handled = mOnLongClickListener.onLongClick(View.this);
2980 }
2981 if (!handled) {
2982 handled = showContextMenu();
2983 }
2984 if (handled) {
2985 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2986 }
2987 return handled;
2988 }
2989
2990 /**
2991 * Bring up the context menu for this view.
2992 *
2993 * @return Whether a context menu was displayed.
2994 */
2995 public boolean showContextMenu() {
2996 return getParent().showContextMenuForChild(this);
2997 }
2998
2999 /**
Adam Powell6e346362010-07-23 10:18:23 -07003000 * Start an action mode.
3001 *
3002 * @param callback Callback that will control the lifecycle of the action mode
3003 * @return The new action mode if it is started, null otherwise
3004 *
3005 * @see ActionMode
3006 */
3007 public ActionMode startActionMode(ActionMode.Callback callback) {
3008 return getParent().startActionModeForChild(this, callback);
3009 }
3010
3011 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 * Register a callback to be invoked when a key is pressed in this view.
3013 * @param l the key listener to attach to this view
3014 */
3015 public void setOnKeyListener(OnKeyListener l) {
3016 mOnKeyListener = l;
3017 }
3018
3019 /**
3020 * Register a callback to be invoked when a touch event is sent to this view.
3021 * @param l the touch listener to attach to this view
3022 */
3023 public void setOnTouchListener(OnTouchListener l) {
3024 mOnTouchListener = l;
3025 }
3026
3027 /**
Chris Tate32affef2010-10-18 15:29:21 -07003028 * Register a callback to be invoked when a drag event is sent to this view.
3029 * @param l The drag listener to attach to this view
3030 */
3031 public void setOnDragListener(OnDragListener l) {
3032 mOnDragListener = l;
3033 }
3034
3035 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
3037 *
3038 * Note: this does not check whether this {@link View} should get focus, it just
3039 * gives it focus no matter what. It should only be called internally by framework
3040 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3041 *
3042 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
3043 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
3044 * focus moved when requestFocus() is called. It may not always
3045 * apply, in which case use the default View.FOCUS_DOWN.
3046 * @param previouslyFocusedRect The rectangle of the view that had focus
3047 * prior in this View's coordinate system.
3048 */
3049 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3050 if (DBG) {
3051 System.out.println(this + " requestFocus()");
3052 }
3053
3054 if ((mPrivateFlags & FOCUSED) == 0) {
3055 mPrivateFlags |= FOCUSED;
3056
3057 if (mParent != null) {
3058 mParent.requestChildFocus(this, this);
3059 }
3060
3061 onFocusChanged(true, direction, previouslyFocusedRect);
3062 refreshDrawableState();
3063 }
3064 }
3065
3066 /**
3067 * Request that a rectangle of this view be visible on the screen,
3068 * scrolling if necessary just enough.
3069 *
3070 * <p>A View should call this if it maintains some notion of which part
3071 * of its content is interesting. For example, a text editing view
3072 * should call this when its cursor moves.
3073 *
3074 * @param rectangle The rectangle.
3075 * @return Whether any parent scrolled.
3076 */
3077 public boolean requestRectangleOnScreen(Rect rectangle) {
3078 return requestRectangleOnScreen(rectangle, false);
3079 }
3080
3081 /**
3082 * Request that a rectangle of this view be visible on the screen,
3083 * scrolling if necessary just enough.
3084 *
3085 * <p>A View should call this if it maintains some notion of which part
3086 * of its content is interesting. For example, a text editing view
3087 * should call this when its cursor moves.
3088 *
3089 * <p>When <code>immediate</code> is set to true, scrolling will not be
3090 * animated.
3091 *
3092 * @param rectangle The rectangle.
3093 * @param immediate True to forbid animated scrolling, false otherwise
3094 * @return Whether any parent scrolled.
3095 */
3096 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3097 View child = this;
3098 ViewParent parent = mParent;
3099 boolean scrolled = false;
3100 while (parent != null) {
3101 scrolled |= parent.requestChildRectangleOnScreen(child,
3102 rectangle, immediate);
3103
3104 // offset rect so next call has the rectangle in the
3105 // coordinate system of its direct child.
3106 rectangle.offset(child.getLeft(), child.getTop());
3107 rectangle.offset(-child.getScrollX(), -child.getScrollY());
3108
3109 if (!(parent instanceof View)) {
3110 break;
3111 }
Romain Guy8506ab42009-06-11 17:35:47 -07003112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003113 child = (View) parent;
3114 parent = child.getParent();
3115 }
3116 return scrolled;
3117 }
3118
3119 /**
3120 * Called when this view wants to give up focus. This will cause
3121 * {@link #onFocusChanged} to be called.
3122 */
3123 public void clearFocus() {
3124 if (DBG) {
3125 System.out.println(this + " clearFocus()");
3126 }
3127
3128 if ((mPrivateFlags & FOCUSED) != 0) {
3129 mPrivateFlags &= ~FOCUSED;
3130
3131 if (mParent != null) {
3132 mParent.clearChildFocus(this);
3133 }
3134
3135 onFocusChanged(false, 0, null);
3136 refreshDrawableState();
3137 }
3138 }
3139
3140 /**
3141 * Called to clear the focus of a view that is about to be removed.
3142 * Doesn't call clearChildFocus, which prevents this view from taking
3143 * focus again before it has been removed from the parent
3144 */
3145 void clearFocusForRemoval() {
3146 if ((mPrivateFlags & FOCUSED) != 0) {
3147 mPrivateFlags &= ~FOCUSED;
3148
3149 onFocusChanged(false, 0, null);
3150 refreshDrawableState();
3151 }
3152 }
3153
3154 /**
3155 * Called internally by the view system when a new view is getting focus.
3156 * This is what clears the old focus.
3157 */
3158 void unFocus() {
3159 if (DBG) {
3160 System.out.println(this + " unFocus()");
3161 }
3162
3163 if ((mPrivateFlags & FOCUSED) != 0) {
3164 mPrivateFlags &= ~FOCUSED;
3165
3166 onFocusChanged(false, 0, null);
3167 refreshDrawableState();
3168 }
3169 }
3170
3171 /**
3172 * Returns true if this view has focus iteself, or is the ancestor of the
3173 * view that has focus.
3174 *
3175 * @return True if this view has or contains focus, false otherwise.
3176 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003177 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 public boolean hasFocus() {
3179 return (mPrivateFlags & FOCUSED) != 0;
3180 }
3181
3182 /**
3183 * Returns true if this view is focusable or if it contains a reachable View
3184 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3185 * is a View whose parents do not block descendants focus.
3186 *
3187 * Only {@link #VISIBLE} views are considered focusable.
3188 *
3189 * @return True if the view is focusable or if the view contains a focusable
3190 * View, false otherwise.
3191 *
3192 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3193 */
3194 public boolean hasFocusable() {
3195 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3196 }
3197
3198 /**
3199 * Called by the view system when the focus state of this view changes.
3200 * When the focus change event is caused by directional navigation, direction
3201 * and previouslyFocusedRect provide insight into where the focus is coming from.
3202 * When overriding, be sure to call up through to the super class so that
3203 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07003204 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 * @param gainFocus True if the View has focus; false otherwise.
3206 * @param direction The direction focus has moved when requestFocus()
3207 * is called to give this view focus. Values are
Jeff Brown4e6319b2010-12-13 10:36:51 -08003208 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3209 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3210 * It may not always apply, in which case use the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 * @param previouslyFocusedRect The rectangle, in this view's coordinate
3212 * system, of the previously focused view. If applicable, this will be
3213 * passed in as finer grained information about where the focus is coming
3214 * from (in addition to direction). Will be <code>null</code> otherwise.
3215 */
3216 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003217 if (gainFocus) {
3218 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3219 }
3220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 InputMethodManager imm = InputMethodManager.peekInstance();
3222 if (!gainFocus) {
3223 if (isPressed()) {
3224 setPressed(false);
3225 }
3226 if (imm != null && mAttachInfo != null
3227 && mAttachInfo.mHasWindowFocus) {
3228 imm.focusOut(this);
3229 }
Romain Guya2431d02009-04-30 16:30:00 -07003230 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 } else if (imm != null && mAttachInfo != null
3232 && mAttachInfo.mHasWindowFocus) {
3233 imm.focusIn(this);
3234 }
Romain Guy8506ab42009-06-11 17:35:47 -07003235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 invalidate();
3237 if (mOnFocusChangeListener != null) {
3238 mOnFocusChangeListener.onFocusChange(this, gainFocus);
3239 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003240
3241 if (mAttachInfo != null) {
3242 mAttachInfo.mKeyDispatchState.reset(this);
3243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 }
3245
3246 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07003247 * {@inheritDoc}
3248 */
3249 public void sendAccessibilityEvent(int eventType) {
3250 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3251 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3252 }
3253 }
3254
3255 /**
3256 * {@inheritDoc}
3257 */
3258 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3259 event.setClassName(getClass().getName());
3260 event.setPackageName(getContext().getPackageName());
3261 event.setEnabled(isEnabled());
3262 event.setContentDescription(mContentDescription);
3263
3264 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3265 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3266 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3267 event.setItemCount(focusablesTempList.size());
3268 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3269 focusablesTempList.clear();
3270 }
3271
3272 dispatchPopulateAccessibilityEvent(event);
3273
3274 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3275 }
3276
3277 /**
3278 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3279 * to be populated.
3280 *
3281 * @param event The event.
3282 *
3283 * @return True if the event population was completed.
3284 */
3285 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3286 return false;
3287 }
3288
3289 /**
3290 * Gets the {@link View} description. It briefly describes the view and is
3291 * primarily used for accessibility support. Set this property to enable
3292 * better accessibility support for your application. This is especially
3293 * true for views that do not have textual representation (For example,
3294 * ImageButton).
3295 *
3296 * @return The content descriptiopn.
3297 *
3298 * @attr ref android.R.styleable#View_contentDescription
3299 */
3300 public CharSequence getContentDescription() {
3301 return mContentDescription;
3302 }
3303
3304 /**
3305 * Sets the {@link View} description. It briefly describes the view and is
3306 * primarily used for accessibility support. Set this property to enable
3307 * better accessibility support for your application. This is especially
3308 * true for views that do not have textual representation (For example,
3309 * ImageButton).
3310 *
3311 * @param contentDescription The content description.
3312 *
3313 * @attr ref android.R.styleable#View_contentDescription
3314 */
3315 public void setContentDescription(CharSequence contentDescription) {
3316 mContentDescription = contentDescription;
3317 }
3318
3319 /**
Romain Guya2431d02009-04-30 16:30:00 -07003320 * Invoked whenever this view loses focus, either by losing window focus or by losing
3321 * focus within its window. This method can be used to clear any state tied to the
3322 * focus. For instance, if a button is held pressed with the trackball and the window
3323 * loses focus, this method can be used to cancel the press.
3324 *
3325 * Subclasses of View overriding this method should always call super.onFocusLost().
3326 *
3327 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003328 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003329 *
3330 * @hide pending API council approval
3331 */
3332 protected void onFocusLost() {
3333 resetPressedState();
3334 }
3335
3336 private void resetPressedState() {
3337 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3338 return;
3339 }
3340
3341 if (isPressed()) {
3342 setPressed(false);
3343
3344 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003345 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003346 }
3347 }
3348 }
3349
3350 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 * Returns true if this view has focus
3352 *
3353 * @return True if this view has focus, false otherwise.
3354 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003355 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 public boolean isFocused() {
3357 return (mPrivateFlags & FOCUSED) != 0;
3358 }
3359
3360 /**
3361 * Find the view in the hierarchy rooted at this view that currently has
3362 * focus.
3363 *
3364 * @return The view that currently has focus, or null if no focused view can
3365 * be found.
3366 */
3367 public View findFocus() {
3368 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3369 }
3370
3371 /**
3372 * Change whether this view is one of the set of scrollable containers in
3373 * its window. This will be used to determine whether the window can
3374 * resize or must pan when a soft input area is open -- scrollable
3375 * containers allow the window to use resize mode since the container
3376 * will appropriately shrink.
3377 */
3378 public void setScrollContainer(boolean isScrollContainer) {
3379 if (isScrollContainer) {
3380 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3381 mAttachInfo.mScrollContainers.add(this);
3382 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3383 }
3384 mPrivateFlags |= SCROLL_CONTAINER;
3385 } else {
3386 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3387 mAttachInfo.mScrollContainers.remove(this);
3388 }
3389 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3390 }
3391 }
3392
3393 /**
3394 * Returns the quality of the drawing cache.
3395 *
3396 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3397 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3398 *
3399 * @see #setDrawingCacheQuality(int)
3400 * @see #setDrawingCacheEnabled(boolean)
3401 * @see #isDrawingCacheEnabled()
3402 *
3403 * @attr ref android.R.styleable#View_drawingCacheQuality
3404 */
3405 public int getDrawingCacheQuality() {
3406 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3407 }
3408
3409 /**
3410 * Set the drawing cache quality of this view. This value is used only when the
3411 * drawing cache is enabled
3412 *
3413 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3414 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3415 *
3416 * @see #getDrawingCacheQuality()
3417 * @see #setDrawingCacheEnabled(boolean)
3418 * @see #isDrawingCacheEnabled()
3419 *
3420 * @attr ref android.R.styleable#View_drawingCacheQuality
3421 */
3422 public void setDrawingCacheQuality(int quality) {
3423 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3424 }
3425
3426 /**
3427 * Returns whether the screen should remain on, corresponding to the current
3428 * value of {@link #KEEP_SCREEN_ON}.
3429 *
3430 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3431 *
3432 * @see #setKeepScreenOn(boolean)
3433 *
3434 * @attr ref android.R.styleable#View_keepScreenOn
3435 */
3436 public boolean getKeepScreenOn() {
3437 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3438 }
3439
3440 /**
3441 * Controls whether the screen should remain on, modifying the
3442 * value of {@link #KEEP_SCREEN_ON}.
3443 *
3444 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3445 *
3446 * @see #getKeepScreenOn()
3447 *
3448 * @attr ref android.R.styleable#View_keepScreenOn
3449 */
3450 public void setKeepScreenOn(boolean keepScreenOn) {
3451 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3452 }
3453
3454 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003455 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3456 * @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 -08003457 *
3458 * @attr ref android.R.styleable#View_nextFocusLeft
3459 */
3460 public int getNextFocusLeftId() {
3461 return mNextFocusLeftId;
3462 }
3463
3464 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003465 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3466 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
3467 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 *
3469 * @attr ref android.R.styleable#View_nextFocusLeft
3470 */
3471 public void setNextFocusLeftId(int nextFocusLeftId) {
3472 mNextFocusLeftId = nextFocusLeftId;
3473 }
3474
3475 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003476 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3477 * @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 -08003478 *
3479 * @attr ref android.R.styleable#View_nextFocusRight
3480 */
3481 public int getNextFocusRightId() {
3482 return mNextFocusRightId;
3483 }
3484
3485 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003486 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3487 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
3488 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 *
3490 * @attr ref android.R.styleable#View_nextFocusRight
3491 */
3492 public void setNextFocusRightId(int nextFocusRightId) {
3493 mNextFocusRightId = nextFocusRightId;
3494 }
3495
3496 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003497 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3498 * @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 -08003499 *
3500 * @attr ref android.R.styleable#View_nextFocusUp
3501 */
3502 public int getNextFocusUpId() {
3503 return mNextFocusUpId;
3504 }
3505
3506 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003507 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3508 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
3509 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 *
3511 * @attr ref android.R.styleable#View_nextFocusUp
3512 */
3513 public void setNextFocusUpId(int nextFocusUpId) {
3514 mNextFocusUpId = nextFocusUpId;
3515 }
3516
3517 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003518 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3519 * @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 -08003520 *
3521 * @attr ref android.R.styleable#View_nextFocusDown
3522 */
3523 public int getNextFocusDownId() {
3524 return mNextFocusDownId;
3525 }
3526
3527 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003528 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3529 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
3530 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 *
3532 * @attr ref android.R.styleable#View_nextFocusDown
3533 */
3534 public void setNextFocusDownId(int nextFocusDownId) {
3535 mNextFocusDownId = nextFocusDownId;
3536 }
3537
3538 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003539 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3540 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3541 *
3542 * @attr ref android.R.styleable#View_nextFocusForward
3543 */
3544 public int getNextFocusForwardId() {
3545 return mNextFocusForwardId;
3546 }
3547
3548 /**
3549 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3550 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
3551 * decide automatically.
3552 *
3553 * @attr ref android.R.styleable#View_nextFocusForward
3554 */
3555 public void setNextFocusForwardId(int nextFocusForwardId) {
3556 mNextFocusForwardId = nextFocusForwardId;
3557 }
3558
3559 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003560 * Returns the visibility of this view and all of its ancestors
3561 *
3562 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3563 */
3564 public boolean isShown() {
3565 View current = this;
3566 //noinspection ConstantConditions
3567 do {
3568 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3569 return false;
3570 }
3571 ViewParent parent = current.mParent;
3572 if (parent == null) {
3573 return false; // We are not attached to the view root
3574 }
3575 if (!(parent instanceof View)) {
3576 return true;
3577 }
3578 current = (View) parent;
3579 } while (current != null);
3580
3581 return false;
3582 }
3583
3584 /**
3585 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3586 * is set
3587 *
3588 * @param insets Insets for system windows
3589 *
3590 * @return True if this view applied the insets, false otherwise
3591 */
3592 protected boolean fitSystemWindows(Rect insets) {
3593 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3594 mPaddingLeft = insets.left;
3595 mPaddingTop = insets.top;
3596 mPaddingRight = insets.right;
3597 mPaddingBottom = insets.bottom;
3598 requestLayout();
3599 return true;
3600 }
3601 return false;
3602 }
3603
3604 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003605 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3606 * @return True if window has FITS_SYSTEM_WINDOWS set
3607 *
3608 * @hide
3609 */
3610 public boolean isFitsSystemWindowsFlagSet() {
3611 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3612 }
3613
3614 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 * Returns the visibility status for this view.
3616 *
3617 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3618 * @attr ref android.R.styleable#View_visibility
3619 */
3620 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003621 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3622 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3623 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 })
3625 public int getVisibility() {
3626 return mViewFlags & VISIBILITY_MASK;
3627 }
3628
3629 /**
3630 * Set the enabled state of this view.
3631 *
3632 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3633 * @attr ref android.R.styleable#View_visibility
3634 */
3635 @RemotableViewMethod
3636 public void setVisibility(int visibility) {
3637 setFlags(visibility, VISIBILITY_MASK);
3638 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3639 }
3640
3641 /**
3642 * Returns the enabled status for this view. The interpretation of the
3643 * enabled state varies by subclass.
3644 *
3645 * @return True if this view is enabled, false otherwise.
3646 */
3647 @ViewDebug.ExportedProperty
3648 public boolean isEnabled() {
3649 return (mViewFlags & ENABLED_MASK) == ENABLED;
3650 }
3651
3652 /**
3653 * Set the enabled state of this view. The interpretation of the enabled
3654 * state varies by subclass.
3655 *
3656 * @param enabled True if this view is enabled, false otherwise.
3657 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003658 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003660 if (enabled == isEnabled()) return;
3661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3663
3664 /*
3665 * The View most likely has to change its appearance, so refresh
3666 * the drawable state.
3667 */
3668 refreshDrawableState();
3669
3670 // Invalidate too, since the default behavior for views is to be
3671 // be drawn at 50% alpha rather than to change the drawable.
3672 invalidate();
3673 }
3674
3675 /**
3676 * Set whether this view can receive the focus.
3677 *
3678 * Setting this to false will also ensure that this view is not focusable
3679 * in touch mode.
3680 *
3681 * @param focusable If true, this view can receive the focus.
3682 *
3683 * @see #setFocusableInTouchMode(boolean)
3684 * @attr ref android.R.styleable#View_focusable
3685 */
3686 public void setFocusable(boolean focusable) {
3687 if (!focusable) {
3688 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3689 }
3690 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3691 }
3692
3693 /**
3694 * Set whether this view can receive focus while in touch mode.
3695 *
3696 * Setting this to true will also ensure that this view is focusable.
3697 *
3698 * @param focusableInTouchMode If true, this view can receive the focus while
3699 * in touch mode.
3700 *
3701 * @see #setFocusable(boolean)
3702 * @attr ref android.R.styleable#View_focusableInTouchMode
3703 */
3704 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3705 // Focusable in touch mode should always be set before the focusable flag
3706 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3707 // which, in touch mode, will not successfully request focus on this view
3708 // because the focusable in touch mode flag is not set
3709 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3710 if (focusableInTouchMode) {
3711 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3712 }
3713 }
3714
3715 /**
3716 * Set whether this view should have sound effects enabled for events such as
3717 * clicking and touching.
3718 *
3719 * <p>You may wish to disable sound effects for a view if you already play sounds,
3720 * for instance, a dial key that plays dtmf tones.
3721 *
3722 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3723 * @see #isSoundEffectsEnabled()
3724 * @see #playSoundEffect(int)
3725 * @attr ref android.R.styleable#View_soundEffectsEnabled
3726 */
3727 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3728 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3729 }
3730
3731 /**
3732 * @return whether this view should have sound effects enabled for events such as
3733 * clicking and touching.
3734 *
3735 * @see #setSoundEffectsEnabled(boolean)
3736 * @see #playSoundEffect(int)
3737 * @attr ref android.R.styleable#View_soundEffectsEnabled
3738 */
3739 @ViewDebug.ExportedProperty
3740 public boolean isSoundEffectsEnabled() {
3741 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3742 }
3743
3744 /**
3745 * Set whether this view should have haptic feedback for events such as
3746 * long presses.
3747 *
3748 * <p>You may wish to disable haptic feedback if your view already controls
3749 * its own haptic feedback.
3750 *
3751 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3752 * @see #isHapticFeedbackEnabled()
3753 * @see #performHapticFeedback(int)
3754 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3755 */
3756 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3757 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3758 }
3759
3760 /**
3761 * @return whether this view should have haptic feedback enabled for events
3762 * long presses.
3763 *
3764 * @see #setHapticFeedbackEnabled(boolean)
3765 * @see #performHapticFeedback(int)
3766 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3767 */
3768 @ViewDebug.ExportedProperty
3769 public boolean isHapticFeedbackEnabled() {
3770 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3771 }
3772
3773 /**
3774 * If this view doesn't do any drawing on its own, set this flag to
3775 * allow further optimizations. By default, this flag is not set on
3776 * View, but could be set on some View subclasses such as ViewGroup.
3777 *
3778 * Typically, if you override {@link #onDraw} you should clear this flag.
3779 *
3780 * @param willNotDraw whether or not this View draw on its own
3781 */
3782 public void setWillNotDraw(boolean willNotDraw) {
3783 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3784 }
3785
3786 /**
3787 * Returns whether or not this View draws on its own.
3788 *
3789 * @return true if this view has nothing to draw, false otherwise
3790 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003791 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 public boolean willNotDraw() {
3793 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3794 }
3795
3796 /**
3797 * When a View's drawing cache is enabled, drawing is redirected to an
3798 * offscreen bitmap. Some views, like an ImageView, must be able to
3799 * bypass this mechanism if they already draw a single bitmap, to avoid
3800 * unnecessary usage of the memory.
3801 *
3802 * @param willNotCacheDrawing true if this view does not cache its
3803 * drawing, false otherwise
3804 */
3805 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3806 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3807 }
3808
3809 /**
3810 * Returns whether or not this View can cache its drawing or not.
3811 *
3812 * @return true if this view does not cache its drawing, false otherwise
3813 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003814 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 public boolean willNotCacheDrawing() {
3816 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3817 }
3818
3819 /**
3820 * Indicates whether this view reacts to click events or not.
3821 *
3822 * @return true if the view is clickable, false otherwise
3823 *
3824 * @see #setClickable(boolean)
3825 * @attr ref android.R.styleable#View_clickable
3826 */
3827 @ViewDebug.ExportedProperty
3828 public boolean isClickable() {
3829 return (mViewFlags & CLICKABLE) == CLICKABLE;
3830 }
3831
3832 /**
3833 * Enables or disables click events for this view. When a view
3834 * is clickable it will change its state to "pressed" on every click.
3835 * Subclasses should set the view clickable to visually react to
3836 * user's clicks.
3837 *
3838 * @param clickable true to make the view clickable, false otherwise
3839 *
3840 * @see #isClickable()
3841 * @attr ref android.R.styleable#View_clickable
3842 */
3843 public void setClickable(boolean clickable) {
3844 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3845 }
3846
3847 /**
3848 * Indicates whether this view reacts to long click events or not.
3849 *
3850 * @return true if the view is long clickable, false otherwise
3851 *
3852 * @see #setLongClickable(boolean)
3853 * @attr ref android.R.styleable#View_longClickable
3854 */
3855 public boolean isLongClickable() {
3856 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3857 }
3858
3859 /**
3860 * Enables or disables long click events for this view. When a view is long
3861 * clickable it reacts to the user holding down the button for a longer
3862 * duration than a tap. This event can either launch the listener or a
3863 * context menu.
3864 *
3865 * @param longClickable true to make the view long clickable, false otherwise
3866 * @see #isLongClickable()
3867 * @attr ref android.R.styleable#View_longClickable
3868 */
3869 public void setLongClickable(boolean longClickable) {
3870 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3871 }
3872
3873 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003874 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 *
3876 * @see #isClickable()
3877 * @see #setClickable(boolean)
3878 *
3879 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3880 * the View's internal state from a previously set "pressed" state.
3881 */
3882 public void setPressed(boolean pressed) {
3883 if (pressed) {
3884 mPrivateFlags |= PRESSED;
3885 } else {
3886 mPrivateFlags &= ~PRESSED;
3887 }
3888 refreshDrawableState();
3889 dispatchSetPressed(pressed);
3890 }
3891
3892 /**
3893 * Dispatch setPressed to all of this View's children.
3894 *
3895 * @see #setPressed(boolean)
3896 *
3897 * @param pressed The new pressed state
3898 */
3899 protected void dispatchSetPressed(boolean pressed) {
3900 }
3901
3902 /**
3903 * Indicates whether the view is currently in pressed state. Unless
3904 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3905 * the pressed state.
3906 *
3907 * @see #setPressed
3908 * @see #isClickable()
3909 * @see #setClickable(boolean)
3910 *
3911 * @return true if the view is currently pressed, false otherwise
3912 */
3913 public boolean isPressed() {
3914 return (mPrivateFlags & PRESSED) == PRESSED;
3915 }
3916
3917 /**
3918 * Indicates whether this view will save its state (that is,
3919 * whether its {@link #onSaveInstanceState} method will be called).
3920 *
3921 * @return Returns true if the view state saving is enabled, else false.
3922 *
3923 * @see #setSaveEnabled(boolean)
3924 * @attr ref android.R.styleable#View_saveEnabled
3925 */
3926 public boolean isSaveEnabled() {
3927 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3928 }
3929
3930 /**
3931 * Controls whether the saving of this view's state is
3932 * enabled (that is, whether its {@link #onSaveInstanceState} method
3933 * will be called). Note that even if freezing is enabled, the
3934 * view still must have an id assigned to it (via {@link #setId setId()})
3935 * for its state to be saved. This flag can only disable the
3936 * saving of this view; any child views may still have their state saved.
3937 *
3938 * @param enabled Set to false to <em>disable</em> state saving, or true
3939 * (the default) to allow it.
3940 *
3941 * @see #isSaveEnabled()
3942 * @see #setId(int)
3943 * @see #onSaveInstanceState()
3944 * @attr ref android.R.styleable#View_saveEnabled
3945 */
3946 public void setSaveEnabled(boolean enabled) {
3947 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3948 }
3949
Jeff Brown85a31762010-09-01 17:01:00 -07003950 /**
3951 * Gets whether the framework should discard touches when the view's
3952 * window is obscured by another visible window.
3953 * Refer to the {@link View} security documentation for more details.
3954 *
3955 * @return True if touch filtering is enabled.
3956 *
3957 * @see #setFilterTouchesWhenObscured(boolean)
3958 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3959 */
3960 @ViewDebug.ExportedProperty
3961 public boolean getFilterTouchesWhenObscured() {
3962 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3963 }
3964
3965 /**
3966 * Sets whether the framework should discard touches when the view's
3967 * window is obscured by another visible window.
3968 * Refer to the {@link View} security documentation for more details.
3969 *
3970 * @param enabled True if touch filtering should be enabled.
3971 *
3972 * @see #getFilterTouchesWhenObscured
3973 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3974 */
3975 public void setFilterTouchesWhenObscured(boolean enabled) {
3976 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3977 FILTER_TOUCHES_WHEN_OBSCURED);
3978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979
3980 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003981 * Indicates whether the entire hierarchy under this view will save its
3982 * state when a state saving traversal occurs from its parent. The default
3983 * is true; if false, these views will not be saved unless
3984 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3985 *
3986 * @return Returns true if the view state saving from parent is enabled, else false.
3987 *
3988 * @see #setSaveFromParentEnabled(boolean)
3989 */
3990 public boolean isSaveFromParentEnabled() {
3991 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3992 }
3993
3994 /**
3995 * Controls whether the entire hierarchy under this view will save its
3996 * state when a state saving traversal occurs from its parent. The default
3997 * is true; if false, these views will not be saved unless
3998 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3999 *
4000 * @param enabled Set to false to <em>disable</em> state saving, or true
4001 * (the default) to allow it.
4002 *
4003 * @see #isSaveFromParentEnabled()
4004 * @see #setId(int)
4005 * @see #onSaveInstanceState()
4006 */
4007 public void setSaveFromParentEnabled(boolean enabled) {
4008 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4009 }
4010
4011
4012 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 * Returns whether this View is able to take focus.
4014 *
4015 * @return True if this view can take focus, or false otherwise.
4016 * @attr ref android.R.styleable#View_focusable
4017 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004018 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 public final boolean isFocusable() {
4020 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4021 }
4022
4023 /**
4024 * When a view is focusable, it may not want to take focus when in touch mode.
4025 * For example, a button would like focus when the user is navigating via a D-pad
4026 * so that the user can click on it, but once the user starts touching the screen,
4027 * the button shouldn't take focus
4028 * @return Whether the view is focusable in touch mode.
4029 * @attr ref android.R.styleable#View_focusableInTouchMode
4030 */
4031 @ViewDebug.ExportedProperty
4032 public final boolean isFocusableInTouchMode() {
4033 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4034 }
4035
4036 /**
4037 * Find the nearest view in the specified direction that can take focus.
4038 * This does not actually give focus to that view.
4039 *
4040 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4041 *
4042 * @return The nearest focusable in the specified direction, or null if none
4043 * can be found.
4044 */
4045 public View focusSearch(int direction) {
4046 if (mParent != null) {
4047 return mParent.focusSearch(this, direction);
4048 } else {
4049 return null;
4050 }
4051 }
4052
4053 /**
4054 * This method is the last chance for the focused view and its ancestors to
4055 * respond to an arrow key. This is called when the focused view did not
4056 * consume the key internally, nor could the view system find a new view in
4057 * the requested direction to give focus to.
4058 *
4059 * @param focused The currently focused view.
4060 * @param direction The direction focus wants to move. One of FOCUS_UP,
4061 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4062 * @return True if the this view consumed this unhandled move.
4063 */
4064 public boolean dispatchUnhandledMove(View focused, int direction) {
4065 return false;
4066 }
4067
4068 /**
4069 * If a user manually specified the next view id for a particular direction,
Jeff Brown4e6319b2010-12-13 10:36:51 -08004070 * use the root to look up the view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 * @param root The root view of the hierarchy containing this view.
Jeff Brown4e6319b2010-12-13 10:36:51 -08004072 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4073 * or FOCUS_BACKWARD.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 * @return The user specified next view, or null if there is none.
4075 */
4076 View findUserSetNextFocus(View root, int direction) {
4077 switch (direction) {
4078 case FOCUS_LEFT:
4079 if (mNextFocusLeftId == View.NO_ID) return null;
4080 return findViewShouldExist(root, mNextFocusLeftId);
4081 case FOCUS_RIGHT:
4082 if (mNextFocusRightId == View.NO_ID) return null;
4083 return findViewShouldExist(root, mNextFocusRightId);
4084 case FOCUS_UP:
4085 if (mNextFocusUpId == View.NO_ID) return null;
4086 return findViewShouldExist(root, mNextFocusUpId);
4087 case FOCUS_DOWN:
4088 if (mNextFocusDownId == View.NO_ID) return null;
4089 return findViewShouldExist(root, mNextFocusDownId);
Jeff Brown4e6319b2010-12-13 10:36:51 -08004090 case FOCUS_FORWARD:
4091 if (mNextFocusForwardId == View.NO_ID) return null;
4092 return findViewShouldExist(root, mNextFocusForwardId);
4093 case FOCUS_BACKWARD: {
4094 final int id = mID;
4095 return root.findViewByPredicate(new Predicate<View>() {
4096 @Override
4097 public boolean apply(View t) {
4098 return t.mNextFocusForwardId == id;
4099 }
4100 });
4101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 }
4103 return null;
4104 }
4105
4106 private static View findViewShouldExist(View root, int childViewId) {
4107 View result = root.findViewById(childViewId);
4108 if (result == null) {
4109 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4110 + "by user for id " + childViewId);
4111 }
4112 return result;
4113 }
4114
4115 /**
4116 * Find and return all focusable views that are descendants of this view,
4117 * possibly including this view if it is focusable itself.
4118 *
4119 * @param direction The direction of the focus
4120 * @return A list of focusable views
4121 */
4122 public ArrayList<View> getFocusables(int direction) {
4123 ArrayList<View> result = new ArrayList<View>(24);
4124 addFocusables(result, direction);
4125 return result;
4126 }
4127
4128 /**
4129 * Add any focusable views that are descendants of this view (possibly
4130 * including this view if it is focusable itself) to views. If we are in touch mode,
4131 * only add views that are also focusable in touch mode.
4132 *
4133 * @param views Focusable views found so far
4134 * @param direction The direction of the focus
4135 */
4136 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07004137 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139
svetoslavganov75986cf2009-05-14 22:28:01 -07004140 /**
4141 * Adds any focusable views that are descendants of this view (possibly
4142 * including this view if it is focusable itself) to views. This method
4143 * adds all focusable views regardless if we are in touch mode or
4144 * only views focusable in touch mode if we are in touch mode depending on
4145 * the focusable mode paramater.
4146 *
4147 * @param views Focusable views found so far or null if all we are interested is
4148 * the number of focusables.
4149 * @param direction The direction of the focus.
4150 * @param focusableMode The type of focusables to be added.
4151 *
4152 * @see #FOCUSABLES_ALL
4153 * @see #FOCUSABLES_TOUCH_MODE
4154 */
4155 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4156 if (!isFocusable()) {
4157 return;
4158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159
svetoslavganov75986cf2009-05-14 22:28:01 -07004160 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4161 isInTouchMode() && !isFocusableInTouchMode()) {
4162 return;
4163 }
4164
4165 if (views != null) {
4166 views.add(this);
4167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 }
4169
4170 /**
4171 * Find and return all touchable views that are descendants of this view,
4172 * possibly including this view if it is touchable itself.
4173 *
4174 * @return A list of touchable views
4175 */
4176 public ArrayList<View> getTouchables() {
4177 ArrayList<View> result = new ArrayList<View>();
4178 addTouchables(result);
4179 return result;
4180 }
4181
4182 /**
4183 * Add any touchable views that are descendants of this view (possibly
4184 * including this view if it is touchable itself) to views.
4185 *
4186 * @param views Touchable views found so far
4187 */
4188 public void addTouchables(ArrayList<View> views) {
4189 final int viewFlags = mViewFlags;
4190
4191 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4192 && (viewFlags & ENABLED_MASK) == ENABLED) {
4193 views.add(this);
4194 }
4195 }
4196
4197 /**
4198 * Call this to try to give focus to a specific view or to one of its
4199 * descendants.
4200 *
4201 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4202 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4203 * while the device is in touch mode.
4204 *
4205 * See also {@link #focusSearch}, which is what you call to say that you
4206 * have focus, and you want your parent to look for the next one.
4207 *
4208 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4209 * {@link #FOCUS_DOWN} and <code>null</code>.
4210 *
4211 * @return Whether this view or one of its descendants actually took focus.
4212 */
4213 public final boolean requestFocus() {
4214 return requestFocus(View.FOCUS_DOWN);
4215 }
4216
4217
4218 /**
4219 * Call this to try to give focus to a specific view or to one of its
4220 * descendants and give it a hint about what direction focus is heading.
4221 *
4222 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4223 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4224 * while the device is in touch mode.
4225 *
4226 * See also {@link #focusSearch}, which is what you call to say that you
4227 * have focus, and you want your parent to look for the next one.
4228 *
4229 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4230 * <code>null</code> set for the previously focused rectangle.
4231 *
4232 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4233 * @return Whether this view or one of its descendants actually took focus.
4234 */
4235 public final boolean requestFocus(int direction) {
4236 return requestFocus(direction, null);
4237 }
4238
4239 /**
4240 * Call this to try to give focus to a specific view or to one of its descendants
4241 * and give it hints about the direction and a specific rectangle that the focus
4242 * is coming from. The rectangle can help give larger views a finer grained hint
4243 * about where focus is coming from, and therefore, where to show selection, or
4244 * forward focus change internally.
4245 *
4246 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4247 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4248 * while the device is in touch mode.
4249 *
4250 * A View will not take focus if it is not visible.
4251 *
4252 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4253 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4254 *
4255 * See also {@link #focusSearch}, which is what you call to say that you
4256 * have focus, and you want your parent to look for the next one.
4257 *
4258 * You may wish to override this method if your custom {@link View} has an internal
4259 * {@link View} that it wishes to forward the request to.
4260 *
4261 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4262 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4263 * to give a finer grained hint about where focus is coming from. May be null
4264 * if there is no hint.
4265 * @return Whether this view or one of its descendants actually took focus.
4266 */
4267 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4268 // need to be focusable
4269 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4270 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4271 return false;
4272 }
4273
4274 // need to be focusable in touch mode if in touch mode
4275 if (isInTouchMode() &&
4276 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4277 return false;
4278 }
4279
4280 // need to not have any parents blocking us
4281 if (hasAncestorThatBlocksDescendantFocus()) {
4282 return false;
4283 }
4284
4285 handleFocusGainInternal(direction, previouslyFocusedRect);
4286 return true;
4287 }
4288
Christopher Tate2c095f32010-10-04 14:13:40 -07004289 /** Gets the ViewRoot, or null if not attached. */
4290 /*package*/ ViewRoot getViewRoot() {
4291 View root = getRootView();
4292 return root != null ? (ViewRoot)root.getParent() : null;
4293 }
4294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 /**
4296 * Call this to try to give focus to a specific view or to one of its descendants. This is a
4297 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4298 * touch mode to request focus when they are touched.
4299 *
4300 * @return Whether this view or one of its descendants actually took focus.
4301 *
4302 * @see #isInTouchMode()
4303 *
4304 */
4305 public final boolean requestFocusFromTouch() {
4306 // Leave touch mode if we need to
4307 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07004308 ViewRoot viewRoot = getViewRoot();
4309 if (viewRoot != null) {
4310 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 }
4312 }
4313 return requestFocus(View.FOCUS_DOWN);
4314 }
4315
4316 /**
4317 * @return Whether any ancestor of this view blocks descendant focus.
4318 */
4319 private boolean hasAncestorThatBlocksDescendantFocus() {
4320 ViewParent ancestor = mParent;
4321 while (ancestor instanceof ViewGroup) {
4322 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4323 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4324 return true;
4325 } else {
4326 ancestor = vgAncestor.getParent();
4327 }
4328 }
4329 return false;
4330 }
4331
4332 /**
Romain Guya440b002010-02-24 15:57:54 -08004333 * @hide
4334 */
4335 public void dispatchStartTemporaryDetach() {
4336 onStartTemporaryDetach();
4337 }
4338
4339 /**
4340 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4342 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004343 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 */
4345 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004346 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004347 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004348 }
4349
4350 /**
4351 * @hide
4352 */
4353 public void dispatchFinishTemporaryDetach() {
4354 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004355 }
Romain Guy8506ab42009-06-11 17:35:47 -07004356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 /**
4358 * Called after {@link #onStartTemporaryDetach} when the container is done
4359 * changing the view.
4360 */
4361 public void onFinishTemporaryDetach() {
4362 }
Romain Guy8506ab42009-06-11 17:35:47 -07004363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 /**
4365 * capture information of this view for later analysis: developement only
4366 * check dynamic switch to make sure we only dump view
4367 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4368 */
4369 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004370 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 return;
4372 }
4373 ViewDebug.dumpCapturedView(subTag, v);
4374 }
4375
4376 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004377 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4378 * for this view's window. Returns null if the view is not currently attached
4379 * to the window. Normally you will not need to use this directly, but
4380 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4381 */
4382 public KeyEvent.DispatcherState getKeyDispatcherState() {
4383 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4384 }
4385
4386 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 * Dispatch a key event before it is processed by any input method
4388 * associated with the view hierarchy. This can be used to intercept
4389 * key events in special situations before the IME consumes them; a
4390 * typical example would be handling the BACK key to update the application's
4391 * UI instead of allowing the IME to see it and close itself.
4392 *
4393 * @param event The key event to be dispatched.
4394 * @return True if the event was handled, false otherwise.
4395 */
4396 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4397 return onKeyPreIme(event.getKeyCode(), event);
4398 }
4399
4400 /**
4401 * Dispatch a key event to the next view on the focus path. This path runs
4402 * from the top of the view tree down to the currently focused view. If this
4403 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4404 * the next node down the focus path. This method also fires any key
4405 * listeners.
4406 *
4407 * @param event The key event to be dispatched.
4408 * @return True if the event was handled, false otherwise.
4409 */
4410 public boolean dispatchKeyEvent(KeyEvent event) {
4411 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412
Romain Guyf607bdc2010-09-10 19:20:06 -07004413 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 if (android.util.Config.LOGV) {
4415 captureViewInfo("captureViewKeyEvent", this);
4416 }
4417
Romain Guyf607bdc2010-09-10 19:20:06 -07004418 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4420 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4421 return true;
4422 }
4423
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004424 return event.dispatch(this, mAttachInfo != null
4425 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004426 }
4427
4428 /**
4429 * Dispatches a key shortcut event.
4430 *
4431 * @param event The key event to be dispatched.
4432 * @return True if the event was handled by the view, false otherwise.
4433 */
4434 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4435 return onKeyShortcut(event.getKeyCode(), event);
4436 }
4437
4438 /**
4439 * Pass the touch screen motion event down to the target view, or this
4440 * view if it is the target.
4441 *
4442 * @param event The motion event to be dispatched.
4443 * @return True if the event was handled by the view, false otherwise.
4444 */
4445 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004446 if (!onFilterTouchEventForSecurity(event)) {
4447 return false;
4448 }
4449
Romain Guyf607bdc2010-09-10 19:20:06 -07004450 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004451 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4452 mOnTouchListener.onTouch(this, event)) {
4453 return true;
4454 }
4455 return onTouchEvent(event);
4456 }
4457
4458 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004459 * Filter the touch event to apply security policies.
4460 *
4461 * @param event The motion event to be filtered.
4462 * @return True if the event should be dispatched, false if the event should be dropped.
4463 *
4464 * @see #getFilterTouchesWhenObscured
4465 */
4466 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004467 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004468 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4469 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4470 // Window is obscured, drop this touch.
4471 return false;
4472 }
4473 return true;
4474 }
4475
4476 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 * Pass a trackball motion event down to the focused view.
4478 *
4479 * @param event The motion event to be dispatched.
4480 * @return True if the event was handled by the view, false otherwise.
4481 */
4482 public boolean dispatchTrackballEvent(MotionEvent event) {
4483 //Log.i("view", "view=" + this + ", " + event.toString());
4484 return onTrackballEvent(event);
4485 }
4486
4487 /**
4488 * Called when the window containing this view gains or loses window focus.
4489 * ViewGroups should override to route to their children.
4490 *
4491 * @param hasFocus True if the window containing this view now has focus,
4492 * false otherwise.
4493 */
4494 public void dispatchWindowFocusChanged(boolean hasFocus) {
4495 onWindowFocusChanged(hasFocus);
4496 }
4497
4498 /**
4499 * Called when the window containing this view gains or loses focus. Note
4500 * that this is separate from view focus: to receive key events, both
4501 * your view and its window must have focus. If a window is displayed
4502 * on top of yours that takes input focus, then your own window will lose
4503 * focus but the view focus will remain unchanged.
4504 *
4505 * @param hasWindowFocus True if the window containing this view now has
4506 * focus, false otherwise.
4507 */
4508 public void onWindowFocusChanged(boolean hasWindowFocus) {
4509 InputMethodManager imm = InputMethodManager.peekInstance();
4510 if (!hasWindowFocus) {
4511 if (isPressed()) {
4512 setPressed(false);
4513 }
4514 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4515 imm.focusOut(this);
4516 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004517 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004518 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004519 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4521 imm.focusIn(this);
4522 }
4523 refreshDrawableState();
4524 }
4525
4526 /**
4527 * Returns true if this view is in a window that currently has window focus.
4528 * Note that this is not the same as the view itself having focus.
4529 *
4530 * @return True if this view is in a window that currently has window focus.
4531 */
4532 public boolean hasWindowFocus() {
4533 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4534 }
4535
4536 /**
Adam Powell326d8082009-12-09 15:10:07 -08004537 * Dispatch a view visibility change down the view hierarchy.
4538 * ViewGroups should override to route to their children.
4539 * @param changedView The view whose visibility changed. Could be 'this' or
4540 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004541 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4542 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004543 */
4544 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4545 onVisibilityChanged(changedView, visibility);
4546 }
4547
4548 /**
4549 * Called when the visibility of the view or an ancestor of the view is changed.
4550 * @param changedView The view whose visibility changed. Could be 'this' or
4551 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004552 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4553 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004554 */
4555 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004556 if (visibility == VISIBLE) {
4557 if (mAttachInfo != null) {
4558 initialAwakenScrollBars();
4559 } else {
4560 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4561 }
4562 }
Adam Powell326d8082009-12-09 15:10:07 -08004563 }
4564
4565 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004566 * Dispatch a hint about whether this view is displayed. For instance, when
4567 * a View moves out of the screen, it might receives a display hint indicating
4568 * the view is not displayed. Applications should not <em>rely</em> on this hint
4569 * as there is no guarantee that they will receive one.
4570 *
4571 * @param hint A hint about whether or not this view is displayed:
4572 * {@link #VISIBLE} or {@link #INVISIBLE}.
4573 */
4574 public void dispatchDisplayHint(int hint) {
4575 onDisplayHint(hint);
4576 }
4577
4578 /**
4579 * Gives this view a hint about whether is displayed or not. For instance, when
4580 * a View moves out of the screen, it might receives a display hint indicating
4581 * the view is not displayed. Applications should not <em>rely</em> on this hint
4582 * as there is no guarantee that they will receive one.
4583 *
4584 * @param hint A hint about whether or not this view is displayed:
4585 * {@link #VISIBLE} or {@link #INVISIBLE}.
4586 */
4587 protected void onDisplayHint(int hint) {
4588 }
4589
4590 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 * Dispatch a window visibility change down the view hierarchy.
4592 * ViewGroups should override to route to their children.
4593 *
4594 * @param visibility The new visibility of the window.
4595 *
4596 * @see #onWindowVisibilityChanged
4597 */
4598 public void dispatchWindowVisibilityChanged(int visibility) {
4599 onWindowVisibilityChanged(visibility);
4600 }
4601
4602 /**
4603 * Called when the window containing has change its visibility
4604 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4605 * that this tells you whether or not your window is being made visible
4606 * to the window manager; this does <em>not</em> tell you whether or not
4607 * your window is obscured by other windows on the screen, even if it
4608 * is itself visible.
4609 *
4610 * @param visibility The new visibility of the window.
4611 */
4612 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004613 if (visibility == VISIBLE) {
4614 initialAwakenScrollBars();
4615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 }
4617
4618 /**
4619 * Returns the current visibility of the window this view is attached to
4620 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4621 *
4622 * @return Returns the current visibility of the view's window.
4623 */
4624 public int getWindowVisibility() {
4625 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4626 }
4627
4628 /**
4629 * Retrieve the overall visible display size in which the window this view is
4630 * attached to has been positioned in. This takes into account screen
4631 * decorations above the window, for both cases where the window itself
4632 * is being position inside of them or the window is being placed under
4633 * then and covered insets are used for the window to position its content
4634 * inside. In effect, this tells you the available area where content can
4635 * be placed and remain visible to users.
4636 *
4637 * <p>This function requires an IPC back to the window manager to retrieve
4638 * the requested information, so should not be used in performance critical
4639 * code like drawing.
4640 *
4641 * @param outRect Filled in with the visible display frame. If the view
4642 * is not attached to a window, this is simply the raw display size.
4643 */
4644 public void getWindowVisibleDisplayFrame(Rect outRect) {
4645 if (mAttachInfo != null) {
4646 try {
4647 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4648 } catch (RemoteException e) {
4649 return;
4650 }
4651 // XXX This is really broken, and probably all needs to be done
4652 // in the window manager, and we need to know more about whether
4653 // we want the area behind or in front of the IME.
4654 final Rect insets = mAttachInfo.mVisibleInsets;
4655 outRect.left += insets.left;
4656 outRect.top += insets.top;
4657 outRect.right -= insets.right;
4658 outRect.bottom -= insets.bottom;
4659 return;
4660 }
4661 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4662 outRect.set(0, 0, d.getWidth(), d.getHeight());
4663 }
4664
4665 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004666 * Dispatch a notification about a resource configuration change down
4667 * the view hierarchy.
4668 * ViewGroups should override to route to their children.
4669 *
4670 * @param newConfig The new resource configuration.
4671 *
4672 * @see #onConfigurationChanged
4673 */
4674 public void dispatchConfigurationChanged(Configuration newConfig) {
4675 onConfigurationChanged(newConfig);
4676 }
4677
4678 /**
4679 * Called when the current configuration of the resources being used
4680 * by the application have changed. You can use this to decide when
4681 * to reload resources that can changed based on orientation and other
4682 * configuration characterstics. You only need to use this if you are
4683 * not relying on the normal {@link android.app.Activity} mechanism of
4684 * recreating the activity instance upon a configuration change.
4685 *
4686 * @param newConfig The new resource configuration.
4687 */
4688 protected void onConfigurationChanged(Configuration newConfig) {
4689 }
4690
4691 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004692 * Private function to aggregate all per-view attributes in to the view
4693 * root.
4694 */
4695 void dispatchCollectViewAttributes(int visibility) {
4696 performCollectViewAttributes(visibility);
4697 }
4698
4699 void performCollectViewAttributes(int visibility) {
4700 //noinspection PointlessBitwiseExpression
4701 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4702 == (VISIBLE | KEEP_SCREEN_ON)) {
4703 mAttachInfo.mKeepScreenOn = true;
4704 }
4705 }
4706
4707 void needGlobalAttributesUpdate(boolean force) {
4708 AttachInfo ai = mAttachInfo;
4709 if (ai != null) {
4710 if (ai.mKeepScreenOn || force) {
4711 ai.mRecomputeGlobalAttributes = true;
4712 }
4713 }
4714 }
4715
4716 /**
4717 * Returns whether the device is currently in touch mode. Touch mode is entered
4718 * once the user begins interacting with the device by touch, and affects various
4719 * things like whether focus is always visible to the user.
4720 *
4721 * @return Whether the device is in touch mode.
4722 */
4723 @ViewDebug.ExportedProperty
4724 public boolean isInTouchMode() {
4725 if (mAttachInfo != null) {
4726 return mAttachInfo.mInTouchMode;
4727 } else {
4728 return ViewRoot.isInTouchMode();
4729 }
4730 }
4731
4732 /**
4733 * Returns the context the view is running in, through which it can
4734 * access the current theme, resources, etc.
4735 *
4736 * @return The view's Context.
4737 */
4738 @ViewDebug.CapturedViewProperty
4739 public final Context getContext() {
4740 return mContext;
4741 }
4742
4743 /**
4744 * Handle a key event before it is processed by any input method
4745 * associated with the view hierarchy. This can be used to intercept
4746 * key events in special situations before the IME consumes them; a
4747 * typical example would be handling the BACK key to update the application's
4748 * UI instead of allowing the IME to see it and close itself.
4749 *
4750 * @param keyCode The value in event.getKeyCode().
4751 * @param event Description of the key event.
4752 * @return If you handled the event, return true. If you want to allow the
4753 * event to be handled by the next receiver, return false.
4754 */
4755 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4756 return false;
4757 }
4758
4759 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004760 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
4761 * KeyEvent.Callback.onKeyDown()}: perform press of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004762 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4763 * is released, if the view is enabled and clickable.
4764 *
4765 * @param keyCode A key code that represents the button pressed, from
4766 * {@link android.view.KeyEvent}.
4767 * @param event The KeyEvent object that defines the button action.
4768 */
4769 public boolean onKeyDown(int keyCode, KeyEvent event) {
4770 boolean result = false;
4771
4772 switch (keyCode) {
4773 case KeyEvent.KEYCODE_DPAD_CENTER:
4774 case KeyEvent.KEYCODE_ENTER: {
4775 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4776 return true;
4777 }
4778 // Long clickable items don't necessarily have to be clickable
4779 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4780 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4781 (event.getRepeatCount() == 0)) {
4782 setPressed(true);
4783 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004784 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004785 }
4786 return true;
4787 }
4788 break;
4789 }
4790 }
4791 return result;
4792 }
4793
4794 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004795 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4796 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4797 * the event).
4798 */
4799 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4800 return false;
4801 }
4802
4803 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004804 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
4805 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004806 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4807 * {@link KeyEvent#KEYCODE_ENTER} is released.
4808 *
4809 * @param keyCode A key code that represents the button pressed, from
4810 * {@link android.view.KeyEvent}.
4811 * @param event The KeyEvent object that defines the button action.
4812 */
4813 public boolean onKeyUp(int keyCode, KeyEvent event) {
4814 boolean result = false;
4815
4816 switch (keyCode) {
4817 case KeyEvent.KEYCODE_DPAD_CENTER:
4818 case KeyEvent.KEYCODE_ENTER: {
4819 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4820 return true;
4821 }
4822 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4823 setPressed(false);
4824
4825 if (!mHasPerformedLongPress) {
4826 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004827 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004828
4829 result = performClick();
4830 }
4831 }
4832 break;
4833 }
4834 }
4835 return result;
4836 }
4837
4838 /**
4839 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4840 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4841 * the event).
4842 *
4843 * @param keyCode A key code that represents the button pressed, from
4844 * {@link android.view.KeyEvent}.
4845 * @param repeatCount The number of times the action was made.
4846 * @param event The KeyEvent object that defines the button action.
4847 */
4848 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4849 return false;
4850 }
4851
4852 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08004853 * Called on the focused view when a key shortcut event is not handled.
4854 * Override this method to implement local key shortcuts for the View.
4855 * Key shortcuts can also be implemented by setting the
4856 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004857 *
4858 * @param keyCode The value in event.getKeyCode().
4859 * @param event Description of the key event.
4860 * @return If you handled the event, return true. If you want to allow the
4861 * event to be handled by the next receiver, return false.
4862 */
4863 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4864 return false;
4865 }
4866
4867 /**
4868 * Check whether the called view is a text editor, in which case it
4869 * would make sense to automatically display a soft input window for
4870 * it. Subclasses should override this if they implement
4871 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004872 * a call on that method would return a non-null InputConnection, and
4873 * they are really a first-class editor that the user would normally
4874 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004875 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004876 * <p>The default implementation always returns false. This does
4877 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4878 * will not be called or the user can not otherwise perform edits on your
4879 * view; it is just a hint to the system that this is not the primary
4880 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004881 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004882 * @return Returns true if this view is a text editor, else false.
4883 */
4884 public boolean onCheckIsTextEditor() {
4885 return false;
4886 }
Romain Guy8506ab42009-06-11 17:35:47 -07004887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004888 /**
4889 * Create a new InputConnection for an InputMethod to interact
4890 * with the view. The default implementation returns null, since it doesn't
4891 * support input methods. You can override this to implement such support.
4892 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004893 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004894 * <p>When implementing this, you probably also want to implement
4895 * {@link #onCheckIsTextEditor()} to indicate you will return a
4896 * non-null InputConnection.
4897 *
4898 * @param outAttrs Fill in with attribute information about the connection.
4899 */
4900 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4901 return null;
4902 }
4903
4904 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004905 * Called by the {@link android.view.inputmethod.InputMethodManager}
4906 * when a view who is not the current
4907 * input connection target is trying to make a call on the manager. The
4908 * default implementation returns false; you can override this to return
4909 * true for certain views if you are performing InputConnection proxying
4910 * to them.
4911 * @param view The View that is making the InputMethodManager call.
4912 * @return Return true to allow the call, false to reject.
4913 */
4914 public boolean checkInputConnectionProxy(View view) {
4915 return false;
4916 }
Romain Guy8506ab42009-06-11 17:35:47 -07004917
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004918 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004919 * Show the context menu for this view. It is not safe to hold on to the
4920 * menu after returning from this method.
4921 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004922 * You should normally not overload this method. Overload
4923 * {@link #onCreateContextMenu(ContextMenu)} or define an
4924 * {@link OnCreateContextMenuListener} to add items to the context menu.
4925 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004926 * @param menu The context menu to populate
4927 */
4928 public void createContextMenu(ContextMenu menu) {
4929 ContextMenuInfo menuInfo = getContextMenuInfo();
4930
4931 // Sets the current menu info so all items added to menu will have
4932 // my extra info set.
4933 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4934
4935 onCreateContextMenu(menu);
4936 if (mOnCreateContextMenuListener != null) {
4937 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4938 }
4939
4940 // Clear the extra information so subsequent items that aren't mine don't
4941 // have my extra info.
4942 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4943
4944 if (mParent != null) {
4945 mParent.createContextMenu(menu);
4946 }
4947 }
4948
4949 /**
4950 * Views should implement this if they have extra information to associate
4951 * with the context menu. The return result is supplied as a parameter to
4952 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4953 * callback.
4954 *
4955 * @return Extra information about the item for which the context menu
4956 * should be shown. This information will vary across different
4957 * subclasses of View.
4958 */
4959 protected ContextMenuInfo getContextMenuInfo() {
4960 return null;
4961 }
4962
4963 /**
4964 * Views should implement this if the view itself is going to add items to
4965 * the context menu.
4966 *
4967 * @param menu the context menu to populate
4968 */
4969 protected void onCreateContextMenu(ContextMenu menu) {
4970 }
4971
4972 /**
4973 * Implement this method to handle trackball motion events. The
4974 * <em>relative</em> movement of the trackball since the last event
4975 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4976 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4977 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4978 * they will often be fractional values, representing the more fine-grained
4979 * movement information available from a trackball).
4980 *
4981 * @param event The motion event.
4982 * @return True if the event was handled, false otherwise.
4983 */
4984 public boolean onTrackballEvent(MotionEvent event) {
4985 return false;
4986 }
4987
4988 /**
4989 * Implement this method to handle touch screen motion events.
4990 *
4991 * @param event The motion event.
4992 * @return True if the event was handled, false otherwise.
4993 */
4994 public boolean onTouchEvent(MotionEvent event) {
4995 final int viewFlags = mViewFlags;
4996
4997 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4998 // A disabled view that is clickable still consumes the touch
4999 // events, it just doesn't respond to them.
5000 return (((viewFlags & CLICKABLE) == CLICKABLE ||
5001 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
5002 }
5003
5004 if (mTouchDelegate != null) {
5005 if (mTouchDelegate.onTouchEvent(event)) {
5006 return true;
5007 }
5008 }
5009
5010 if (((viewFlags & CLICKABLE) == CLICKABLE ||
5011 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
5012 switch (event.getAction()) {
5013 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08005014 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
5015 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 // take focus if we don't have it already and we should in
5017 // touch mode.
5018 boolean focusTaken = false;
5019 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
5020 focusTaken = requestFocus();
5021 }
5022
5023 if (!mHasPerformedLongPress) {
5024 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05005025 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005026
5027 // Only perform take click actions if we were in the pressed state
5028 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08005029 // Use a Runnable and post this rather than calling
5030 // performClick directly. This lets other visual state
5031 // of the view update before click actions start.
5032 if (mPerformClick == null) {
5033 mPerformClick = new PerformClick();
5034 }
5035 if (!post(mPerformClick)) {
5036 performClick();
5037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 }
5039 }
5040
5041 if (mUnsetPressedState == null) {
5042 mUnsetPressedState = new UnsetPressedState();
5043 }
5044
Adam Powelle14579b2009-12-16 18:39:52 -08005045 if (prepressed) {
5046 mPrivateFlags |= PRESSED;
5047 refreshDrawableState();
5048 postDelayed(mUnsetPressedState,
5049 ViewConfiguration.getPressedStateDuration());
5050 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005051 // If the post failed, unpress right now
5052 mUnsetPressedState.run();
5053 }
Adam Powelle14579b2009-12-16 18:39:52 -08005054 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005055 }
5056 break;
5057
5058 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08005059 if (mPendingCheckForTap == null) {
5060 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005061 }
Adam Powelle14579b2009-12-16 18:39:52 -08005062 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08005063 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08005064 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 break;
5066
5067 case MotionEvent.ACTION_CANCEL:
5068 mPrivateFlags &= ~PRESSED;
5069 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08005070 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005071 break;
5072
5073 case MotionEvent.ACTION_MOVE:
5074 final int x = (int) event.getX();
5075 final int y = (int) event.getY();
5076
5077 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07005078 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005079 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08005080 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005081 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08005082 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05005083 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005084
5085 // Need to switch from pressed to not pressed
5086 mPrivateFlags &= ~PRESSED;
5087 refreshDrawableState();
5088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089 }
5090 break;
5091 }
5092 return true;
5093 }
5094
5095 return false;
5096 }
5097
5098 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05005099 * Remove the longpress detection timer.
5100 */
5101 private void removeLongPressCallback() {
5102 if (mPendingCheckForLongPress != null) {
5103 removeCallbacks(mPendingCheckForLongPress);
5104 }
5105 }
Adam Powelle14579b2009-12-16 18:39:52 -08005106
5107 /**
Romain Guya440b002010-02-24 15:57:54 -08005108 * Remove the prepress detection timer.
5109 */
5110 private void removeUnsetPressCallback() {
5111 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
5112 setPressed(false);
5113 removeCallbacks(mUnsetPressedState);
5114 }
5115 }
5116
5117 /**
Adam Powelle14579b2009-12-16 18:39:52 -08005118 * Remove the tap detection timer.
5119 */
5120 private void removeTapCallback() {
5121 if (mPendingCheckForTap != null) {
5122 mPrivateFlags &= ~PREPRESSED;
5123 removeCallbacks(mPendingCheckForTap);
5124 }
5125 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05005126
5127 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 * Cancels a pending long press. Your subclass can use this if you
5129 * want the context menu to come up if the user presses and holds
5130 * at the same place, but you don't want it to come up if they press
5131 * and then move around enough to cause scrolling.
5132 */
5133 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05005134 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08005135
5136 /*
5137 * The prepressed state handled by the tap callback is a display
5138 * construct, but the tap callback will post a long press callback
5139 * less its own timeout. Remove it here.
5140 */
5141 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005142 }
5143
5144 /**
5145 * Sets the TouchDelegate for this View.
5146 */
5147 public void setTouchDelegate(TouchDelegate delegate) {
5148 mTouchDelegate = delegate;
5149 }
5150
5151 /**
5152 * Gets the TouchDelegate for this View.
5153 */
5154 public TouchDelegate getTouchDelegate() {
5155 return mTouchDelegate;
5156 }
5157
5158 /**
5159 * Set flags controlling behavior of this view.
5160 *
5161 * @param flags Constant indicating the value which should be set
5162 * @param mask Constant indicating the bit range that should be changed
5163 */
5164 void setFlags(int flags, int mask) {
5165 int old = mViewFlags;
5166 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
5167
5168 int changed = mViewFlags ^ old;
5169 if (changed == 0) {
5170 return;
5171 }
5172 int privateFlags = mPrivateFlags;
5173
5174 /* Check if the FOCUSABLE bit has changed */
5175 if (((changed & FOCUSABLE_MASK) != 0) &&
5176 ((privateFlags & HAS_BOUNDS) !=0)) {
5177 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
5178 && ((privateFlags & FOCUSED) != 0)) {
5179 /* Give up focus if we are no longer focusable */
5180 clearFocus();
5181 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
5182 && ((privateFlags & FOCUSED) == 0)) {
5183 /*
5184 * Tell the view system that we are now available to take focus
5185 * if no one else already has it.
5186 */
5187 if (mParent != null) mParent.focusableViewAvailable(this);
5188 }
5189 }
5190
5191 if ((flags & VISIBILITY_MASK) == VISIBLE) {
5192 if ((changed & VISIBILITY_MASK) != 0) {
5193 /*
5194 * If this view is becoming visible, set the DRAWN flag so that
5195 * the next invalidate() will not be skipped.
5196 */
5197 mPrivateFlags |= DRAWN;
5198
5199 needGlobalAttributesUpdate(true);
5200
5201 // a view becoming visible is worth notifying the parent
5202 // about in case nothing has focus. even if this specific view
5203 // isn't focusable, it may contain something that is, so let
5204 // the root view try to give this focus if nothing else does.
5205 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
5206 mParent.focusableViewAvailable(this);
5207 }
5208 }
5209 }
5210
5211 /* Check if the GONE bit has changed */
5212 if ((changed & GONE) != 0) {
5213 needGlobalAttributesUpdate(false);
5214 requestLayout();
5215 invalidate();
5216
Romain Guyecd80ee2009-12-03 17:13:02 -08005217 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5218 if (hasFocus()) clearFocus();
5219 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 }
5221 if (mAttachInfo != null) {
5222 mAttachInfo.mViewVisibilityChanged = true;
5223 }
5224 }
5225
5226 /* Check if the VISIBLE bit has changed */
5227 if ((changed & INVISIBLE) != 0) {
5228 needGlobalAttributesUpdate(false);
5229 invalidate();
5230
5231 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5232 // root view becoming invisible shouldn't clear focus
5233 if (getRootView() != this) {
5234 clearFocus();
5235 }
5236 }
5237 if (mAttachInfo != null) {
5238 mAttachInfo.mViewVisibilityChanged = true;
5239 }
5240 }
5241
Adam Powell326d8082009-12-09 15:10:07 -08005242 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07005243 if (mParent instanceof ViewGroup) {
5244 ((ViewGroup)mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
5245 }
Adam Powell326d8082009-12-09 15:10:07 -08005246 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5247 }
5248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005249 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5250 destroyDrawingCache();
5251 }
5252
5253 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5254 destroyDrawingCache();
5255 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5256 }
5257
5258 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5259 destroyDrawingCache();
5260 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5261 }
5262
5263 if ((changed & DRAW_MASK) != 0) {
5264 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5265 if (mBGDrawable != null) {
5266 mPrivateFlags &= ~SKIP_DRAW;
5267 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5268 } else {
5269 mPrivateFlags |= SKIP_DRAW;
5270 }
5271 } else {
5272 mPrivateFlags &= ~SKIP_DRAW;
5273 }
5274 requestLayout();
5275 invalidate();
5276 }
5277
5278 if ((changed & KEEP_SCREEN_ON) != 0) {
5279 if (mParent != null) {
5280 mParent.recomputeViewAttributes(this);
5281 }
5282 }
5283 }
5284
5285 /**
5286 * Change the view's z order in the tree, so it's on top of other sibling
5287 * views
5288 */
5289 public void bringToFront() {
5290 if (mParent != null) {
5291 mParent.bringChildToFront(this);
5292 }
5293 }
5294
5295 /**
5296 * This is called in response to an internal scroll in this view (i.e., the
5297 * view scrolled its own contents). This is typically as a result of
5298 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5299 * called.
5300 *
5301 * @param l Current horizontal scroll origin.
5302 * @param t Current vertical scroll origin.
5303 * @param oldl Previous horizontal scroll origin.
5304 * @param oldt Previous vertical scroll origin.
5305 */
5306 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5307 mBackgroundSizeChanged = true;
5308
5309 final AttachInfo ai = mAttachInfo;
5310 if (ai != null) {
5311 ai.mViewScrollChanged = true;
5312 }
5313 }
5314
5315 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005316 * Interface definition for a callback to be invoked when the layout bounds of a view
5317 * changes due to layout processing.
5318 */
5319 public interface OnLayoutChangeListener {
5320 /**
5321 * Called when the focus state of a view has changed.
5322 *
5323 * @param v The view whose state has changed.
5324 * @param left The new value of the view's left property.
5325 * @param top The new value of the view's top property.
5326 * @param right The new value of the view's right property.
5327 * @param bottom The new value of the view's bottom property.
5328 * @param oldLeft The previous value of the view's left property.
5329 * @param oldTop The previous value of the view's top property.
5330 * @param oldRight The previous value of the view's right property.
5331 * @param oldBottom The previous value of the view's bottom property.
5332 */
5333 void onLayoutChange(View v, int left, int top, int right, int bottom,
5334 int oldLeft, int oldTop, int oldRight, int oldBottom);
5335 }
5336
5337 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005338 * This is called during layout when the size of this view has changed. If
5339 * you were just added to the view hierarchy, you're called with the old
5340 * values of 0.
5341 *
5342 * @param w Current width of this view.
5343 * @param h Current height of this view.
5344 * @param oldw Old width of this view.
5345 * @param oldh Old height of this view.
5346 */
5347 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5348 }
5349
5350 /**
5351 * Called by draw to draw the child views. This may be overridden
5352 * by derived classes to gain control just before its children are drawn
5353 * (but after its own view has been drawn).
5354 * @param canvas the canvas on which to draw the view
5355 */
5356 protected void dispatchDraw(Canvas canvas) {
5357 }
5358
5359 /**
5360 * Gets the parent of this view. Note that the parent is a
5361 * ViewParent and not necessarily a View.
5362 *
5363 * @return Parent of this view.
5364 */
5365 public final ViewParent getParent() {
5366 return mParent;
5367 }
5368
5369 /**
5370 * Return the scrolled left position of this view. This is the left edge of
5371 * the displayed part of your view. You do not need to draw any pixels
5372 * farther left, since those are outside of the frame of your view on
5373 * screen.
5374 *
5375 * @return The left edge of the displayed part of your view, in pixels.
5376 */
5377 public final int getScrollX() {
5378 return mScrollX;
5379 }
5380
5381 /**
5382 * Return the scrolled top position of this view. This is the top edge of
5383 * the displayed part of your view. You do not need to draw any pixels above
5384 * it, since those are outside of the frame of your view on screen.
5385 *
5386 * @return The top edge of the displayed part of your view, in pixels.
5387 */
5388 public final int getScrollY() {
5389 return mScrollY;
5390 }
5391
5392 /**
5393 * Return the width of the your view.
5394 *
5395 * @return The width of your view, in pixels.
5396 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005397 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005398 public final int getWidth() {
5399 return mRight - mLeft;
5400 }
5401
5402 /**
5403 * Return the height of your view.
5404 *
5405 * @return The height of your view, in pixels.
5406 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005407 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005408 public final int getHeight() {
5409 return mBottom - mTop;
5410 }
5411
5412 /**
5413 * Return the visible drawing bounds of your view. Fills in the output
5414 * rectangle with the values from getScrollX(), getScrollY(),
5415 * getWidth(), and getHeight().
5416 *
5417 * @param outRect The (scrolled) drawing bounds of the view.
5418 */
5419 public void getDrawingRect(Rect outRect) {
5420 outRect.left = mScrollX;
5421 outRect.top = mScrollY;
5422 outRect.right = mScrollX + (mRight - mLeft);
5423 outRect.bottom = mScrollY + (mBottom - mTop);
5424 }
5425
5426 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005427 * Like {@link #getMeasuredWidthAndState()}, but only returns the
5428 * raw width component (that is the result is masked by
5429 * {@link #MEASURED_SIZE_MASK}).
5430 *
5431 * @return The raw measured width of this view.
5432 */
5433 public final int getMeasuredWidth() {
5434 return mMeasuredWidth & MEASURED_SIZE_MASK;
5435 }
5436
5437 /**
5438 * Return the full width measurement information for this view as computed
5439 * by the most recent call to {@link #measure}. This result is a bit mask
5440 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 * This should be used during measurement and layout calculations only. Use
5442 * {@link #getWidth()} to see how wide a view is after layout.
5443 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005444 * @return The measured width of this view as a bit mask.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08005446 public final int getMeasuredWidthAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 return mMeasuredWidth;
5448 }
5449
5450 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005451 * Like {@link #getMeasuredHeightAndState()}, but only returns the
5452 * raw width component (that is the result is masked by
5453 * {@link #MEASURED_SIZE_MASK}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005455 * @return The raw measured height of this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456 */
5457 public final int getMeasuredHeight() {
Dianne Hackborn189ee182010-12-02 21:48:53 -08005458 return mMeasuredHeight & MEASURED_SIZE_MASK;
5459 }
5460
5461 /**
5462 * Return the full height measurement information for this view as computed
5463 * by the most recent call to {@link #measure}. This result is a bit mask
5464 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5465 * This should be used during measurement and layout calculations only. Use
5466 * {@link #getHeight()} to see how wide a view is after layout.
5467 *
5468 * @return The measured width of this view as a bit mask.
5469 */
5470 public final int getMeasuredHeightAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005471 return mMeasuredHeight;
5472 }
5473
5474 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005475 * Return only the state bits of {@link #getMeasuredWidthAndState()}
5476 * and {@link #getMeasuredHeightAndState()}, combined into one integer.
5477 * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
5478 * and the height component is at the shifted bits
5479 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
5480 */
5481 public final int getMeasuredState() {
5482 return (mMeasuredWidth&MEASURED_STATE_MASK)
5483 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
5484 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
5485 }
5486
5487 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005488 * The transform matrix of this view, which is calculated based on the current
5489 * roation, scale, and pivot properties.
5490 *
5491 * @see #getRotation()
5492 * @see #getScaleX()
5493 * @see #getScaleY()
5494 * @see #getPivotX()
5495 * @see #getPivotY()
5496 * @return The current transform matrix for the view
5497 */
5498 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005499 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005500 return mMatrix;
5501 }
5502
5503 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005504 * Utility function to determine if the value is far enough away from zero to be
5505 * considered non-zero.
5506 * @param value A floating point value to check for zero-ness
5507 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5508 */
5509 private static boolean nonzero(float value) {
5510 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5511 }
5512
5513 /**
Jeff Brown86671742010-09-30 20:00:15 -07005514 * Returns true if the transform matrix is the identity matrix.
5515 * Recomputes the matrix if necessary.
Romain Guy33e72ae2010-07-17 12:40:29 -07005516 *
5517 * @return True if the transform matrix is the identity matrix, false otherwise.
5518 */
Jeff Brown86671742010-09-30 20:00:15 -07005519 final boolean hasIdentityMatrix() {
5520 updateMatrix();
5521 return mMatrixIsIdentity;
5522 }
5523
5524 /**
5525 * Recomputes the transform matrix if necessary.
5526 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005527 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005528 if (mMatrixDirty) {
5529 // transform-related properties have changed since the last time someone
5530 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005531
5532 // Figure out if we need to update the pivot point
5533 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005534 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005535 mPrevWidth = mRight - mLeft;
5536 mPrevHeight = mBottom - mTop;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -08005537 mPivotX = mPrevWidth / 2f;
5538 mPivotY = mPrevHeight / 2f;
Chet Haasefd2b0022010-08-06 13:08:56 -07005539 }
5540 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005541 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005542 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5543 mMatrix.setTranslate(mTranslationX, mTranslationY);
5544 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5545 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5546 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005547 if (mCamera == null) {
5548 mCamera = new Camera();
5549 matrix3D = new Matrix();
5550 }
5551 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005552 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005553 mCamera.rotateX(mRotationX);
5554 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005555 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005556 mCamera.getMatrix(matrix3D);
5557 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005558 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005559 mMatrix.postConcat(matrix3D);
5560 mCamera.restore();
5561 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005562 mMatrixDirty = false;
5563 mMatrixIsIdentity = mMatrix.isIdentity();
5564 mInverseMatrixDirty = true;
5565 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005566 }
5567
5568 /**
5569 * Utility method to retrieve the inverse of the current mMatrix property.
5570 * We cache the matrix to avoid recalculating it when transform properties
5571 * have not changed.
5572 *
5573 * @return The inverse of the current matrix of this view.
5574 */
Jeff Brown86671742010-09-30 20:00:15 -07005575 final Matrix getInverseMatrix() {
5576 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005577 if (mInverseMatrixDirty) {
5578 if (mInverseMatrix == null) {
5579 mInverseMatrix = new Matrix();
5580 }
5581 mMatrix.invert(mInverseMatrix);
5582 mInverseMatrixDirty = false;
5583 }
5584 return mInverseMatrix;
5585 }
5586
5587 /**
5588 * The degrees that the view is rotated around the pivot point.
5589 *
5590 * @see #getPivotX()
5591 * @see #getPivotY()
5592 * @return The degrees of rotation.
5593 */
5594 public float getRotation() {
5595 return mRotation;
5596 }
5597
5598 /**
Chet Haase897247b2010-09-09 14:54:47 -07005599 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5600 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005601 *
5602 * @param rotation The degrees of rotation.
5603 * @see #getPivotX()
5604 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005605 *
5606 * @attr ref android.R.styleable#View_rotation
Chet Haasec3aa3612010-06-17 08:50:37 -07005607 */
5608 public void setRotation(float rotation) {
5609 if (mRotation != rotation) {
5610 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005611 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005612 mRotation = rotation;
5613 mMatrixDirty = true;
5614 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005615 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005616 }
5617 }
5618
5619 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005620 * The degrees that the view is rotated around the vertical axis through the pivot point.
5621 *
5622 * @see #getPivotX()
5623 * @see #getPivotY()
5624 * @return The degrees of Y rotation.
5625 */
5626 public float getRotationY() {
5627 return mRotationY;
5628 }
5629
5630 /**
Chet Haase897247b2010-09-09 14:54:47 -07005631 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5632 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5633 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005634 *
5635 * @param rotationY The degrees of Y rotation.
5636 * @see #getPivotX()
5637 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005638 *
5639 * @attr ref android.R.styleable#View_rotationY
Chet Haasefd2b0022010-08-06 13:08:56 -07005640 */
5641 public void setRotationY(float rotationY) {
5642 if (mRotationY != rotationY) {
5643 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005644 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005645 mRotationY = rotationY;
5646 mMatrixDirty = true;
5647 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005648 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005649 }
5650 }
5651
5652 /**
5653 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5654 *
5655 * @see #getPivotX()
5656 * @see #getPivotY()
5657 * @return The degrees of X rotation.
5658 */
5659 public float getRotationX() {
5660 return mRotationX;
5661 }
5662
5663 /**
Chet Haase897247b2010-09-09 14:54:47 -07005664 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5665 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5666 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005667 *
5668 * @param rotationX The degrees of X rotation.
5669 * @see #getPivotX()
5670 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005671 *
5672 * @attr ref android.R.styleable#View_rotationX
Chet Haasefd2b0022010-08-06 13:08:56 -07005673 */
5674 public void setRotationX(float rotationX) {
5675 if (mRotationX != rotationX) {
5676 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005677 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005678 mRotationX = rotationX;
5679 mMatrixDirty = true;
5680 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005681 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005682 }
5683 }
5684
5685 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005686 * The amount that the view is scaled in x around the pivot point, as a proportion of
5687 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5688 *
Joe Onorato93162322010-09-16 15:42:01 -04005689 * <p>By default, this is 1.0f.
5690 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005691 * @see #getPivotX()
5692 * @see #getPivotY()
5693 * @return The scaling factor.
5694 */
5695 public float getScaleX() {
5696 return mScaleX;
5697 }
5698
5699 /**
5700 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5701 * the view's unscaled width. A value of 1 means that no scaling is applied.
5702 *
5703 * @param scaleX The scaling factor.
5704 * @see #getPivotX()
5705 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005706 *
5707 * @attr ref android.R.styleable#View_scaleX
Chet Haasec3aa3612010-06-17 08:50:37 -07005708 */
5709 public void setScaleX(float scaleX) {
5710 if (mScaleX != scaleX) {
5711 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005712 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005713 mScaleX = scaleX;
5714 mMatrixDirty = true;
5715 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005716 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005717 }
5718 }
5719
5720 /**
5721 * The amount that the view is scaled in y around the pivot point, as a proportion of
5722 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5723 *
Joe Onorato93162322010-09-16 15:42:01 -04005724 * <p>By default, this is 1.0f.
5725 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005726 * @see #getPivotX()
5727 * @see #getPivotY()
5728 * @return The scaling factor.
5729 */
5730 public float getScaleY() {
5731 return mScaleY;
5732 }
5733
5734 /**
5735 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5736 * the view's unscaled width. A value of 1 means that no scaling is applied.
5737 *
5738 * @param scaleY The scaling factor.
5739 * @see #getPivotX()
5740 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005741 *
5742 * @attr ref android.R.styleable#View_scaleY
Chet Haasec3aa3612010-06-17 08:50:37 -07005743 */
5744 public void setScaleY(float scaleY) {
5745 if (mScaleY != scaleY) {
5746 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005747 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005748 mScaleY = scaleY;
5749 mMatrixDirty = true;
5750 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005751 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005752 }
5753 }
5754
5755 /**
5756 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5757 * and {@link #setScaleX(float) scaled}.
5758 *
5759 * @see #getRotation()
5760 * @see #getScaleX()
5761 * @see #getScaleY()
5762 * @see #getPivotY()
5763 * @return The x location of the pivot point.
5764 */
5765 public float getPivotX() {
5766 return mPivotX;
5767 }
5768
5769 /**
5770 * Sets the x location of the point around which the view is
5771 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005772 * By default, the pivot point is centered on the object.
5773 * Setting this property disables this behavior and causes the view to use only the
5774 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005775 *
5776 * @param pivotX The x location of the pivot point.
5777 * @see #getRotation()
5778 * @see #getScaleX()
5779 * @see #getScaleY()
5780 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005781 *
5782 * @attr ref android.R.styleable#View_transformPivotX
Chet Haasec3aa3612010-06-17 08:50:37 -07005783 */
5784 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005785 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005786 if (mPivotX != pivotX) {
5787 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005788 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005789 mPivotX = pivotX;
5790 mMatrixDirty = true;
5791 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005792 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005793 }
5794 }
5795
5796 /**
5797 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5798 * and {@link #setScaleY(float) scaled}.
5799 *
5800 * @see #getRotation()
5801 * @see #getScaleX()
5802 * @see #getScaleY()
5803 * @see #getPivotY()
5804 * @return The y location of the pivot point.
5805 */
5806 public float getPivotY() {
5807 return mPivotY;
5808 }
5809
5810 /**
5811 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005812 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5813 * Setting this property disables this behavior and causes the view to use only the
5814 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005815 *
5816 * @param pivotY The y location of the pivot point.
5817 * @see #getRotation()
5818 * @see #getScaleX()
5819 * @see #getScaleY()
5820 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005821 *
5822 * @attr ref android.R.styleable#View_transformPivotY
Chet Haasec3aa3612010-06-17 08:50:37 -07005823 */
5824 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005825 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005826 if (mPivotY != pivotY) {
5827 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005828 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005829 mPivotY = pivotY;
5830 mMatrixDirty = true;
5831 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005832 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005833 }
5834 }
5835
5836 /**
5837 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5838 * completely transparent and 1 means the view is completely opaque.
5839 *
Joe Onorato93162322010-09-16 15:42:01 -04005840 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005841 * @return The opacity of the view.
5842 */
5843 public float getAlpha() {
5844 return mAlpha;
5845 }
5846
5847 /**
Romain Guy171c5922011-01-06 10:04:23 -08005848 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5849 * completely transparent and 1 means the view is completely opaque.</p>
5850 *
5851 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
5852 * responsible for applying the opacity itself. Otherwise, calling this method is
5853 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
5854 * setting a hardware layer.</p>
Chet Haasec3aa3612010-06-17 08:50:37 -07005855 *
5856 * @param alpha The opacity of the view.
Chet Haase73066682010-11-29 15:55:32 -08005857 *
Romain Guy171c5922011-01-06 10:04:23 -08005858 * @see #setLayerType(int, android.graphics.Paint)
5859 *
Chet Haase73066682010-11-29 15:55:32 -08005860 * @attr ref android.R.styleable#View_alpha
Chet Haasec3aa3612010-06-17 08:50:37 -07005861 */
5862 public void setAlpha(float alpha) {
5863 mAlpha = alpha;
Chet Haaseed032702010-10-01 14:05:54 -07005864 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07005865 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005866 // subclass is handling alpha - don't optimize rendering cache invalidation
5867 invalidate();
5868 } else {
Romain Guya3496a92010-10-12 11:53:24 -07005869 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005870 invalidate(false);
5871 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005872 }
5873
5874 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 * Top position of this view relative to its parent.
5876 *
5877 * @return The top of this view, in pixels.
5878 */
5879 @ViewDebug.CapturedViewProperty
5880 public final int getTop() {
5881 return mTop;
5882 }
5883
5884 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005885 * Sets the top position of this view relative to its parent. This method is meant to be called
5886 * by the layout system and should not generally be called otherwise, because the property
5887 * may be changed at any time by the layout.
5888 *
5889 * @param top The top of this view, in pixels.
5890 */
5891 public final void setTop(int top) {
5892 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07005893 updateMatrix();
5894 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005895 final ViewParent p = mParent;
5896 if (p != null && mAttachInfo != null) {
5897 final Rect r = mAttachInfo.mTmpInvalRect;
5898 int minTop;
5899 int yLoc;
5900 if (top < mTop) {
5901 minTop = top;
5902 yLoc = top - mTop;
5903 } else {
5904 minTop = mTop;
5905 yLoc = 0;
5906 }
5907 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5908 p.invalidateChild(this, r);
5909 }
5910 } else {
5911 // Double-invalidation is necessary to capture view's old and new areas
5912 invalidate();
5913 }
5914
Chet Haaseed032702010-10-01 14:05:54 -07005915 int width = mRight - mLeft;
5916 int oldHeight = mBottom - mTop;
5917
Chet Haase21cd1382010-09-01 17:42:29 -07005918 mTop = top;
5919
Chet Haaseed032702010-10-01 14:05:54 -07005920 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5921
Chet Haase21cd1382010-09-01 17:42:29 -07005922 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005923 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5924 // A change in dimension means an auto-centered pivot point changes, too
5925 mMatrixDirty = true;
5926 }
Chet Haase21cd1382010-09-01 17:42:29 -07005927 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5928 invalidate();
5929 }
Chet Haase55dbb652010-12-21 20:15:08 -08005930 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07005931 }
5932 }
5933
5934 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005935 * Bottom position of this view relative to its parent.
5936 *
5937 * @return The bottom of this view, in pixels.
5938 */
5939 @ViewDebug.CapturedViewProperty
5940 public final int getBottom() {
5941 return mBottom;
5942 }
5943
5944 /**
Michael Jurkadab559a2011-01-04 20:31:51 -08005945 * True if this view has changed since the last time being drawn.
5946 *
5947 * @return The dirty state of this view.
5948 */
5949 public boolean isDirty() {
5950 return (mPrivateFlags & DIRTY_MASK) != 0;
5951 }
5952
5953 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005954 * Sets the bottom position of this view relative to its parent. This method is meant to be
5955 * called by the layout system and should not generally be called otherwise, because the
5956 * property may be changed at any time by the layout.
5957 *
5958 * @param bottom The bottom of this view, in pixels.
5959 */
5960 public final void setBottom(int bottom) {
5961 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07005962 updateMatrix();
5963 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005964 final ViewParent p = mParent;
5965 if (p != null && mAttachInfo != null) {
5966 final Rect r = mAttachInfo.mTmpInvalRect;
5967 int maxBottom;
5968 if (bottom < mBottom) {
5969 maxBottom = mBottom;
5970 } else {
5971 maxBottom = bottom;
5972 }
5973 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5974 p.invalidateChild(this, r);
5975 }
5976 } else {
5977 // Double-invalidation is necessary to capture view's old and new areas
5978 invalidate();
5979 }
5980
Chet Haaseed032702010-10-01 14:05:54 -07005981 int width = mRight - mLeft;
5982 int oldHeight = mBottom - mTop;
5983
Chet Haase21cd1382010-09-01 17:42:29 -07005984 mBottom = bottom;
5985
Chet Haaseed032702010-10-01 14:05:54 -07005986 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5987
Chet Haase21cd1382010-09-01 17:42:29 -07005988 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005989 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5990 // A change in dimension means an auto-centered pivot point changes, too
5991 mMatrixDirty = true;
5992 }
Chet Haase21cd1382010-09-01 17:42:29 -07005993 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5994 invalidate();
5995 }
Chet Haase55dbb652010-12-21 20:15:08 -08005996 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07005997 }
5998 }
5999
6000 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 * Left position of this view relative to its parent.
6002 *
6003 * @return The left edge of this view, in pixels.
6004 */
6005 @ViewDebug.CapturedViewProperty
6006 public final int getLeft() {
6007 return mLeft;
6008 }
6009
6010 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006011 * Sets the left position of this view relative to its parent. This method is meant to be called
6012 * by the layout system and should not generally be called otherwise, because the property
6013 * may be changed at any time by the layout.
6014 *
6015 * @param left The bottom of this view, in pixels.
6016 */
6017 public final void setLeft(int left) {
6018 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07006019 updateMatrix();
6020 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006021 final ViewParent p = mParent;
6022 if (p != null && mAttachInfo != null) {
6023 final Rect r = mAttachInfo.mTmpInvalRect;
6024 int minLeft;
6025 int xLoc;
6026 if (left < mLeft) {
6027 minLeft = left;
6028 xLoc = left - mLeft;
6029 } else {
6030 minLeft = mLeft;
6031 xLoc = 0;
6032 }
6033 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
6034 p.invalidateChild(this, r);
6035 }
6036 } else {
6037 // Double-invalidation is necessary to capture view's old and new areas
6038 invalidate();
6039 }
6040
Chet Haaseed032702010-10-01 14:05:54 -07006041 int oldWidth = mRight - mLeft;
6042 int height = mBottom - mTop;
6043
Chet Haase21cd1382010-09-01 17:42:29 -07006044 mLeft = left;
6045
Chet Haaseed032702010-10-01 14:05:54 -07006046 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6047
Chet Haase21cd1382010-09-01 17:42:29 -07006048 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006049 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6050 // A change in dimension means an auto-centered pivot point changes, too
6051 mMatrixDirty = true;
6052 }
Chet Haase21cd1382010-09-01 17:42:29 -07006053 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6054 invalidate();
6055 }
Chet Haase55dbb652010-12-21 20:15:08 -08006056 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006057 }
6058 }
6059
6060 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 * Right position of this view relative to its parent.
6062 *
6063 * @return The right edge of this view, in pixels.
6064 */
6065 @ViewDebug.CapturedViewProperty
6066 public final int getRight() {
6067 return mRight;
6068 }
6069
6070 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006071 * Sets the right position of this view relative to its parent. This method is meant to be called
6072 * by the layout system and should not generally be called otherwise, because the property
6073 * may be changed at any time by the layout.
6074 *
6075 * @param right The bottom of this view, in pixels.
6076 */
6077 public final void setRight(int right) {
6078 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07006079 updateMatrix();
6080 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006081 final ViewParent p = mParent;
6082 if (p != null && mAttachInfo != null) {
6083 final Rect r = mAttachInfo.mTmpInvalRect;
6084 int maxRight;
6085 if (right < mRight) {
6086 maxRight = mRight;
6087 } else {
6088 maxRight = right;
6089 }
6090 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
6091 p.invalidateChild(this, r);
6092 }
6093 } else {
6094 // Double-invalidation is necessary to capture view's old and new areas
6095 invalidate();
6096 }
6097
Chet Haaseed032702010-10-01 14:05:54 -07006098 int oldWidth = mRight - mLeft;
6099 int height = mBottom - mTop;
6100
Chet Haase21cd1382010-09-01 17:42:29 -07006101 mRight = right;
6102
Chet Haaseed032702010-10-01 14:05:54 -07006103 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6104
Chet Haase21cd1382010-09-01 17:42:29 -07006105 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006106 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6107 // A change in dimension means an auto-centered pivot point changes, too
6108 mMatrixDirty = true;
6109 }
Chet Haase21cd1382010-09-01 17:42:29 -07006110 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6111 invalidate();
6112 }
Chet Haase55dbb652010-12-21 20:15:08 -08006113 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006114 }
6115 }
6116
6117 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006118 * The visual x position of this view, in pixels. This is equivalent to the
6119 * {@link #setTranslationX(float) translationX} property plus the current
6120 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07006121 *
Chet Haasedf030d22010-07-30 17:22:38 -07006122 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006123 */
Chet Haasedf030d22010-07-30 17:22:38 -07006124 public float getX() {
6125 return mLeft + mTranslationX;
6126 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006127
Chet Haasedf030d22010-07-30 17:22:38 -07006128 /**
6129 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
6130 * {@link #setTranslationX(float) translationX} property to be the difference between
6131 * the x value passed in and the current {@link #getLeft() left} property.
6132 *
6133 * @param x The visual x position of this view, in pixels.
6134 */
6135 public void setX(float x) {
6136 setTranslationX(x - mLeft);
6137 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006138
Chet Haasedf030d22010-07-30 17:22:38 -07006139 /**
6140 * The visual y position of this view, in pixels. This is equivalent to the
6141 * {@link #setTranslationY(float) translationY} property plus the current
6142 * {@link #getTop() top} property.
6143 *
6144 * @return The visual y position of this view, in pixels.
6145 */
6146 public float getY() {
6147 return mTop + mTranslationY;
6148 }
6149
6150 /**
6151 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
6152 * {@link #setTranslationY(float) translationY} property to be the difference between
6153 * the y value passed in and the current {@link #getTop() top} property.
6154 *
6155 * @param y The visual y position of this view, in pixels.
6156 */
6157 public void setY(float y) {
6158 setTranslationY(y - mTop);
6159 }
6160
6161
6162 /**
6163 * The horizontal location of this view relative to its {@link #getLeft() left} position.
6164 * This position is post-layout, in addition to wherever the object's
6165 * layout placed it.
6166 *
6167 * @return The horizontal position of this view relative to its left position, in pixels.
6168 */
6169 public float getTranslationX() {
6170 return mTranslationX;
6171 }
6172
6173 /**
6174 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
6175 * This effectively positions the object post-layout, in addition to wherever the object's
6176 * layout placed it.
6177 *
6178 * @param translationX The horizontal position of this view relative to its left position,
6179 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006180 *
6181 * @attr ref android.R.styleable#View_translationX
Chet Haasedf030d22010-07-30 17:22:38 -07006182 */
6183 public void setTranslationX(float translationX) {
6184 if (mTranslationX != translationX) {
6185 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006186 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006187 mTranslationX = translationX;
6188 mMatrixDirty = true;
6189 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006190 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006191 }
6192 }
6193
6194 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006195 * The horizontal location of this view relative to its {@link #getTop() top} position.
6196 * This position is post-layout, in addition to wherever the object's
6197 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006198 *
Chet Haasedf030d22010-07-30 17:22:38 -07006199 * @return The vertical position of this view relative to its top position,
6200 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006201 */
Chet Haasedf030d22010-07-30 17:22:38 -07006202 public float getTranslationY() {
6203 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07006204 }
6205
6206 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006207 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
6208 * This effectively positions the object post-layout, in addition to wherever the object's
6209 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006210 *
Chet Haasedf030d22010-07-30 17:22:38 -07006211 * @param translationY The vertical position of this view relative to its top position,
6212 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006213 *
6214 * @attr ref android.R.styleable#View_translationY
Chet Haasec3aa3612010-06-17 08:50:37 -07006215 */
Chet Haasedf030d22010-07-30 17:22:38 -07006216 public void setTranslationY(float translationY) {
6217 if (mTranslationY != translationY) {
6218 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006219 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006220 mTranslationY = translationY;
6221 mMatrixDirty = true;
6222 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006223 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006224 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006225 }
6226
6227 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006228 * Hit rectangle in parent's coordinates
6229 *
6230 * @param outRect The hit rectangle of the view.
6231 */
6232 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07006233 updateMatrix();
6234 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006235 outRect.set(mLeft, mTop, mRight, mBottom);
6236 } else {
6237 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07006238 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07006239 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07006240 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
6241 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07006242 }
6243 }
6244
6245 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07006246 * Determines whether the given point, in local coordinates is inside the view.
6247 */
6248 /*package*/ final boolean pointInView(float localX, float localY) {
6249 return localX >= 0 && localX < (mRight - mLeft)
6250 && localY >= 0 && localY < (mBottom - mTop);
6251 }
6252
6253 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07006254 * Utility method to determine whether the given point, in local coordinates,
6255 * is inside the view, where the area of the view is expanded by the slop factor.
6256 * This method is called while processing touch-move events to determine if the event
6257 * is still within the view.
6258 */
6259 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07006260 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07006261 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 }
6263
6264 /**
6265 * When a view has focus and the user navigates away from it, the next view is searched for
6266 * starting from the rectangle filled in by this method.
6267 *
6268 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
6269 * view maintains some idea of internal selection, such as a cursor, or a selected row
6270 * or column, you should override this method and fill in a more specific rectangle.
6271 *
6272 * @param r The rectangle to fill in, in this view's coordinates.
6273 */
6274 public void getFocusedRect(Rect r) {
6275 getDrawingRect(r);
6276 }
6277
6278 /**
6279 * If some part of this view is not clipped by any of its parents, then
6280 * return that area in r in global (root) coordinates. To convert r to local
6281 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
6282 * -globalOffset.y)) If the view is completely clipped or translated out,
6283 * return false.
6284 *
6285 * @param r If true is returned, r holds the global coordinates of the
6286 * visible portion of this view.
6287 * @param globalOffset If true is returned, globalOffset holds the dx,dy
6288 * between this view and its root. globalOffet may be null.
6289 * @return true if r is non-empty (i.e. part of the view is visible at the
6290 * root level.
6291 */
6292 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6293 int width = mRight - mLeft;
6294 int height = mBottom - mTop;
6295 if (width > 0 && height > 0) {
6296 r.set(0, 0, width, height);
6297 if (globalOffset != null) {
6298 globalOffset.set(-mScrollX, -mScrollY);
6299 }
6300 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6301 }
6302 return false;
6303 }
6304
6305 public final boolean getGlobalVisibleRect(Rect r) {
6306 return getGlobalVisibleRect(r, null);
6307 }
6308
6309 public final boolean getLocalVisibleRect(Rect r) {
6310 Point offset = new Point();
6311 if (getGlobalVisibleRect(r, offset)) {
6312 r.offset(-offset.x, -offset.y); // make r local
6313 return true;
6314 }
6315 return false;
6316 }
6317
6318 /**
6319 * Offset this view's vertical location by the specified number of pixels.
6320 *
6321 * @param offset the number of pixels to offset the view by
6322 */
6323 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006324 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006325 updateMatrix();
6326 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006327 final ViewParent p = mParent;
6328 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006329 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006330 int minTop;
6331 int maxBottom;
6332 int yLoc;
6333 if (offset < 0) {
6334 minTop = mTop + offset;
6335 maxBottom = mBottom;
6336 yLoc = offset;
6337 } else {
6338 minTop = mTop;
6339 maxBottom = mBottom + offset;
6340 yLoc = 0;
6341 }
6342 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6343 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006344 }
6345 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006346 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006347 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006348
Chet Haasec3aa3612010-06-17 08:50:37 -07006349 mTop += offset;
6350 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006351
Chet Haasec3aa3612010-06-17 08:50:37 -07006352 if (!mMatrixIsIdentity) {
6353 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006354 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006355 }
6356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 }
6358
6359 /**
6360 * Offset this view's horizontal location by the specified amount of pixels.
6361 *
6362 * @param offset the numer of pixels to offset the view by
6363 */
6364 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006365 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006366 updateMatrix();
6367 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006368 final ViewParent p = mParent;
6369 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006370 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006371 int minLeft;
6372 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006373 if (offset < 0) {
6374 minLeft = mLeft + offset;
6375 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006376 } else {
6377 minLeft = mLeft;
6378 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006379 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006380 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07006381 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006382 }
6383 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006384 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006385 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006386
Chet Haasec3aa3612010-06-17 08:50:37 -07006387 mLeft += offset;
6388 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006389
Chet Haasec3aa3612010-06-17 08:50:37 -07006390 if (!mMatrixIsIdentity) {
6391 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006392 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006393 }
6394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 }
6396
6397 /**
6398 * Get the LayoutParams associated with this view. All views should have
6399 * layout parameters. These supply parameters to the <i>parent</i> of this
6400 * view specifying how it should be arranged. There are many subclasses of
6401 * ViewGroup.LayoutParams, and these correspond to the different subclasses
6402 * of ViewGroup that are responsible for arranging their children.
6403 * @return The LayoutParams associated with this view
6404 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07006405 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 public ViewGroup.LayoutParams getLayoutParams() {
6407 return mLayoutParams;
6408 }
6409
6410 /**
6411 * Set the layout parameters associated with this view. These supply
6412 * parameters to the <i>parent</i> of this view specifying how it should be
6413 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6414 * correspond to the different subclasses of ViewGroup that are responsible
6415 * for arranging their children.
6416 *
6417 * @param params the layout parameters for this view
6418 */
6419 public void setLayoutParams(ViewGroup.LayoutParams params) {
6420 if (params == null) {
6421 throw new NullPointerException("params == null");
6422 }
6423 mLayoutParams = params;
6424 requestLayout();
6425 }
6426
6427 /**
6428 * Set the scrolled position of your view. This will cause a call to
6429 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6430 * invalidated.
6431 * @param x the x position to scroll to
6432 * @param y the y position to scroll to
6433 */
6434 public void scrollTo(int x, int y) {
6435 if (mScrollX != x || mScrollY != y) {
6436 int oldX = mScrollX;
6437 int oldY = mScrollY;
6438 mScrollX = x;
6439 mScrollY = y;
6440 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006441 if (!awakenScrollBars()) {
6442 invalidate();
6443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 }
6445 }
6446
6447 /**
6448 * Move the scrolled position of your view. This will cause a call to
6449 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6450 * invalidated.
6451 * @param x the amount of pixels to scroll by horizontally
6452 * @param y the amount of pixels to scroll by vertically
6453 */
6454 public void scrollBy(int x, int y) {
6455 scrollTo(mScrollX + x, mScrollY + y);
6456 }
6457
6458 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006459 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6460 * animation to fade the scrollbars out after a default delay. If a subclass
6461 * provides animated scrolling, the start delay should equal the duration
6462 * of the scrolling animation.</p>
6463 *
6464 * <p>The animation starts only if at least one of the scrollbars is
6465 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6466 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6467 * this method returns true, and false otherwise. If the animation is
6468 * started, this method calls {@link #invalidate()}; in that case the
6469 * caller should not call {@link #invalidate()}.</p>
6470 *
6471 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006472 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006473 *
6474 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6475 * and {@link #scrollTo(int, int)}.</p>
6476 *
6477 * @return true if the animation is played, false otherwise
6478 *
6479 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006480 * @see #scrollBy(int, int)
6481 * @see #scrollTo(int, int)
6482 * @see #isHorizontalScrollBarEnabled()
6483 * @see #isVerticalScrollBarEnabled()
6484 * @see #setHorizontalScrollBarEnabled(boolean)
6485 * @see #setVerticalScrollBarEnabled(boolean)
6486 */
6487 protected boolean awakenScrollBars() {
6488 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006489 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006490 }
6491
6492 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006493 * Trigger the scrollbars to draw.
6494 * This method differs from awakenScrollBars() only in its default duration.
6495 * initialAwakenScrollBars() will show the scroll bars for longer than
6496 * usual to give the user more of a chance to notice them.
6497 *
6498 * @return true if the animation is played, false otherwise.
6499 */
6500 private boolean initialAwakenScrollBars() {
6501 return mScrollCache != null &&
6502 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6503 }
6504
6505 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006506 * <p>
6507 * Trigger the scrollbars to draw. When invoked this method starts an
6508 * animation to fade the scrollbars out after a fixed delay. If a subclass
6509 * provides animated scrolling, the start delay should equal the duration of
6510 * the scrolling animation.
6511 * </p>
6512 *
6513 * <p>
6514 * The animation starts only if at least one of the scrollbars is enabled,
6515 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6516 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6517 * this method returns true, and false otherwise. If the animation is
6518 * started, this method calls {@link #invalidate()}; in that case the caller
6519 * should not call {@link #invalidate()}.
6520 * </p>
6521 *
6522 * <p>
6523 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006524 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006525 * </p>
6526 *
6527 * @param startDelay the delay, in milliseconds, after which the animation
6528 * should start; when the delay is 0, the animation starts
6529 * immediately
6530 * @return true if the animation is played, false otherwise
6531 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006532 * @see #scrollBy(int, int)
6533 * @see #scrollTo(int, int)
6534 * @see #isHorizontalScrollBarEnabled()
6535 * @see #isVerticalScrollBarEnabled()
6536 * @see #setHorizontalScrollBarEnabled(boolean)
6537 * @see #setVerticalScrollBarEnabled(boolean)
6538 */
6539 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006540 return awakenScrollBars(startDelay, true);
6541 }
6542
6543 /**
6544 * <p>
6545 * Trigger the scrollbars to draw. When invoked this method starts an
6546 * animation to fade the scrollbars out after a fixed delay. If a subclass
6547 * provides animated scrolling, the start delay should equal the duration of
6548 * the scrolling animation.
6549 * </p>
6550 *
6551 * <p>
6552 * The animation starts only if at least one of the scrollbars is enabled,
6553 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6554 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6555 * this method returns true, and false otherwise. If the animation is
6556 * started, this method calls {@link #invalidate()} if the invalidate parameter
6557 * is set to true; in that case the caller
6558 * should not call {@link #invalidate()}.
6559 * </p>
6560 *
6561 * <p>
6562 * This method should be invoked everytime a subclass directly updates the
6563 * scroll parameters.
6564 * </p>
6565 *
6566 * @param startDelay the delay, in milliseconds, after which the animation
6567 * should start; when the delay is 0, the animation starts
6568 * immediately
6569 *
6570 * @param invalidate Wheter this method should call invalidate
6571 *
6572 * @return true if the animation is played, false otherwise
6573 *
6574 * @see #scrollBy(int, int)
6575 * @see #scrollTo(int, int)
6576 * @see #isHorizontalScrollBarEnabled()
6577 * @see #isVerticalScrollBarEnabled()
6578 * @see #setHorizontalScrollBarEnabled(boolean)
6579 * @see #setVerticalScrollBarEnabled(boolean)
6580 */
6581 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006582 final ScrollabilityCache scrollCache = mScrollCache;
6583
6584 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6585 return false;
6586 }
6587
6588 if (scrollCache.scrollBar == null) {
6589 scrollCache.scrollBar = new ScrollBarDrawable();
6590 }
6591
6592 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6593
Mike Cleron290947b2009-09-29 18:34:32 -07006594 if (invalidate) {
6595 // Invalidate to show the scrollbars
6596 invalidate();
6597 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006598
6599 if (scrollCache.state == ScrollabilityCache.OFF) {
6600 // FIXME: this is copied from WindowManagerService.
6601 // We should get this value from the system when it
6602 // is possible to do so.
6603 final int KEY_REPEAT_FIRST_DELAY = 750;
6604 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6605 }
6606
6607 // Tell mScrollCache when we should start fading. This may
6608 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006609 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006610 scrollCache.fadeStartTime = fadeStartTime;
6611 scrollCache.state = ScrollabilityCache.ON;
6612
6613 // Schedule our fader to run, unscheduling any old ones first
6614 if (mAttachInfo != null) {
6615 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6616 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6617 }
6618
6619 return true;
6620 }
6621
6622 return false;
6623 }
6624
6625 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006626 * Mark the the area defined by dirty as needing to be drawn. If the view is
6627 * visible, {@link #onDraw} will be called at some point in the future.
6628 * This must be called from a UI thread. To call from a non-UI thread, call
6629 * {@link #postInvalidate()}.
6630 *
6631 * WARNING: This method is destructive to dirty.
6632 * @param dirty the rectangle representing the bounds of the dirty region
6633 */
6634 public void invalidate(Rect dirty) {
6635 if (ViewDebug.TRACE_HIERARCHY) {
6636 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6637 }
6638
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006639 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6640 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6642 final ViewParent p = mParent;
6643 final AttachInfo ai = mAttachInfo;
Romain Guyaf636eb2010-12-09 17:47:21 -08006644 if (p != null && ai != null && ai.mHardwareAccelerated) {
6645 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6646 // with a null dirty rect, which tells the ViewRoot to redraw everything
6647 p.invalidateChild(this, null);
6648 return;
6649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 if (p != null && ai != null) {
6651 final int scrollX = mScrollX;
6652 final int scrollY = mScrollY;
6653 final Rect r = ai.mTmpInvalRect;
6654 r.set(dirty.left - scrollX, dirty.top - scrollY,
6655 dirty.right - scrollX, dirty.bottom - scrollY);
6656 mParent.invalidateChild(this, r);
6657 }
6658 }
6659 }
6660
6661 /**
6662 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6663 * The coordinates of the dirty rect are relative to the view.
6664 * If the view is visible, {@link #onDraw} will be called at some point
6665 * in the future. This must be called from a UI thread. To call
6666 * from a non-UI thread, call {@link #postInvalidate()}.
6667 * @param l the left position of the dirty region
6668 * @param t the top position of the dirty region
6669 * @param r the right position of the dirty region
6670 * @param b the bottom position of the dirty region
6671 */
6672 public void invalidate(int l, int t, int r, int b) {
6673 if (ViewDebug.TRACE_HIERARCHY) {
6674 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6675 }
6676
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006677 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6678 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6680 final ViewParent p = mParent;
6681 final AttachInfo ai = mAttachInfo;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006682 if (p != null && ai != null && ai.mHardwareAccelerated) {
6683 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6684 // with a null dirty rect, which tells the ViewRoot to redraw everything
6685 p.invalidateChild(this, null);
6686 return;
6687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006688 if (p != null && ai != null && l < r && t < b) {
6689 final int scrollX = mScrollX;
6690 final int scrollY = mScrollY;
6691 final Rect tmpr = ai.mTmpInvalRect;
6692 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6693 p.invalidateChild(this, tmpr);
6694 }
6695 }
6696 }
6697
6698 /**
6699 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6700 * be called at some point in the future. This must be called from a
6701 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6702 */
6703 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006704 invalidate(true);
6705 }
6706
6707 /**
6708 * This is where the invalidate() work actually happens. A full invalidate()
6709 * causes the drawing cache to be invalidated, but this function can be called with
6710 * invalidateCache set to false to skip that invalidation step for cases that do not
6711 * need it (for example, a component that remains at the same dimensions with the same
6712 * content).
6713 *
6714 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6715 * well. This is usually true for a full invalidate, but may be set to false if the
6716 * View's contents or dimensions have not changed.
6717 */
6718 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 if (ViewDebug.TRACE_HIERARCHY) {
6720 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6721 }
6722
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006723 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6724 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID)) {
Chet Haaseed032702010-10-01 14:05:54 -07006725 mPrivateFlags &= ~DRAWN;
6726 if (invalidateCache) {
6727 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006730 final ViewParent p = mParent;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006731 if (p != null && ai != null && ai.mHardwareAccelerated) {
6732 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6733 // with a null dirty rect, which tells the ViewRoot to redraw everything
6734 p.invalidateChild(this, null);
6735 return;
6736 }
Michael Jurkaebefea42010-11-15 16:04:01 -08006737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 if (p != null && ai != null) {
6739 final Rect r = ai.mTmpInvalRect;
6740 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6741 // Don't call invalidate -- we don't want to internally scroll
6742 // our own bounds
6743 p.invalidateChild(this, r);
6744 }
6745 }
6746 }
6747
6748 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006749 * Indicates whether this View is opaque. An opaque View guarantees that it will
6750 * draw all the pixels overlapping its bounds using a fully opaque color.
6751 *
6752 * Subclasses of View should override this method whenever possible to indicate
6753 * whether an instance is opaque. Opaque Views are treated in a special way by
6754 * the View hierarchy, possibly allowing it to perform optimizations during
6755 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006756 *
Romain Guy24443ea2009-05-11 11:56:30 -07006757 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006758 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006759 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006760 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006761 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6762 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006763 }
6764
Adam Powell20232d02010-12-08 21:08:53 -08006765 /**
6766 * @hide
6767 */
6768 protected void computeOpaqueFlags() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006769 // Opaque if:
6770 // - Has a background
6771 // - Background is opaque
6772 // - Doesn't have scrollbars or scrollbars are inside overlay
6773
6774 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6775 mPrivateFlags |= OPAQUE_BACKGROUND;
6776 } else {
6777 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6778 }
6779
6780 final int flags = mViewFlags;
6781 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6782 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6783 mPrivateFlags |= OPAQUE_SCROLLBARS;
6784 } else {
6785 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6786 }
6787 }
6788
6789 /**
6790 * @hide
6791 */
6792 protected boolean hasOpaqueScrollbars() {
6793 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006794 }
6795
6796 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 * @return A handler associated with the thread running the View. This
6798 * handler can be used to pump events in the UI events queue.
6799 */
6800 public Handler getHandler() {
6801 if (mAttachInfo != null) {
6802 return mAttachInfo.mHandler;
6803 }
6804 return null;
6805 }
6806
6807 /**
6808 * Causes the Runnable to be added to the message queue.
6809 * The runnable will be run on the user interface thread.
6810 *
6811 * @param action The Runnable that will be executed.
6812 *
6813 * @return Returns true if the Runnable was successfully placed in to the
6814 * message queue. Returns false on failure, usually because the
6815 * looper processing the message queue is exiting.
6816 */
6817 public boolean post(Runnable action) {
6818 Handler handler;
6819 if (mAttachInfo != null) {
6820 handler = mAttachInfo.mHandler;
6821 } else {
6822 // Assume that post will succeed later
6823 ViewRoot.getRunQueue().post(action);
6824 return true;
6825 }
6826
6827 return handler.post(action);
6828 }
6829
6830 /**
6831 * Causes the Runnable to be added to the message queue, to be run
6832 * after the specified amount of time elapses.
6833 * The runnable will be run on the user interface thread.
6834 *
6835 * @param action The Runnable that will be executed.
6836 * @param delayMillis The delay (in milliseconds) until the Runnable
6837 * will be executed.
6838 *
6839 * @return true if the Runnable was successfully placed in to the
6840 * message queue. Returns false on failure, usually because the
6841 * looper processing the message queue is exiting. Note that a
6842 * result of true does not mean the Runnable will be processed --
6843 * if the looper is quit before the delivery time of the message
6844 * occurs then the message will be dropped.
6845 */
6846 public boolean postDelayed(Runnable action, long delayMillis) {
6847 Handler handler;
6848 if (mAttachInfo != null) {
6849 handler = mAttachInfo.mHandler;
6850 } else {
6851 // Assume that post will succeed later
6852 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6853 return true;
6854 }
6855
6856 return handler.postDelayed(action, delayMillis);
6857 }
6858
6859 /**
6860 * Removes the specified Runnable from the message queue.
6861 *
6862 * @param action The Runnable to remove from the message handling queue
6863 *
6864 * @return true if this view could ask the Handler to remove the Runnable,
6865 * false otherwise. When the returned value is true, the Runnable
6866 * may or may not have been actually removed from the message queue
6867 * (for instance, if the Runnable was not in the queue already.)
6868 */
6869 public boolean removeCallbacks(Runnable action) {
6870 Handler handler;
6871 if (mAttachInfo != null) {
6872 handler = mAttachInfo.mHandler;
6873 } else {
6874 // Assume that post will succeed later
6875 ViewRoot.getRunQueue().removeCallbacks(action);
6876 return true;
6877 }
6878
6879 handler.removeCallbacks(action);
6880 return true;
6881 }
6882
6883 /**
6884 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6885 * Use this to invalidate the View from a non-UI thread.
6886 *
6887 * @see #invalidate()
6888 */
6889 public void postInvalidate() {
6890 postInvalidateDelayed(0);
6891 }
6892
6893 /**
6894 * Cause an invalidate of the specified area to happen on a subsequent cycle
6895 * through the event loop. Use this to invalidate the View from a non-UI thread.
6896 *
6897 * @param left The left coordinate of the rectangle to invalidate.
6898 * @param top The top coordinate of the rectangle to invalidate.
6899 * @param right The right coordinate of the rectangle to invalidate.
6900 * @param bottom The bottom coordinate of the rectangle to invalidate.
6901 *
6902 * @see #invalidate(int, int, int, int)
6903 * @see #invalidate(Rect)
6904 */
6905 public void postInvalidate(int left, int top, int right, int bottom) {
6906 postInvalidateDelayed(0, left, top, right, bottom);
6907 }
6908
6909 /**
6910 * Cause an invalidate to happen on a subsequent cycle through the event
6911 * loop. Waits for the specified amount of time.
6912 *
6913 * @param delayMilliseconds the duration in milliseconds to delay the
6914 * invalidation by
6915 */
6916 public void postInvalidateDelayed(long delayMilliseconds) {
6917 // We try only with the AttachInfo because there's no point in invalidating
6918 // if we are not attached to our window
6919 if (mAttachInfo != null) {
6920 Message msg = Message.obtain();
6921 msg.what = AttachInfo.INVALIDATE_MSG;
6922 msg.obj = this;
6923 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6924 }
6925 }
6926
6927 /**
6928 * Cause an invalidate of the specified area to happen on a subsequent cycle
6929 * through the event loop. Waits for the specified amount of time.
6930 *
6931 * @param delayMilliseconds the duration in milliseconds to delay the
6932 * invalidation by
6933 * @param left The left coordinate of the rectangle to invalidate.
6934 * @param top The top coordinate of the rectangle to invalidate.
6935 * @param right The right coordinate of the rectangle to invalidate.
6936 * @param bottom The bottom coordinate of the rectangle to invalidate.
6937 */
6938 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6939 int right, int bottom) {
6940
6941 // We try only with the AttachInfo because there's no point in invalidating
6942 // if we are not attached to our window
6943 if (mAttachInfo != null) {
6944 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6945 info.target = this;
6946 info.left = left;
6947 info.top = top;
6948 info.right = right;
6949 info.bottom = bottom;
6950
6951 final Message msg = Message.obtain();
6952 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6953 msg.obj = info;
6954 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6955 }
6956 }
6957
6958 /**
6959 * Called by a parent to request that a child update its values for mScrollX
6960 * and mScrollY if necessary. This will typically be done if the child is
6961 * animating a scroll using a {@link android.widget.Scroller Scroller}
6962 * object.
6963 */
6964 public void computeScroll() {
6965 }
6966
6967 /**
6968 * <p>Indicate whether the horizontal edges are faded when the view is
6969 * scrolled horizontally.</p>
6970 *
6971 * @return true if the horizontal edges should are faded on scroll, false
6972 * otherwise
6973 *
6974 * @see #setHorizontalFadingEdgeEnabled(boolean)
6975 * @attr ref android.R.styleable#View_fadingEdge
6976 */
6977 public boolean isHorizontalFadingEdgeEnabled() {
6978 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6979 }
6980
6981 /**
6982 * <p>Define whether the horizontal edges should be faded when this view
6983 * is scrolled horizontally.</p>
6984 *
6985 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6986 * be faded when the view is scrolled
6987 * horizontally
6988 *
6989 * @see #isHorizontalFadingEdgeEnabled()
6990 * @attr ref android.R.styleable#View_fadingEdge
6991 */
6992 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6993 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6994 if (horizontalFadingEdgeEnabled) {
6995 initScrollCache();
6996 }
6997
6998 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6999 }
7000 }
7001
7002 /**
7003 * <p>Indicate whether the vertical edges are faded when the view is
7004 * scrolled horizontally.</p>
7005 *
7006 * @return true if the vertical edges should are faded on scroll, false
7007 * otherwise
7008 *
7009 * @see #setVerticalFadingEdgeEnabled(boolean)
7010 * @attr ref android.R.styleable#View_fadingEdge
7011 */
7012 public boolean isVerticalFadingEdgeEnabled() {
7013 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
7014 }
7015
7016 /**
7017 * <p>Define whether the vertical edges should be faded when this view
7018 * is scrolled vertically.</p>
7019 *
7020 * @param verticalFadingEdgeEnabled true if the vertical edges should
7021 * be faded when the view is scrolled
7022 * vertically
7023 *
7024 * @see #isVerticalFadingEdgeEnabled()
7025 * @attr ref android.R.styleable#View_fadingEdge
7026 */
7027 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
7028 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
7029 if (verticalFadingEdgeEnabled) {
7030 initScrollCache();
7031 }
7032
7033 mViewFlags ^= FADING_EDGE_VERTICAL;
7034 }
7035 }
7036
7037 /**
7038 * Returns the strength, or intensity, of the top faded edge. The strength is
7039 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7040 * returns 0.0 or 1.0 but no value in between.
7041 *
7042 * Subclasses should override this method to provide a smoother fade transition
7043 * when scrolling occurs.
7044 *
7045 * @return the intensity of the top fade as a float between 0.0f and 1.0f
7046 */
7047 protected float getTopFadingEdgeStrength() {
7048 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
7049 }
7050
7051 /**
7052 * Returns the strength, or intensity, of the bottom faded edge. The strength is
7053 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7054 * returns 0.0 or 1.0 but no value in between.
7055 *
7056 * Subclasses should override this method to provide a smoother fade transition
7057 * when scrolling occurs.
7058 *
7059 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
7060 */
7061 protected float getBottomFadingEdgeStrength() {
7062 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
7063 computeVerticalScrollRange() ? 1.0f : 0.0f;
7064 }
7065
7066 /**
7067 * Returns the strength, or intensity, of the left faded edge. The strength is
7068 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7069 * returns 0.0 or 1.0 but no value in between.
7070 *
7071 * Subclasses should override this method to provide a smoother fade transition
7072 * when scrolling occurs.
7073 *
7074 * @return the intensity of the left fade as a float between 0.0f and 1.0f
7075 */
7076 protected float getLeftFadingEdgeStrength() {
7077 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
7078 }
7079
7080 /**
7081 * Returns the strength, or intensity, of the right faded edge. The strength is
7082 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7083 * returns 0.0 or 1.0 but no value in between.
7084 *
7085 * Subclasses should override this method to provide a smoother fade transition
7086 * when scrolling occurs.
7087 *
7088 * @return the intensity of the right fade as a float between 0.0f and 1.0f
7089 */
7090 protected float getRightFadingEdgeStrength() {
7091 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
7092 computeHorizontalScrollRange() ? 1.0f : 0.0f;
7093 }
7094
7095 /**
7096 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
7097 * scrollbar is not drawn by default.</p>
7098 *
7099 * @return true if the horizontal scrollbar should be painted, false
7100 * otherwise
7101 *
7102 * @see #setHorizontalScrollBarEnabled(boolean)
7103 */
7104 public boolean isHorizontalScrollBarEnabled() {
7105 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7106 }
7107
7108 /**
7109 * <p>Define whether the horizontal scrollbar should be drawn or not. The
7110 * scrollbar is not drawn by default.</p>
7111 *
7112 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
7113 * be painted
7114 *
7115 * @see #isHorizontalScrollBarEnabled()
7116 */
7117 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
7118 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
7119 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007120 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007121 recomputePadding();
7122 }
7123 }
7124
7125 /**
7126 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
7127 * scrollbar is not drawn by default.</p>
7128 *
7129 * @return true if the vertical scrollbar should be painted, false
7130 * otherwise
7131 *
7132 * @see #setVerticalScrollBarEnabled(boolean)
7133 */
7134 public boolean isVerticalScrollBarEnabled() {
7135 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
7136 }
7137
7138 /**
7139 * <p>Define whether the vertical scrollbar should be drawn or not. The
7140 * scrollbar is not drawn by default.</p>
7141 *
7142 * @param verticalScrollBarEnabled true if the vertical scrollbar should
7143 * be painted
7144 *
7145 * @see #isVerticalScrollBarEnabled()
7146 */
7147 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
7148 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
7149 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007150 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 recomputePadding();
7152 }
7153 }
7154
Adam Powell20232d02010-12-08 21:08:53 -08007155 /**
7156 * @hide
7157 */
7158 protected void recomputePadding() {
7159 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007160 }
Mike Cleronfe81d382009-09-28 14:22:16 -07007161
7162 /**
7163 * Define whether scrollbars will fade when the view is not scrolling.
7164 *
7165 * @param fadeScrollbars wheter to enable fading
7166 *
7167 */
7168 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
7169 initScrollCache();
7170 final ScrollabilityCache scrollabilityCache = mScrollCache;
7171 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07007172 if (fadeScrollbars) {
7173 scrollabilityCache.state = ScrollabilityCache.OFF;
7174 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07007175 scrollabilityCache.state = ScrollabilityCache.ON;
7176 }
7177 }
7178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007179 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07007180 *
7181 * Returns true if scrollbars will fade when this view is not scrolling
7182 *
7183 * @return true if scrollbar fading is enabled
7184 */
7185 public boolean isScrollbarFadingEnabled() {
7186 return mScrollCache != null && mScrollCache.fadeScrollBars;
7187 }
7188
7189 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
7191 * inset. When inset, they add to the padding of the view. And the scrollbars
7192 * can be drawn inside the padding area or on the edge of the view. For example,
7193 * if a view has a background drawable and you want to draw the scrollbars
7194 * inside the padding specified by the drawable, you can use
7195 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
7196 * appear at the edge of the view, ignoring the padding, then you can use
7197 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
7198 * @param style the style of the scrollbars. Should be one of
7199 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
7200 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
7201 * @see #SCROLLBARS_INSIDE_OVERLAY
7202 * @see #SCROLLBARS_INSIDE_INSET
7203 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7204 * @see #SCROLLBARS_OUTSIDE_INSET
7205 */
7206 public void setScrollBarStyle(int style) {
7207 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
7208 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07007209 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007210 recomputePadding();
7211 }
7212 }
7213
7214 /**
7215 * <p>Returns the current scrollbar style.</p>
7216 * @return the current scrollbar style
7217 * @see #SCROLLBARS_INSIDE_OVERLAY
7218 * @see #SCROLLBARS_INSIDE_INSET
7219 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7220 * @see #SCROLLBARS_OUTSIDE_INSET
7221 */
7222 public int getScrollBarStyle() {
7223 return mViewFlags & SCROLLBARS_STYLE_MASK;
7224 }
7225
7226 /**
7227 * <p>Compute the horizontal range that the horizontal scrollbar
7228 * represents.</p>
7229 *
7230 * <p>The range is expressed in arbitrary units that must be the same as the
7231 * units used by {@link #computeHorizontalScrollExtent()} and
7232 * {@link #computeHorizontalScrollOffset()}.</p>
7233 *
7234 * <p>The default range is the drawing width of this view.</p>
7235 *
7236 * @return the total horizontal range represented by the horizontal
7237 * scrollbar
7238 *
7239 * @see #computeHorizontalScrollExtent()
7240 * @see #computeHorizontalScrollOffset()
7241 * @see android.widget.ScrollBarDrawable
7242 */
7243 protected int computeHorizontalScrollRange() {
7244 return getWidth();
7245 }
7246
7247 /**
7248 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7249 * within the horizontal range. This value is used to compute the position
7250 * of the thumb within the scrollbar's track.</p>
7251 *
7252 * <p>The range is expressed in arbitrary units that must be the same as the
7253 * units used by {@link #computeHorizontalScrollRange()} and
7254 * {@link #computeHorizontalScrollExtent()}.</p>
7255 *
7256 * <p>The default offset is the scroll offset of this view.</p>
7257 *
7258 * @return the horizontal offset of the scrollbar's thumb
7259 *
7260 * @see #computeHorizontalScrollRange()
7261 * @see #computeHorizontalScrollExtent()
7262 * @see android.widget.ScrollBarDrawable
7263 */
7264 protected int computeHorizontalScrollOffset() {
7265 return mScrollX;
7266 }
7267
7268 /**
7269 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7270 * within the horizontal range. This value is used to compute the length
7271 * of the thumb within the scrollbar's track.</p>
7272 *
7273 * <p>The range is expressed in arbitrary units that must be the same as the
7274 * units used by {@link #computeHorizontalScrollRange()} and
7275 * {@link #computeHorizontalScrollOffset()}.</p>
7276 *
7277 * <p>The default extent is the drawing width of this view.</p>
7278 *
7279 * @return the horizontal extent of the scrollbar's thumb
7280 *
7281 * @see #computeHorizontalScrollRange()
7282 * @see #computeHorizontalScrollOffset()
7283 * @see android.widget.ScrollBarDrawable
7284 */
7285 protected int computeHorizontalScrollExtent() {
7286 return getWidth();
7287 }
7288
7289 /**
7290 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7291 *
7292 * <p>The range is expressed in arbitrary units that must be the same as the
7293 * units used by {@link #computeVerticalScrollExtent()} and
7294 * {@link #computeVerticalScrollOffset()}.</p>
7295 *
7296 * @return the total vertical range represented by the vertical scrollbar
7297 *
7298 * <p>The default range is the drawing height of this view.</p>
7299 *
7300 * @see #computeVerticalScrollExtent()
7301 * @see #computeVerticalScrollOffset()
7302 * @see android.widget.ScrollBarDrawable
7303 */
7304 protected int computeVerticalScrollRange() {
7305 return getHeight();
7306 }
7307
7308 /**
7309 * <p>Compute the vertical offset of the vertical scrollbar's thumb
7310 * within the horizontal range. This value is used to compute the position
7311 * of the thumb within the scrollbar's track.</p>
7312 *
7313 * <p>The range is expressed in arbitrary units that must be the same as the
7314 * units used by {@link #computeVerticalScrollRange()} and
7315 * {@link #computeVerticalScrollExtent()}.</p>
7316 *
7317 * <p>The default offset is the scroll offset of this view.</p>
7318 *
7319 * @return the vertical offset of the scrollbar's thumb
7320 *
7321 * @see #computeVerticalScrollRange()
7322 * @see #computeVerticalScrollExtent()
7323 * @see android.widget.ScrollBarDrawable
7324 */
7325 protected int computeVerticalScrollOffset() {
7326 return mScrollY;
7327 }
7328
7329 /**
7330 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7331 * within the vertical range. This value is used to compute the length
7332 * of the thumb within the scrollbar's track.</p>
7333 *
7334 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08007335 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007336 * {@link #computeVerticalScrollOffset()}.</p>
7337 *
7338 * <p>The default extent is the drawing height of this view.</p>
7339 *
7340 * @return the vertical extent of the scrollbar's thumb
7341 *
7342 * @see #computeVerticalScrollRange()
7343 * @see #computeVerticalScrollOffset()
7344 * @see android.widget.ScrollBarDrawable
7345 */
7346 protected int computeVerticalScrollExtent() {
7347 return getHeight();
7348 }
7349
7350 /**
7351 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7352 * scrollbars are painted only if they have been awakened first.</p>
7353 *
7354 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07007355 *
7356 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007357 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08007358 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007359 // scrollbars are drawn only when the animation is running
7360 final ScrollabilityCache cache = mScrollCache;
7361 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007362
7363 int state = cache.state;
7364
7365 if (state == ScrollabilityCache.OFF) {
7366 return;
7367 }
7368
7369 boolean invalidate = false;
7370
7371 if (state == ScrollabilityCache.FADING) {
7372 // We're fading -- get our fade interpolation
7373 if (cache.interpolatorValues == null) {
7374 cache.interpolatorValues = new float[1];
7375 }
7376
7377 float[] values = cache.interpolatorValues;
7378
7379 // Stops the animation if we're done
7380 if (cache.scrollBarInterpolator.timeToValues(values) ==
7381 Interpolator.Result.FREEZE_END) {
7382 cache.state = ScrollabilityCache.OFF;
7383 } else {
7384 cache.scrollBar.setAlpha(Math.round(values[0]));
7385 }
7386
7387 // This will make the scroll bars inval themselves after
7388 // drawing. We only want this when we're fading so that
7389 // we prevent excessive redraws
7390 invalidate = true;
7391 } else {
7392 // We're just on -- but we may have been fading before so
7393 // reset alpha
7394 cache.scrollBar.setAlpha(255);
7395 }
7396
7397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007398 final int viewFlags = mViewFlags;
7399
7400 final boolean drawHorizontalScrollBar =
7401 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7402 final boolean drawVerticalScrollBar =
7403 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7404 && !isVerticalScrollBarHidden();
7405
7406 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7407 final int width = mRight - mLeft;
7408 final int height = mBottom - mTop;
7409
7410 final ScrollBarDrawable scrollBar = cache.scrollBar;
7411 int size = scrollBar.getSize(false);
7412 if (size <= 0) {
7413 size = cache.scrollBarSize;
7414 }
7415
Mike Reede8853fc2009-09-04 14:01:48 -04007416 final int scrollX = mScrollX;
7417 final int scrollY = mScrollY;
7418 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7419
Mike Cleronf116bf82009-09-27 19:14:12 -07007420 int left, top, right, bottom;
7421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007422 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007423 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04007424 computeHorizontalScrollOffset(),
7425 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04007426 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07007427 getVerticalScrollbarWidth() : 0;
7428 top = scrollY + height - size - (mUserPaddingBottom & inside);
7429 left = scrollX + (mPaddingLeft & inside);
7430 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7431 bottom = top + size;
7432 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7433 if (invalidate) {
7434 invalidate(left, top, right, bottom);
7435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007436 }
7437
7438 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04007439 scrollBar.setParameters(computeVerticalScrollRange(),
7440 computeVerticalScrollOffset(),
7441 computeVerticalScrollExtent(), true);
Adam Powell20232d02010-12-08 21:08:53 -08007442 switch (mVerticalScrollbarPosition) {
7443 default:
7444 case SCROLLBAR_POSITION_DEFAULT:
7445 case SCROLLBAR_POSITION_RIGHT:
7446 left = scrollX + width - size - (mUserPaddingRight & inside);
7447 break;
7448 case SCROLLBAR_POSITION_LEFT:
7449 left = scrollX + (mUserPaddingLeft & inside);
7450 break;
7451 }
Mike Cleronf116bf82009-09-27 19:14:12 -07007452 top = scrollY + (mPaddingTop & inside);
7453 right = left + size;
7454 bottom = scrollY + height - (mUserPaddingBottom & inside);
7455 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7456 if (invalidate) {
7457 invalidate(left, top, right, bottom);
7458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007459 }
7460 }
7461 }
7462 }
Romain Guy8506ab42009-06-11 17:35:47 -07007463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007464 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007465 * 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 -08007466 * FastScroller is visible.
7467 * @return whether to temporarily hide the vertical scrollbar
7468 * @hide
7469 */
7470 protected boolean isVerticalScrollBarHidden() {
7471 return false;
7472 }
7473
7474 /**
7475 * <p>Draw the horizontal scrollbar if
7476 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7477 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 * @param canvas the canvas on which to draw the scrollbar
7479 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 *
7481 * @see #isHorizontalScrollBarEnabled()
7482 * @see #computeHorizontalScrollRange()
7483 * @see #computeHorizontalScrollExtent()
7484 * @see #computeHorizontalScrollOffset()
7485 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007486 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007487 */
Romain Guy8fb95422010-08-17 18:38:51 -07007488 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7489 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007490 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007491 scrollBar.draw(canvas);
7492 }
Mike Reede8853fc2009-09-04 14:01:48 -04007493
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007494 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007495 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7496 * returns true.</p>
7497 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007498 * @param canvas the canvas on which to draw the scrollbar
7499 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007500 *
7501 * @see #isVerticalScrollBarEnabled()
7502 * @see #computeVerticalScrollRange()
7503 * @see #computeVerticalScrollExtent()
7504 * @see #computeVerticalScrollOffset()
7505 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007506 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507 */
Romain Guy8fb95422010-08-17 18:38:51 -07007508 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7509 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007510 scrollBar.setBounds(l, t, r, b);
7511 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007512 }
7513
7514 /**
7515 * Implement this to do your drawing.
7516 *
7517 * @param canvas the canvas on which the background will be drawn
7518 */
7519 protected void onDraw(Canvas canvas) {
7520 }
7521
7522 /*
7523 * Caller is responsible for calling requestLayout if necessary.
7524 * (This allows addViewInLayout to not request a new layout.)
7525 */
7526 void assignParent(ViewParent parent) {
7527 if (mParent == null) {
7528 mParent = parent;
7529 } else if (parent == null) {
7530 mParent = null;
7531 } else {
7532 throw new RuntimeException("view " + this + " being added, but"
7533 + " it already has a parent");
7534 }
7535 }
7536
7537 /**
7538 * This is called when the view is attached to a window. At this point it
7539 * has a Surface and will start drawing. Note that this function is
7540 * guaranteed to be called before {@link #onDraw}, however it may be called
7541 * any time before the first onDraw -- including before or after
7542 * {@link #onMeasure}.
7543 *
7544 * @see #onDetachedFromWindow()
7545 */
7546 protected void onAttachedToWindow() {
7547 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7548 mParent.requestTransparentRegion(this);
7549 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007550 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7551 initialAwakenScrollBars();
7552 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7553 }
Chet Haasea9b61ac2010-12-20 07:40:25 -08007554 jumpDrawablesToCurrentState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007555 }
7556
7557 /**
7558 * This is called when the view is detached from a window. At this point it
7559 * no longer has a surface for drawing.
7560 *
7561 * @see #onAttachedToWindow()
7562 */
7563 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007564 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guy6c319ca2011-01-11 14:29:25 -08007565
Romain Guya440b002010-02-24 15:57:54 -08007566 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007567 removeLongPressCallback();
Romain Guy6c319ca2011-01-11 14:29:25 -08007568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007569 destroyDrawingCache();
Romain Guy6c319ca2011-01-11 14:29:25 -08007570
7571 if (mHardwareLayer != null) {
7572 mHardwareLayer.destroy();
7573 mHardwareLayer = null;
7574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007575 }
7576
7577 /**
7578 * @return The number of times this view has been attached to a window
7579 */
7580 protected int getWindowAttachCount() {
7581 return mWindowAttachCount;
7582 }
7583
7584 /**
7585 * Retrieve a unique token identifying the window this view is attached to.
7586 * @return Return the window's token for use in
7587 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7588 */
7589 public IBinder getWindowToken() {
7590 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7591 }
7592
7593 /**
7594 * Retrieve a unique token identifying the top-level "real" window of
7595 * the window that this view is attached to. That is, this is like
7596 * {@link #getWindowToken}, except if the window this view in is a panel
7597 * window (attached to another containing window), then the token of
7598 * the containing window is returned instead.
7599 *
7600 * @return Returns the associated window token, either
7601 * {@link #getWindowToken()} or the containing window's token.
7602 */
7603 public IBinder getApplicationWindowToken() {
7604 AttachInfo ai = mAttachInfo;
7605 if (ai != null) {
7606 IBinder appWindowToken = ai.mPanelParentWindowToken;
7607 if (appWindowToken == null) {
7608 appWindowToken = ai.mWindowToken;
7609 }
7610 return appWindowToken;
7611 }
7612 return null;
7613 }
7614
7615 /**
7616 * Retrieve private session object this view hierarchy is using to
7617 * communicate with the window manager.
7618 * @return the session object to communicate with the window manager
7619 */
7620 /*package*/ IWindowSession getWindowSession() {
7621 return mAttachInfo != null ? mAttachInfo.mSession : null;
7622 }
7623
7624 /**
7625 * @param info the {@link android.view.View.AttachInfo} to associated with
7626 * this view
7627 */
7628 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7629 //System.out.println("Attached! " + this);
7630 mAttachInfo = info;
7631 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007632 // We will need to evaluate the drawable state at least once.
7633 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007634 if (mFloatingTreeObserver != null) {
7635 info.mTreeObserver.merge(mFloatingTreeObserver);
7636 mFloatingTreeObserver = null;
7637 }
7638 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7639 mAttachInfo.mScrollContainers.add(this);
7640 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7641 }
7642 performCollectViewAttributes(visibility);
7643 onAttachedToWindow();
7644 int vis = info.mWindowVisibility;
7645 if (vis != GONE) {
7646 onWindowVisibilityChanged(vis);
7647 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007648 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7649 // If nobody has evaluated the drawable state yet, then do it now.
7650 refreshDrawableState();
7651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 }
7653
7654 void dispatchDetachedFromWindow() {
7655 //System.out.println("Detached! " + this);
7656 AttachInfo info = mAttachInfo;
7657 if (info != null) {
7658 int vis = info.mWindowVisibility;
7659 if (vis != GONE) {
7660 onWindowVisibilityChanged(GONE);
7661 }
7662 }
7663
7664 onDetachedFromWindow();
7665 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7666 mAttachInfo.mScrollContainers.remove(this);
7667 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7668 }
7669 mAttachInfo = null;
7670 }
7671
7672 /**
7673 * Store this view hierarchy's frozen state into the given container.
7674 *
7675 * @param container The SparseArray in which to save the view's state.
7676 *
7677 * @see #restoreHierarchyState
7678 * @see #dispatchSaveInstanceState
7679 * @see #onSaveInstanceState
7680 */
7681 public void saveHierarchyState(SparseArray<Parcelable> container) {
7682 dispatchSaveInstanceState(container);
7683 }
7684
7685 /**
7686 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7687 * May be overridden to modify how freezing happens to a view's children; for example, some
7688 * views may want to not store state for their children.
7689 *
7690 * @param container The SparseArray in which to save the view's state.
7691 *
7692 * @see #dispatchRestoreInstanceState
7693 * @see #saveHierarchyState
7694 * @see #onSaveInstanceState
7695 */
7696 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7697 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7698 mPrivateFlags &= ~SAVE_STATE_CALLED;
7699 Parcelable state = onSaveInstanceState();
7700 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7701 throw new IllegalStateException(
7702 "Derived class did not call super.onSaveInstanceState()");
7703 }
7704 if (state != null) {
7705 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7706 // + ": " + state);
7707 container.put(mID, state);
7708 }
7709 }
7710 }
7711
7712 /**
7713 * Hook allowing a view to generate a representation of its internal state
7714 * that can later be used to create a new instance with that same state.
7715 * This state should only contain information that is not persistent or can
7716 * not be reconstructed later. For example, you will never store your
7717 * current position on screen because that will be computed again when a
7718 * new instance of the view is placed in its view hierarchy.
7719 * <p>
7720 * Some examples of things you may store here: the current cursor position
7721 * in a text view (but usually not the text itself since that is stored in a
7722 * content provider or other persistent storage), the currently selected
7723 * item in a list view.
7724 *
7725 * @return Returns a Parcelable object containing the view's current dynamic
7726 * state, or null if there is nothing interesting to save. The
7727 * default implementation returns null.
7728 * @see #onRestoreInstanceState
7729 * @see #saveHierarchyState
7730 * @see #dispatchSaveInstanceState
7731 * @see #setSaveEnabled(boolean)
7732 */
7733 protected Parcelable onSaveInstanceState() {
7734 mPrivateFlags |= SAVE_STATE_CALLED;
7735 return BaseSavedState.EMPTY_STATE;
7736 }
7737
7738 /**
7739 * Restore this view hierarchy's frozen state from the given container.
7740 *
7741 * @param container The SparseArray which holds previously frozen states.
7742 *
7743 * @see #saveHierarchyState
7744 * @see #dispatchRestoreInstanceState
7745 * @see #onRestoreInstanceState
7746 */
7747 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7748 dispatchRestoreInstanceState(container);
7749 }
7750
7751 /**
7752 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7753 * children. May be overridden to modify how restoreing happens to a view's children; for
7754 * example, some views may want to not store state for their children.
7755 *
7756 * @param container The SparseArray which holds previously saved state.
7757 *
7758 * @see #dispatchSaveInstanceState
7759 * @see #restoreHierarchyState
7760 * @see #onRestoreInstanceState
7761 */
7762 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7763 if (mID != NO_ID) {
7764 Parcelable state = container.get(mID);
7765 if (state != null) {
7766 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7767 // + ": " + state);
7768 mPrivateFlags &= ~SAVE_STATE_CALLED;
7769 onRestoreInstanceState(state);
7770 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7771 throw new IllegalStateException(
7772 "Derived class did not call super.onRestoreInstanceState()");
7773 }
7774 }
7775 }
7776 }
7777
7778 /**
7779 * Hook allowing a view to re-apply a representation of its internal state that had previously
7780 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7781 * null state.
7782 *
7783 * @param state The frozen state that had previously been returned by
7784 * {@link #onSaveInstanceState}.
7785 *
7786 * @see #onSaveInstanceState
7787 * @see #restoreHierarchyState
7788 * @see #dispatchRestoreInstanceState
7789 */
7790 protected void onRestoreInstanceState(Parcelable state) {
7791 mPrivateFlags |= SAVE_STATE_CALLED;
7792 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007793 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7794 + "received " + state.getClass().toString() + " instead. This usually happens "
7795 + "when two views of different type have the same id in the same hierarchy. "
7796 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7797 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007798 }
7799 }
7800
7801 /**
7802 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7803 *
7804 * @return the drawing start time in milliseconds
7805 */
7806 public long getDrawingTime() {
7807 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7808 }
7809
7810 /**
7811 * <p>Enables or disables the duplication of the parent's state into this view. When
7812 * duplication is enabled, this view gets its drawable state from its parent rather
7813 * than from its own internal properties.</p>
7814 *
7815 * <p>Note: in the current implementation, setting this property to true after the
7816 * view was added to a ViewGroup might have no effect at all. This property should
7817 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7818 *
7819 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7820 * property is enabled, an exception will be thrown.</p>
7821 *
7822 * @param enabled True to enable duplication of the parent's drawable state, false
7823 * to disable it.
7824 *
7825 * @see #getDrawableState()
7826 * @see #isDuplicateParentStateEnabled()
7827 */
7828 public void setDuplicateParentStateEnabled(boolean enabled) {
7829 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7830 }
7831
7832 /**
7833 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7834 *
7835 * @return True if this view's drawable state is duplicated from the parent,
7836 * false otherwise
7837 *
7838 * @see #getDrawableState()
7839 * @see #setDuplicateParentStateEnabled(boolean)
7840 */
7841 public boolean isDuplicateParentStateEnabled() {
7842 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7843 }
7844
7845 /**
Romain Guy171c5922011-01-06 10:04:23 -08007846 * <p>Specifies the type of layer backing this view. The layer can be
7847 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
7848 * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
7849 *
7850 * <p>A layer is associated with an optional {@link android.graphics.Paint}
7851 * instance that controls how the layer is composed on screen. The following
7852 * properties of the paint are taken into account when composing the layer:</p>
7853 * <ul>
7854 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
7855 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
7856 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
7857 * </ul>
7858 *
7859 * <p>If this view has an alpha value set to < 1.0 by calling
7860 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
7861 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
7862 * equivalent to setting a hardware layer on this view and providing a paint with
7863 * the desired alpha value.<p>
7864 *
7865 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
7866 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
7867 * for more information on when and how to use layers.</p>
7868 *
7869 * @param layerType The ype of layer to use with this view, must be one of
7870 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
7871 * {@link #LAYER_TYPE_HARDWARE}
7872 * @param paint The paint used to compose the layer. This argument is optional
7873 * and can be null. It is ignored when the layer type is
7874 * {@link #LAYER_TYPE_NONE}
7875 *
7876 * @see #getLayerType()
7877 * @see #LAYER_TYPE_NONE
7878 * @see #LAYER_TYPE_SOFTWARE
7879 * @see #LAYER_TYPE_HARDWARE
7880 * @see #setAlpha(float)
7881 *
7882 * @attr ref android.R.styleable#View_layerType
7883 */
7884 public void setLayerType(int layerType, Paint paint) {
7885 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
7886 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
7887 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
7888 }
Romain Guy6c319ca2011-01-11 14:29:25 -08007889
7890 if (layerType == mLayerType) return;
Romain Guy171c5922011-01-06 10:04:23 -08007891
7892 // Destroy any previous software drawing cache if needed
Romain Guy6c319ca2011-01-11 14:29:25 -08007893 switch (mLayerType) {
7894 case LAYER_TYPE_SOFTWARE:
7895 if (mDrawingCache != null) {
7896 mDrawingCache.recycle();
7897 mDrawingCache = null;
7898 }
7899
7900 if (mUnscaledDrawingCache != null) {
7901 mUnscaledDrawingCache.recycle();
7902 mUnscaledDrawingCache = null;
7903 }
7904 break;
7905 case LAYER_TYPE_HARDWARE:
7906 if (mHardwareLayer != null) {
7907 mHardwareLayer.destroy();
7908 mHardwareLayer = null;
7909 }
7910 break;
7911 default:
7912 break;
Romain Guy171c5922011-01-06 10:04:23 -08007913 }
7914
7915 mLayerType = layerType;
7916 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
7917
Romain Guy6c319ca2011-01-11 14:29:25 -08007918 // TODO: Make sure we invalidate the parent's display list
Romain Guy171c5922011-01-06 10:04:23 -08007919 invalidate();
7920 }
7921
7922 /**
7923 * Indicates what type of layer is currently associated with this view. By default
7924 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
7925 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
7926 * for more information on the different types of layers.
7927 *
7928 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
7929 * {@link #LAYER_TYPE_HARDWARE}
7930 *
7931 * @see #setLayerType(int, android.graphics.Paint)
7932 * @see #LAYER_TYPE_NONE
7933 * @see #LAYER_TYPE_SOFTWARE
7934 * @see #LAYER_TYPE_HARDWARE
7935 */
7936 public int getLayerType() {
7937 return mLayerType;
7938 }
Romain Guy6c319ca2011-01-11 14:29:25 -08007939
7940 /**
7941 * <p>Returns a hardware layer that can be used to draw this view again
7942 * without executing its draw method.</p>
7943 *
7944 * @return A HardwareLayer ready to render, or null if an error occurred.
7945 */
7946 HardwareLayer getHardwareLayer(Canvas currentCanvas) {
7947 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
7948 return null;
7949 }
7950
7951 final int width = mRight - mLeft;
7952 final int height = mBottom - mTop;
7953
7954 if (width == 0 || height == 0) {
7955 return null;
7956 }
7957
7958 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
7959 if (mHardwareLayer == null) {
7960 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
7961 width, height, isOpaque());
7962 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
7963 mHardwareLayer.resize(width, height);
7964 }
7965
7966 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
7967 try {
7968 canvas.setViewport(width, height);
7969 canvas.onPreDraw();
7970
7971 computeScroll();
7972 canvas.translate(-mScrollX, -mScrollY);
7973
7974 final int restoreCount = canvas.save();
7975
7976 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
7977
7978 // Fast path for layouts with no backgrounds
7979 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7980 mPrivateFlags &= ~DIRTY_MASK;
7981 dispatchDraw(canvas);
7982 } else {
7983 draw(canvas);
7984 }
7985
7986 canvas.restoreToCount(restoreCount);
7987 } finally {
7988 canvas.onPostDraw();
7989 mHardwareLayer.end(currentCanvas);
7990 }
7991 }
7992
7993 return mHardwareLayer;
7994 }
Romain Guy171c5922011-01-06 10:04:23 -08007995
7996 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
7998 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
7999 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
8000 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
8001 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
8002 * null.</p>
Romain Guy171c5922011-01-06 10:04:23 -08008003 *
8004 * <p>Enabling the drawing cache is similar to
8005 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
8006 * acceleration is turned off. When hardware acceleration is turned on enabling the
8007 * drawing cache has either no effect or the cache used at drawing time is not a bitmap.
8008 * This API can however be used to manually generate a bitmap copy of this view.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009 *
8010 * @param enabled true to enable the drawing cache, false otherwise
8011 *
8012 * @see #isDrawingCacheEnabled()
8013 * @see #getDrawingCache()
8014 * @see #buildDrawingCache()
Romain Guy171c5922011-01-06 10:04:23 -08008015 * @see #setLayerType(int, android.graphics.Paint)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008016 */
8017 public void setDrawingCacheEnabled(boolean enabled) {
8018 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
8019 }
8020
8021 /**
8022 * <p>Indicates whether the drawing cache is enabled for this view.</p>
8023 *
8024 * @return true if the drawing cache is enabled
8025 *
8026 * @see #setDrawingCacheEnabled(boolean)
8027 * @see #getDrawingCache()
8028 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07008029 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008030 public boolean isDrawingCacheEnabled() {
8031 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
8032 }
8033
8034 /**
Romain Guyb051e892010-09-28 19:09:36 -07008035 * <p>Returns a display list that can be used to draw this view again
8036 * without executing its draw method.</p>
8037 *
8038 * @return A DisplayList ready to replay, or null if caching is not enabled.
8039 */
8040 DisplayList getDisplayList() {
8041 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8042 return null;
8043 }
Romain Guyb051e892010-09-28 19:09:36 -07008044 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8045 return null;
8046 }
8047
8048 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
Chet Haase9e90a992011-01-04 16:23:21 -08008049 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
8050 mDisplayList == null || !mDisplayList.isValid())) {
Romain Guyb051e892010-09-28 19:09:36 -07008051
Chet Haase9e90a992011-01-04 16:23:21 -08008052 if (mDisplayList == null) {
8053 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
8054 }
Romain Guyb051e892010-09-28 19:09:36 -07008055
8056 final HardwareCanvas canvas = mDisplayList.start();
8057 try {
8058 int width = mRight - mLeft;
8059 int height = mBottom - mTop;
8060
8061 canvas.setViewport(width, height);
8062 canvas.onPreDraw();
8063
8064 final int restoreCount = canvas.save();
8065
Romain Guy2fe9a8f2010-10-04 20:17:01 -07008066 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07008067
8068 // Fast path for layouts with no backgrounds
8069 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8070 mPrivateFlags &= ~DIRTY_MASK;
8071 dispatchDraw(canvas);
8072 } else {
8073 draw(canvas);
8074 }
8075
8076 canvas.restoreToCount(restoreCount);
8077 } finally {
8078 canvas.onPostDraw();
8079
8080 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07008081 }
8082 }
8083
8084 return mDisplayList;
8085 }
8086
8087 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008088 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
8089 *
8090 * @return A non-scaled bitmap representing this view or null if cache is disabled.
8091 *
8092 * @see #getDrawingCache(boolean)
8093 */
8094 public Bitmap getDrawingCache() {
8095 return getDrawingCache(false);
8096 }
8097
8098 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
8100 * is null when caching is disabled. If caching is enabled and the cache is not ready,
8101 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
8102 * draw from the cache when the cache is enabled. To benefit from the cache, you must
8103 * request the drawing cache by calling this method and draw it on screen if the
8104 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008105 *
8106 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8107 * this method will create a bitmap of the same size as this view. Because this bitmap
8108 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8109 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8110 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8111 * size than the view. This implies that your application must be able to handle this
8112 * size.</p>
8113 *
8114 * @param autoScale Indicates whether the generated bitmap should be scaled based on
8115 * the current density of the screen when the application is in compatibility
8116 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008118 * @return A bitmap representing this view or null if cache is disabled.
8119 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008120 * @see #setDrawingCacheEnabled(boolean)
8121 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07008122 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008123 * @see #destroyDrawingCache()
8124 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008125 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008126 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8127 return null;
8128 }
8129 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008130 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008131 }
Romain Guy02890fd2010-08-06 17:58:44 -07008132 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 }
8134
8135 /**
8136 * <p>Frees the resources used by the drawing cache. If you call
8137 * {@link #buildDrawingCache()} manually without calling
8138 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8139 * should cleanup the cache with this method afterwards.</p>
8140 *
8141 * @see #setDrawingCacheEnabled(boolean)
8142 * @see #buildDrawingCache()
8143 * @see #getDrawingCache()
8144 */
8145 public void destroyDrawingCache() {
8146 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008147 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 mDrawingCache = null;
8149 }
Romain Guyfbd8f692009-06-26 14:51:58 -07008150 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008151 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07008152 mUnscaledDrawingCache = null;
8153 }
Romain Guyb051e892010-09-28 19:09:36 -07008154 if (mDisplayList != null) {
Chet Haase9e90a992011-01-04 16:23:21 -08008155 mDisplayList.invalidate();
Romain Guyb051e892010-09-28 19:09:36 -07008156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 }
8158
8159 /**
8160 * Setting a solid background color for the drawing cache's bitmaps will improve
8161 * perfromance and memory usage. Note, though that this should only be used if this
8162 * view will always be drawn on top of a solid color.
8163 *
8164 * @param color The background color to use for the drawing cache's bitmap
8165 *
8166 * @see #setDrawingCacheEnabled(boolean)
8167 * @see #buildDrawingCache()
8168 * @see #getDrawingCache()
8169 */
8170 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08008171 if (color != mDrawingCacheBackgroundColor) {
8172 mDrawingCacheBackgroundColor = color;
8173 mPrivateFlags &= ~DRAWING_CACHE_VALID;
8174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 }
8176
8177 /**
8178 * @see #setDrawingCacheBackgroundColor(int)
8179 *
8180 * @return The background color to used for the drawing cache's bitmap
8181 */
8182 public int getDrawingCacheBackgroundColor() {
8183 return mDrawingCacheBackgroundColor;
8184 }
8185
8186 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008187 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
8188 *
8189 * @see #buildDrawingCache(boolean)
8190 */
8191 public void buildDrawingCache() {
8192 buildDrawingCache(false);
8193 }
8194
8195 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008196 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
8197 *
8198 * <p>If you call {@link #buildDrawingCache()} manually without calling
8199 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8200 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008201 *
8202 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8203 * this method will create a bitmap of the same size as this view. Because this bitmap
8204 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8205 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8206 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8207 * size than the view. This implies that your application must be able to handle this
8208 * size.</p>
Romain Guy0d9275e2010-10-26 14:22:30 -07008209 *
8210 * <p>You should avoid calling this method when hardware acceleration is enabled. If
8211 * you do not need the drawing cache bitmap, calling this method will increase memory
8212 * usage and cause the view to be rendered in software once, thus negatively impacting
8213 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008214 *
8215 * @see #getDrawingCache()
8216 * @see #destroyDrawingCache()
8217 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008218 public void buildDrawingCache(boolean autoScale) {
8219 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07008220 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008221
8222 if (ViewDebug.TRACE_HIERARCHY) {
8223 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
8224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225
Romain Guy8506ab42009-06-11 17:35:47 -07008226 int width = mRight - mLeft;
8227 int height = mBottom - mTop;
8228
8229 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07008230 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07008231
Romain Guye1123222009-06-29 14:24:56 -07008232 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008233 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
8234 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07008235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008236
8237 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07008238 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08008239 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008240
8241 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07008242 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08008243 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008244 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
8245 destroyDrawingCache();
8246 return;
8247 }
8248
8249 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07008250 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008251
8252 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008253 Bitmap.Config quality;
8254 if (!opaque) {
8255 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
8256 case DRAWING_CACHE_QUALITY_AUTO:
8257 quality = Bitmap.Config.ARGB_8888;
8258 break;
8259 case DRAWING_CACHE_QUALITY_LOW:
8260 quality = Bitmap.Config.ARGB_4444;
8261 break;
8262 case DRAWING_CACHE_QUALITY_HIGH:
8263 quality = Bitmap.Config.ARGB_8888;
8264 break;
8265 default:
8266 quality = Bitmap.Config.ARGB_8888;
8267 break;
8268 }
8269 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07008270 // Optimization for translucent windows
8271 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08008272 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008273 }
8274
8275 // Try to cleanup memory
8276 if (bitmap != null) bitmap.recycle();
8277
8278 try {
8279 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07008280 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07008281 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07008282 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008283 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07008284 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008285 }
Adam Powell26153a32010-11-08 15:22:27 -08008286 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008287 } catch (OutOfMemoryError e) {
8288 // If there is not enough memory to create the bitmap cache, just
8289 // ignore the issue as bitmap caches are not required to draw the
8290 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07008291 if (autoScale) {
8292 mDrawingCache = null;
8293 } else {
8294 mUnscaledDrawingCache = null;
8295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 return;
8297 }
8298
8299 clear = drawingCacheBackgroundColor != 0;
8300 }
8301
8302 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008303 if (attachInfo != null) {
8304 canvas = attachInfo.mCanvas;
8305 if (canvas == null) {
8306 canvas = new Canvas();
8307 }
8308 canvas.setBitmap(bitmap);
8309 // Temporarily clobber the cached Canvas in case one of our children
8310 // is also using a drawing cache. Without this, the children would
8311 // steal the canvas by attaching their own bitmap to it and bad, bad
8312 // thing would happen (invisible views, corrupted drawings, etc.)
8313 attachInfo.mCanvas = null;
8314 } else {
8315 // This case should hopefully never or seldom happen
8316 canvas = new Canvas(bitmap);
8317 }
8318
8319 if (clear) {
8320 bitmap.eraseColor(drawingCacheBackgroundColor);
8321 }
8322
8323 computeScroll();
8324 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07008325
Romain Guye1123222009-06-29 14:24:56 -07008326 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008327 final float scale = attachInfo.mApplicationScale;
8328 canvas.scale(scale, scale);
8329 }
8330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008331 canvas.translate(-mScrollX, -mScrollY);
8332
Romain Guy5bcdff42009-05-14 21:27:18 -07008333 mPrivateFlags |= DRAWN;
Romain Guy171c5922011-01-06 10:04:23 -08008334 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
8335 mLayerType != LAYER_TYPE_NONE) {
Romain Guy0d9275e2010-10-26 14:22:30 -07008336 mPrivateFlags |= DRAWING_CACHE_VALID;
8337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338
8339 // Fast path for layouts with no backgrounds
8340 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8341 if (ViewDebug.TRACE_HIERARCHY) {
8342 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8343 }
Romain Guy5bcdff42009-05-14 21:27:18 -07008344 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008345 dispatchDraw(canvas);
8346 } else {
8347 draw(canvas);
8348 }
8349
8350 canvas.restoreToCount(restoreCount);
8351
8352 if (attachInfo != null) {
8353 // Restore the cached Canvas for our siblings
8354 attachInfo.mCanvas = canvas;
8355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008356 }
8357 }
8358
8359 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008360 * Create a snapshot of the view into a bitmap. We should probably make
8361 * some form of this public, but should think about the API.
8362 */
Romain Guy223ff5c2010-03-02 17:07:47 -08008363 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008364 int width = mRight - mLeft;
8365 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008366
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008367 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07008368 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008369 width = (int) ((width * scale) + 0.5f);
8370 height = (int) ((height * scale) + 0.5f);
8371
Romain Guy8c11e312009-09-14 15:15:30 -07008372 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008373 if (bitmap == null) {
8374 throw new OutOfMemoryError();
8375 }
8376
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008377 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8378
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008379 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008380 if (attachInfo != null) {
8381 canvas = attachInfo.mCanvas;
8382 if (canvas == null) {
8383 canvas = new Canvas();
8384 }
8385 canvas.setBitmap(bitmap);
8386 // Temporarily clobber the cached Canvas in case one of our children
8387 // is also using a drawing cache. Without this, the children would
8388 // steal the canvas by attaching their own bitmap to it and bad, bad
8389 // things would happen (invisible views, corrupted drawings, etc.)
8390 attachInfo.mCanvas = null;
8391 } else {
8392 // This case should hopefully never or seldom happen
8393 canvas = new Canvas(bitmap);
8394 }
8395
Romain Guy5bcdff42009-05-14 21:27:18 -07008396 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008397 bitmap.eraseColor(backgroundColor);
8398 }
8399
8400 computeScroll();
8401 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008402 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008403 canvas.translate(-mScrollX, -mScrollY);
8404
Romain Guy5bcdff42009-05-14 21:27:18 -07008405 // Temporarily remove the dirty mask
8406 int flags = mPrivateFlags;
8407 mPrivateFlags &= ~DIRTY_MASK;
8408
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008409 // Fast path for layouts with no backgrounds
8410 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8411 dispatchDraw(canvas);
8412 } else {
8413 draw(canvas);
8414 }
8415
Romain Guy5bcdff42009-05-14 21:27:18 -07008416 mPrivateFlags = flags;
8417
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008418 canvas.restoreToCount(restoreCount);
8419
8420 if (attachInfo != null) {
8421 // Restore the cached Canvas for our siblings
8422 attachInfo.mCanvas = canvas;
8423 }
Romain Guy8506ab42009-06-11 17:35:47 -07008424
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008425 return bitmap;
8426 }
8427
8428 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008429 * Indicates whether this View is currently in edit mode. A View is usually
8430 * in edit mode when displayed within a developer tool. For instance, if
8431 * this View is being drawn by a visual user interface builder, this method
8432 * should return true.
8433 *
8434 * Subclasses should check the return value of this method to provide
8435 * different behaviors if their normal behavior might interfere with the
8436 * host environment. For instance: the class spawns a thread in its
8437 * constructor, the drawing code relies on device-specific features, etc.
8438 *
8439 * This method is usually checked in the drawing code of custom widgets.
8440 *
8441 * @return True if this View is in edit mode, false otherwise.
8442 */
8443 public boolean isInEditMode() {
8444 return false;
8445 }
8446
8447 /**
8448 * If the View draws content inside its padding and enables fading edges,
8449 * it needs to support padding offsets. Padding offsets are added to the
8450 * fading edges to extend the length of the fade so that it covers pixels
8451 * drawn inside the padding.
8452 *
8453 * Subclasses of this class should override this method if they need
8454 * to draw content inside the padding.
8455 *
8456 * @return True if padding offset must be applied, false otherwise.
8457 *
8458 * @see #getLeftPaddingOffset()
8459 * @see #getRightPaddingOffset()
8460 * @see #getTopPaddingOffset()
8461 * @see #getBottomPaddingOffset()
8462 *
8463 * @since CURRENT
8464 */
8465 protected boolean isPaddingOffsetRequired() {
8466 return false;
8467 }
8468
8469 /**
8470 * Amount by which to extend the left fading region. Called only when
8471 * {@link #isPaddingOffsetRequired()} returns true.
8472 *
8473 * @return The left padding offset in pixels.
8474 *
8475 * @see #isPaddingOffsetRequired()
8476 *
8477 * @since CURRENT
8478 */
8479 protected int getLeftPaddingOffset() {
8480 return 0;
8481 }
8482
8483 /**
8484 * Amount by which to extend the right fading region. Called only when
8485 * {@link #isPaddingOffsetRequired()} returns true.
8486 *
8487 * @return The right padding offset in pixels.
8488 *
8489 * @see #isPaddingOffsetRequired()
8490 *
8491 * @since CURRENT
8492 */
8493 protected int getRightPaddingOffset() {
8494 return 0;
8495 }
8496
8497 /**
8498 * Amount by which to extend the top fading region. Called only when
8499 * {@link #isPaddingOffsetRequired()} returns true.
8500 *
8501 * @return The top padding offset in pixels.
8502 *
8503 * @see #isPaddingOffsetRequired()
8504 *
8505 * @since CURRENT
8506 */
8507 protected int getTopPaddingOffset() {
8508 return 0;
8509 }
8510
8511 /**
8512 * Amount by which to extend the bottom fading region. Called only when
8513 * {@link #isPaddingOffsetRequired()} returns true.
8514 *
8515 * @return The bottom padding offset in pixels.
8516 *
8517 * @see #isPaddingOffsetRequired()
8518 *
8519 * @since CURRENT
8520 */
8521 protected int getBottomPaddingOffset() {
8522 return 0;
8523 }
8524
8525 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008526 * <p>Indicates whether this view is attached to an hardware accelerated
8527 * window or not.</p>
8528 *
8529 * <p>Even if this method returns true, it does not mean that every call
8530 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8531 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8532 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8533 * window is hardware accelerated,
8534 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8535 * return false, and this method will return true.</p>
8536 *
8537 * @return True if the view is attached to a window and the window is
8538 * hardware accelerated; false in any other case.
8539 */
8540 public boolean isHardwareAccelerated() {
8541 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8542 }
8543
8544 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008545 * Manually render this view (and all of its children) to the given Canvas.
8546 * The view must have already done a full layout before this function is
Chet Haasec75ec332010-12-17 07:44:30 -08008547 * called. When implementing a view, implement {@link #onDraw} instead of
8548 * overriding this method. If you do need to override this method, call
8549 * the superclass version.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008550 *
8551 * @param canvas The Canvas to which the View is rendered.
8552 */
8553 public void draw(Canvas canvas) {
8554 if (ViewDebug.TRACE_HIERARCHY) {
8555 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8556 }
8557
Romain Guy5bcdff42009-05-14 21:27:18 -07008558 final int privateFlags = mPrivateFlags;
8559 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8560 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8561 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 /*
8564 * Draw traversal performs several drawing steps which must be executed
8565 * in the appropriate order:
8566 *
8567 * 1. Draw the background
8568 * 2. If necessary, save the canvas' layers to prepare for fading
8569 * 3. Draw view's content
8570 * 4. Draw children
8571 * 5. If necessary, draw the fading edges and restore layers
8572 * 6. Draw decorations (scrollbars for instance)
8573 */
8574
8575 // Step 1, draw the background, if needed
8576 int saveCount;
8577
Romain Guy24443ea2009-05-11 11:56:30 -07008578 if (!dirtyOpaque) {
8579 final Drawable background = mBGDrawable;
8580 if (background != null) {
8581 final int scrollX = mScrollX;
8582 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008583
Romain Guy24443ea2009-05-11 11:56:30 -07008584 if (mBackgroundSizeChanged) {
8585 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8586 mBackgroundSizeChanged = false;
8587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008588
Romain Guy24443ea2009-05-11 11:56:30 -07008589 if ((scrollX | scrollY) == 0) {
8590 background.draw(canvas);
8591 } else {
8592 canvas.translate(scrollX, scrollY);
8593 background.draw(canvas);
8594 canvas.translate(-scrollX, -scrollY);
8595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 }
8597 }
8598
8599 // skip step 2 & 5 if possible (common case)
8600 final int viewFlags = mViewFlags;
8601 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8602 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8603 if (!verticalEdges && !horizontalEdges) {
8604 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008605 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008606
8607 // Step 4, draw the children
8608 dispatchDraw(canvas);
8609
8610 // Step 6, draw decorations (scrollbars)
8611 onDrawScrollBars(canvas);
8612
8613 // we're done...
8614 return;
8615 }
8616
8617 /*
8618 * Here we do the full fledged routine...
8619 * (this is an uncommon case where speed matters less,
8620 * this is why we repeat some of the tests that have been
8621 * done above)
8622 */
8623
8624 boolean drawTop = false;
8625 boolean drawBottom = false;
8626 boolean drawLeft = false;
8627 boolean drawRight = false;
8628
8629 float topFadeStrength = 0.0f;
8630 float bottomFadeStrength = 0.0f;
8631 float leftFadeStrength = 0.0f;
8632 float rightFadeStrength = 0.0f;
8633
8634 // Step 2, save the canvas' layers
8635 int paddingLeft = mPaddingLeft;
8636 int paddingTop = mPaddingTop;
8637
8638 final boolean offsetRequired = isPaddingOffsetRequired();
8639 if (offsetRequired) {
8640 paddingLeft += getLeftPaddingOffset();
8641 paddingTop += getTopPaddingOffset();
8642 }
8643
8644 int left = mScrollX + paddingLeft;
8645 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8646 int top = mScrollY + paddingTop;
8647 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8648
8649 if (offsetRequired) {
8650 right += getRightPaddingOffset();
8651 bottom += getBottomPaddingOffset();
8652 }
8653
8654 final ScrollabilityCache scrollabilityCache = mScrollCache;
8655 int length = scrollabilityCache.fadingEdgeLength;
8656
8657 // clip the fade length if top and bottom fades overlap
8658 // overlapping fades produce odd-looking artifacts
8659 if (verticalEdges && (top + length > bottom - length)) {
8660 length = (bottom - top) / 2;
8661 }
8662
8663 // also clip horizontal fades if necessary
8664 if (horizontalEdges && (left + length > right - length)) {
8665 length = (right - left) / 2;
8666 }
8667
8668 if (verticalEdges) {
8669 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008670 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008671 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008672 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008673 }
8674
8675 if (horizontalEdges) {
8676 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008677 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008679 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 }
8681
8682 saveCount = canvas.getSaveCount();
8683
8684 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008685 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8687
8688 if (drawTop) {
8689 canvas.saveLayer(left, top, right, top + length, null, flags);
8690 }
8691
8692 if (drawBottom) {
8693 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8694 }
8695
8696 if (drawLeft) {
8697 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8698 }
8699
8700 if (drawRight) {
8701 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8702 }
8703 } else {
8704 scrollabilityCache.setFadeColor(solidColor);
8705 }
8706
8707 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008708 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709
8710 // Step 4, draw the children
8711 dispatchDraw(canvas);
8712
8713 // Step 5, draw the fade effect and restore layers
8714 final Paint p = scrollabilityCache.paint;
8715 final Matrix matrix = scrollabilityCache.matrix;
8716 final Shader fade = scrollabilityCache.shader;
8717 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8718
8719 if (drawTop) {
8720 matrix.setScale(1, fadeHeight * topFadeStrength);
8721 matrix.postTranslate(left, top);
8722 fade.setLocalMatrix(matrix);
8723 canvas.drawRect(left, top, right, top + length, p);
8724 }
8725
8726 if (drawBottom) {
8727 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8728 matrix.postRotate(180);
8729 matrix.postTranslate(left, bottom);
8730 fade.setLocalMatrix(matrix);
8731 canvas.drawRect(left, bottom - length, right, bottom, p);
8732 }
8733
8734 if (drawLeft) {
8735 matrix.setScale(1, fadeHeight * leftFadeStrength);
8736 matrix.postRotate(-90);
8737 matrix.postTranslate(left, top);
8738 fade.setLocalMatrix(matrix);
8739 canvas.drawRect(left, top, left + length, bottom, p);
8740 }
8741
8742 if (drawRight) {
8743 matrix.setScale(1, fadeHeight * rightFadeStrength);
8744 matrix.postRotate(90);
8745 matrix.postTranslate(right, top);
8746 fade.setLocalMatrix(matrix);
8747 canvas.drawRect(right - length, top, right, bottom, p);
8748 }
8749
8750 canvas.restoreToCount(saveCount);
8751
8752 // Step 6, draw decorations (scrollbars)
8753 onDrawScrollBars(canvas);
8754 }
8755
8756 /**
8757 * Override this if your view is known to always be drawn on top of a solid color background,
8758 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8759 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8760 * should be set to 0xFF.
8761 *
8762 * @see #setVerticalFadingEdgeEnabled
8763 * @see #setHorizontalFadingEdgeEnabled
8764 *
8765 * @return The known solid color background for this view, or 0 if the color may vary
8766 */
8767 public int getSolidColor() {
8768 return 0;
8769 }
8770
8771 /**
8772 * Build a human readable string representation of the specified view flags.
8773 *
8774 * @param flags the view flags to convert to a string
8775 * @return a String representing the supplied flags
8776 */
8777 private static String printFlags(int flags) {
8778 String output = "";
8779 int numFlags = 0;
8780 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8781 output += "TAKES_FOCUS";
8782 numFlags++;
8783 }
8784
8785 switch (flags & VISIBILITY_MASK) {
8786 case INVISIBLE:
8787 if (numFlags > 0) {
8788 output += " ";
8789 }
8790 output += "INVISIBLE";
8791 // USELESS HERE numFlags++;
8792 break;
8793 case GONE:
8794 if (numFlags > 0) {
8795 output += " ";
8796 }
8797 output += "GONE";
8798 // USELESS HERE numFlags++;
8799 break;
8800 default:
8801 break;
8802 }
8803 return output;
8804 }
8805
8806 /**
8807 * Build a human readable string representation of the specified private
8808 * view flags.
8809 *
8810 * @param privateFlags the private view flags to convert to a string
8811 * @return a String representing the supplied flags
8812 */
8813 private static String printPrivateFlags(int privateFlags) {
8814 String output = "";
8815 int numFlags = 0;
8816
8817 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8818 output += "WANTS_FOCUS";
8819 numFlags++;
8820 }
8821
8822 if ((privateFlags & FOCUSED) == FOCUSED) {
8823 if (numFlags > 0) {
8824 output += " ";
8825 }
8826 output += "FOCUSED";
8827 numFlags++;
8828 }
8829
8830 if ((privateFlags & SELECTED) == SELECTED) {
8831 if (numFlags > 0) {
8832 output += " ";
8833 }
8834 output += "SELECTED";
8835 numFlags++;
8836 }
8837
8838 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8839 if (numFlags > 0) {
8840 output += " ";
8841 }
8842 output += "IS_ROOT_NAMESPACE";
8843 numFlags++;
8844 }
8845
8846 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8847 if (numFlags > 0) {
8848 output += " ";
8849 }
8850 output += "HAS_BOUNDS";
8851 numFlags++;
8852 }
8853
8854 if ((privateFlags & DRAWN) == DRAWN) {
8855 if (numFlags > 0) {
8856 output += " ";
8857 }
8858 output += "DRAWN";
8859 // USELESS HERE numFlags++;
8860 }
8861 return output;
8862 }
8863
8864 /**
8865 * <p>Indicates whether or not this view's layout will be requested during
8866 * the next hierarchy layout pass.</p>
8867 *
8868 * @return true if the layout will be forced during next layout pass
8869 */
8870 public boolean isLayoutRequested() {
8871 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8872 }
8873
8874 /**
8875 * Assign a size and position to a view and all of its
8876 * descendants
8877 *
8878 * <p>This is the second phase of the layout mechanism.
8879 * (The first is measuring). In this phase, each parent calls
8880 * layout on all of its children to position them.
8881 * This is typically done using the child measurements
8882 * that were stored in the measure pass().
8883 *
8884 * Derived classes with children should override
8885 * onLayout. In that method, they should
Chet Haase21cd1382010-09-01 17:42:29 -07008886 * call layout on each of their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008887 *
8888 * @param l Left position, relative to parent
8889 * @param t Top position, relative to parent
8890 * @param r Right position, relative to parent
8891 * @param b Bottom position, relative to parent
8892 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008893 @SuppressWarnings({"unchecked"})
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008894 public final void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008895 int oldL = mLeft;
8896 int oldT = mTop;
8897 int oldB = mBottom;
8898 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008899 boolean changed = setFrame(l, t, r, b);
8900 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8901 if (ViewDebug.TRACE_HIERARCHY) {
8902 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8903 }
8904
8905 onLayout(changed, l, t, r, b);
8906 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008907
8908 if (mOnLayoutChangeListeners != null) {
8909 ArrayList<OnLayoutChangeListener> listenersCopy =
8910 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8911 int numListeners = listenersCopy.size();
8912 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07008913 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07008914 }
8915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008916 }
8917 mPrivateFlags &= ~FORCE_LAYOUT;
8918 }
8919
8920 /**
8921 * Called from layout when this view should
8922 * assign a size and position to each of its children.
8923 *
8924 * Derived classes with children should override
8925 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008926 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927 * @param changed This is a new size or position for this view
8928 * @param left Left position, relative to parent
8929 * @param top Top position, relative to parent
8930 * @param right Right position, relative to parent
8931 * @param bottom Bottom position, relative to parent
8932 */
8933 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8934 }
8935
8936 /**
8937 * Assign a size and position to this view.
8938 *
8939 * This is called from layout.
8940 *
8941 * @param left Left position, relative to parent
8942 * @param top Top position, relative to parent
8943 * @param right Right position, relative to parent
8944 * @param bottom Bottom position, relative to parent
8945 * @return true if the new size and position are different than the
8946 * previous ones
8947 * {@hide}
8948 */
8949 protected boolean setFrame(int left, int top, int right, int bottom) {
8950 boolean changed = false;
8951
8952 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008953 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008954 + right + "," + bottom + ")");
8955 }
8956
8957 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8958 changed = true;
8959
8960 // Remember our drawn bit
8961 int drawn = mPrivateFlags & DRAWN;
8962
8963 // Invalidate our old position
8964 invalidate();
8965
8966
8967 int oldWidth = mRight - mLeft;
8968 int oldHeight = mBottom - mTop;
8969
8970 mLeft = left;
8971 mTop = top;
8972 mRight = right;
8973 mBottom = bottom;
8974
8975 mPrivateFlags |= HAS_BOUNDS;
8976
8977 int newWidth = right - left;
8978 int newHeight = bottom - top;
8979
8980 if (newWidth != oldWidth || newHeight != oldHeight) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08008981 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8982 // A change in dimension means an auto-centered pivot point changes, too
8983 mMatrixDirty = true;
8984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8986 }
8987
8988 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8989 // If we are visible, force the DRAWN bit to on so that
8990 // this invalidate will go through (at least to our parent).
8991 // This is because someone may have invalidated this view
Chet Haase6c7ad5d2010-12-28 08:40:00 -08008992 // before this call to setFrame came in, thereby clearing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008993 // the DRAWN bit.
8994 mPrivateFlags |= DRAWN;
8995 invalidate();
8996 }
8997
8998 // Reset drawn bit to original value (invalidate turns it off)
8999 mPrivateFlags |= drawn;
9000
9001 mBackgroundSizeChanged = true;
9002 }
9003 return changed;
9004 }
9005
9006 /**
9007 * Finalize inflating a view from XML. This is called as the last phase
9008 * of inflation, after all child views have been added.
9009 *
9010 * <p>Even if the subclass overrides onFinishInflate, they should always be
9011 * sure to call the super method, so that we get called.
9012 */
9013 protected void onFinishInflate() {
9014 }
9015
9016 /**
9017 * Returns the resources associated with this view.
9018 *
9019 * @return Resources object.
9020 */
9021 public Resources getResources() {
9022 return mResources;
9023 }
9024
9025 /**
9026 * Invalidates the specified Drawable.
9027 *
9028 * @param drawable the drawable to invalidate
9029 */
9030 public void invalidateDrawable(Drawable drawable) {
9031 if (verifyDrawable(drawable)) {
9032 final Rect dirty = drawable.getBounds();
9033 final int scrollX = mScrollX;
9034 final int scrollY = mScrollY;
9035
9036 invalidate(dirty.left + scrollX, dirty.top + scrollY,
9037 dirty.right + scrollX, dirty.bottom + scrollY);
9038 }
9039 }
9040
9041 /**
9042 * Schedules an action on a drawable to occur at a specified time.
9043 *
9044 * @param who the recipient of the action
9045 * @param what the action to run on the drawable
9046 * @param when the time at which the action must occur. Uses the
9047 * {@link SystemClock#uptimeMillis} timebase.
9048 */
9049 public void scheduleDrawable(Drawable who, Runnable what, long when) {
9050 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9051 mAttachInfo.mHandler.postAtTime(what, who, when);
9052 }
9053 }
9054
9055 /**
9056 * Cancels a scheduled action on a drawable.
9057 *
9058 * @param who the recipient of the action
9059 * @param what the action to cancel
9060 */
9061 public void unscheduleDrawable(Drawable who, Runnable what) {
9062 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9063 mAttachInfo.mHandler.removeCallbacks(what, who);
9064 }
9065 }
9066
9067 /**
9068 * Unschedule any events associated with the given Drawable. This can be
9069 * used when selecting a new Drawable into a view, so that the previous
9070 * one is completely unscheduled.
9071 *
9072 * @param who The Drawable to unschedule.
9073 *
9074 * @see #drawableStateChanged
9075 */
9076 public void unscheduleDrawable(Drawable who) {
9077 if (mAttachInfo != null) {
9078 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
9079 }
9080 }
9081
9082 /**
9083 * If your view subclass is displaying its own Drawable objects, it should
9084 * override this function and return true for any Drawable it is
9085 * displaying. This allows animations for those drawables to be
9086 * scheduled.
9087 *
9088 * <p>Be sure to call through to the super class when overriding this
9089 * function.
9090 *
9091 * @param who The Drawable to verify. Return true if it is one you are
9092 * displaying, else return the result of calling through to the
9093 * super class.
9094 *
9095 * @return boolean If true than the Drawable is being displayed in the
9096 * view; else false and it is not allowed to animate.
9097 *
9098 * @see #unscheduleDrawable
9099 * @see #drawableStateChanged
9100 */
9101 protected boolean verifyDrawable(Drawable who) {
9102 return who == mBGDrawable;
9103 }
9104
9105 /**
9106 * This function is called whenever the state of the view changes in such
9107 * a way that it impacts the state of drawables being shown.
9108 *
9109 * <p>Be sure to call through to the superclass when overriding this
9110 * function.
9111 *
9112 * @see Drawable#setState
9113 */
9114 protected void drawableStateChanged() {
9115 Drawable d = mBGDrawable;
9116 if (d != null && d.isStateful()) {
9117 d.setState(getDrawableState());
9118 }
9119 }
9120
9121 /**
9122 * Call this to force a view to update its drawable state. This will cause
9123 * drawableStateChanged to be called on this view. Views that are interested
9124 * in the new state should call getDrawableState.
9125 *
9126 * @see #drawableStateChanged
9127 * @see #getDrawableState
9128 */
9129 public void refreshDrawableState() {
9130 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9131 drawableStateChanged();
9132
9133 ViewParent parent = mParent;
9134 if (parent != null) {
9135 parent.childDrawableStateChanged(this);
9136 }
9137 }
9138
9139 /**
9140 * Return an array of resource IDs of the drawable states representing the
9141 * current state of the view.
9142 *
9143 * @return The current drawable state
9144 *
9145 * @see Drawable#setState
9146 * @see #drawableStateChanged
9147 * @see #onCreateDrawableState
9148 */
9149 public final int[] getDrawableState() {
9150 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
9151 return mDrawableState;
9152 } else {
9153 mDrawableState = onCreateDrawableState(0);
9154 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
9155 return mDrawableState;
9156 }
9157 }
9158
9159 /**
9160 * Generate the new {@link android.graphics.drawable.Drawable} state for
9161 * this view. This is called by the view
9162 * system when the cached Drawable state is determined to be invalid. To
9163 * retrieve the current state, you should use {@link #getDrawableState}.
9164 *
9165 * @param extraSpace if non-zero, this is the number of extra entries you
9166 * would like in the returned array in which you can place your own
9167 * states.
9168 *
9169 * @return Returns an array holding the current {@link Drawable} state of
9170 * the view.
9171 *
9172 * @see #mergeDrawableStates
9173 */
9174 protected int[] onCreateDrawableState(int extraSpace) {
9175 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
9176 mParent instanceof View) {
9177 return ((View) mParent).onCreateDrawableState(extraSpace);
9178 }
9179
9180 int[] drawableState;
9181
9182 int privateFlags = mPrivateFlags;
9183
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009184 int viewStateIndex = 0;
9185 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
9186 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
9187 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07009188 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009189 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
9190 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08009191 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
9192 // This is set if HW acceleration is requested, even if the current
9193 // process doesn't allow it. This is just to allow app preview
9194 // windows to better match their app.
9195 viewStateIndex |= VIEW_STATE_ACCELERATED;
9196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009197
9198 drawableState = VIEW_STATE_SETS[viewStateIndex];
9199
9200 //noinspection ConstantIfStatement
9201 if (false) {
9202 Log.i("View", "drawableStateIndex=" + viewStateIndex);
9203 Log.i("View", toString()
9204 + " pressed=" + ((privateFlags & PRESSED) != 0)
9205 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
9206 + " fo=" + hasFocus()
9207 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009208 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009209 + ": " + Arrays.toString(drawableState));
9210 }
9211
9212 if (extraSpace == 0) {
9213 return drawableState;
9214 }
9215
9216 final int[] fullState;
9217 if (drawableState != null) {
9218 fullState = new int[drawableState.length + extraSpace];
9219 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
9220 } else {
9221 fullState = new int[extraSpace];
9222 }
9223
9224 return fullState;
9225 }
9226
9227 /**
9228 * Merge your own state values in <var>additionalState</var> into the base
9229 * state values <var>baseState</var> that were returned by
9230 * {@link #onCreateDrawableState}.
9231 *
9232 * @param baseState The base state values returned by
9233 * {@link #onCreateDrawableState}, which will be modified to also hold your
9234 * own additional state values.
9235 *
9236 * @param additionalState The additional state values you would like
9237 * added to <var>baseState</var>; this array is not modified.
9238 *
9239 * @return As a convenience, the <var>baseState</var> array you originally
9240 * passed into the function is returned.
9241 *
9242 * @see #onCreateDrawableState
9243 */
9244 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
9245 final int N = baseState.length;
9246 int i = N - 1;
9247 while (i >= 0 && baseState[i] == 0) {
9248 i--;
9249 }
9250 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
9251 return baseState;
9252 }
9253
9254 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07009255 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
9256 * on all Drawable objects associated with this view.
9257 */
9258 public void jumpDrawablesToCurrentState() {
9259 if (mBGDrawable != null) {
9260 mBGDrawable.jumpToCurrentState();
9261 }
9262 }
9263
9264 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009265 * Sets the background color for this view.
9266 * @param color the color of the background
9267 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009268 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009269 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07009270 if (mBGDrawable instanceof ColorDrawable) {
9271 ((ColorDrawable) mBGDrawable).setColor(color);
9272 } else {
9273 setBackgroundDrawable(new ColorDrawable(color));
9274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009275 }
9276
9277 /**
9278 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07009279 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009280 * @param resid The identifier of the resource.
9281 * @attr ref android.R.styleable#View_background
9282 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009283 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009284 public void setBackgroundResource(int resid) {
9285 if (resid != 0 && resid == mBackgroundResource) {
9286 return;
9287 }
9288
9289 Drawable d= null;
9290 if (resid != 0) {
9291 d = mResources.getDrawable(resid);
9292 }
9293 setBackgroundDrawable(d);
9294
9295 mBackgroundResource = resid;
9296 }
9297
9298 /**
9299 * Set the background to a given Drawable, or remove the background. If the
9300 * background has padding, this View's padding is set to the background's
9301 * padding. However, when a background is removed, this View's padding isn't
9302 * touched. If setting the padding is desired, please use
9303 * {@link #setPadding(int, int, int, int)}.
9304 *
9305 * @param d The Drawable to use as the background, or null to remove the
9306 * background
9307 */
9308 public void setBackgroundDrawable(Drawable d) {
9309 boolean requestLayout = false;
9310
9311 mBackgroundResource = 0;
9312
9313 /*
9314 * Regardless of whether we're setting a new background or not, we want
9315 * to clear the previous drawable.
9316 */
9317 if (mBGDrawable != null) {
9318 mBGDrawable.setCallback(null);
9319 unscheduleDrawable(mBGDrawable);
9320 }
9321
9322 if (d != null) {
9323 Rect padding = sThreadLocal.get();
9324 if (padding == null) {
9325 padding = new Rect();
9326 sThreadLocal.set(padding);
9327 }
9328 if (d.getPadding(padding)) {
9329 setPadding(padding.left, padding.top, padding.right, padding.bottom);
9330 }
9331
9332 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
9333 // if it has a different minimum size, we should layout again
9334 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9335 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9336 requestLayout = true;
9337 }
9338
9339 d.setCallback(this);
9340 if (d.isStateful()) {
9341 d.setState(getDrawableState());
9342 }
9343 d.setVisible(getVisibility() == VISIBLE, false);
9344 mBGDrawable = d;
9345
9346 if ((mPrivateFlags & SKIP_DRAW) != 0) {
9347 mPrivateFlags &= ~SKIP_DRAW;
9348 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9349 requestLayout = true;
9350 }
9351 } else {
9352 /* Remove the background */
9353 mBGDrawable = null;
9354
9355 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9356 /*
9357 * This view ONLY drew the background before and we're removing
9358 * the background, so now it won't draw anything
9359 * (hence we SKIP_DRAW)
9360 */
9361 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9362 mPrivateFlags |= SKIP_DRAW;
9363 }
9364
9365 /*
9366 * When the background is set, we try to apply its padding to this
9367 * View. When the background is removed, we don't touch this View's
9368 * padding. This is noted in the Javadocs. Hence, we don't need to
9369 * requestLayout(), the invalidate() below is sufficient.
9370 */
9371
9372 // The old background's minimum size could have affected this
9373 // View's layout, so let's requestLayout
9374 requestLayout = true;
9375 }
9376
Romain Guy8f1344f52009-05-15 16:03:59 -07009377 computeOpaqueFlags();
9378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009379 if (requestLayout) {
9380 requestLayout();
9381 }
9382
9383 mBackgroundSizeChanged = true;
9384 invalidate();
9385 }
9386
9387 /**
9388 * Gets the background drawable
9389 * @return The drawable used as the background for this view, if any.
9390 */
9391 public Drawable getBackground() {
9392 return mBGDrawable;
9393 }
9394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009395 /**
9396 * Sets the padding. The view may add on the space required to display
9397 * the scrollbars, depending on the style and visibility of the scrollbars.
9398 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9399 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9400 * from the values set in this call.
9401 *
9402 * @attr ref android.R.styleable#View_padding
9403 * @attr ref android.R.styleable#View_paddingBottom
9404 * @attr ref android.R.styleable#View_paddingLeft
9405 * @attr ref android.R.styleable#View_paddingRight
9406 * @attr ref android.R.styleable#View_paddingTop
9407 * @param left the left padding in pixels
9408 * @param top the top padding in pixels
9409 * @param right the right padding in pixels
9410 * @param bottom the bottom padding in pixels
9411 */
9412 public void setPadding(int left, int top, int right, int bottom) {
9413 boolean changed = false;
9414
Adam Powell20232d02010-12-08 21:08:53 -08009415 mUserPaddingLeft = left;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009416 mUserPaddingRight = right;
9417 mUserPaddingBottom = bottom;
9418
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009419 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07009420
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009421 // Common case is there are no scroll bars.
9422 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009423 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
Adam Powell20232d02010-12-08 21:08:53 -08009424 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9425 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009426 ? 0 : getVerticalScrollbarWidth();
Adam Powell20232d02010-12-08 21:08:53 -08009427 switch (mVerticalScrollbarPosition) {
9428 case SCROLLBAR_POSITION_DEFAULT:
9429 case SCROLLBAR_POSITION_RIGHT:
9430 right += offset;
9431 break;
9432 case SCROLLBAR_POSITION_LEFT:
9433 left += offset;
9434 break;
9435 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009436 }
Adam Powell20232d02010-12-08 21:08:53 -08009437 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009438 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9439 ? 0 : getHorizontalScrollbarHeight();
9440 }
9441 }
Romain Guy8506ab42009-06-11 17:35:47 -07009442
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009443 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009444 changed = true;
9445 mPaddingLeft = left;
9446 }
9447 if (mPaddingTop != top) {
9448 changed = true;
9449 mPaddingTop = top;
9450 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009451 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009452 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009453 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009454 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009455 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009456 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009457 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009458 }
9459
9460 if (changed) {
9461 requestLayout();
9462 }
9463 }
9464
9465 /**
9466 * Returns the top padding of this view.
9467 *
9468 * @return the top padding in pixels
9469 */
9470 public int getPaddingTop() {
9471 return mPaddingTop;
9472 }
9473
9474 /**
9475 * Returns the bottom padding of this view. If there are inset and enabled
9476 * scrollbars, this value may include the space required to display the
9477 * scrollbars as well.
9478 *
9479 * @return the bottom padding in pixels
9480 */
9481 public int getPaddingBottom() {
9482 return mPaddingBottom;
9483 }
9484
9485 /**
9486 * Returns the left padding of this view. If there are inset and enabled
9487 * scrollbars, this value may include the space required to display the
9488 * scrollbars as well.
9489 *
9490 * @return the left padding in pixels
9491 */
9492 public int getPaddingLeft() {
9493 return mPaddingLeft;
9494 }
9495
9496 /**
9497 * Returns the right padding of this view. If there are inset and enabled
9498 * scrollbars, this value may include the space required to display the
9499 * scrollbars as well.
9500 *
9501 * @return the right padding in pixels
9502 */
9503 public int getPaddingRight() {
9504 return mPaddingRight;
9505 }
9506
9507 /**
9508 * Changes the selection state of this view. A view can be selected or not.
9509 * Note that selection is not the same as focus. Views are typically
9510 * selected in the context of an AdapterView like ListView or GridView;
9511 * the selected view is the view that is highlighted.
9512 *
9513 * @param selected true if the view must be selected, false otherwise
9514 */
9515 public void setSelected(boolean selected) {
9516 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9517 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009518 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009519 invalidate();
9520 refreshDrawableState();
9521 dispatchSetSelected(selected);
9522 }
9523 }
9524
9525 /**
9526 * Dispatch setSelected to all of this View's children.
9527 *
9528 * @see #setSelected(boolean)
9529 *
9530 * @param selected The new selected state
9531 */
9532 protected void dispatchSetSelected(boolean selected) {
9533 }
9534
9535 /**
9536 * Indicates the selection state of this view.
9537 *
9538 * @return true if the view is selected, false otherwise
9539 */
9540 @ViewDebug.ExportedProperty
9541 public boolean isSelected() {
9542 return (mPrivateFlags & SELECTED) != 0;
9543 }
9544
9545 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009546 * Changes the activated state of this view. A view can be activated or not.
9547 * Note that activation is not the same as selection. Selection is
9548 * a transient property, representing the view (hierarchy) the user is
9549 * currently interacting with. Activation is a longer-term state that the
9550 * user can move views in and out of. For example, in a list view with
9551 * single or multiple selection enabled, the views in the current selection
9552 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9553 * here.) The activated state is propagated down to children of the view it
9554 * is set on.
9555 *
9556 * @param activated true if the view must be activated, false otherwise
9557 */
9558 public void setActivated(boolean activated) {
9559 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9560 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
9561 invalidate();
9562 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009563 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009564 }
9565 }
9566
9567 /**
9568 * Dispatch setActivated to all of this View's children.
9569 *
9570 * @see #setActivated(boolean)
9571 *
9572 * @param activated The new activated state
9573 */
9574 protected void dispatchSetActivated(boolean activated) {
9575 }
9576
9577 /**
9578 * Indicates the activation state of this view.
9579 *
9580 * @return true if the view is activated, false otherwise
9581 */
9582 @ViewDebug.ExportedProperty
9583 public boolean isActivated() {
9584 return (mPrivateFlags & ACTIVATED) != 0;
9585 }
9586
9587 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009588 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9589 * observer can be used to get notifications when global events, like
9590 * layout, happen.
9591 *
9592 * The returned ViewTreeObserver observer is not guaranteed to remain
9593 * valid for the lifetime of this View. If the caller of this method keeps
9594 * a long-lived reference to ViewTreeObserver, it should always check for
9595 * the return value of {@link ViewTreeObserver#isAlive()}.
9596 *
9597 * @return The ViewTreeObserver for this view's hierarchy.
9598 */
9599 public ViewTreeObserver getViewTreeObserver() {
9600 if (mAttachInfo != null) {
9601 return mAttachInfo.mTreeObserver;
9602 }
9603 if (mFloatingTreeObserver == null) {
9604 mFloatingTreeObserver = new ViewTreeObserver();
9605 }
9606 return mFloatingTreeObserver;
9607 }
9608
9609 /**
9610 * <p>Finds the topmost view in the current view hierarchy.</p>
9611 *
9612 * @return the topmost view containing this view
9613 */
9614 public View getRootView() {
9615 if (mAttachInfo != null) {
9616 final View v = mAttachInfo.mRootView;
9617 if (v != null) {
9618 return v;
9619 }
9620 }
Romain Guy8506ab42009-06-11 17:35:47 -07009621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009622 View parent = this;
9623
9624 while (parent.mParent != null && parent.mParent instanceof View) {
9625 parent = (View) parent.mParent;
9626 }
9627
9628 return parent;
9629 }
9630
9631 /**
9632 * <p>Computes the coordinates of this view on the screen. The argument
9633 * must be an array of two integers. After the method returns, the array
9634 * contains the x and y location in that order.</p>
9635 *
9636 * @param location an array of two integers in which to hold the coordinates
9637 */
9638 public void getLocationOnScreen(int[] location) {
9639 getLocationInWindow(location);
9640
9641 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009642 if (info != null) {
9643 location[0] += info.mWindowLeft;
9644 location[1] += info.mWindowTop;
9645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009646 }
9647
9648 /**
9649 * <p>Computes the coordinates of this view in its window. The argument
9650 * must be an array of two integers. After the method returns, the array
9651 * contains the x and y location in that order.</p>
9652 *
9653 * @param location an array of two integers in which to hold the coordinates
9654 */
9655 public void getLocationInWindow(int[] location) {
9656 if (location == null || location.length < 2) {
9657 throw new IllegalArgumentException("location must be an array of "
9658 + "two integers");
9659 }
9660
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009661 location[0] = mLeft + (int) (mTranslationX + 0.5f);
9662 location[1] = mTop + (int) (mTranslationY + 0.5f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009663
9664 ViewParent viewParent = mParent;
9665 while (viewParent instanceof View) {
9666 final View view = (View)viewParent;
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009667 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
9668 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009669 viewParent = view.mParent;
9670 }
Romain Guy8506ab42009-06-11 17:35:47 -07009671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009672 if (viewParent instanceof ViewRoot) {
9673 // *cough*
9674 final ViewRoot vr = (ViewRoot)viewParent;
9675 location[1] -= vr.mCurScrollY;
9676 }
9677 }
9678
9679 /**
9680 * {@hide}
9681 * @param id the id of the view to be found
9682 * @return the view of the specified id, null if cannot be found
9683 */
9684 protected View findViewTraversal(int id) {
9685 if (id == mID) {
9686 return this;
9687 }
9688 return null;
9689 }
9690
9691 /**
9692 * {@hide}
9693 * @param tag the tag of the view to be found
9694 * @return the view of specified tag, null if cannot be found
9695 */
9696 protected View findViewWithTagTraversal(Object tag) {
9697 if (tag != null && tag.equals(mTag)) {
9698 return this;
9699 }
9700 return null;
9701 }
9702
9703 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009704 * {@hide}
9705 * @param predicate The predicate to evaluate.
9706 * @return The first view that matches the predicate or null.
9707 */
9708 protected View findViewByPredicateTraversal(Predicate<View> predicate) {
9709 if (predicate.apply(this)) {
9710 return this;
9711 }
9712 return null;
9713 }
9714
9715 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009716 * Look for a child view with the given id. If this view has the given
9717 * id, return this view.
9718 *
9719 * @param id The id to search for.
9720 * @return The view that has the given id in the hierarchy or null
9721 */
9722 public final View findViewById(int id) {
9723 if (id < 0) {
9724 return null;
9725 }
9726 return findViewTraversal(id);
9727 }
9728
9729 /**
9730 * Look for a child view with the given tag. If this view has the given
9731 * tag, return this view.
9732 *
9733 * @param tag The tag to search for, using "tag.equals(getTag())".
9734 * @return The View that has the given tag in the hierarchy or null
9735 */
9736 public final View findViewWithTag(Object tag) {
9737 if (tag == null) {
9738 return null;
9739 }
9740 return findViewWithTagTraversal(tag);
9741 }
9742
9743 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009744 * {@hide}
9745 * Look for a child view that matches the specified predicate.
9746 * If this view matches the predicate, return this view.
9747 *
9748 * @param predicate The predicate to evaluate.
9749 * @return The first view that matches the predicate or null.
9750 */
9751 public final View findViewByPredicate(Predicate<View> predicate) {
9752 return findViewByPredicateTraversal(predicate);
9753 }
9754
9755 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009756 * Sets the identifier for this view. The identifier does not have to be
9757 * unique in this view's hierarchy. The identifier should be a positive
9758 * number.
9759 *
9760 * @see #NO_ID
9761 * @see #getId
9762 * @see #findViewById
9763 *
9764 * @param id a number used to identify the view
9765 *
9766 * @attr ref android.R.styleable#View_id
9767 */
9768 public void setId(int id) {
9769 mID = id;
9770 }
9771
9772 /**
9773 * {@hide}
9774 *
9775 * @param isRoot true if the view belongs to the root namespace, false
9776 * otherwise
9777 */
9778 public void setIsRootNamespace(boolean isRoot) {
9779 if (isRoot) {
9780 mPrivateFlags |= IS_ROOT_NAMESPACE;
9781 } else {
9782 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9783 }
9784 }
9785
9786 /**
9787 * {@hide}
9788 *
9789 * @return true if the view belongs to the root namespace, false otherwise
9790 */
9791 public boolean isRootNamespace() {
9792 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9793 }
9794
9795 /**
9796 * Returns this view's identifier.
9797 *
9798 * @return a positive integer used to identify the view or {@link #NO_ID}
9799 * if the view has no ID
9800 *
9801 * @see #setId
9802 * @see #findViewById
9803 * @attr ref android.R.styleable#View_id
9804 */
9805 @ViewDebug.CapturedViewProperty
9806 public int getId() {
9807 return mID;
9808 }
9809
9810 /**
9811 * Returns this view's tag.
9812 *
9813 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07009814 *
9815 * @see #setTag(Object)
9816 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009817 */
9818 @ViewDebug.ExportedProperty
9819 public Object getTag() {
9820 return mTag;
9821 }
9822
9823 /**
9824 * Sets the tag associated with this view. A tag can be used to mark
9825 * a view in its hierarchy and does not have to be unique within the
9826 * hierarchy. Tags can also be used to store data within a view without
9827 * resorting to another data structure.
9828 *
9829 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07009830 *
9831 * @see #getTag()
9832 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009833 */
9834 public void setTag(final Object tag) {
9835 mTag = tag;
9836 }
9837
9838 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009839 * Returns the tag associated with this view and the specified key.
9840 *
9841 * @param key The key identifying the tag
9842 *
9843 * @return the Object stored in this view as a tag
9844 *
9845 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009846 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009847 */
9848 public Object getTag(int key) {
9849 SparseArray<Object> tags = null;
9850 synchronized (sTagsLock) {
9851 if (sTags != null) {
9852 tags = sTags.get(this);
9853 }
9854 }
9855
9856 if (tags != null) return tags.get(key);
9857 return null;
9858 }
9859
9860 /**
9861 * Sets a tag associated with this view and a key. A tag can be used
9862 * to mark a view in its hierarchy and does not have to be unique within
9863 * the hierarchy. Tags can also be used to store data within a view
9864 * without resorting to another data structure.
9865 *
9866 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009867 * application to ensure it is unique (see the <a
9868 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9869 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009870 * the Android framework or not associated with any package will cause
9871 * an {@link IllegalArgumentException} to be thrown.
9872 *
9873 * @param key The key identifying the tag
9874 * @param tag An Object to tag the view with
9875 *
9876 * @throws IllegalArgumentException If they specified key is not valid
9877 *
9878 * @see #setTag(Object)
9879 * @see #getTag(int)
9880 */
9881 public void setTag(int key, final Object tag) {
9882 // If the package id is 0x00 or 0x01, it's either an undefined package
9883 // or a framework id
9884 if ((key >>> 24) < 2) {
9885 throw new IllegalArgumentException("The key must be an application-specific "
9886 + "resource id.");
9887 }
9888
9889 setTagInternal(this, key, tag);
9890 }
9891
9892 /**
9893 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9894 * framework id.
9895 *
9896 * @hide
9897 */
9898 public void setTagInternal(int key, Object tag) {
9899 if ((key >>> 24) != 0x1) {
9900 throw new IllegalArgumentException("The key must be a framework-specific "
9901 + "resource id.");
9902 }
9903
Romain Guy8506ab42009-06-11 17:35:47 -07009904 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009905 }
9906
9907 private static void setTagInternal(View view, int key, Object tag) {
9908 SparseArray<Object> tags = null;
9909 synchronized (sTagsLock) {
9910 if (sTags == null) {
9911 sTags = new WeakHashMap<View, SparseArray<Object>>();
9912 } else {
9913 tags = sTags.get(view);
9914 }
9915 }
9916
9917 if (tags == null) {
9918 tags = new SparseArray<Object>(2);
9919 synchronized (sTagsLock) {
9920 sTags.put(view, tags);
9921 }
9922 }
9923
9924 tags.put(key, tag);
9925 }
9926
9927 /**
Romain Guy13922e02009-05-12 17:56:14 -07009928 * @param consistency The type of consistency. See ViewDebug for more information.
9929 *
9930 * @hide
9931 */
9932 protected boolean dispatchConsistencyCheck(int consistency) {
9933 return onConsistencyCheck(consistency);
9934 }
9935
9936 /**
9937 * Method that subclasses should implement to check their consistency. The type of
9938 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009939 *
Romain Guy13922e02009-05-12 17:56:14 -07009940 * @param consistency The type of consistency. See ViewDebug for more information.
9941 *
9942 * @throws IllegalStateException if the view is in an inconsistent state.
9943 *
9944 * @hide
9945 */
9946 protected boolean onConsistencyCheck(int consistency) {
9947 boolean result = true;
9948
9949 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9950 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9951
9952 if (checkLayout) {
9953 if (getParent() == null) {
9954 result = false;
9955 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9956 "View " + this + " does not have a parent.");
9957 }
9958
9959 if (mAttachInfo == null) {
9960 result = false;
9961 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9962 "View " + this + " is not attached to a window.");
9963 }
9964 }
9965
9966 if (checkDrawing) {
9967 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9968 // from their draw() method
9969
9970 if ((mPrivateFlags & DRAWN) != DRAWN &&
9971 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9972 result = false;
9973 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9974 "View " + this + " was invalidated but its drawing cache is valid.");
9975 }
9976 }
9977
9978 return result;
9979 }
9980
9981 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009982 * Prints information about this view in the log output, with the tag
9983 * {@link #VIEW_LOG_TAG}.
9984 *
9985 * @hide
9986 */
9987 public void debug() {
9988 debug(0);
9989 }
9990
9991 /**
9992 * Prints information about this view in the log output, with the tag
9993 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
9994 * indentation defined by the <code>depth</code>.
9995 *
9996 * @param depth the indentation level
9997 *
9998 * @hide
9999 */
10000 protected void debug(int depth) {
10001 String output = debugIndent(depth - 1);
10002
10003 output += "+ " + this;
10004 int id = getId();
10005 if (id != -1) {
10006 output += " (id=" + id + ")";
10007 }
10008 Object tag = getTag();
10009 if (tag != null) {
10010 output += " (tag=" + tag + ")";
10011 }
10012 Log.d(VIEW_LOG_TAG, output);
10013
10014 if ((mPrivateFlags & FOCUSED) != 0) {
10015 output = debugIndent(depth) + " FOCUSED";
10016 Log.d(VIEW_LOG_TAG, output);
10017 }
10018
10019 output = debugIndent(depth);
10020 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
10021 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
10022 + "} ";
10023 Log.d(VIEW_LOG_TAG, output);
10024
10025 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
10026 || mPaddingBottom != 0) {
10027 output = debugIndent(depth);
10028 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
10029 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
10030 Log.d(VIEW_LOG_TAG, output);
10031 }
10032
10033 output = debugIndent(depth);
10034 output += "mMeasureWidth=" + mMeasuredWidth +
10035 " mMeasureHeight=" + mMeasuredHeight;
10036 Log.d(VIEW_LOG_TAG, output);
10037
10038 output = debugIndent(depth);
10039 if (mLayoutParams == null) {
10040 output += "BAD! no layout params";
10041 } else {
10042 output = mLayoutParams.debug(output);
10043 }
10044 Log.d(VIEW_LOG_TAG, output);
10045
10046 output = debugIndent(depth);
10047 output += "flags={";
10048 output += View.printFlags(mViewFlags);
10049 output += "}";
10050 Log.d(VIEW_LOG_TAG, output);
10051
10052 output = debugIndent(depth);
10053 output += "privateFlags={";
10054 output += View.printPrivateFlags(mPrivateFlags);
10055 output += "}";
10056 Log.d(VIEW_LOG_TAG, output);
10057 }
10058
10059 /**
10060 * Creates an string of whitespaces used for indentation.
10061 *
10062 * @param depth the indentation level
10063 * @return a String containing (depth * 2 + 3) * 2 white spaces
10064 *
10065 * @hide
10066 */
10067 protected static String debugIndent(int depth) {
10068 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
10069 for (int i = 0; i < (depth * 2) + 3; i++) {
10070 spaces.append(' ').append(' ');
10071 }
10072 return spaces.toString();
10073 }
10074
10075 /**
10076 * <p>Return the offset of the widget's text baseline from the widget's top
10077 * boundary. If this widget does not support baseline alignment, this
10078 * method returns -1. </p>
10079 *
10080 * @return the offset of the baseline within the widget's bounds or -1
10081 * if baseline alignment is not supported
10082 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -070010083 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010084 public int getBaseline() {
10085 return -1;
10086 }
10087
10088 /**
10089 * Call this when something has changed which has invalidated the
10090 * layout of this view. This will schedule a layout pass of the view
10091 * tree.
10092 */
10093 public void requestLayout() {
10094 if (ViewDebug.TRACE_HIERARCHY) {
10095 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
10096 }
10097
10098 mPrivateFlags |= FORCE_LAYOUT;
10099
10100 if (mParent != null && !mParent.isLayoutRequested()) {
10101 mParent.requestLayout();
10102 }
10103 }
10104
10105 /**
10106 * Forces this view to be laid out during the next layout pass.
10107 * This method does not call requestLayout() or forceLayout()
10108 * on the parent.
10109 */
10110 public void forceLayout() {
10111 mPrivateFlags |= FORCE_LAYOUT;
10112 }
10113
10114 /**
10115 * <p>
10116 * This is called to find out how big a view should be. The parent
10117 * supplies constraint information in the width and height parameters.
10118 * </p>
10119 *
10120 * <p>
10121 * The actual mesurement work of a view is performed in
10122 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
10123 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
10124 * </p>
10125 *
10126 *
10127 * @param widthMeasureSpec Horizontal space requirements as imposed by the
10128 * parent
10129 * @param heightMeasureSpec Vertical space requirements as imposed by the
10130 * parent
10131 *
10132 * @see #onMeasure(int, int)
10133 */
10134 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
10135 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
10136 widthMeasureSpec != mOldWidthMeasureSpec ||
10137 heightMeasureSpec != mOldHeightMeasureSpec) {
10138
10139 // first clears the measured dimension flag
10140 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
10141
10142 if (ViewDebug.TRACE_HIERARCHY) {
10143 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
10144 }
10145
10146 // measure ourselves, this should set the measured dimension flag back
10147 onMeasure(widthMeasureSpec, heightMeasureSpec);
10148
10149 // flag not set, setMeasuredDimension() was not invoked, we raise
10150 // an exception to warn the developer
10151 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
10152 throw new IllegalStateException("onMeasure() did not set the"
10153 + " measured dimension by calling"
10154 + " setMeasuredDimension()");
10155 }
10156
10157 mPrivateFlags |= LAYOUT_REQUIRED;
10158 }
10159
10160 mOldWidthMeasureSpec = widthMeasureSpec;
10161 mOldHeightMeasureSpec = heightMeasureSpec;
10162 }
10163
10164 /**
10165 * <p>
10166 * Measure the view and its content to determine the measured width and the
10167 * measured height. This method is invoked by {@link #measure(int, int)} and
10168 * should be overriden by subclasses to provide accurate and efficient
10169 * measurement of their contents.
10170 * </p>
10171 *
10172 * <p>
10173 * <strong>CONTRACT:</strong> When overriding this method, you
10174 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
10175 * measured width and height of this view. Failure to do so will trigger an
10176 * <code>IllegalStateException</code>, thrown by
10177 * {@link #measure(int, int)}. Calling the superclass'
10178 * {@link #onMeasure(int, int)} is a valid use.
10179 * </p>
10180 *
10181 * <p>
10182 * The base class implementation of measure defaults to the background size,
10183 * unless a larger size is allowed by the MeasureSpec. Subclasses should
10184 * override {@link #onMeasure(int, int)} to provide better measurements of
10185 * their content.
10186 * </p>
10187 *
10188 * <p>
10189 * If this method is overridden, it is the subclass's responsibility to make
10190 * sure the measured height and width are at least the view's minimum height
10191 * and width ({@link #getSuggestedMinimumHeight()} and
10192 * {@link #getSuggestedMinimumWidth()}).
10193 * </p>
10194 *
10195 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
10196 * The requirements are encoded with
10197 * {@link android.view.View.MeasureSpec}.
10198 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
10199 * The requirements are encoded with
10200 * {@link android.view.View.MeasureSpec}.
10201 *
10202 * @see #getMeasuredWidth()
10203 * @see #getMeasuredHeight()
10204 * @see #setMeasuredDimension(int, int)
10205 * @see #getSuggestedMinimumHeight()
10206 * @see #getSuggestedMinimumWidth()
10207 * @see android.view.View.MeasureSpec#getMode(int)
10208 * @see android.view.View.MeasureSpec#getSize(int)
10209 */
10210 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10211 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
10212 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
10213 }
10214
10215 /**
10216 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
10217 * measured width and measured height. Failing to do so will trigger an
10218 * exception at measurement time.</p>
10219 *
Dianne Hackborn189ee182010-12-02 21:48:53 -080010220 * @param measuredWidth The measured width of this view. May be a complex
10221 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10222 * {@link #MEASURED_STATE_TOO_SMALL}.
10223 * @param measuredHeight The measured height of this view. May be a complex
10224 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10225 * {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010226 */
10227 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
10228 mMeasuredWidth = measuredWidth;
10229 mMeasuredHeight = measuredHeight;
10230
10231 mPrivateFlags |= MEASURED_DIMENSION_SET;
10232 }
10233
10234 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -080010235 * Merge two states as returned by {@link #getMeasuredState()}.
10236 * @param curState The current state as returned from a view or the result
10237 * of combining multiple views.
10238 * @param newState The new view state to combine.
10239 * @return Returns a new integer reflecting the combination of the two
10240 * states.
10241 */
10242 public static int combineMeasuredStates(int curState, int newState) {
10243 return curState | newState;
10244 }
10245
10246 /**
10247 * Version of {@link #resolveSizeAndState(int, int, int)}
10248 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
10249 */
10250 public static int resolveSize(int size, int measureSpec) {
10251 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
10252 }
10253
10254 /**
10255 * Utility to reconcile a desired size and state, with constraints imposed
10256 * by a MeasureSpec. Will take the desired size, unless a different size
10257 * is imposed by the constraints. The returned value is a compound integer,
10258 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
10259 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
10260 * size is smaller than the size the view wants to be.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010261 *
10262 * @param size How big the view wants to be
10263 * @param measureSpec Constraints imposed by the parent
Dianne Hackborn189ee182010-12-02 21:48:53 -080010264 * @return Size information bit mask as defined by
10265 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010266 */
Dianne Hackborn189ee182010-12-02 21:48:53 -080010267 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010268 int result = size;
10269 int specMode = MeasureSpec.getMode(measureSpec);
10270 int specSize = MeasureSpec.getSize(measureSpec);
10271 switch (specMode) {
10272 case MeasureSpec.UNSPECIFIED:
10273 result = size;
10274 break;
10275 case MeasureSpec.AT_MOST:
Dianne Hackborn189ee182010-12-02 21:48:53 -080010276 if (specSize < size) {
10277 result = specSize | MEASURED_STATE_TOO_SMALL;
10278 } else {
10279 result = size;
10280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010281 break;
10282 case MeasureSpec.EXACTLY:
10283 result = specSize;
10284 break;
10285 }
Dianne Hackborn189ee182010-12-02 21:48:53 -080010286 return result | (childMeasuredState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010287 }
10288
10289 /**
10290 * Utility to return a default size. Uses the supplied size if the
10291 * MeasureSpec imposed no contraints. Will get larger if allowed
10292 * by the MeasureSpec.
10293 *
10294 * @param size Default size for this view
10295 * @param measureSpec Constraints imposed by the parent
10296 * @return The size this view should be.
10297 */
10298 public static int getDefaultSize(int size, int measureSpec) {
10299 int result = size;
10300 int specMode = MeasureSpec.getMode(measureSpec);
10301 int specSize = MeasureSpec.getSize(measureSpec);
10302
10303 switch (specMode) {
10304 case MeasureSpec.UNSPECIFIED:
10305 result = size;
10306 break;
10307 case MeasureSpec.AT_MOST:
10308 case MeasureSpec.EXACTLY:
10309 result = specSize;
10310 break;
10311 }
10312 return result;
10313 }
10314
10315 /**
10316 * Returns the suggested minimum height that the view should use. This
10317 * returns the maximum of the view's minimum height
10318 * and the background's minimum height
10319 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10320 * <p>
10321 * When being used in {@link #onMeasure(int, int)}, the caller should still
10322 * ensure the returned height is within the requirements of the parent.
10323 *
10324 * @return The suggested minimum height of the view.
10325 */
10326 protected int getSuggestedMinimumHeight() {
10327 int suggestedMinHeight = mMinHeight;
10328
10329 if (mBGDrawable != null) {
10330 final int bgMinHeight = mBGDrawable.getMinimumHeight();
10331 if (suggestedMinHeight < bgMinHeight) {
10332 suggestedMinHeight = bgMinHeight;
10333 }
10334 }
10335
10336 return suggestedMinHeight;
10337 }
10338
10339 /**
10340 * Returns the suggested minimum width that the view should use. This
10341 * returns the maximum of the view's minimum width)
10342 * and the background's minimum width
10343 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10344 * <p>
10345 * When being used in {@link #onMeasure(int, int)}, the caller should still
10346 * ensure the returned width is within the requirements of the parent.
10347 *
10348 * @return The suggested minimum width of the view.
10349 */
10350 protected int getSuggestedMinimumWidth() {
10351 int suggestedMinWidth = mMinWidth;
10352
10353 if (mBGDrawable != null) {
10354 final int bgMinWidth = mBGDrawable.getMinimumWidth();
10355 if (suggestedMinWidth < bgMinWidth) {
10356 suggestedMinWidth = bgMinWidth;
10357 }
10358 }
10359
10360 return suggestedMinWidth;
10361 }
10362
10363 /**
10364 * Sets the minimum height of the view. It is not guaranteed the view will
10365 * be able to achieve this minimum height (for example, if its parent layout
10366 * constrains it with less available height).
10367 *
10368 * @param minHeight The minimum height the view will try to be.
10369 */
10370 public void setMinimumHeight(int minHeight) {
10371 mMinHeight = minHeight;
10372 }
10373
10374 /**
10375 * Sets the minimum width of the view. It is not guaranteed the view will
10376 * be able to achieve this minimum width (for example, if its parent layout
10377 * constrains it with less available width).
10378 *
10379 * @param minWidth The minimum width the view will try to be.
10380 */
10381 public void setMinimumWidth(int minWidth) {
10382 mMinWidth = minWidth;
10383 }
10384
10385 /**
10386 * Get the animation currently associated with this view.
10387 *
10388 * @return The animation that is currently playing or
10389 * scheduled to play for this view.
10390 */
10391 public Animation getAnimation() {
10392 return mCurrentAnimation;
10393 }
10394
10395 /**
10396 * Start the specified animation now.
10397 *
10398 * @param animation the animation to start now
10399 */
10400 public void startAnimation(Animation animation) {
10401 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10402 setAnimation(animation);
10403 invalidate();
10404 }
10405
10406 /**
10407 * Cancels any animations for this view.
10408 */
10409 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -080010410 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -080010411 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -080010412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010413 mCurrentAnimation = null;
10414 }
10415
10416 /**
10417 * Sets the next animation to play for this view.
10418 * If you want the animation to play immediately, use
10419 * startAnimation. This method provides allows fine-grained
10420 * control over the start time and invalidation, but you
10421 * must make sure that 1) the animation has a start time set, and
10422 * 2) the view will be invalidated when the animation is supposed to
10423 * start.
10424 *
10425 * @param animation The next animation, or null.
10426 */
10427 public void setAnimation(Animation animation) {
10428 mCurrentAnimation = animation;
10429 if (animation != null) {
10430 animation.reset();
10431 }
10432 }
10433
10434 /**
10435 * Invoked by a parent ViewGroup to notify the start of the animation
10436 * currently associated with this view. If you override this method,
10437 * always call super.onAnimationStart();
10438 *
10439 * @see #setAnimation(android.view.animation.Animation)
10440 * @see #getAnimation()
10441 */
10442 protected void onAnimationStart() {
10443 mPrivateFlags |= ANIMATION_STARTED;
10444 }
10445
10446 /**
10447 * Invoked by a parent ViewGroup to notify the end of the animation
10448 * currently associated with this view. If you override this method,
10449 * always call super.onAnimationEnd();
10450 *
10451 * @see #setAnimation(android.view.animation.Animation)
10452 * @see #getAnimation()
10453 */
10454 protected void onAnimationEnd() {
10455 mPrivateFlags &= ~ANIMATION_STARTED;
10456 }
10457
10458 /**
10459 * Invoked if there is a Transform that involves alpha. Subclass that can
10460 * draw themselves with the specified alpha should return true, and then
10461 * respect that alpha when their onDraw() is called. If this returns false
10462 * then the view may be redirected to draw into an offscreen buffer to
10463 * fulfill the request, which will look fine, but may be slower than if the
10464 * subclass handles it internally. The default implementation returns false.
10465 *
10466 * @param alpha The alpha (0..255) to apply to the view's drawing
10467 * @return true if the view can draw with the specified alpha.
10468 */
10469 protected boolean onSetAlpha(int alpha) {
10470 return false;
10471 }
10472
10473 /**
10474 * This is used by the RootView to perform an optimization when
10475 * the view hierarchy contains one or several SurfaceView.
10476 * SurfaceView is always considered transparent, but its children are not,
10477 * therefore all View objects remove themselves from the global transparent
10478 * region (passed as a parameter to this function).
10479 *
10480 * @param region The transparent region for this ViewRoot (window).
10481 *
10482 * @return Returns true if the effective visibility of the view at this
10483 * point is opaque, regardless of the transparent region; returns false
10484 * if it is possible for underlying windows to be seen behind the view.
10485 *
10486 * {@hide}
10487 */
10488 public boolean gatherTransparentRegion(Region region) {
10489 final AttachInfo attachInfo = mAttachInfo;
10490 if (region != null && attachInfo != null) {
10491 final int pflags = mPrivateFlags;
10492 if ((pflags & SKIP_DRAW) == 0) {
10493 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10494 // remove it from the transparent region.
10495 final int[] location = attachInfo.mTransparentLocation;
10496 getLocationInWindow(location);
10497 region.op(location[0], location[1], location[0] + mRight - mLeft,
10498 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10499 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10500 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10501 // exists, so we remove the background drawable's non-transparent
10502 // parts from this transparent region.
10503 applyDrawableToTransparentRegion(mBGDrawable, region);
10504 }
10505 }
10506 return true;
10507 }
10508
10509 /**
10510 * Play a sound effect for this view.
10511 *
10512 * <p>The framework will play sound effects for some built in actions, such as
10513 * clicking, but you may wish to play these effects in your widget,
10514 * for instance, for internal navigation.
10515 *
10516 * <p>The sound effect will only be played if sound effects are enabled by the user, and
10517 * {@link #isSoundEffectsEnabled()} is true.
10518 *
10519 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10520 */
10521 public void playSoundEffect(int soundConstant) {
10522 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10523 return;
10524 }
10525 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10526 }
10527
10528 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010529 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010530 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010531 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010532 *
10533 * <p>The framework will provide haptic feedback for some built in actions,
10534 * such as long presses, but you may wish to provide feedback for your
10535 * own widget.
10536 *
10537 * <p>The feedback will only be performed if
10538 * {@link #isHapticFeedbackEnabled()} is true.
10539 *
10540 * @param feedbackConstant One of the constants defined in
10541 * {@link HapticFeedbackConstants}
10542 */
10543 public boolean performHapticFeedback(int feedbackConstant) {
10544 return performHapticFeedback(feedbackConstant, 0);
10545 }
10546
10547 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010548 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010549 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010550 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010551 *
10552 * @param feedbackConstant One of the constants defined in
10553 * {@link HapticFeedbackConstants}
10554 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10555 */
10556 public boolean performHapticFeedback(int feedbackConstant, int flags) {
10557 if (mAttachInfo == null) {
10558 return false;
10559 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010560 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010561 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010562 && !isHapticFeedbackEnabled()) {
10563 return false;
10564 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010565 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10566 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010567 }
10568
10569 /**
Christopher Tate2c095f32010-10-04 14:13:40 -070010570 * !!! TODO: real docs
10571 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010572 * The base class implementation makes the shadow the same size and appearance
Christopher Tate2c095f32010-10-04 14:13:40 -070010573 * as the view itself, and positions it with its center at the touch point.
10574 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010575 public static class DragShadowBuilder {
Christopher Tatea0374192010-10-05 13:06:41 -070010576 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010577
10578 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010579 * Construct a shadow builder object for use with the given view.
Christopher Tate2c095f32010-10-04 14:13:40 -070010580 * @param view
10581 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010582 public DragShadowBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010583 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010584 }
10585
Chris Tate6b391282010-10-14 15:48:59 -070010586 final public View getView() {
10587 return mView.get();
10588 }
10589
Christopher Tate2c095f32010-10-04 14:13:40 -070010590 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010591 * Provide the draggable-shadow metrics for the operation: the dimensions of
10592 * the shadow image itself, and the point within that shadow that should
Christopher Tate2c095f32010-10-04 14:13:40 -070010593 * be centered under the touch location while dragging.
10594 * <p>
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010595 * The default implementation sets the dimensions of the shadow to be the
10596 * same as the dimensions of the View itself and centers the shadow under
Christopher Tate2c095f32010-10-04 14:13:40 -070010597 * the touch point.
10598 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010599 * @param shadowSize The application should set the {@code x} member of this
10600 * parameter to the desired shadow width, and the {@code y} member to
Christopher Tate2c095f32010-10-04 14:13:40 -070010601 * the desired height.
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010602 * @param shadowTouchPoint The application should set this point to be the
10603 * location within the shadow that should track directly underneath
Christopher Tate2c095f32010-10-04 14:13:40 -070010604 * the touch point on the screen during a drag.
10605 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010606 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070010607 final View view = mView.get();
10608 if (view != null) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010609 shadowSize.set(view.getWidth(), view.getHeight());
10610 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
Christopher Tatea0374192010-10-05 13:06:41 -070010611 } else {
10612 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10613 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010614 }
10615
10616 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010617 * Draw the shadow image for the upcoming drag. The shadow canvas was
10618 * created with the dimensions supplied by the
10619 * {@link #onProvideShadowMetrics(Point, Point)} callback.
Christopher Tate2c095f32010-10-04 14:13:40 -070010620 *
10621 * @param canvas
10622 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010623 public void onDrawShadow(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070010624 final View view = mView.get();
10625 if (view != null) {
10626 view.draw(canvas);
10627 } else {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010628 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
Christopher Tatea0374192010-10-05 13:06:41 -070010629 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010630 }
10631 }
10632
10633 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010634 * Drag and drop. App calls startDrag(), then callbacks to the shadow builder's
10635 * {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} and
10636 * {@link DragShadowBuilder#onDrawShadow(Canvas)} methods happen, then the drag
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010637 * operation is handed over to the OS.
Christopher Tatea53146c2010-09-07 11:57:52 -070010638 * !!! TODO: real docs
Christopher Tate407b4e92010-11-30 17:14:08 -080010639 *
10640 * @param data !!! TODO
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010641 * @param shadowBuilder !!! TODO
Christopher Tate407b4e92010-11-30 17:14:08 -080010642 * @param myLocalState An arbitrary object that will be passed as part of every DragEvent
10643 * delivered to the calling application during the course of the current drag operation.
10644 * This object is private to the application that called startDrag(), and is not
10645 * visible to other applications. It provides a lightweight way for the application to
10646 * propagate information from the initiator to the recipient of a drag within its own
10647 * application; for example, to help disambiguate between 'copy' and 'move' semantics.
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010648 * @param flags Flags affecting the drag operation. At present no flags are defined;
10649 * pass 0 for this parameter.
Christopher Tate407b4e92010-11-30 17:14:08 -080010650 * @return {@code true} if the drag operation was initiated successfully; {@code false} if
10651 * an error prevented the drag from taking place.
Christopher Tatea53146c2010-09-07 11:57:52 -070010652 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010653 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010654 Object myLocalState, int flags) {
Christopher Tate2c095f32010-10-04 14:13:40 -070010655 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010656 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
Christopher Tatea53146c2010-09-07 11:57:52 -070010657 }
10658 boolean okay = false;
10659
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010660 Point shadowSize = new Point();
10661 Point shadowTouchPoint = new Point();
10662 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
Christopher Tate2c095f32010-10-04 14:13:40 -070010663
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010664 if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
10665 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
10666 throw new IllegalStateException("Drag shadow dimensions must not be negative");
Christopher Tate2c095f32010-10-04 14:13:40 -070010667 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010668
Chris Tatea32dcf72010-10-14 12:13:50 -070010669 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010670 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
10671 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
Chris Tatea32dcf72010-10-14 12:13:50 -070010672 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010673 Surface surface = new Surface();
10674 try {
10675 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010676 flags, shadowSize.x, shadowSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070010677 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070010678 + " surface=" + surface);
10679 if (token != null) {
10680 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070010681 try {
Chris Tate6b391282010-10-14 15:48:59 -070010682 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010683 shadowBuilder.onDrawShadow(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070010684 } finally {
10685 surface.unlockCanvasAndPost(canvas);
10686 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010687
Christopher Tate407b4e92010-11-30 17:14:08 -080010688 final ViewRoot root = getViewRoot();
10689
10690 // Cache the local state object for delivery with DragEvents
10691 root.setLocalDragState(myLocalState);
10692
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010693 // repurpose 'shadowSize' for the last touch point
10694 root.getLastTouchPoint(shadowSize);
Christopher Tate2c095f32010-10-04 14:13:40 -070010695
Christopher Tatea53146c2010-09-07 11:57:52 -070010696 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010697 shadowSize.x, shadowSize.y,
10698 shadowTouchPoint.x, shadowTouchPoint.y, data);
Christopher Tate2c095f32010-10-04 14:13:40 -070010699 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070010700 }
10701 } catch (Exception e) {
10702 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
10703 surface.destroy();
10704 }
10705
10706 return okay;
10707 }
10708
Christopher Tatea53146c2010-09-07 11:57:52 -070010709 /**
10710 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
10711 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
10712 *
10713 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
10714 * being dragged. onDragEvent() should return 'true' if the view can handle
10715 * a drop of that content. A view that returns 'false' here will receive no
10716 * further calls to onDragEvent() about the drag/drop operation.
10717 *
10718 * For DRAG_ENTERED, event.getClipDescription() describes the content being
10719 * dragged. This will be the same content description passed in the
10720 * DRAG_STARTED_EVENT invocation.
10721 *
10722 * For DRAG_EXITED, event.getClipDescription() describes the content being
10723 * dragged. This will be the same content description passed in the
10724 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
10725 * drag-acceptance visual state.
10726 *
10727 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10728 * coordinates of the current drag point. The view must return 'true' if it
10729 * can accept a drop of the current drag content, false otherwise.
10730 *
10731 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10732 * within the view; also, event.getClipData() returns the full data payload
10733 * being dropped. The view should return 'true' if it consumed the dropped
10734 * content, 'false' if it did not.
10735 *
10736 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
10737 * to its normal visual state.
10738 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010739 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070010740 return false;
10741 }
10742
10743 /**
10744 * Views typically don't need to override dispatchDragEvent(); it just calls
Chris Tate32affef2010-10-18 15:29:21 -070010745 * onDragEvent(event) and passes the result up appropriately.
Christopher Tatea53146c2010-09-07 11:57:52 -070010746 */
10747 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070010748 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10749 && mOnDragListener.onDrag(this, event)) {
10750 return true;
10751 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010752 return onDragEvent(event);
10753 }
10754
10755 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070010756 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
10757 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070010758 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070010759 */
10760 public void onCloseSystemDialogs(String reason) {
10761 }
10762
10763 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010764 * Given a Drawable whose bounds have been set to draw into this view,
10765 * update a Region being computed for {@link #gatherTransparentRegion} so
10766 * that any non-transparent parts of the Drawable are removed from the
10767 * given transparent region.
10768 *
10769 * @param dr The Drawable whose transparency is to be applied to the region.
10770 * @param region A Region holding the current transparency information,
10771 * where any parts of the region that are set are considered to be
10772 * transparent. On return, this region will be modified to have the
10773 * transparency information reduced by the corresponding parts of the
10774 * Drawable that are not transparent.
10775 * {@hide}
10776 */
10777 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
10778 if (DBG) {
10779 Log.i("View", "Getting transparent region for: " + this);
10780 }
10781 final Region r = dr.getTransparentRegion();
10782 final Rect db = dr.getBounds();
10783 final AttachInfo attachInfo = mAttachInfo;
10784 if (r != null && attachInfo != null) {
10785 final int w = getRight()-getLeft();
10786 final int h = getBottom()-getTop();
10787 if (db.left > 0) {
10788 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
10789 r.op(0, 0, db.left, h, Region.Op.UNION);
10790 }
10791 if (db.right < w) {
10792 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
10793 r.op(db.right, 0, w, h, Region.Op.UNION);
10794 }
10795 if (db.top > 0) {
10796 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
10797 r.op(0, 0, w, db.top, Region.Op.UNION);
10798 }
10799 if (db.bottom < h) {
10800 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
10801 r.op(0, db.bottom, w, h, Region.Op.UNION);
10802 }
10803 final int[] location = attachInfo.mTransparentLocation;
10804 getLocationInWindow(location);
10805 r.translate(location[0], location[1]);
10806 region.op(r, Region.Op.INTERSECT);
10807 } else {
10808 region.op(db, Region.Op.DIFFERENCE);
10809 }
10810 }
10811
Adam Powelle14579b2009-12-16 18:39:52 -080010812 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010813 mHasPerformedLongPress = false;
10814
10815 if (mPendingCheckForLongPress == null) {
10816 mPendingCheckForLongPress = new CheckForLongPress();
10817 }
10818 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080010819 postDelayed(mPendingCheckForLongPress,
10820 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010821 }
10822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010823 /**
10824 * Inflate a view from an XML resource. This convenience method wraps the {@link
10825 * LayoutInflater} class, which provides a full range of options for view inflation.
10826 *
10827 * @param context The Context object for your activity or application.
10828 * @param resource The resource ID to inflate
10829 * @param root A view group that will be the parent. Used to properly inflate the
10830 * layout_* parameters.
10831 * @see LayoutInflater
10832 */
10833 public static View inflate(Context context, int resource, ViewGroup root) {
10834 LayoutInflater factory = LayoutInflater.from(context);
10835 return factory.inflate(resource, root);
10836 }
Romain Guy33e72ae2010-07-17 12:40:29 -070010837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010838 /**
Adam Powell637d3372010-08-25 14:37:03 -070010839 * Scroll the view with standard behavior for scrolling beyond the normal
10840 * content boundaries. Views that call this method should override
10841 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
10842 * results of an over-scroll operation.
10843 *
10844 * Views can use this method to handle any touch or fling-based scrolling.
10845 *
10846 * @param deltaX Change in X in pixels
10847 * @param deltaY Change in Y in pixels
10848 * @param scrollX Current X scroll value in pixels before applying deltaX
10849 * @param scrollY Current Y scroll value in pixels before applying deltaY
10850 * @param scrollRangeX Maximum content scroll range along the X axis
10851 * @param scrollRangeY Maximum content scroll range along the Y axis
10852 * @param maxOverScrollX Number of pixels to overscroll by in either direction
10853 * along the X axis.
10854 * @param maxOverScrollY Number of pixels to overscroll by in either direction
10855 * along the Y axis.
10856 * @param isTouchEvent true if this scroll operation is the result of a touch event.
10857 * @return true if scrolling was clamped to an over-scroll boundary along either
10858 * axis, false otherwise.
10859 */
10860 protected boolean overScrollBy(int deltaX, int deltaY,
10861 int scrollX, int scrollY,
10862 int scrollRangeX, int scrollRangeY,
10863 int maxOverScrollX, int maxOverScrollY,
10864 boolean isTouchEvent) {
10865 final int overScrollMode = mOverScrollMode;
10866 final boolean canScrollHorizontal =
10867 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
10868 final boolean canScrollVertical =
10869 computeVerticalScrollRange() > computeVerticalScrollExtent();
10870 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
10871 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
10872 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
10873 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
10874
10875 int newScrollX = scrollX + deltaX;
10876 if (!overScrollHorizontal) {
10877 maxOverScrollX = 0;
10878 }
10879
10880 int newScrollY = scrollY + deltaY;
10881 if (!overScrollVertical) {
10882 maxOverScrollY = 0;
10883 }
10884
10885 // Clamp values if at the limits and record
10886 final int left = -maxOverScrollX;
10887 final int right = maxOverScrollX + scrollRangeX;
10888 final int top = -maxOverScrollY;
10889 final int bottom = maxOverScrollY + scrollRangeY;
10890
10891 boolean clampedX = false;
10892 if (newScrollX > right) {
10893 newScrollX = right;
10894 clampedX = true;
10895 } else if (newScrollX < left) {
10896 newScrollX = left;
10897 clampedX = true;
10898 }
10899
10900 boolean clampedY = false;
10901 if (newScrollY > bottom) {
10902 newScrollY = bottom;
10903 clampedY = true;
10904 } else if (newScrollY < top) {
10905 newScrollY = top;
10906 clampedY = true;
10907 }
10908
10909 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
10910
10911 return clampedX || clampedY;
10912 }
10913
10914 /**
10915 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
10916 * respond to the results of an over-scroll operation.
10917 *
10918 * @param scrollX New X scroll value in pixels
10919 * @param scrollY New Y scroll value in pixels
10920 * @param clampedX True if scrollX was clamped to an over-scroll boundary
10921 * @param clampedY True if scrollY was clamped to an over-scroll boundary
10922 */
10923 protected void onOverScrolled(int scrollX, int scrollY,
10924 boolean clampedX, boolean clampedY) {
10925 // Intentionally empty.
10926 }
10927
10928 /**
10929 * Returns the over-scroll mode for this view. The result will be
10930 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10931 * (allow over-scrolling only if the view content is larger than the container),
10932 * or {@link #OVER_SCROLL_NEVER}.
10933 *
10934 * @return This view's over-scroll mode.
10935 */
10936 public int getOverScrollMode() {
10937 return mOverScrollMode;
10938 }
10939
10940 /**
10941 * Set the over-scroll mode for this view. Valid over-scroll modes are
10942 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10943 * (allow over-scrolling only if the view content is larger than the container),
10944 * or {@link #OVER_SCROLL_NEVER}.
10945 *
10946 * Setting the over-scroll mode of a view will have an effect only if the
10947 * view is capable of scrolling.
10948 *
10949 * @param overScrollMode The new over-scroll mode for this view.
10950 */
10951 public void setOverScrollMode(int overScrollMode) {
10952 if (overScrollMode != OVER_SCROLL_ALWAYS &&
10953 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
10954 overScrollMode != OVER_SCROLL_NEVER) {
10955 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
10956 }
10957 mOverScrollMode = overScrollMode;
10958 }
10959
10960 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010961 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
10962 * Each MeasureSpec represents a requirement for either the width or the height.
10963 * A MeasureSpec is comprised of a size and a mode. There are three possible
10964 * modes:
10965 * <dl>
10966 * <dt>UNSPECIFIED</dt>
10967 * <dd>
10968 * The parent has not imposed any constraint on the child. It can be whatever size
10969 * it wants.
10970 * </dd>
10971 *
10972 * <dt>EXACTLY</dt>
10973 * <dd>
10974 * The parent has determined an exact size for the child. The child is going to be
10975 * given those bounds regardless of how big it wants to be.
10976 * </dd>
10977 *
10978 * <dt>AT_MOST</dt>
10979 * <dd>
10980 * The child can be as large as it wants up to the specified size.
10981 * </dd>
10982 * </dl>
10983 *
10984 * MeasureSpecs are implemented as ints to reduce object allocation. This class
10985 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
10986 */
10987 public static class MeasureSpec {
10988 private static final int MODE_SHIFT = 30;
10989 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
10990
10991 /**
10992 * Measure specification mode: The parent has not imposed any constraint
10993 * on the child. It can be whatever size it wants.
10994 */
10995 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
10996
10997 /**
10998 * Measure specification mode: The parent has determined an exact size
10999 * for the child. The child is going to be given those bounds regardless
11000 * of how big it wants to be.
11001 */
11002 public static final int EXACTLY = 1 << MODE_SHIFT;
11003
11004 /**
11005 * Measure specification mode: The child can be as large as it wants up
11006 * to the specified size.
11007 */
11008 public static final int AT_MOST = 2 << MODE_SHIFT;
11009
11010 /**
11011 * Creates a measure specification based on the supplied size and mode.
11012 *
11013 * The mode must always be one of the following:
11014 * <ul>
11015 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
11016 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
11017 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
11018 * </ul>
11019 *
11020 * @param size the size of the measure specification
11021 * @param mode the mode of the measure specification
11022 * @return the measure specification based on size and mode
11023 */
11024 public static int makeMeasureSpec(int size, int mode) {
11025 return size + mode;
11026 }
11027
11028 /**
11029 * Extracts the mode from the supplied measure specification.
11030 *
11031 * @param measureSpec the measure specification to extract the mode from
11032 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
11033 * {@link android.view.View.MeasureSpec#AT_MOST} or
11034 * {@link android.view.View.MeasureSpec#EXACTLY}
11035 */
11036 public static int getMode(int measureSpec) {
11037 return (measureSpec & MODE_MASK);
11038 }
11039
11040 /**
11041 * Extracts the size from the supplied measure specification.
11042 *
11043 * @param measureSpec the measure specification to extract the size from
11044 * @return the size in pixels defined in the supplied measure specification
11045 */
11046 public static int getSize(int measureSpec) {
11047 return (measureSpec & ~MODE_MASK);
11048 }
11049
11050 /**
11051 * Returns a String representation of the specified measure
11052 * specification.
11053 *
11054 * @param measureSpec the measure specification to convert to a String
11055 * @return a String with the following format: "MeasureSpec: MODE SIZE"
11056 */
11057 public static String toString(int measureSpec) {
11058 int mode = getMode(measureSpec);
11059 int size = getSize(measureSpec);
11060
11061 StringBuilder sb = new StringBuilder("MeasureSpec: ");
11062
11063 if (mode == UNSPECIFIED)
11064 sb.append("UNSPECIFIED ");
11065 else if (mode == EXACTLY)
11066 sb.append("EXACTLY ");
11067 else if (mode == AT_MOST)
11068 sb.append("AT_MOST ");
11069 else
11070 sb.append(mode).append(" ");
11071
11072 sb.append(size);
11073 return sb.toString();
11074 }
11075 }
11076
11077 class CheckForLongPress implements Runnable {
11078
11079 private int mOriginalWindowAttachCount;
11080
11081 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011082 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011083 && mOriginalWindowAttachCount == mWindowAttachCount) {
11084 if (performLongClick()) {
11085 mHasPerformedLongPress = true;
11086 }
11087 }
11088 }
11089
11090 public void rememberWindowAttachCount() {
11091 mOriginalWindowAttachCount = mWindowAttachCount;
11092 }
11093 }
Adam Powelle14579b2009-12-16 18:39:52 -080011094
11095 private final class CheckForTap implements Runnable {
11096 public void run() {
11097 mPrivateFlags &= ~PREPRESSED;
11098 mPrivateFlags |= PRESSED;
11099 refreshDrawableState();
11100 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
11101 postCheckForLongClick(ViewConfiguration.getTapTimeout());
11102 }
11103 }
11104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011105
Adam Powella35d7682010-03-12 14:48:13 -080011106 private final class PerformClick implements Runnable {
11107 public void run() {
11108 performClick();
11109 }
11110 }
11111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011112 /**
11113 * Interface definition for a callback to be invoked when a key event is
11114 * dispatched to this view. The callback will be invoked before the key
11115 * event is given to the view.
11116 */
11117 public interface OnKeyListener {
11118 /**
11119 * Called when a key is dispatched to a view. This allows listeners to
11120 * get a chance to respond before the target view.
11121 *
11122 * @param v The view the key has been dispatched to.
11123 * @param keyCode The code for the physical key that was pressed
11124 * @param event The KeyEvent object containing full information about
11125 * the event.
11126 * @return True if the listener has consumed the event, false otherwise.
11127 */
11128 boolean onKey(View v, int keyCode, KeyEvent event);
11129 }
11130
11131 /**
11132 * Interface definition for a callback to be invoked when a touch event is
11133 * dispatched to this view. The callback will be invoked before the touch
11134 * event is given to the view.
11135 */
11136 public interface OnTouchListener {
11137 /**
11138 * Called when a touch event is dispatched to a view. This allows listeners to
11139 * get a chance to respond before the target view.
11140 *
11141 * @param v The view the touch event has been dispatched to.
11142 * @param event The MotionEvent object containing full information about
11143 * the event.
11144 * @return True if the listener has consumed the event, false otherwise.
11145 */
11146 boolean onTouch(View v, MotionEvent event);
11147 }
11148
11149 /**
11150 * Interface definition for a callback to be invoked when a view has been clicked and held.
11151 */
11152 public interface OnLongClickListener {
11153 /**
11154 * Called when a view has been clicked and held.
11155 *
11156 * @param v The view that was clicked and held.
11157 *
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -080011158 * @return true if the callback consumed the long click, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011159 */
11160 boolean onLongClick(View v);
11161 }
11162
11163 /**
Chris Tate32affef2010-10-18 15:29:21 -070011164 * Interface definition for a callback to be invoked when a drag is being dispatched
11165 * to this view. The callback will be invoked before the hosting view's own
11166 * onDrag(event) method. If the listener wants to fall back to the hosting view's
11167 * onDrag(event) behavior, it should return 'false' from this callback.
11168 */
11169 public interface OnDragListener {
11170 /**
11171 * Called when a drag event is dispatched to a view. This allows listeners
11172 * to get a chance to override base View behavior.
11173 *
11174 * @param v The view the drag has been dispatched to.
11175 * @param event The DragEvent object containing full information
11176 * about the event.
11177 * @return true if the listener consumed the DragEvent, false in order to fall
11178 * back to the view's default handling.
11179 */
11180 boolean onDrag(View v, DragEvent event);
11181 }
11182
11183 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011184 * Interface definition for a callback to be invoked when the focus state of
11185 * a view changed.
11186 */
11187 public interface OnFocusChangeListener {
11188 /**
11189 * Called when the focus state of a view has changed.
11190 *
11191 * @param v The view whose state has changed.
11192 * @param hasFocus The new focus state of v.
11193 */
11194 void onFocusChange(View v, boolean hasFocus);
11195 }
11196
11197 /**
11198 * Interface definition for a callback to be invoked when a view is clicked.
11199 */
11200 public interface OnClickListener {
11201 /**
11202 * Called when a view has been clicked.
11203 *
11204 * @param v The view that was clicked.
11205 */
11206 void onClick(View v);
11207 }
11208
11209 /**
11210 * Interface definition for a callback to be invoked when the context menu
11211 * for this view is being built.
11212 */
11213 public interface OnCreateContextMenuListener {
11214 /**
11215 * Called when the context menu for this view is being built. It is not
11216 * safe to hold onto the menu after this method returns.
11217 *
11218 * @param menu The context menu that is being built
11219 * @param v The view for which the context menu is being built
11220 * @param menuInfo Extra information about the item for which the
11221 * context menu should be shown. This information will vary
11222 * depending on the class of v.
11223 */
11224 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
11225 }
11226
11227 private final class UnsetPressedState implements Runnable {
11228 public void run() {
11229 setPressed(false);
11230 }
11231 }
11232
11233 /**
11234 * Base class for derived classes that want to save and restore their own
11235 * state in {@link android.view.View#onSaveInstanceState()}.
11236 */
11237 public static class BaseSavedState extends AbsSavedState {
11238 /**
11239 * Constructor used when reading from a parcel. Reads the state of the superclass.
11240 *
11241 * @param source
11242 */
11243 public BaseSavedState(Parcel source) {
11244 super(source);
11245 }
11246
11247 /**
11248 * Constructor called by derived classes when creating their SavedState objects
11249 *
11250 * @param superState The state of the superclass of this view
11251 */
11252 public BaseSavedState(Parcelable superState) {
11253 super(superState);
11254 }
11255
11256 public static final Parcelable.Creator<BaseSavedState> CREATOR =
11257 new Parcelable.Creator<BaseSavedState>() {
11258 public BaseSavedState createFromParcel(Parcel in) {
11259 return new BaseSavedState(in);
11260 }
11261
11262 public BaseSavedState[] newArray(int size) {
11263 return new BaseSavedState[size];
11264 }
11265 };
11266 }
11267
11268 /**
11269 * A set of information given to a view when it is attached to its parent
11270 * window.
11271 */
11272 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011273 interface Callbacks {
11274 void playSoundEffect(int effectId);
11275 boolean performHapticFeedback(int effectId, boolean always);
11276 }
11277
11278 /**
11279 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11280 * to a Handler. This class contains the target (View) to invalidate and
11281 * the coordinates of the dirty rectangle.
11282 *
11283 * For performance purposes, this class also implements a pool of up to
11284 * POOL_LIMIT objects that get reused. This reduces memory allocations
11285 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011286 */
Romain Guyd928d682009-03-31 17:52:16 -070011287 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011288 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070011289 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11290 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070011291 public InvalidateInfo newInstance() {
11292 return new InvalidateInfo();
11293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011294
Romain Guyd928d682009-03-31 17:52:16 -070011295 public void onAcquired(InvalidateInfo element) {
11296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297
Romain Guyd928d682009-03-31 17:52:16 -070011298 public void onReleased(InvalidateInfo element) {
11299 }
11300 }, POOL_LIMIT)
11301 );
11302
11303 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011304
11305 View target;
11306
11307 int left;
11308 int top;
11309 int right;
11310 int bottom;
11311
Romain Guyd928d682009-03-31 17:52:16 -070011312 public void setNextPoolable(InvalidateInfo element) {
11313 mNext = element;
11314 }
11315
11316 public InvalidateInfo getNextPoolable() {
11317 return mNext;
11318 }
11319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011320 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070011321 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011322 }
11323
11324 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070011325 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011326 }
11327 }
11328
11329 final IWindowSession mSession;
11330
11331 final IWindow mWindow;
11332
11333 final IBinder mWindowToken;
11334
11335 final Callbacks mRootCallbacks;
11336
11337 /**
11338 * The top view of the hierarchy.
11339 */
11340 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070011341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011342 IBinder mPanelParentWindowToken;
11343 Surface mSurface;
11344
Romain Guyb051e892010-09-28 19:09:36 -070011345 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080011346 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070011347 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070011348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011349 /**
Romain Guy8506ab42009-06-11 17:35:47 -070011350 * Scale factor used by the compatibility mode
11351 */
11352 float mApplicationScale;
11353
11354 /**
11355 * Indicates whether the application is in compatibility mode
11356 */
11357 boolean mScalingRequired;
11358
11359 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011360 * Left position of this view's window
11361 */
11362 int mWindowLeft;
11363
11364 /**
11365 * Top position of this view's window
11366 */
11367 int mWindowTop;
11368
11369 /**
Adam Powell26153a32010-11-08 15:22:27 -080011370 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070011371 */
Adam Powell26153a32010-11-08 15:22:27 -080011372 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070011373
11374 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011375 * For windows that are full-screen but using insets to layout inside
11376 * of the screen decorations, these are the current insets for the
11377 * content of the window.
11378 */
11379 final Rect mContentInsets = new Rect();
11380
11381 /**
11382 * For windows that are full-screen but using insets to layout inside
11383 * of the screen decorations, these are the current insets for the
11384 * actual visible parts of the window.
11385 */
11386 final Rect mVisibleInsets = new Rect();
11387
11388 /**
11389 * The internal insets given by this window. This value is
11390 * supplied by the client (through
11391 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11392 * be given to the window manager when changed to be used in laying
11393 * out windows behind it.
11394 */
11395 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11396 = new ViewTreeObserver.InternalInsetsInfo();
11397
11398 /**
11399 * All views in the window's hierarchy that serve as scroll containers,
11400 * used to determine if the window can be resized or must be panned
11401 * to adjust for a soft input area.
11402 */
11403 final ArrayList<View> mScrollContainers = new ArrayList<View>();
11404
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070011405 final KeyEvent.DispatcherState mKeyDispatchState
11406 = new KeyEvent.DispatcherState();
11407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011408 /**
11409 * Indicates whether the view's window currently has the focus.
11410 */
11411 boolean mHasWindowFocus;
11412
11413 /**
11414 * The current visibility of the window.
11415 */
11416 int mWindowVisibility;
11417
11418 /**
11419 * Indicates the time at which drawing started to occur.
11420 */
11421 long mDrawingTime;
11422
11423 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070011424 * Indicates whether or not ignoring the DIRTY_MASK flags.
11425 */
11426 boolean mIgnoreDirtyState;
11427
11428 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011429 * Indicates whether the view's window is currently in touch mode.
11430 */
11431 boolean mInTouchMode;
11432
11433 /**
11434 * Indicates that ViewRoot should trigger a global layout change
11435 * the next time it performs a traversal
11436 */
11437 boolean mRecomputeGlobalAttributes;
11438
11439 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011440 * Set during a traveral if any views want to keep the screen on.
11441 */
11442 boolean mKeepScreenOn;
11443
11444 /**
11445 * Set if the visibility of any views has changed.
11446 */
11447 boolean mViewVisibilityChanged;
11448
11449 /**
11450 * Set to true if a view has been scrolled.
11451 */
11452 boolean mViewScrollChanged;
11453
11454 /**
11455 * Global to the view hierarchy used as a temporary for dealing with
11456 * x/y points in the transparent region computations.
11457 */
11458 final int[] mTransparentLocation = new int[2];
11459
11460 /**
11461 * Global to the view hierarchy used as a temporary for dealing with
11462 * x/y points in the ViewGroup.invalidateChild implementation.
11463 */
11464 final int[] mInvalidateChildLocation = new int[2];
11465
Chet Haasec3aa3612010-06-17 08:50:37 -070011466
11467 /**
11468 * Global to the view hierarchy used as a temporary for dealing with
11469 * x/y location when view is transformed.
11470 */
11471 final float[] mTmpTransformLocation = new float[2];
11472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 /**
11474 * The view tree observer used to dispatch global events like
11475 * layout, pre-draw, touch mode change, etc.
11476 */
11477 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11478
11479 /**
11480 * A Canvas used by the view hierarchy to perform bitmap caching.
11481 */
11482 Canvas mCanvas;
11483
11484 /**
11485 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11486 * handler can be used to pump events in the UI events queue.
11487 */
11488 final Handler mHandler;
11489
11490 /**
11491 * Identifier for messages requesting the view to be invalidated.
11492 * Such messages should be sent to {@link #mHandler}.
11493 */
11494 static final int INVALIDATE_MSG = 0x1;
11495
11496 /**
11497 * Identifier for messages requesting the view to invalidate a region.
11498 * Such messages should be sent to {@link #mHandler}.
11499 */
11500 static final int INVALIDATE_RECT_MSG = 0x2;
11501
11502 /**
11503 * Temporary for use in computing invalidate rectangles while
11504 * calling up the hierarchy.
11505 */
11506 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070011507
11508 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070011509 * Temporary for use in computing hit areas with transformed views
11510 */
11511 final RectF mTmpTransformRect = new RectF();
11512
11513 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070011514 * Temporary list for use in collecting focusable descendents of a view.
11515 */
11516 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011518 /**
11519 * Creates a new set of attachment information with the specified
11520 * events handler and thread.
11521 *
11522 * @param handler the events handler the view must use
11523 */
11524 AttachInfo(IWindowSession session, IWindow window,
11525 Handler handler, Callbacks effectPlayer) {
11526 mSession = session;
11527 mWindow = window;
11528 mWindowToken = window.asBinder();
11529 mHandler = handler;
11530 mRootCallbacks = effectPlayer;
11531 }
11532 }
11533
11534 /**
11535 * <p>ScrollabilityCache holds various fields used by a View when scrolling
11536 * is supported. This avoids keeping too many unused fields in most
11537 * instances of View.</p>
11538 */
Mike Cleronf116bf82009-09-27 19:14:12 -070011539 private static class ScrollabilityCache implements Runnable {
11540
11541 /**
11542 * Scrollbars are not visible
11543 */
11544 public static final int OFF = 0;
11545
11546 /**
11547 * Scrollbars are visible
11548 */
11549 public static final int ON = 1;
11550
11551 /**
11552 * Scrollbars are fading away
11553 */
11554 public static final int FADING = 2;
11555
11556 public boolean fadeScrollBars;
11557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011558 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070011559 public int scrollBarDefaultDelayBeforeFade;
11560 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011561
11562 public int scrollBarSize;
11563 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070011564 public float[] interpolatorValues;
11565 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011566
11567 public final Paint paint;
11568 public final Matrix matrix;
11569 public Shader shader;
11570
Mike Cleronf116bf82009-09-27 19:14:12 -070011571 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11572
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011573 private static final float[] OPAQUE = { 255 };
11574 private static final float[] TRANSPARENT = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070011575
11576 /**
11577 * When fading should start. This time moves into the future every time
11578 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11579 */
11580 public long fadeStartTime;
11581
11582
11583 /**
11584 * The current state of the scrollbars: ON, OFF, or FADING
11585 */
11586 public int state = OFF;
11587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011588 private int mLastColor;
11589
Mike Cleronf116bf82009-09-27 19:14:12 -070011590 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011591 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11592 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070011593 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11594 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011595
11596 paint = new Paint();
11597 matrix = new Matrix();
11598 // use use a height of 1, and then wack the matrix each time we
11599 // actually use it.
11600 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011602 paint.setShader(shader);
11603 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070011604 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011605 }
Romain Guy8506ab42009-06-11 17:35:47 -070011606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011607 public void setFadeColor(int color) {
11608 if (color != 0 && color != mLastColor) {
11609 mLastColor = color;
11610 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070011611
Romain Guye55e1a72009-08-27 10:42:26 -070011612 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11613 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011615 paint.setShader(shader);
11616 // Restore the default transfer mode (src_over)
11617 paint.setXfermode(null);
11618 }
11619 }
Mike Cleronf116bf82009-09-27 19:14:12 -070011620
11621 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070011622 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070011623 if (now >= fadeStartTime) {
11624
11625 // the animation fades the scrollbars out by changing
11626 // the opacity (alpha) from fully opaque to fully
11627 // transparent
11628 int nextFrame = (int) now;
11629 int framesCount = 0;
11630
11631 Interpolator interpolator = scrollBarInterpolator;
11632
11633 // Start opaque
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011634 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
Mike Cleronf116bf82009-09-27 19:14:12 -070011635
11636 // End transparent
11637 nextFrame += scrollBarFadeDuration;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011638 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
Mike Cleronf116bf82009-09-27 19:14:12 -070011639
11640 state = FADING;
11641
11642 // Kick off the fade animation
11643 host.invalidate();
11644 }
11645 }
11646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011647 }
11648}