blob: 63450de02512bb6b3a229e0c8b4e86cdfb5001e6 [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
Christopher Tatea53146c2010-09-07 11:57:52 -070019import android.content.ClipData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080021import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070025import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070027import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.graphics.LinearGradient;
29import android.graphics.Matrix;
30import android.graphics.Paint;
31import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070032import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
35import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070036import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.graphics.Region;
38import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Message;
44import android.os.Parcel;
45import android.os.Parcelable;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.os.SystemProperties;
49import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070051import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070052import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070053import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070054import android.util.Pools;
55import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.view.ContextMenu.ContextMenuInfo;
svetoslavganov75986cf2009-05-14 22:28:01 -070057import android.view.accessibility.AccessibilityEvent;
58import android.view.accessibility.AccessibilityEventSource;
59import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070061import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070062import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.view.inputmethod.InputConnection;
64import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.widget.ScrollBarDrawable;
Romain Guyf607bdc2010-09-10 19:20:06 -070066import com.android.internal.R;
67import com.android.internal.view.menu.MenuBuilder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
svetoslavganov75986cf2009-05-14 22:28:01 -070069import java.lang.reflect.InvocationTargetException;
70import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import java.util.ArrayList;
72import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070073import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070074import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075
76/**
77 * <p>
78 * This class represents the basic building block for user interface components. A View
79 * occupies a rectangular area on the screen and is responsible for drawing and
80 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070081 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
83 * are invisible containers that hold other Views (or other ViewGroups) and define
84 * their layout properties.
85 * </p>
86 *
87 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070088 * <p>For an introduction to using this class to develop your
89 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070091 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
93 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
94 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
95 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
100 * </p>
101 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700102 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 * <a name="Using"></a>
104 * <h3>Using Views</h3>
105 * <p>
106 * All of the views in a window are arranged in a single tree. You can add views
107 * either from code or by specifying a tree of views in one or more XML layout
108 * files. There are many specialized subclasses of views that act as controls or
109 * are capable of displaying text, images, or other content.
110 * </p>
111 * <p>
112 * Once you have created a tree of views, there are typically a few types of
113 * common operations you may wish to perform:
114 * <ul>
115 * <li><strong>Set properties:</strong> for example setting the text of a
116 * {@link android.widget.TextView}. The available properties and the methods
117 * that set them will vary among the different subclasses of views. Note that
118 * properties that are known at build time can be set in the XML layout
119 * files.</li>
120 * <li><strong>Set focus:</strong> The framework will handled moving focus in
121 * response to user input. To force focus to a specific view, call
122 * {@link #requestFocus}.</li>
123 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
124 * that will be notified when something interesting happens to the view. For
125 * example, all views will let you set a listener to be notified when the view
126 * gains or loses focus. You can register such a listener using
127 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
128 * specialized listeners. For example, a Button exposes a listener to notify
129 * clients when the button is clicked.</li>
130 * <li><strong>Set visibility:</strong> You can hide or show views using
131 * {@link #setVisibility}.</li>
132 * </ul>
133 * </p>
134 * <p><em>
135 * Note: The Android framework is responsible for measuring, laying out and
136 * drawing views. You should not call methods that perform these actions on
137 * views yourself unless you are actually implementing a
138 * {@link android.view.ViewGroup}.
139 * </em></p>
140 *
141 * <a name="Lifecycle"></a>
142 * <h3>Implementing a Custom View</h3>
143 *
144 * <p>
145 * To implement a custom view, you will usually begin by providing overrides for
146 * some of the standard methods that the framework calls on all views. You do
147 * not need to override all of these methods. In fact, you can start by just
148 * overriding {@link #onDraw(android.graphics.Canvas)}.
149 * <table border="2" width="85%" align="center" cellpadding="5">
150 * <thead>
151 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
152 * </thead>
153 *
154 * <tbody>
155 * <tr>
156 * <td rowspan="2">Creation</td>
157 * <td>Constructors</td>
158 * <td>There is a form of the constructor that are called when the view
159 * is created from code and a form that is called when the view is
160 * inflated from a layout file. The second form should parse and apply
161 * any attributes defined in the layout file.
162 * </td>
163 * </tr>
164 * <tr>
165 * <td><code>{@link #onFinishInflate()}</code></td>
166 * <td>Called after a view and all of its children has been inflated
167 * from XML.</td>
168 * </tr>
169 *
170 * <tr>
171 * <td rowspan="3">Layout</td>
172 * <td><code>{@link #onMeasure}</code></td>
173 * <td>Called to determine the size requirements for this view and all
174 * of its children.
175 * </td>
176 * </tr>
177 * <tr>
178 * <td><code>{@link #onLayout}</code></td>
179 * <td>Called when this view should assign a size and position to all
180 * of its children.
181 * </td>
182 * </tr>
183 * <tr>
184 * <td><code>{@link #onSizeChanged}</code></td>
185 * <td>Called when the size of this view has changed.
186 * </td>
187 * </tr>
188 *
189 * <tr>
190 * <td>Drawing</td>
191 * <td><code>{@link #onDraw}</code></td>
192 * <td>Called when the view should render its content.
193 * </td>
194 * </tr>
195 *
196 * <tr>
197 * <td rowspan="4">Event processing</td>
198 * <td><code>{@link #onKeyDown}</code></td>
199 * <td>Called when a new key event occurs.
200 * </td>
201 * </tr>
202 * <tr>
203 * <td><code>{@link #onKeyUp}</code></td>
204 * <td>Called when a key up event occurs.
205 * </td>
206 * </tr>
207 * <tr>
208 * <td><code>{@link #onTrackballEvent}</code></td>
209 * <td>Called when a trackball motion event occurs.
210 * </td>
211 * </tr>
212 * <tr>
213 * <td><code>{@link #onTouchEvent}</code></td>
214 * <td>Called when a touch screen motion event occurs.
215 * </td>
216 * </tr>
217 *
218 * <tr>
219 * <td rowspan="2">Focus</td>
220 * <td><code>{@link #onFocusChanged}</code></td>
221 * <td>Called when the view gains or loses focus.
222 * </td>
223 * </tr>
224 *
225 * <tr>
226 * <td><code>{@link #onWindowFocusChanged}</code></td>
227 * <td>Called when the window containing the view gains or loses focus.
228 * </td>
229 * </tr>
230 *
231 * <tr>
232 * <td rowspan="3">Attaching</td>
233 * <td><code>{@link #onAttachedToWindow()}</code></td>
234 * <td>Called when the view is attached to a window.
235 * </td>
236 * </tr>
237 *
238 * <tr>
239 * <td><code>{@link #onDetachedFromWindow}</code></td>
240 * <td>Called when the view is detached from its window.
241 * </td>
242 * </tr>
243 *
244 * <tr>
245 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
246 * <td>Called when the visibility of the window containing the view
247 * has changed.
248 * </td>
249 * </tr>
250 * </tbody>
251 *
252 * </table>
253 * </p>
254 *
255 * <a name="IDs"></a>
256 * <h3>IDs</h3>
257 * Views may have an integer id associated with them. These ids are typically
258 * assigned in the layout XML files, and are used to find specific views within
259 * the view tree. A common pattern is to:
260 * <ul>
261 * <li>Define a Button in the layout file and assign it a unique ID.
262 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700263 * &lt;Button
264 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 * android:layout_width="wrap_content"
266 * android:layout_height="wrap_content"
267 * android:text="@string/my_button_text"/&gt;
268 * </pre></li>
269 * <li>From the onCreate method of an Activity, find the Button
270 * <pre class="prettyprint">
271 * Button myButton = (Button) findViewById(R.id.my_button);
272 * </pre></li>
273 * </ul>
274 * <p>
275 * View IDs need not be unique throughout the tree, but it is good practice to
276 * ensure that they are at least unique within the part of the tree you are
277 * searching.
278 * </p>
279 *
280 * <a name="Position"></a>
281 * <h3>Position</h3>
282 * <p>
283 * The geometry of a view is that of a rectangle. A view has a location,
284 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
285 * two dimensions, expressed as a width and a height. The unit for location
286 * and dimensions is the pixel.
287 * </p>
288 *
289 * <p>
290 * It is possible to retrieve the location of a view by invoking the methods
291 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
292 * coordinate of the rectangle representing the view. The latter returns the
293 * top, or Y, coordinate of the rectangle representing the view. These methods
294 * both return the location of the view relative to its parent. For instance,
295 * when getLeft() returns 20, that means the view is located 20 pixels to the
296 * right of the left edge of its direct parent.
297 * </p>
298 *
299 * <p>
300 * In addition, several convenience methods are offered to avoid unnecessary
301 * computations, namely {@link #getRight()} and {@link #getBottom()}.
302 * These methods return the coordinates of the right and bottom edges of the
303 * rectangle representing the view. For instance, calling {@link #getRight()}
304 * is similar to the following computation: <code>getLeft() + getWidth()</code>
305 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
306 * </p>
307 *
308 * <a name="SizePaddingMargins"></a>
309 * <h3>Size, padding and margins</h3>
310 * <p>
311 * The size of a view is expressed with a width and a height. A view actually
312 * possess two pairs of width and height values.
313 * </p>
314 *
315 * <p>
316 * The first pair is known as <em>measured width</em> and
317 * <em>measured height</em>. These dimensions define how big a view wants to be
318 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
319 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
320 * and {@link #getMeasuredHeight()}.
321 * </p>
322 *
323 * <p>
324 * The second pair is simply known as <em>width</em> and <em>height</em>, or
325 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
326 * dimensions define the actual size of the view on screen, at drawing time and
327 * after layout. These values may, but do not have to, be different from the
328 * measured width and height. The width and height can be obtained by calling
329 * {@link #getWidth()} and {@link #getHeight()}.
330 * </p>
331 *
332 * <p>
333 * To measure its dimensions, a view takes into account its padding. The padding
334 * is expressed in pixels for the left, top, right and bottom parts of the view.
335 * Padding can be used to offset the content of the view by a specific amount of
336 * pixels. For instance, a left padding of 2 will push the view's content by
337 * 2 pixels to the right of the left edge. Padding can be set using the
338 * {@link #setPadding(int, int, int, int)} method and queried by calling
339 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
340 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
341 * </p>
342 *
343 * <p>
344 * Even though a view can define a padding, it does not provide any support for
345 * margins. However, view groups provide such a support. Refer to
346 * {@link android.view.ViewGroup} and
347 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
348 * </p>
349 *
350 * <a name="Layout"></a>
351 * <h3>Layout</h3>
352 * <p>
353 * Layout is a two pass process: a measure pass and a layout pass. The measuring
354 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
355 * of the view tree. Each view pushes dimension specifications down the tree
356 * during the recursion. At the end of the measure pass, every view has stored
357 * its measurements. The second pass happens in
358 * {@link #layout(int,int,int,int)} and is also top-down. During
359 * this pass each parent is responsible for positioning all of its children
360 * using the sizes computed in the measure pass.
361 * </p>
362 *
363 * <p>
364 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
365 * {@link #getMeasuredHeight()} values must be set, along with those for all of
366 * that view's descendants. A view's measured width and measured height values
367 * must respect the constraints imposed by the view's parents. This guarantees
368 * that at the end of the measure pass, all parents accept all of their
369 * children's measurements. A parent view may call measure() more than once on
370 * its children. For example, the parent may measure each child once with
371 * unspecified dimensions to find out how big they want to be, then call
372 * measure() on them again with actual numbers if the sum of all the children's
373 * unconstrained sizes is too big or too small.
374 * </p>
375 *
376 * <p>
377 * The measure pass uses two classes to communicate dimensions. The
378 * {@link MeasureSpec} class is used by views to tell their parents how they
379 * want to be measured and positioned. The base LayoutParams class just
380 * describes how big the view wants to be for both width and height. For each
381 * dimension, it can specify one of:
382 * <ul>
383 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800384 * <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 -0800385 * (minus padding)
386 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
387 * enclose its content (plus padding).
388 * </ul>
389 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
390 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
391 * an X and Y value.
392 * </p>
393 *
394 * <p>
395 * MeasureSpecs are used to push requirements down the tree from parent to
396 * child. A MeasureSpec can be in one of three modes:
397 * <ul>
398 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
399 * of a child view. For example, a LinearLayout may call measure() on its child
400 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
401 * tall the child view wants to be given a width of 240 pixels.
402 * <li>EXACTLY: This is used by the parent to impose an exact size on the
403 * child. The child must use this size, and guarantee that all of its
404 * descendants will fit within this size.
405 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
406 * child. The child must gurantee that it and all of its descendants will fit
407 * within this size.
408 * </ul>
409 * </p>
410 *
411 * <p>
412 * To intiate a layout, call {@link #requestLayout}. This method is typically
413 * called by a view on itself when it believes that is can no longer fit within
414 * its current bounds.
415 * </p>
416 *
417 * <a name="Drawing"></a>
418 * <h3>Drawing</h3>
419 * <p>
420 * Drawing is handled by walking the tree and rendering each view that
421 * intersects the the invalid region. Because the tree is traversed in-order,
422 * this means that parents will draw before (i.e., behind) their children, with
423 * siblings drawn in the order they appear in the tree.
424 * If you set a background drawable for a View, then the View will draw it for you
425 * before calling back to its <code>onDraw()</code> method.
426 * </p>
427 *
428 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700429 * 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 -0800430 * </p>
431 *
432 * <p>
433 * To force a view to draw, call {@link #invalidate()}.
434 * </p>
435 *
436 * <a name="EventHandlingThreading"></a>
437 * <h3>Event Handling and Threading</h3>
438 * <p>
439 * The basic cycle of a view is as follows:
440 * <ol>
441 * <li>An event comes in and is dispatched to the appropriate view. The view
442 * handles the event and notifies any listeners.</li>
443 * <li>If in the course of processing the event, the view's bounds may need
444 * to be changed, the view will call {@link #requestLayout()}.</li>
445 * <li>Similarly, if in the course of processing the event the view's appearance
446 * may need to be changed, the view will call {@link #invalidate()}.</li>
447 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
448 * the framework will take care of measuring, laying out, and drawing the tree
449 * as appropriate.</li>
450 * </ol>
451 * </p>
452 *
453 * <p><em>Note: The entire view tree is single threaded. You must always be on
454 * the UI thread when calling any method on any view.</em>
455 * If you are doing work on other threads and want to update the state of a view
456 * from that thread, you should use a {@link Handler}.
457 * </p>
458 *
459 * <a name="FocusHandling"></a>
460 * <h3>Focus Handling</h3>
461 * <p>
462 * The framework will handle routine focus movement in response to user input.
463 * This includes changing the focus as views are removed or hidden, or as new
464 * views become available. Views indicate their willingness to take focus
465 * through the {@link #isFocusable} method. To change whether a view can take
466 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
467 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
468 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
469 * </p>
470 * <p>
471 * Focus movement is based on an algorithm which finds the nearest neighbor in a
472 * given direction. In rare cases, the default algorithm may not match the
473 * intended behavior of the developer. In these situations, you can provide
474 * explicit overrides by using these XML attributes in the layout file:
475 * <pre>
476 * nextFocusDown
477 * nextFocusLeft
478 * nextFocusRight
479 * nextFocusUp
480 * </pre>
481 * </p>
482 *
483 *
484 * <p>
485 * To get a particular view to take focus, call {@link #requestFocus()}.
486 * </p>
487 *
488 * <a name="TouchMode"></a>
489 * <h3>Touch Mode</h3>
490 * <p>
491 * When a user is navigating a user interface via directional keys such as a D-pad, it is
492 * necessary to give focus to actionable items such as buttons so the user can see
493 * what will take input. If the device has touch capabilities, however, and the user
494 * begins interacting with the interface by touching it, it is no longer necessary to
495 * always highlight, or give focus to, a particular view. This motivates a mode
496 * for interaction named 'touch mode'.
497 * </p>
498 * <p>
499 * For a touch capable device, once the user touches the screen, the device
500 * will enter touch mode. From this point onward, only views for which
501 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
502 * Other views that are touchable, like buttons, will not take focus when touched; they will
503 * only fire the on click listeners.
504 * </p>
505 * <p>
506 * Any time a user hits a directional key, such as a D-pad direction, the view device will
507 * exit touch mode, and find a view to take focus, so that the user may resume interacting
508 * with the user interface without touching the screen again.
509 * </p>
510 * <p>
511 * The touch mode state is maintained across {@link android.app.Activity}s. Call
512 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
513 * </p>
514 *
515 * <a name="Scrolling"></a>
516 * <h3>Scrolling</h3>
517 * <p>
518 * The framework provides basic support for views that wish to internally
519 * scroll their content. This includes keeping track of the X and Y scroll
520 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700521 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
522 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 * </p>
524 *
525 * <a name="Tags"></a>
526 * <h3>Tags</h3>
527 * <p>
528 * Unlike IDs, tags are not used to identify views. Tags are essentially an
529 * extra piece of information that can be associated with a view. They are most
530 * often used as a convenience to store data related to views in the views
531 * themselves rather than by putting them in a separate structure.
532 * </p>
533 *
534 * <a name="Animation"></a>
535 * <h3>Animation</h3>
536 * <p>
537 * You can attach an {@link Animation} object to a view using
538 * {@link #setAnimation(Animation)} or
539 * {@link #startAnimation(Animation)}. The animation can alter the scale,
540 * rotation, translation and alpha of a view over time. If the animation is
541 * attached to a view that has children, the animation will affect the entire
542 * subtree rooted by that node. When an animation is started, the framework will
543 * take care of redrawing the appropriate views until the animation completes.
544 * </p>
545 *
Jeff Brown85a31762010-09-01 17:01:00 -0700546 * <a name="Security"></a>
547 * <h3>Security</h3>
548 * <p>
549 * Sometimes it is essential that an application be able to verify that an action
550 * is being performed with the full knowledge and consent of the user, such as
551 * granting a permission request, making a purchase or clicking on an advertisement.
552 * Unfortunately, a malicious application could try to spoof the user into
553 * performing these actions, unaware, by concealing the intended purpose of the view.
554 * As a remedy, the framework offers a touch filtering mechanism that can be used to
555 * improve the security of views that provide access to sensitive functionality.
556 * </p><p>
557 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
558 * andoird:filterTouchesWhenObscured attribute to true. When enabled, the framework
559 * will discard touches that are received whenever the view's window is obscured by
560 * another visible window. As a result, the view will not receive touches whenever a
561 * toast, dialog or other window appears above the view's window.
562 * </p><p>
563 * For more fine-grained control over security, consider overriding the
564 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
565 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
566 * </p>
567 *
Romain Guyd6a463a2009-05-21 23:10:10 -0700568 * @attr ref android.R.styleable#View_background
569 * @attr ref android.R.styleable#View_clickable
570 * @attr ref android.R.styleable#View_contentDescription
571 * @attr ref android.R.styleable#View_drawingCacheQuality
572 * @attr ref android.R.styleable#View_duplicateParentState
573 * @attr ref android.R.styleable#View_id
574 * @attr ref android.R.styleable#View_fadingEdge
575 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700576 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700578 * @attr ref android.R.styleable#View_isScrollContainer
579 * @attr ref android.R.styleable#View_focusable
580 * @attr ref android.R.styleable#View_focusableInTouchMode
581 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
582 * @attr ref android.R.styleable#View_keepScreenOn
583 * @attr ref android.R.styleable#View_longClickable
584 * @attr ref android.R.styleable#View_minHeight
585 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 * @attr ref android.R.styleable#View_nextFocusDown
587 * @attr ref android.R.styleable#View_nextFocusLeft
588 * @attr ref android.R.styleable#View_nextFocusRight
589 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700590 * @attr ref android.R.styleable#View_onClick
591 * @attr ref android.R.styleable#View_padding
592 * @attr ref android.R.styleable#View_paddingBottom
593 * @attr ref android.R.styleable#View_paddingLeft
594 * @attr ref android.R.styleable#View_paddingRight
595 * @attr ref android.R.styleable#View_paddingTop
596 * @attr ref android.R.styleable#View_saveEnabled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 * @attr ref android.R.styleable#View_scrollX
598 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700599 * @attr ref android.R.styleable#View_scrollbarSize
600 * @attr ref android.R.styleable#View_scrollbarStyle
601 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700602 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
603 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
605 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 * @attr ref android.R.styleable#View_scrollbarThumbVertical
607 * @attr ref android.R.styleable#View_scrollbarTrackVertical
608 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
609 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700610 * @attr ref android.R.styleable#View_soundEffectsEnabled
611 * @attr ref android.R.styleable#View_tag
612 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 *
614 * @see android.view.ViewGroup
615 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700616public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 private static final boolean DBG = false;
618
619 /**
620 * The logging tag used by this class with android.util.Log.
621 */
622 protected static final String VIEW_LOG_TAG = "View";
623
624 /**
625 * Used to mark a View that has no ID.
626 */
627 public static final int NO_ID = -1;
628
629 /**
630 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
631 * calling setFlags.
632 */
633 private static final int NOT_FOCUSABLE = 0x00000000;
634
635 /**
636 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
637 * setFlags.
638 */
639 private static final int FOCUSABLE = 0x00000001;
640
641 /**
642 * Mask for use with setFlags indicating bits used for focus.
643 */
644 private static final int FOCUSABLE_MASK = 0x00000001;
645
646 /**
647 * This view will adjust its padding to fit sytem windows (e.g. status bar)
648 */
649 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
650
651 /**
652 * This view is visible. Use with {@link #setVisibility}.
653 */
654 public static final int VISIBLE = 0x00000000;
655
656 /**
657 * This view is invisible, but it still takes up space for layout purposes.
658 * Use with {@link #setVisibility}.
659 */
660 public static final int INVISIBLE = 0x00000004;
661
662 /**
663 * This view is invisible, and it doesn't take any space for layout
664 * purposes. Use with {@link #setVisibility}.
665 */
666 public static final int GONE = 0x00000008;
667
668 /**
669 * Mask for use with setFlags indicating bits used for visibility.
670 * {@hide}
671 */
672 static final int VISIBILITY_MASK = 0x0000000C;
673
674 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
675
676 /**
677 * This view is enabled. Intrepretation varies by subclass.
678 * Use with ENABLED_MASK when calling setFlags.
679 * {@hide}
680 */
681 static final int ENABLED = 0x00000000;
682
683 /**
684 * This view is disabled. Intrepretation varies by subclass.
685 * Use with ENABLED_MASK when calling setFlags.
686 * {@hide}
687 */
688 static final int DISABLED = 0x00000020;
689
690 /**
691 * Mask for use with setFlags indicating bits used for indicating whether
692 * this view is enabled
693 * {@hide}
694 */
695 static final int ENABLED_MASK = 0x00000020;
696
697 /**
698 * This view won't draw. {@link #onDraw} won't be called and further
699 * optimizations
700 * will be performed. It is okay to have this flag set and a background.
701 * Use with DRAW_MASK when calling setFlags.
702 * {@hide}
703 */
704 static final int WILL_NOT_DRAW = 0x00000080;
705
706 /**
707 * Mask for use with setFlags indicating bits used for indicating whether
708 * this view is will draw
709 * {@hide}
710 */
711 static final int DRAW_MASK = 0x00000080;
712
713 /**
714 * <p>This view doesn't show scrollbars.</p>
715 * {@hide}
716 */
717 static final int SCROLLBARS_NONE = 0x00000000;
718
719 /**
720 * <p>This view shows horizontal scrollbars.</p>
721 * {@hide}
722 */
723 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
724
725 /**
726 * <p>This view shows vertical scrollbars.</p>
727 * {@hide}
728 */
729 static final int SCROLLBARS_VERTICAL = 0x00000200;
730
731 /**
732 * <p>Mask for use with setFlags indicating bits used for indicating which
733 * scrollbars are enabled.</p>
734 * {@hide}
735 */
736 static final int SCROLLBARS_MASK = 0x00000300;
737
Jeff Brown85a31762010-09-01 17:01:00 -0700738 /**
739 * Indicates that the view should filter touches when its window is obscured.
740 * Refer to the class comments for more information about this security feature.
741 * {@hide}
742 */
743 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
744
745 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746
747 /**
748 * <p>This view doesn't show fading edges.</p>
749 * {@hide}
750 */
751 static final int FADING_EDGE_NONE = 0x00000000;
752
753 /**
754 * <p>This view shows horizontal fading edges.</p>
755 * {@hide}
756 */
757 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
758
759 /**
760 * <p>This view shows vertical fading edges.</p>
761 * {@hide}
762 */
763 static final int FADING_EDGE_VERTICAL = 0x00002000;
764
765 /**
766 * <p>Mask for use with setFlags indicating bits used for indicating which
767 * fading edges are enabled.</p>
768 * {@hide}
769 */
770 static final int FADING_EDGE_MASK = 0x00003000;
771
772 /**
773 * <p>Indicates this view can be clicked. When clickable, a View reacts
774 * to clicks by notifying the OnClickListener.<p>
775 * {@hide}
776 */
777 static final int CLICKABLE = 0x00004000;
778
779 /**
780 * <p>Indicates this view is caching its drawing into a bitmap.</p>
781 * {@hide}
782 */
783 static final int DRAWING_CACHE_ENABLED = 0x00008000;
784
785 /**
786 * <p>Indicates that no icicle should be saved for this view.<p>
787 * {@hide}
788 */
789 static final int SAVE_DISABLED = 0x000010000;
790
791 /**
792 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
793 * property.</p>
794 * {@hide}
795 */
796 static final int SAVE_DISABLED_MASK = 0x000010000;
797
798 /**
799 * <p>Indicates that no drawing cache should ever be created for this view.<p>
800 * {@hide}
801 */
802 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
803
804 /**
805 * <p>Indicates this view can take / keep focus when int touch mode.</p>
806 * {@hide}
807 */
808 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
809
810 /**
811 * <p>Enables low quality mode for the drawing cache.</p>
812 */
813 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
814
815 /**
816 * <p>Enables high quality mode for the drawing cache.</p>
817 */
818 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
819
820 /**
821 * <p>Enables automatic quality mode for the drawing cache.</p>
822 */
823 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
824
825 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
826 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
827 };
828
829 /**
830 * <p>Mask for use with setFlags indicating bits used for the cache
831 * quality property.</p>
832 * {@hide}
833 */
834 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
835
836 /**
837 * <p>
838 * Indicates this view can be long clicked. When long clickable, a View
839 * reacts to long clicks by notifying the OnLongClickListener or showing a
840 * context menu.
841 * </p>
842 * {@hide}
843 */
844 static final int LONG_CLICKABLE = 0x00200000;
845
846 /**
847 * <p>Indicates that this view gets its drawable states from its direct parent
848 * and ignores its original internal states.</p>
849 *
850 * @hide
851 */
852 static final int DUPLICATE_PARENT_STATE = 0x00400000;
853
854 /**
855 * The scrollbar style to display the scrollbars inside the content area,
856 * without increasing the padding. The scrollbars will be overlaid with
857 * translucency on the view's content.
858 */
859 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
860
861 /**
862 * The scrollbar style to display the scrollbars inside the padded area,
863 * increasing the padding of the view. The scrollbars will not overlap the
864 * content area of the view.
865 */
866 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
867
868 /**
869 * The scrollbar style to display the scrollbars at the edge of the view,
870 * without increasing the padding. The scrollbars will be overlaid with
871 * translucency.
872 */
873 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
874
875 /**
876 * The scrollbar style to display the scrollbars at the edge of the view,
877 * increasing the padding of the view. The scrollbars will only overlap the
878 * background, if any.
879 */
880 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
881
882 /**
883 * Mask to check if the scrollbar style is overlay or inset.
884 * {@hide}
885 */
886 static final int SCROLLBARS_INSET_MASK = 0x01000000;
887
888 /**
889 * Mask to check if the scrollbar style is inside or outside.
890 * {@hide}
891 */
892 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
893
894 /**
895 * Mask for scrollbar style.
896 * {@hide}
897 */
898 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
899
900 /**
901 * View flag indicating that the screen should remain on while the
902 * window containing this view is visible to the user. This effectively
903 * takes care of automatically setting the WindowManager's
904 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
905 */
906 public static final int KEEP_SCREEN_ON = 0x04000000;
907
908 /**
909 * View flag indicating whether this view should have sound effects enabled
910 * for events such as clicking and touching.
911 */
912 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
913
914 /**
915 * View flag indicating whether this view should have haptic feedback
916 * enabled for events such as long presses.
917 */
918 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
919
920 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700921 * <p>Indicates that the view hierarchy should stop saving state when
922 * it reaches this view. If state saving is initiated immediately at
923 * the view, it will be allowed.
924 * {@hide}
925 */
926 static final int PARENT_SAVE_DISABLED = 0x20000000;
927
928 /**
929 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
930 * {@hide}
931 */
932 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
933
934 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700935 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
936 * should add all focusable Views regardless if they are focusable in touch mode.
937 */
938 public static final int FOCUSABLES_ALL = 0x00000000;
939
940 /**
941 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
942 * should add only Views focusable in touch mode.
943 */
944 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
945
946 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 * Use with {@link #focusSearch}. Move focus to the previous selectable
948 * item.
949 */
950 public static final int FOCUS_BACKWARD = 0x00000001;
951
952 /**
953 * Use with {@link #focusSearch}. Move focus to the next selectable
954 * item.
955 */
956 public static final int FOCUS_FORWARD = 0x00000002;
957
958 /**
959 * Use with {@link #focusSearch}. Move focus to the left.
960 */
961 public static final int FOCUS_LEFT = 0x00000011;
962
963 /**
964 * Use with {@link #focusSearch}. Move focus up.
965 */
966 public static final int FOCUS_UP = 0x00000021;
967
968 /**
969 * Use with {@link #focusSearch}. Move focus to the right.
970 */
971 public static final int FOCUS_RIGHT = 0x00000042;
972
973 /**
974 * Use with {@link #focusSearch}. Move focus down.
975 */
976 public static final int FOCUS_DOWN = 0x00000082;
977
978 /**
979 * Base View state sets
980 */
981 // Singles
982 /**
983 * Indicates the view has no states set. States are used with
984 * {@link android.graphics.drawable.Drawable} to change the drawing of the
985 * view depending on its state.
986 *
987 * @see android.graphics.drawable.Drawable
988 * @see #getDrawableState()
989 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -0700990 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 /**
992 * Indicates the view is enabled. States are used with
993 * {@link android.graphics.drawable.Drawable} to change the drawing of the
994 * view depending on its state.
995 *
996 * @see android.graphics.drawable.Drawable
997 * @see #getDrawableState()
998 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -0700999 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 /**
1001 * Indicates the view is focused. States are used with
1002 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1003 * view depending on its state.
1004 *
1005 * @see android.graphics.drawable.Drawable
1006 * @see #getDrawableState()
1007 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001008 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 /**
1010 * Indicates the view is selected. States are used with
1011 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1012 * view depending on its state.
1013 *
1014 * @see android.graphics.drawable.Drawable
1015 * @see #getDrawableState()
1016 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001017 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 /**
1019 * Indicates the view is pressed. States are used with
1020 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1021 * view depending on its state.
1022 *
1023 * @see android.graphics.drawable.Drawable
1024 * @see #getDrawableState()
1025 * @hide
1026 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001027 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 /**
1029 * Indicates the view's window has focus. States are used with
1030 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1031 * view depending on its state.
1032 *
1033 * @see android.graphics.drawable.Drawable
1034 * @see #getDrawableState()
1035 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001036 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 // Doubles
1038 /**
1039 * Indicates the view is enabled and has the focus.
1040 *
1041 * @see #ENABLED_STATE_SET
1042 * @see #FOCUSED_STATE_SET
1043 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001044 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 /**
1046 * Indicates the view is enabled and selected.
1047 *
1048 * @see #ENABLED_STATE_SET
1049 * @see #SELECTED_STATE_SET
1050 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001051 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 /**
1053 * Indicates the view is enabled and that its window has focus.
1054 *
1055 * @see #ENABLED_STATE_SET
1056 * @see #WINDOW_FOCUSED_STATE_SET
1057 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001058 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 /**
1060 * Indicates the view is focused and selected.
1061 *
1062 * @see #FOCUSED_STATE_SET
1063 * @see #SELECTED_STATE_SET
1064 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001065 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 /**
1067 * Indicates the view has the focus and that its window has the focus.
1068 *
1069 * @see #FOCUSED_STATE_SET
1070 * @see #WINDOW_FOCUSED_STATE_SET
1071 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001072 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 /**
1074 * Indicates the view is selected and that its window has the focus.
1075 *
1076 * @see #SELECTED_STATE_SET
1077 * @see #WINDOW_FOCUSED_STATE_SET
1078 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001079 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 // Triples
1081 /**
1082 * Indicates the view is enabled, focused and selected.
1083 *
1084 * @see #ENABLED_STATE_SET
1085 * @see #FOCUSED_STATE_SET
1086 * @see #SELECTED_STATE_SET
1087 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001088 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 /**
1090 * Indicates the view is enabled, focused and its window has the focus.
1091 *
1092 * @see #ENABLED_STATE_SET
1093 * @see #FOCUSED_STATE_SET
1094 * @see #WINDOW_FOCUSED_STATE_SET
1095 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001096 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 /**
1098 * Indicates the view is enabled, selected and its window has the focus.
1099 *
1100 * @see #ENABLED_STATE_SET
1101 * @see #SELECTED_STATE_SET
1102 * @see #WINDOW_FOCUSED_STATE_SET
1103 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001104 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 /**
1106 * Indicates the view is focused, selected and its window has the focus.
1107 *
1108 * @see #FOCUSED_STATE_SET
1109 * @see #SELECTED_STATE_SET
1110 * @see #WINDOW_FOCUSED_STATE_SET
1111 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001112 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 /**
1114 * Indicates the view is enabled, focused, selected and its window
1115 * has the focus.
1116 *
1117 * @see #ENABLED_STATE_SET
1118 * @see #FOCUSED_STATE_SET
1119 * @see #SELECTED_STATE_SET
1120 * @see #WINDOW_FOCUSED_STATE_SET
1121 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001122 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 /**
1124 * Indicates the view is pressed and its window has the focus.
1125 *
1126 * @see #PRESSED_STATE_SET
1127 * @see #WINDOW_FOCUSED_STATE_SET
1128 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001129 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 /**
1131 * Indicates the view is pressed and selected.
1132 *
1133 * @see #PRESSED_STATE_SET
1134 * @see #SELECTED_STATE_SET
1135 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001136 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 /**
1138 * Indicates the view is pressed, selected and its window has the focus.
1139 *
1140 * @see #PRESSED_STATE_SET
1141 * @see #SELECTED_STATE_SET
1142 * @see #WINDOW_FOCUSED_STATE_SET
1143 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001144 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 /**
1146 * Indicates the view is pressed and focused.
1147 *
1148 * @see #PRESSED_STATE_SET
1149 * @see #FOCUSED_STATE_SET
1150 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001151 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 /**
1153 * Indicates the view is pressed, focused and its window has the focus.
1154 *
1155 * @see #PRESSED_STATE_SET
1156 * @see #FOCUSED_STATE_SET
1157 * @see #WINDOW_FOCUSED_STATE_SET
1158 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001159 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 /**
1161 * Indicates the view is pressed, focused and selected.
1162 *
1163 * @see #PRESSED_STATE_SET
1164 * @see #SELECTED_STATE_SET
1165 * @see #FOCUSED_STATE_SET
1166 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001167 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 /**
1169 * Indicates the view is pressed, focused, selected and its window has the focus.
1170 *
1171 * @see #PRESSED_STATE_SET
1172 * @see #FOCUSED_STATE_SET
1173 * @see #SELECTED_STATE_SET
1174 * @see #WINDOW_FOCUSED_STATE_SET
1175 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001176 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 /**
1178 * Indicates the view is pressed and enabled.
1179 *
1180 * @see #PRESSED_STATE_SET
1181 * @see #ENABLED_STATE_SET
1182 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001183 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 /**
1185 * Indicates the view is pressed, enabled and its window has the focus.
1186 *
1187 * @see #PRESSED_STATE_SET
1188 * @see #ENABLED_STATE_SET
1189 * @see #WINDOW_FOCUSED_STATE_SET
1190 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001191 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 /**
1193 * Indicates the view is pressed, enabled and selected.
1194 *
1195 * @see #PRESSED_STATE_SET
1196 * @see #ENABLED_STATE_SET
1197 * @see #SELECTED_STATE_SET
1198 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001199 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 /**
1201 * Indicates the view is pressed, enabled, selected and its window has the
1202 * focus.
1203 *
1204 * @see #PRESSED_STATE_SET
1205 * @see #ENABLED_STATE_SET
1206 * @see #SELECTED_STATE_SET
1207 * @see #WINDOW_FOCUSED_STATE_SET
1208 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001209 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 /**
1211 * Indicates the view is pressed, enabled and focused.
1212 *
1213 * @see #PRESSED_STATE_SET
1214 * @see #ENABLED_STATE_SET
1215 * @see #FOCUSED_STATE_SET
1216 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001217 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 /**
1219 * Indicates the view is pressed, enabled, focused and its window has the
1220 * focus.
1221 *
1222 * @see #PRESSED_STATE_SET
1223 * @see #ENABLED_STATE_SET
1224 * @see #FOCUSED_STATE_SET
1225 * @see #WINDOW_FOCUSED_STATE_SET
1226 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001227 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 /**
1229 * Indicates the view is pressed, enabled, focused and selected.
1230 *
1231 * @see #PRESSED_STATE_SET
1232 * @see #ENABLED_STATE_SET
1233 * @see #SELECTED_STATE_SET
1234 * @see #FOCUSED_STATE_SET
1235 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001236 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 /**
1238 * Indicates the view is pressed, enabled, focused, selected and its window
1239 * has the focus.
1240 *
1241 * @see #PRESSED_STATE_SET
1242 * @see #ENABLED_STATE_SET
1243 * @see #SELECTED_STATE_SET
1244 * @see #FOCUSED_STATE_SET
1245 * @see #WINDOW_FOCUSED_STATE_SET
1246 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001247 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248
1249 /**
1250 * The order here is very important to {@link #getDrawableState()}
1251 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001252 private static final int[][] VIEW_STATE_SETS;
1253
Romain Guyb051e892010-09-28 19:09:36 -07001254 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1255 static final int VIEW_STATE_SELECTED = 1 << 1;
1256 static final int VIEW_STATE_FOCUSED = 1 << 2;
1257 static final int VIEW_STATE_ENABLED = 1 << 3;
1258 static final int VIEW_STATE_PRESSED = 1 << 4;
1259 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001260
1261 static final int[] VIEW_STATE_IDS = new int[] {
1262 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1263 R.attr.state_selected, VIEW_STATE_SELECTED,
1264 R.attr.state_focused, VIEW_STATE_FOCUSED,
1265 R.attr.state_enabled, VIEW_STATE_ENABLED,
1266 R.attr.state_pressed, VIEW_STATE_PRESSED,
1267 R.attr.state_activated, VIEW_STATE_ACTIVATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 };
1269
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001270 static {
1271 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001272 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001273 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001274 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001275 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001276 orderedIds[i * 2] = viewState;
1277 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001278 }
1279 }
1280 }
Romain Guyb051e892010-09-28 19:09:36 -07001281 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1282 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1283 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001284 int numBits = Integer.bitCount(i);
1285 int[] set = new int[numBits];
1286 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001287 for (int j = 0; j < orderedIds.length; j += 2) {
1288 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001289 set[pos++] = orderedIds[j];
1290 }
1291 }
1292 VIEW_STATE_SETS[i] = set;
1293 }
1294
1295 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1296 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1297 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1298 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1299 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1300 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1301 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1302 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1303 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1304 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1305 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1306 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1307 | VIEW_STATE_FOCUSED];
1308 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1309 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1310 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1311 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1312 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1313 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1314 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1315 | VIEW_STATE_ENABLED];
1316 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1317 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1318 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1319 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1320 | VIEW_STATE_ENABLED];
1321 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1322 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1323 | VIEW_STATE_ENABLED];
1324 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1325 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1326 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1327
1328 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1329 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1330 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1331 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1332 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1333 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1334 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1335 | VIEW_STATE_PRESSED];
1336 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1337 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1338 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1339 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1340 | VIEW_STATE_PRESSED];
1341 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1342 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1343 | VIEW_STATE_PRESSED];
1344 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1345 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1346 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1347 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1348 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1349 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1350 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1351 | VIEW_STATE_PRESSED];
1352 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1353 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1354 | VIEW_STATE_PRESSED];
1355 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1356 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1357 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1358 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1359 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1360 | VIEW_STATE_PRESSED];
1361 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1362 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1363 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1364 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1365 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1366 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1367 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1368 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1369 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1370 | VIEW_STATE_PRESSED];
1371 }
1372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 /**
1374 * Used by views that contain lists of items. This state indicates that
1375 * the view is showing the last item.
1376 * @hide
1377 */
1378 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1379 /**
1380 * Used by views that contain lists of items. This state indicates that
1381 * the view is showing the first item.
1382 * @hide
1383 */
1384 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1385 /**
1386 * Used by views that contain lists of items. This state indicates that
1387 * the view is showing the middle item.
1388 * @hide
1389 */
1390 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1391 /**
1392 * Used by views that contain lists of items. This state indicates that
1393 * the view is showing only one item.
1394 * @hide
1395 */
1396 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1397 /**
1398 * Used by views that contain lists of items. This state indicates that
1399 * the view is pressed and showing the last item.
1400 * @hide
1401 */
1402 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1403 /**
1404 * Used by views that contain lists of items. This state indicates that
1405 * the view is pressed and showing the first item.
1406 * @hide
1407 */
1408 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1409 /**
1410 * Used by views that contain lists of items. This state indicates that
1411 * the view is pressed and showing the middle item.
1412 * @hide
1413 */
1414 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1415 /**
1416 * Used by views that contain lists of items. This state indicates that
1417 * the view is pressed and showing only one item.
1418 * @hide
1419 */
1420 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1421
1422 /**
1423 * Temporary Rect currently for use in setBackground(). This will probably
1424 * be extended in the future to hold our own class with more than just
1425 * a Rect. :)
1426 */
1427 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001428
1429 /**
1430 * Map used to store views' tags.
1431 */
1432 private static WeakHashMap<View, SparseArray<Object>> sTags;
1433
1434 /**
1435 * Lock used to access sTags.
1436 */
1437 private static final Object sTagsLock = new Object();
1438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 /**
1440 * The animation currently associated with this view.
1441 * @hide
1442 */
1443 protected Animation mCurrentAnimation = null;
1444
1445 /**
1446 * Width as measured during measure pass.
1447 * {@hide}
1448 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001449 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 protected int mMeasuredWidth;
1451
1452 /**
1453 * Height as measured during measure pass.
1454 * {@hide}
1455 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001456 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 protected int mMeasuredHeight;
1458
1459 /**
1460 * The view's identifier.
1461 * {@hide}
1462 *
1463 * @see #setId(int)
1464 * @see #getId()
1465 */
1466 @ViewDebug.ExportedProperty(resolveId = true)
1467 int mID = NO_ID;
1468
1469 /**
1470 * The view's tag.
1471 * {@hide}
1472 *
1473 * @see #setTag(Object)
1474 * @see #getTag()
1475 */
1476 protected Object mTag;
1477
1478 // for mPrivateFlags:
1479 /** {@hide} */
1480 static final int WANTS_FOCUS = 0x00000001;
1481 /** {@hide} */
1482 static final int FOCUSED = 0x00000002;
1483 /** {@hide} */
1484 static final int SELECTED = 0x00000004;
1485 /** {@hide} */
1486 static final int IS_ROOT_NAMESPACE = 0x00000008;
1487 /** {@hide} */
1488 static final int HAS_BOUNDS = 0x00000010;
1489 /** {@hide} */
1490 static final int DRAWN = 0x00000020;
1491 /**
1492 * When this flag is set, this view is running an animation on behalf of its
1493 * children and should therefore not cancel invalidate requests, even if they
1494 * lie outside of this view's bounds.
1495 *
1496 * {@hide}
1497 */
1498 static final int DRAW_ANIMATION = 0x00000040;
1499 /** {@hide} */
1500 static final int SKIP_DRAW = 0x00000080;
1501 /** {@hide} */
1502 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1503 /** {@hide} */
1504 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1505 /** {@hide} */
1506 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1507 /** {@hide} */
1508 static final int MEASURED_DIMENSION_SET = 0x00000800;
1509 /** {@hide} */
1510 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001511 /** {@hide} */
1512 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513
1514 private static final int PRESSED = 0x00004000;
1515
1516 /** {@hide} */
1517 static final int DRAWING_CACHE_VALID = 0x00008000;
1518 /**
1519 * Flag used to indicate that this view should be drawn once more (and only once
1520 * more) after its animation has completed.
1521 * {@hide}
1522 */
1523 static final int ANIMATION_STARTED = 0x00010000;
1524
1525 private static final int SAVE_STATE_CALLED = 0x00020000;
1526
1527 /**
1528 * Indicates that the View returned true when onSetAlpha() was called and that
1529 * the alpha must be restored.
1530 * {@hide}
1531 */
1532 static final int ALPHA_SET = 0x00040000;
1533
1534 /**
1535 * Set by {@link #setScrollContainer(boolean)}.
1536 */
1537 static final int SCROLL_CONTAINER = 0x00080000;
1538
1539 /**
1540 * Set by {@link #setScrollContainer(boolean)}.
1541 */
1542 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1543
1544 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001545 * View flag indicating whether this view was invalidated (fully or partially.)
1546 *
1547 * @hide
1548 */
1549 static final int DIRTY = 0x00200000;
1550
1551 /**
1552 * View flag indicating whether this view was invalidated by an opaque
1553 * invalidate request.
1554 *
1555 * @hide
1556 */
1557 static final int DIRTY_OPAQUE = 0x00400000;
1558
1559 /**
1560 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1561 *
1562 * @hide
1563 */
1564 static final int DIRTY_MASK = 0x00600000;
1565
1566 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001567 * Indicates whether the background is opaque.
1568 *
1569 * @hide
1570 */
1571 static final int OPAQUE_BACKGROUND = 0x00800000;
1572
1573 /**
1574 * Indicates whether the scrollbars are opaque.
1575 *
1576 * @hide
1577 */
1578 static final int OPAQUE_SCROLLBARS = 0x01000000;
1579
1580 /**
1581 * Indicates whether the view is opaque.
1582 *
1583 * @hide
1584 */
1585 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001586
1587 /**
1588 * Indicates a prepressed state;
1589 * the short time between ACTION_DOWN and recognizing
1590 * a 'real' press. Prepressed is used to recognize quick taps
1591 * even when they are shorter than ViewConfiguration.getTapTimeout().
1592 *
1593 * @hide
1594 */
1595 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001596
1597 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001598 * Indicates whether the view is temporarily detached.
1599 *
1600 * @hide
1601 */
1602 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001603
1604 /**
1605 * Indicates that we should awaken scroll bars once attached
1606 *
1607 * @hide
1608 */
1609 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001610
1611 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001612 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1613 * for transform operations
1614 *
1615 * @hide
1616 */
Adam Powellf37df072010-09-17 16:22:49 -07001617 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001618
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001619 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001620 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001621
Chet Haasefd2b0022010-08-06 13:08:56 -07001622 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 * The parent this view is attached to.
1624 * {@hide}
1625 *
1626 * @see #getParent()
1627 */
1628 protected ViewParent mParent;
1629
1630 /**
1631 * {@hide}
1632 */
1633 AttachInfo mAttachInfo;
1634
1635 /**
1636 * {@hide}
1637 */
Romain Guy809a7f62009-05-14 15:44:42 -07001638 @ViewDebug.ExportedProperty(flagMapping = {
1639 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1640 name = "FORCE_LAYOUT"),
1641 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1642 name = "LAYOUT_REQUIRED"),
1643 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001644 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001645 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1646 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1647 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1648 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1649 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 int mPrivateFlags;
1651
1652 /**
1653 * Count of how many windows this view has been attached to.
1654 */
1655 int mWindowAttachCount;
1656
1657 /**
1658 * The layout parameters associated with this view and used by the parent
1659 * {@link android.view.ViewGroup} to determine how this view should be
1660 * laid out.
1661 * {@hide}
1662 */
1663 protected ViewGroup.LayoutParams mLayoutParams;
1664
1665 /**
1666 * The view flags hold various views states.
1667 * {@hide}
1668 */
1669 @ViewDebug.ExportedProperty
1670 int mViewFlags;
1671
1672 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001673 * The transform matrix for the View. This transform is calculated internally
1674 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1675 * is used by default. Do *not* use this variable directly; instead call
1676 * getMatrix(), which will automatically recalculate the matrix if necessary
1677 * to get the correct matrix based on the latest rotation and scale properties.
1678 */
1679 private final Matrix mMatrix = new Matrix();
1680
1681 /**
1682 * The transform matrix for the View. This transform is calculated internally
1683 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1684 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001685 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001686 * to get the correct matrix based on the latest rotation and scale properties.
1687 */
1688 private Matrix mInverseMatrix;
1689
1690 /**
1691 * An internal variable that tracks whether we need to recalculate the
1692 * transform matrix, based on whether the rotation or scaleX/Y properties
1693 * have changed since the matrix was last calculated.
1694 */
1695 private boolean mMatrixDirty = false;
1696
1697 /**
1698 * An internal variable that tracks whether we need to recalculate the
1699 * transform matrix, based on whether the rotation or scaleX/Y properties
1700 * have changed since the matrix was last calculated.
1701 */
1702 private boolean mInverseMatrixDirty = true;
1703
1704 /**
1705 * A variable that tracks whether we need to recalculate the
1706 * transform matrix, based on whether the rotation or scaleX/Y properties
1707 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001708 * is only valid after a call to updateMatrix() or to a function that
1709 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001710 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001711 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001712
1713 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001714 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1715 */
1716 private Camera mCamera = null;
1717
1718 /**
1719 * This matrix is used when computing the matrix for 3D rotations.
1720 */
1721 private Matrix matrix3D = null;
1722
1723 /**
1724 * These prev values are used to recalculate a centered pivot point when necessary. The
1725 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1726 * set), so thes values are only used then as well.
1727 */
1728 private int mPrevWidth = -1;
1729 private int mPrevHeight = -1;
1730
1731 /**
1732 * Convenience value to check for float values that are close enough to zero to be considered
1733 * zero.
1734 */
Romain Guy2542d192010-08-18 11:47:12 -07001735 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001736
1737 /**
1738 * The degrees rotation around the vertical axis through the pivot point.
1739 */
1740 @ViewDebug.ExportedProperty
1741 private float mRotationY = 0f;
1742
1743 /**
1744 * The degrees rotation around the horizontal axis through the pivot point.
1745 */
1746 @ViewDebug.ExportedProperty
1747 private float mRotationX = 0f;
1748
1749 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001750 * The degrees rotation around the pivot point.
1751 */
1752 @ViewDebug.ExportedProperty
1753 private float mRotation = 0f;
1754
1755 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001756 * The amount of translation of the object away from its left property (post-layout).
1757 */
1758 @ViewDebug.ExportedProperty
1759 private float mTranslationX = 0f;
1760
1761 /**
1762 * The amount of translation of the object away from its top property (post-layout).
1763 */
1764 @ViewDebug.ExportedProperty
1765 private float mTranslationY = 0f;
1766
1767 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001768 * The amount of scale in the x direction around the pivot point. A
1769 * value of 1 means no scaling is applied.
1770 */
1771 @ViewDebug.ExportedProperty
1772 private float mScaleX = 1f;
1773
1774 /**
1775 * The amount of scale in the y direction around the pivot point. A
1776 * value of 1 means no scaling is applied.
1777 */
1778 @ViewDebug.ExportedProperty
1779 private float mScaleY = 1f;
1780
1781 /**
1782 * The amount of scale in the x direction around the pivot point. A
1783 * value of 1 means no scaling is applied.
1784 */
1785 @ViewDebug.ExportedProperty
1786 private float mPivotX = 0f;
1787
1788 /**
1789 * The amount of scale in the y direction around the pivot point. A
1790 * value of 1 means no scaling is applied.
1791 */
1792 @ViewDebug.ExportedProperty
1793 private float mPivotY = 0f;
1794
1795 /**
1796 * The opacity of the View. This is a value from 0 to 1, where 0 means
1797 * completely transparent and 1 means completely opaque.
1798 */
1799 @ViewDebug.ExportedProperty
1800 private float mAlpha = 1f;
1801
1802 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 * The distance in pixels from the left edge of this view's parent
1804 * to the left edge of this view.
1805 * {@hide}
1806 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001807 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 protected int mLeft;
1809 /**
1810 * The distance in pixels from the left edge of this view's parent
1811 * to the right edge of this view.
1812 * {@hide}
1813 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001814 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 protected int mRight;
1816 /**
1817 * The distance in pixels from the top edge of this view's parent
1818 * to the top edge of this view.
1819 * {@hide}
1820 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001821 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 protected int mTop;
1823 /**
1824 * The distance in pixels from the top edge of this view's parent
1825 * to the bottom edge of this view.
1826 * {@hide}
1827 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001828 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 protected int mBottom;
1830
1831 /**
1832 * The offset, in pixels, by which the content of this view is scrolled
1833 * horizontally.
1834 * {@hide}
1835 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001836 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 protected int mScrollX;
1838 /**
1839 * The offset, in pixels, by which the content of this view is scrolled
1840 * vertically.
1841 * {@hide}
1842 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001843 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 protected int mScrollY;
1845
1846 /**
1847 * The left padding in pixels, that is the distance in pixels between the
1848 * left edge of this view and the left edge of its content.
1849 * {@hide}
1850 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001851 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 protected int mPaddingLeft;
1853 /**
1854 * The right padding in pixels, that is the distance in pixels between the
1855 * right edge of this view and the right edge of its content.
1856 * {@hide}
1857 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001858 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 protected int mPaddingRight;
1860 /**
1861 * The top padding in pixels, that is the distance in pixels between the
1862 * top edge of this view and the top edge of its content.
1863 * {@hide}
1864 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001865 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 protected int mPaddingTop;
1867 /**
1868 * The bottom padding in pixels, that is the distance in pixels between the
1869 * bottom edge of this view and the bottom edge of its content.
1870 * {@hide}
1871 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001872 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 protected int mPaddingBottom;
1874
1875 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001876 * Briefly describes the view and is primarily used for accessibility support.
1877 */
1878 private CharSequence mContentDescription;
1879
1880 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 * Cache the paddingRight set by the user to append to the scrollbar's size.
1882 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001883 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 int mUserPaddingRight;
1885
1886 /**
1887 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1888 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001889 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 int mUserPaddingBottom;
1891
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001892 /**
1893 * @hide
1894 */
1895 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1896 /**
1897 * @hide
1898 */
1899 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900
1901 private Resources mResources = null;
1902
1903 private Drawable mBGDrawable;
1904
1905 private int mBackgroundResource;
1906 private boolean mBackgroundSizeChanged;
1907
1908 /**
1909 * Listener used to dispatch focus change events.
1910 * This field should be made private, so it is hidden from the SDK.
1911 * {@hide}
1912 */
1913 protected OnFocusChangeListener mOnFocusChangeListener;
1914
1915 /**
Chet Haase21cd1382010-09-01 17:42:29 -07001916 * Listeners for layout change events.
1917 */
1918 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
1919
1920 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 * Listener used to dispatch click events.
1922 * This field should be made private, so it is hidden from the SDK.
1923 * {@hide}
1924 */
1925 protected OnClickListener mOnClickListener;
1926
1927 /**
1928 * Listener used to dispatch long click events.
1929 * This field should be made private, so it is hidden from the SDK.
1930 * {@hide}
1931 */
1932 protected OnLongClickListener mOnLongClickListener;
1933
1934 /**
1935 * Listener used to build the context menu.
1936 * This field should be made private, so it is hidden from the SDK.
1937 * {@hide}
1938 */
1939 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
1940
1941 private OnKeyListener mOnKeyListener;
1942
1943 private OnTouchListener mOnTouchListener;
1944
1945 /**
1946 * The application environment this view lives in.
1947 * This field should be made private, so it is hidden from the SDK.
1948 * {@hide}
1949 */
1950 protected Context mContext;
1951
1952 private ScrollabilityCache mScrollCache;
1953
1954 private int[] mDrawableState = null;
1955
Romain Guy02890fd2010-08-06 17:58:44 -07001956 private Bitmap mDrawingCache;
1957 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07001958 private DisplayList mDisplayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959
1960 /**
1961 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
1962 * the user may specify which view to go to next.
1963 */
1964 private int mNextFocusLeftId = View.NO_ID;
1965
1966 /**
1967 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
1968 * the user may specify which view to go to next.
1969 */
1970 private int mNextFocusRightId = View.NO_ID;
1971
1972 /**
1973 * When this view has focus and the next focus is {@link #FOCUS_UP},
1974 * the user may specify which view to go to next.
1975 */
1976 private int mNextFocusUpId = View.NO_ID;
1977
1978 /**
1979 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
1980 * the user may specify which view to go to next.
1981 */
1982 private int mNextFocusDownId = View.NO_ID;
1983
1984 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08001985 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08001986 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08001987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 private UnsetPressedState mUnsetPressedState;
1989
1990 /**
1991 * Whether the long press's action has been invoked. The tap's action is invoked on the
1992 * up event while a long press is invoked as soon as the long press duration is reached, so
1993 * a long press could be performed before the tap is checked, in which case the tap's action
1994 * should not be invoked.
1995 */
1996 private boolean mHasPerformedLongPress;
1997
1998 /**
1999 * The minimum height of the view. We'll try our best to have the height
2000 * of this view to at least this amount.
2001 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002002 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 private int mMinHeight;
2004
2005 /**
2006 * The minimum width of the view. We'll try our best to have the width
2007 * of this view to at least this amount.
2008 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002009 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 private int mMinWidth;
2011
2012 /**
2013 * The delegate to handle touch events that are physically in this view
2014 * but should be handled by another view.
2015 */
2016 private TouchDelegate mTouchDelegate = null;
2017
2018 /**
2019 * Solid color to use as a background when creating the drawing cache. Enables
2020 * the cache to use 16 bit bitmaps instead of 32 bit.
2021 */
2022 private int mDrawingCacheBackgroundColor = 0;
2023
2024 /**
2025 * Special tree observer used when mAttachInfo is null.
2026 */
2027 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002028
2029 /**
2030 * Cache the touch slop from the context that created the view.
2031 */
2032 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002035 * Cache drag/drop state
2036 *
2037 */
2038 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002039 private int mThumbnailWidth;
2040 private int mThumbnailHeight;
2041
2042 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 * Simple constructor to use when creating a view from code.
2044 *
2045 * @param context The Context the view is running in, through which it can
2046 * access the current theme, resources, etc.
2047 */
2048 public View(Context context) {
2049 mContext = context;
2050 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002051 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002052 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
2054
2055 /**
2056 * Constructor that is called when inflating a view from XML. This is called
2057 * when a view is being constructed from an XML file, supplying attributes
2058 * that were specified in the XML file. This version uses a default style of
2059 * 0, so the only attribute values applied are those in the Context's Theme
2060 * and the given AttributeSet.
2061 *
2062 * <p>
2063 * The method onFinishInflate() will be called after all children have been
2064 * added.
2065 *
2066 * @param context The Context the view is running in, through which it can
2067 * access the current theme, resources, etc.
2068 * @param attrs The attributes of the XML tag that is inflating the view.
2069 * @see #View(Context, AttributeSet, int)
2070 */
2071 public View(Context context, AttributeSet attrs) {
2072 this(context, attrs, 0);
2073 }
2074
2075 /**
2076 * Perform inflation from XML and apply a class-specific base style. This
2077 * constructor of View allows subclasses to use their own base style when
2078 * they are inflating. For example, a Button class's constructor would call
2079 * this version of the super class constructor and supply
2080 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2081 * the theme's button style to modify all of the base view attributes (in
2082 * particular its background) as well as the Button class's attributes.
2083 *
2084 * @param context The Context the view is running in, through which it can
2085 * access the current theme, resources, etc.
2086 * @param attrs The attributes of the XML tag that is inflating the view.
2087 * @param defStyle The default style to apply to this view. If 0, no style
2088 * will be applied (beyond what is included in the theme). This may
2089 * either be an attribute resource, whose value will be retrieved
2090 * from the current theme, or an explicit style resource.
2091 * @see #View(Context, AttributeSet)
2092 */
2093 public View(Context context, AttributeSet attrs, int defStyle) {
2094 this(context);
2095
2096 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2097 defStyle, 0);
2098
2099 Drawable background = null;
2100
2101 int leftPadding = -1;
2102 int topPadding = -1;
2103 int rightPadding = -1;
2104 int bottomPadding = -1;
2105
2106 int padding = -1;
2107
2108 int viewFlagValues = 0;
2109 int viewFlagMasks = 0;
2110
2111 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 int x = 0;
2114 int y = 0;
2115
2116 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2117
2118 final int N = a.getIndexCount();
2119 for (int i = 0; i < N; i++) {
2120 int attr = a.getIndex(i);
2121 switch (attr) {
2122 case com.android.internal.R.styleable.View_background:
2123 background = a.getDrawable(attr);
2124 break;
2125 case com.android.internal.R.styleable.View_padding:
2126 padding = a.getDimensionPixelSize(attr, -1);
2127 break;
2128 case com.android.internal.R.styleable.View_paddingLeft:
2129 leftPadding = a.getDimensionPixelSize(attr, -1);
2130 break;
2131 case com.android.internal.R.styleable.View_paddingTop:
2132 topPadding = a.getDimensionPixelSize(attr, -1);
2133 break;
2134 case com.android.internal.R.styleable.View_paddingRight:
2135 rightPadding = a.getDimensionPixelSize(attr, -1);
2136 break;
2137 case com.android.internal.R.styleable.View_paddingBottom:
2138 bottomPadding = a.getDimensionPixelSize(attr, -1);
2139 break;
2140 case com.android.internal.R.styleable.View_scrollX:
2141 x = a.getDimensionPixelOffset(attr, 0);
2142 break;
2143 case com.android.internal.R.styleable.View_scrollY:
2144 y = a.getDimensionPixelOffset(attr, 0);
2145 break;
2146 case com.android.internal.R.styleable.View_id:
2147 mID = a.getResourceId(attr, NO_ID);
2148 break;
2149 case com.android.internal.R.styleable.View_tag:
2150 mTag = a.getText(attr);
2151 break;
2152 case com.android.internal.R.styleable.View_fitsSystemWindows:
2153 if (a.getBoolean(attr, false)) {
2154 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2155 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2156 }
2157 break;
2158 case com.android.internal.R.styleable.View_focusable:
2159 if (a.getBoolean(attr, false)) {
2160 viewFlagValues |= FOCUSABLE;
2161 viewFlagMasks |= FOCUSABLE_MASK;
2162 }
2163 break;
2164 case com.android.internal.R.styleable.View_focusableInTouchMode:
2165 if (a.getBoolean(attr, false)) {
2166 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2167 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2168 }
2169 break;
2170 case com.android.internal.R.styleable.View_clickable:
2171 if (a.getBoolean(attr, false)) {
2172 viewFlagValues |= CLICKABLE;
2173 viewFlagMasks |= CLICKABLE;
2174 }
2175 break;
2176 case com.android.internal.R.styleable.View_longClickable:
2177 if (a.getBoolean(attr, false)) {
2178 viewFlagValues |= LONG_CLICKABLE;
2179 viewFlagMasks |= LONG_CLICKABLE;
2180 }
2181 break;
2182 case com.android.internal.R.styleable.View_saveEnabled:
2183 if (!a.getBoolean(attr, true)) {
2184 viewFlagValues |= SAVE_DISABLED;
2185 viewFlagMasks |= SAVE_DISABLED_MASK;
2186 }
2187 break;
2188 case com.android.internal.R.styleable.View_duplicateParentState:
2189 if (a.getBoolean(attr, false)) {
2190 viewFlagValues |= DUPLICATE_PARENT_STATE;
2191 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2192 }
2193 break;
2194 case com.android.internal.R.styleable.View_visibility:
2195 final int visibility = a.getInt(attr, 0);
2196 if (visibility != 0) {
2197 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2198 viewFlagMasks |= VISIBILITY_MASK;
2199 }
2200 break;
2201 case com.android.internal.R.styleable.View_drawingCacheQuality:
2202 final int cacheQuality = a.getInt(attr, 0);
2203 if (cacheQuality != 0) {
2204 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2205 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2206 }
2207 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002208 case com.android.internal.R.styleable.View_contentDescription:
2209 mContentDescription = a.getString(attr);
2210 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2212 if (!a.getBoolean(attr, true)) {
2213 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2214 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2215 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002216 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2218 if (!a.getBoolean(attr, true)) {
2219 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2220 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2221 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002222 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 case R.styleable.View_scrollbars:
2224 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2225 if (scrollbars != SCROLLBARS_NONE) {
2226 viewFlagValues |= scrollbars;
2227 viewFlagMasks |= SCROLLBARS_MASK;
2228 initializeScrollbars(a);
2229 }
2230 break;
2231 case R.styleable.View_fadingEdge:
2232 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2233 if (fadingEdge != FADING_EDGE_NONE) {
2234 viewFlagValues |= fadingEdge;
2235 viewFlagMasks |= FADING_EDGE_MASK;
2236 initializeFadingEdge(a);
2237 }
2238 break;
2239 case R.styleable.View_scrollbarStyle:
2240 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2241 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2242 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2243 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2244 }
2245 break;
2246 case R.styleable.View_isScrollContainer:
2247 setScrollContainer = true;
2248 if (a.getBoolean(attr, false)) {
2249 setScrollContainer(true);
2250 }
2251 break;
2252 case com.android.internal.R.styleable.View_keepScreenOn:
2253 if (a.getBoolean(attr, false)) {
2254 viewFlagValues |= KEEP_SCREEN_ON;
2255 viewFlagMasks |= KEEP_SCREEN_ON;
2256 }
2257 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002258 case R.styleable.View_filterTouchesWhenObscured:
2259 if (a.getBoolean(attr, false)) {
2260 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2261 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2262 }
2263 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 case R.styleable.View_nextFocusLeft:
2265 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2266 break;
2267 case R.styleable.View_nextFocusRight:
2268 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2269 break;
2270 case R.styleable.View_nextFocusUp:
2271 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2272 break;
2273 case R.styleable.View_nextFocusDown:
2274 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2275 break;
2276 case R.styleable.View_minWidth:
2277 mMinWidth = a.getDimensionPixelSize(attr, 0);
2278 break;
2279 case R.styleable.View_minHeight:
2280 mMinHeight = a.getDimensionPixelSize(attr, 0);
2281 break;
Romain Guy9a817362009-05-01 10:57:14 -07002282 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002283 if (context.isRestricted()) {
2284 throw new IllegalStateException("The android:onClick attribute cannot "
2285 + "be used within a restricted context");
2286 }
2287
Romain Guy9a817362009-05-01 10:57:14 -07002288 final String handlerName = a.getString(attr);
2289 if (handlerName != null) {
2290 setOnClickListener(new OnClickListener() {
2291 private Method mHandler;
2292
2293 public void onClick(View v) {
2294 if (mHandler == null) {
2295 try {
2296 mHandler = getContext().getClass().getMethod(handlerName,
2297 View.class);
2298 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002299 int id = getId();
2300 String idText = id == NO_ID ? "" : " with id '"
2301 + getContext().getResources().getResourceEntryName(
2302 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002303 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002304 handlerName + "(View) in the activity "
2305 + getContext().getClass() + " for onClick handler"
2306 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002307 }
2308 }
2309
2310 try {
2311 mHandler.invoke(getContext(), View.this);
2312 } catch (IllegalAccessException e) {
2313 throw new IllegalStateException("Could not execute non "
2314 + "public method of the activity", e);
2315 } catch (InvocationTargetException e) {
2316 throw new IllegalStateException("Could not execute "
2317 + "method of the activity", e);
2318 }
2319 }
2320 });
2321 }
2322 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 }
2324 }
2325
2326 if (background != null) {
2327 setBackgroundDrawable(background);
2328 }
2329
2330 if (padding >= 0) {
2331 leftPadding = padding;
2332 topPadding = padding;
2333 rightPadding = padding;
2334 bottomPadding = padding;
2335 }
2336
2337 // If the user specified the padding (either with android:padding or
2338 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2339 // use the default padding or the padding from the background drawable
2340 // (stored at this point in mPadding*)
2341 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2342 topPadding >= 0 ? topPadding : mPaddingTop,
2343 rightPadding >= 0 ? rightPadding : mPaddingRight,
2344 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2345
2346 if (viewFlagMasks != 0) {
2347 setFlags(viewFlagValues, viewFlagMasks);
2348 }
2349
2350 // Needs to be called after mViewFlags is set
2351 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2352 recomputePadding();
2353 }
2354
2355 if (x != 0 || y != 0) {
2356 scrollTo(x, y);
2357 }
2358
2359 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2360 setScrollContainer(true);
2361 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002362
2363 computeOpaqueFlags();
2364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 a.recycle();
2366 }
2367
2368 /**
2369 * Non-public constructor for use in testing
2370 */
2371 View() {
2372 }
2373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 /**
2375 * <p>
2376 * Initializes the fading edges from a given set of styled attributes. This
2377 * method should be called by subclasses that need fading edges and when an
2378 * instance of these subclasses is created programmatically rather than
2379 * being inflated from XML. This method is automatically called when the XML
2380 * is inflated.
2381 * </p>
2382 *
2383 * @param a the styled attributes set to initialize the fading edges from
2384 */
2385 protected void initializeFadingEdge(TypedArray a) {
2386 initScrollCache();
2387
2388 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2389 R.styleable.View_fadingEdgeLength,
2390 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2391 }
2392
2393 /**
2394 * Returns the size of the vertical faded edges used to indicate that more
2395 * content in this view is visible.
2396 *
2397 * @return The size in pixels of the vertical faded edge or 0 if vertical
2398 * faded edges are not enabled for this view.
2399 * @attr ref android.R.styleable#View_fadingEdgeLength
2400 */
2401 public int getVerticalFadingEdgeLength() {
2402 if (isVerticalFadingEdgeEnabled()) {
2403 ScrollabilityCache cache = mScrollCache;
2404 if (cache != null) {
2405 return cache.fadingEdgeLength;
2406 }
2407 }
2408 return 0;
2409 }
2410
2411 /**
2412 * Set the size of the faded edge used to indicate that more content in this
2413 * view is available. Will not change whether the fading edge is enabled; use
2414 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2415 * to enable the fading edge for the vertical or horizontal fading edges.
2416 *
2417 * @param length The size in pixels of the faded edge used to indicate that more
2418 * content in this view is visible.
2419 */
2420 public void setFadingEdgeLength(int length) {
2421 initScrollCache();
2422 mScrollCache.fadingEdgeLength = length;
2423 }
2424
2425 /**
2426 * Returns the size of the horizontal faded edges used to indicate that more
2427 * content in this view is visible.
2428 *
2429 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2430 * faded edges are not enabled for this view.
2431 * @attr ref android.R.styleable#View_fadingEdgeLength
2432 */
2433 public int getHorizontalFadingEdgeLength() {
2434 if (isHorizontalFadingEdgeEnabled()) {
2435 ScrollabilityCache cache = mScrollCache;
2436 if (cache != null) {
2437 return cache.fadingEdgeLength;
2438 }
2439 }
2440 return 0;
2441 }
2442
2443 /**
2444 * Returns the width of the vertical scrollbar.
2445 *
2446 * @return The width in pixels of the vertical scrollbar or 0 if there
2447 * is no vertical scrollbar.
2448 */
2449 public int getVerticalScrollbarWidth() {
2450 ScrollabilityCache cache = mScrollCache;
2451 if (cache != null) {
2452 ScrollBarDrawable scrollBar = cache.scrollBar;
2453 if (scrollBar != null) {
2454 int size = scrollBar.getSize(true);
2455 if (size <= 0) {
2456 size = cache.scrollBarSize;
2457 }
2458 return size;
2459 }
2460 return 0;
2461 }
2462 return 0;
2463 }
2464
2465 /**
2466 * Returns the height of the horizontal scrollbar.
2467 *
2468 * @return The height in pixels of the horizontal scrollbar or 0 if
2469 * there is no horizontal scrollbar.
2470 */
2471 protected int getHorizontalScrollbarHeight() {
2472 ScrollabilityCache cache = mScrollCache;
2473 if (cache != null) {
2474 ScrollBarDrawable scrollBar = cache.scrollBar;
2475 if (scrollBar != null) {
2476 int size = scrollBar.getSize(false);
2477 if (size <= 0) {
2478 size = cache.scrollBarSize;
2479 }
2480 return size;
2481 }
2482 return 0;
2483 }
2484 return 0;
2485 }
2486
2487 /**
2488 * <p>
2489 * Initializes the scrollbars from a given set of styled attributes. This
2490 * method should be called by subclasses that need scrollbars and when an
2491 * instance of these subclasses is created programmatically rather than
2492 * being inflated from XML. This method is automatically called when the XML
2493 * is inflated.
2494 * </p>
2495 *
2496 * @param a the styled attributes set to initialize the scrollbars from
2497 */
2498 protected void initializeScrollbars(TypedArray a) {
2499 initScrollCache();
2500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002502
2503 if (scrollabilityCache.scrollBar == null) {
2504 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2505 }
2506
Romain Guy8bda2482010-03-02 11:42:11 -08002507 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508
Mike Cleronf116bf82009-09-27 19:14:12 -07002509 if (!fadeScrollbars) {
2510 scrollabilityCache.state = ScrollabilityCache.ON;
2511 }
2512 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2513
2514
2515 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2516 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2517 .getScrollBarFadeDuration());
2518 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2519 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2520 ViewConfiguration.getScrollDefaultDelay());
2521
2522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2524 com.android.internal.R.styleable.View_scrollbarSize,
2525 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2526
2527 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2528 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2529
2530 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2531 if (thumb != null) {
2532 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2533 }
2534
2535 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2536 false);
2537 if (alwaysDraw) {
2538 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2539 }
2540
2541 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2542 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2543
2544 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2545 if (thumb != null) {
2546 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2547 }
2548
2549 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2550 false);
2551 if (alwaysDraw) {
2552 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2553 }
2554
2555 // Re-apply user/background padding so that scrollbar(s) get added
2556 recomputePadding();
2557 }
2558
2559 /**
2560 * <p>
2561 * Initalizes the scrollability cache if necessary.
2562 * </p>
2563 */
2564 private void initScrollCache() {
2565 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002566 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 }
2568 }
2569
2570 /**
2571 * Register a callback to be invoked when focus of this view changed.
2572 *
2573 * @param l The callback that will run.
2574 */
2575 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2576 mOnFocusChangeListener = l;
2577 }
2578
2579 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002580 * Add a listener that will be called when the bounds of the view change due to
2581 * layout processing.
2582 *
2583 * @param listener The listener that will be called when layout bounds change.
2584 */
2585 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2586 if (mOnLayoutChangeListeners == null) {
2587 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2588 }
2589 mOnLayoutChangeListeners.add(listener);
2590 }
2591
2592 /**
2593 * Remove a listener for layout changes.
2594 *
2595 * @param listener The listener for layout bounds change.
2596 */
2597 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2598 if (mOnLayoutChangeListeners == null) {
2599 return;
2600 }
2601 mOnLayoutChangeListeners.remove(listener);
2602 }
2603
2604 /**
2605 * Gets the current list of listeners for layout changes.
2606 * @return
2607 */
2608 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2609 return mOnLayoutChangeListeners;
2610 }
2611
2612 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 * Returns the focus-change callback registered for this view.
2614 *
2615 * @return The callback, or null if one is not registered.
2616 */
2617 public OnFocusChangeListener getOnFocusChangeListener() {
2618 return mOnFocusChangeListener;
2619 }
2620
2621 /**
2622 * Register a callback to be invoked when this view is clicked. If this view is not
2623 * clickable, it becomes clickable.
2624 *
2625 * @param l The callback that will run
2626 *
2627 * @see #setClickable(boolean)
2628 */
2629 public void setOnClickListener(OnClickListener l) {
2630 if (!isClickable()) {
2631 setClickable(true);
2632 }
2633 mOnClickListener = l;
2634 }
2635
2636 /**
2637 * Register a callback to be invoked when this view is clicked and held. If this view is not
2638 * long clickable, it becomes long clickable.
2639 *
2640 * @param l The callback that will run
2641 *
2642 * @see #setLongClickable(boolean)
2643 */
2644 public void setOnLongClickListener(OnLongClickListener l) {
2645 if (!isLongClickable()) {
2646 setLongClickable(true);
2647 }
2648 mOnLongClickListener = l;
2649 }
2650
2651 /**
2652 * Register a callback to be invoked when the context menu for this view is
2653 * being built. If this view is not long clickable, it becomes long clickable.
2654 *
2655 * @param l The callback that will run
2656 *
2657 */
2658 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2659 if (!isLongClickable()) {
2660 setLongClickable(true);
2661 }
2662 mOnCreateContextMenuListener = l;
2663 }
2664
2665 /**
2666 * Call this view's OnClickListener, if it is defined.
2667 *
2668 * @return True there was an assigned OnClickListener that was called, false
2669 * otherwise is returned.
2670 */
2671 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002672 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 if (mOnClickListener != null) {
2675 playSoundEffect(SoundEffectConstants.CLICK);
2676 mOnClickListener.onClick(this);
2677 return true;
2678 }
2679
2680 return false;
2681 }
2682
2683 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002684 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2685 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002687 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 */
2689 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002690 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 boolean handled = false;
2693 if (mOnLongClickListener != null) {
2694 handled = mOnLongClickListener.onLongClick(View.this);
2695 }
2696 if (!handled) {
2697 handled = showContextMenu();
2698 }
2699 if (handled) {
2700 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2701 }
2702 return handled;
2703 }
2704
2705 /**
2706 * Bring up the context menu for this view.
2707 *
2708 * @return Whether a context menu was displayed.
2709 */
2710 public boolean showContextMenu() {
2711 return getParent().showContextMenuForChild(this);
2712 }
2713
2714 /**
Adam Powell6e346362010-07-23 10:18:23 -07002715 * Start an action mode.
2716 *
2717 * @param callback Callback that will control the lifecycle of the action mode
2718 * @return The new action mode if it is started, null otherwise
2719 *
2720 * @see ActionMode
2721 */
2722 public ActionMode startActionMode(ActionMode.Callback callback) {
2723 return getParent().startActionModeForChild(this, callback);
2724 }
2725
2726 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 * Register a callback to be invoked when a key is pressed in this view.
2728 * @param l the key listener to attach to this view
2729 */
2730 public void setOnKeyListener(OnKeyListener l) {
2731 mOnKeyListener = l;
2732 }
2733
2734 /**
2735 * Register a callback to be invoked when a touch event is sent to this view.
2736 * @param l the touch listener to attach to this view
2737 */
2738 public void setOnTouchListener(OnTouchListener l) {
2739 mOnTouchListener = l;
2740 }
2741
2742 /**
2743 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2744 *
2745 * Note: this does not check whether this {@link View} should get focus, it just
2746 * gives it focus no matter what. It should only be called internally by framework
2747 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2748 *
2749 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2750 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2751 * focus moved when requestFocus() is called. It may not always
2752 * apply, in which case use the default View.FOCUS_DOWN.
2753 * @param previouslyFocusedRect The rectangle of the view that had focus
2754 * prior in this View's coordinate system.
2755 */
2756 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2757 if (DBG) {
2758 System.out.println(this + " requestFocus()");
2759 }
2760
2761 if ((mPrivateFlags & FOCUSED) == 0) {
2762 mPrivateFlags |= FOCUSED;
2763
2764 if (mParent != null) {
2765 mParent.requestChildFocus(this, this);
2766 }
2767
2768 onFocusChanged(true, direction, previouslyFocusedRect);
2769 refreshDrawableState();
2770 }
2771 }
2772
2773 /**
2774 * Request that a rectangle of this view be visible on the screen,
2775 * scrolling if necessary just enough.
2776 *
2777 * <p>A View should call this if it maintains some notion of which part
2778 * of its content is interesting. For example, a text editing view
2779 * should call this when its cursor moves.
2780 *
2781 * @param rectangle The rectangle.
2782 * @return Whether any parent scrolled.
2783 */
2784 public boolean requestRectangleOnScreen(Rect rectangle) {
2785 return requestRectangleOnScreen(rectangle, false);
2786 }
2787
2788 /**
2789 * Request that a rectangle of this view be visible on the screen,
2790 * scrolling if necessary just enough.
2791 *
2792 * <p>A View should call this if it maintains some notion of which part
2793 * of its content is interesting. For example, a text editing view
2794 * should call this when its cursor moves.
2795 *
2796 * <p>When <code>immediate</code> is set to true, scrolling will not be
2797 * animated.
2798 *
2799 * @param rectangle The rectangle.
2800 * @param immediate True to forbid animated scrolling, false otherwise
2801 * @return Whether any parent scrolled.
2802 */
2803 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
2804 View child = this;
2805 ViewParent parent = mParent;
2806 boolean scrolled = false;
2807 while (parent != null) {
2808 scrolled |= parent.requestChildRectangleOnScreen(child,
2809 rectangle, immediate);
2810
2811 // offset rect so next call has the rectangle in the
2812 // coordinate system of its direct child.
2813 rectangle.offset(child.getLeft(), child.getTop());
2814 rectangle.offset(-child.getScrollX(), -child.getScrollY());
2815
2816 if (!(parent instanceof View)) {
2817 break;
2818 }
Romain Guy8506ab42009-06-11 17:35:47 -07002819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 child = (View) parent;
2821 parent = child.getParent();
2822 }
2823 return scrolled;
2824 }
2825
2826 /**
2827 * Called when this view wants to give up focus. This will cause
2828 * {@link #onFocusChanged} to be called.
2829 */
2830 public void clearFocus() {
2831 if (DBG) {
2832 System.out.println(this + " clearFocus()");
2833 }
2834
2835 if ((mPrivateFlags & FOCUSED) != 0) {
2836 mPrivateFlags &= ~FOCUSED;
2837
2838 if (mParent != null) {
2839 mParent.clearChildFocus(this);
2840 }
2841
2842 onFocusChanged(false, 0, null);
2843 refreshDrawableState();
2844 }
2845 }
2846
2847 /**
2848 * Called to clear the focus of a view that is about to be removed.
2849 * Doesn't call clearChildFocus, which prevents this view from taking
2850 * focus again before it has been removed from the parent
2851 */
2852 void clearFocusForRemoval() {
2853 if ((mPrivateFlags & FOCUSED) != 0) {
2854 mPrivateFlags &= ~FOCUSED;
2855
2856 onFocusChanged(false, 0, null);
2857 refreshDrawableState();
2858 }
2859 }
2860
2861 /**
2862 * Called internally by the view system when a new view is getting focus.
2863 * This is what clears the old focus.
2864 */
2865 void unFocus() {
2866 if (DBG) {
2867 System.out.println(this + " unFocus()");
2868 }
2869
2870 if ((mPrivateFlags & FOCUSED) != 0) {
2871 mPrivateFlags &= ~FOCUSED;
2872
2873 onFocusChanged(false, 0, null);
2874 refreshDrawableState();
2875 }
2876 }
2877
2878 /**
2879 * Returns true if this view has focus iteself, or is the ancestor of the
2880 * view that has focus.
2881 *
2882 * @return True if this view has or contains focus, false otherwise.
2883 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002884 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 public boolean hasFocus() {
2886 return (mPrivateFlags & FOCUSED) != 0;
2887 }
2888
2889 /**
2890 * Returns true if this view is focusable or if it contains a reachable View
2891 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
2892 * is a View whose parents do not block descendants focus.
2893 *
2894 * Only {@link #VISIBLE} views are considered focusable.
2895 *
2896 * @return True if the view is focusable or if the view contains a focusable
2897 * View, false otherwise.
2898 *
2899 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
2900 */
2901 public boolean hasFocusable() {
2902 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
2903 }
2904
2905 /**
2906 * Called by the view system when the focus state of this view changes.
2907 * When the focus change event is caused by directional navigation, direction
2908 * and previouslyFocusedRect provide insight into where the focus is coming from.
2909 * When overriding, be sure to call up through to the super class so that
2910 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07002911 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 * @param gainFocus True if the View has focus; false otherwise.
2913 * @param direction The direction focus has moved when requestFocus()
2914 * is called to give this view focus. Values are
Romain Guyea4823c2009-12-08 15:03:39 -08002915 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT} or
2916 * {@link #FOCUS_RIGHT}. It may not always apply, in which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 * case use the default.
2918 * @param previouslyFocusedRect The rectangle, in this view's coordinate
2919 * system, of the previously focused view. If applicable, this will be
2920 * passed in as finer grained information about where the focus is coming
2921 * from (in addition to direction). Will be <code>null</code> otherwise.
2922 */
2923 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07002924 if (gainFocus) {
2925 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2926 }
2927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 InputMethodManager imm = InputMethodManager.peekInstance();
2929 if (!gainFocus) {
2930 if (isPressed()) {
2931 setPressed(false);
2932 }
2933 if (imm != null && mAttachInfo != null
2934 && mAttachInfo.mHasWindowFocus) {
2935 imm.focusOut(this);
2936 }
Romain Guya2431d02009-04-30 16:30:00 -07002937 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 } else if (imm != null && mAttachInfo != null
2939 && mAttachInfo.mHasWindowFocus) {
2940 imm.focusIn(this);
2941 }
Romain Guy8506ab42009-06-11 17:35:47 -07002942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 invalidate();
2944 if (mOnFocusChangeListener != null) {
2945 mOnFocusChangeListener.onFocusChange(this, gainFocus);
2946 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002947
2948 if (mAttachInfo != null) {
2949 mAttachInfo.mKeyDispatchState.reset(this);
2950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 }
2952
2953 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002954 * {@inheritDoc}
2955 */
2956 public void sendAccessibilityEvent(int eventType) {
2957 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2958 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
2959 }
2960 }
2961
2962 /**
2963 * {@inheritDoc}
2964 */
2965 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
2966 event.setClassName(getClass().getName());
2967 event.setPackageName(getContext().getPackageName());
2968 event.setEnabled(isEnabled());
2969 event.setContentDescription(mContentDescription);
2970
2971 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
2972 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
2973 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
2974 event.setItemCount(focusablesTempList.size());
2975 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
2976 focusablesTempList.clear();
2977 }
2978
2979 dispatchPopulateAccessibilityEvent(event);
2980
2981 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
2982 }
2983
2984 /**
2985 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
2986 * to be populated.
2987 *
2988 * @param event The event.
2989 *
2990 * @return True if the event population was completed.
2991 */
2992 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2993 return false;
2994 }
2995
2996 /**
2997 * Gets the {@link View} description. It briefly describes the view and is
2998 * primarily used for accessibility support. Set this property to enable
2999 * better accessibility support for your application. This is especially
3000 * true for views that do not have textual representation (For example,
3001 * ImageButton).
3002 *
3003 * @return The content descriptiopn.
3004 *
3005 * @attr ref android.R.styleable#View_contentDescription
3006 */
3007 public CharSequence getContentDescription() {
3008 return mContentDescription;
3009 }
3010
3011 /**
3012 * Sets the {@link View} description. It briefly describes the view and is
3013 * primarily used for accessibility support. Set this property to enable
3014 * better accessibility support for your application. This is especially
3015 * true for views that do not have textual representation (For example,
3016 * ImageButton).
3017 *
3018 * @param contentDescription The content description.
3019 *
3020 * @attr ref android.R.styleable#View_contentDescription
3021 */
3022 public void setContentDescription(CharSequence contentDescription) {
3023 mContentDescription = contentDescription;
3024 }
3025
3026 /**
Romain Guya2431d02009-04-30 16:30:00 -07003027 * Invoked whenever this view loses focus, either by losing window focus or by losing
3028 * focus within its window. This method can be used to clear any state tied to the
3029 * focus. For instance, if a button is held pressed with the trackball and the window
3030 * loses focus, this method can be used to cancel the press.
3031 *
3032 * Subclasses of View overriding this method should always call super.onFocusLost().
3033 *
3034 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003035 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003036 *
3037 * @hide pending API council approval
3038 */
3039 protected void onFocusLost() {
3040 resetPressedState();
3041 }
3042
3043 private void resetPressedState() {
3044 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3045 return;
3046 }
3047
3048 if (isPressed()) {
3049 setPressed(false);
3050
3051 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003052 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003053 }
3054 }
3055 }
3056
3057 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 * Returns true if this view has focus
3059 *
3060 * @return True if this view has focus, false otherwise.
3061 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003062 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003063 public boolean isFocused() {
3064 return (mPrivateFlags & FOCUSED) != 0;
3065 }
3066
3067 /**
3068 * Find the view in the hierarchy rooted at this view that currently has
3069 * focus.
3070 *
3071 * @return The view that currently has focus, or null if no focused view can
3072 * be found.
3073 */
3074 public View findFocus() {
3075 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3076 }
3077
3078 /**
3079 * Change whether this view is one of the set of scrollable containers in
3080 * its window. This will be used to determine whether the window can
3081 * resize or must pan when a soft input area is open -- scrollable
3082 * containers allow the window to use resize mode since the container
3083 * will appropriately shrink.
3084 */
3085 public void setScrollContainer(boolean isScrollContainer) {
3086 if (isScrollContainer) {
3087 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3088 mAttachInfo.mScrollContainers.add(this);
3089 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3090 }
3091 mPrivateFlags |= SCROLL_CONTAINER;
3092 } else {
3093 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3094 mAttachInfo.mScrollContainers.remove(this);
3095 }
3096 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3097 }
3098 }
3099
3100 /**
3101 * Returns the quality of the drawing cache.
3102 *
3103 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3104 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3105 *
3106 * @see #setDrawingCacheQuality(int)
3107 * @see #setDrawingCacheEnabled(boolean)
3108 * @see #isDrawingCacheEnabled()
3109 *
3110 * @attr ref android.R.styleable#View_drawingCacheQuality
3111 */
3112 public int getDrawingCacheQuality() {
3113 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3114 }
3115
3116 /**
3117 * Set the drawing cache quality of this view. This value is used only when the
3118 * drawing cache is enabled
3119 *
3120 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3121 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3122 *
3123 * @see #getDrawingCacheQuality()
3124 * @see #setDrawingCacheEnabled(boolean)
3125 * @see #isDrawingCacheEnabled()
3126 *
3127 * @attr ref android.R.styleable#View_drawingCacheQuality
3128 */
3129 public void setDrawingCacheQuality(int quality) {
3130 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3131 }
3132
3133 /**
3134 * Returns whether the screen should remain on, corresponding to the current
3135 * value of {@link #KEEP_SCREEN_ON}.
3136 *
3137 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3138 *
3139 * @see #setKeepScreenOn(boolean)
3140 *
3141 * @attr ref android.R.styleable#View_keepScreenOn
3142 */
3143 public boolean getKeepScreenOn() {
3144 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3145 }
3146
3147 /**
3148 * Controls whether the screen should remain on, modifying the
3149 * value of {@link #KEEP_SCREEN_ON}.
3150 *
3151 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3152 *
3153 * @see #getKeepScreenOn()
3154 *
3155 * @attr ref android.R.styleable#View_keepScreenOn
3156 */
3157 public void setKeepScreenOn(boolean keepScreenOn) {
3158 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3159 }
3160
3161 /**
3162 * @return The user specified next focus ID.
3163 *
3164 * @attr ref android.R.styleable#View_nextFocusLeft
3165 */
3166 public int getNextFocusLeftId() {
3167 return mNextFocusLeftId;
3168 }
3169
3170 /**
3171 * Set the id of the view to use for the next focus
3172 *
3173 * @param nextFocusLeftId
3174 *
3175 * @attr ref android.R.styleable#View_nextFocusLeft
3176 */
3177 public void setNextFocusLeftId(int nextFocusLeftId) {
3178 mNextFocusLeftId = nextFocusLeftId;
3179 }
3180
3181 /**
3182 * @return The user specified next focus ID.
3183 *
3184 * @attr ref android.R.styleable#View_nextFocusRight
3185 */
3186 public int getNextFocusRightId() {
3187 return mNextFocusRightId;
3188 }
3189
3190 /**
3191 * Set the id of the view to use for the next focus
3192 *
3193 * @param nextFocusRightId
3194 *
3195 * @attr ref android.R.styleable#View_nextFocusRight
3196 */
3197 public void setNextFocusRightId(int nextFocusRightId) {
3198 mNextFocusRightId = nextFocusRightId;
3199 }
3200
3201 /**
3202 * @return The user specified next focus ID.
3203 *
3204 * @attr ref android.R.styleable#View_nextFocusUp
3205 */
3206 public int getNextFocusUpId() {
3207 return mNextFocusUpId;
3208 }
3209
3210 /**
3211 * Set the id of the view to use for the next focus
3212 *
3213 * @param nextFocusUpId
3214 *
3215 * @attr ref android.R.styleable#View_nextFocusUp
3216 */
3217 public void setNextFocusUpId(int nextFocusUpId) {
3218 mNextFocusUpId = nextFocusUpId;
3219 }
3220
3221 /**
3222 * @return The user specified next focus ID.
3223 *
3224 * @attr ref android.R.styleable#View_nextFocusDown
3225 */
3226 public int getNextFocusDownId() {
3227 return mNextFocusDownId;
3228 }
3229
3230 /**
3231 * Set the id of the view to use for the next focus
3232 *
3233 * @param nextFocusDownId
3234 *
3235 * @attr ref android.R.styleable#View_nextFocusDown
3236 */
3237 public void setNextFocusDownId(int nextFocusDownId) {
3238 mNextFocusDownId = nextFocusDownId;
3239 }
3240
3241 /**
3242 * Returns the visibility of this view and all of its ancestors
3243 *
3244 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3245 */
3246 public boolean isShown() {
3247 View current = this;
3248 //noinspection ConstantConditions
3249 do {
3250 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3251 return false;
3252 }
3253 ViewParent parent = current.mParent;
3254 if (parent == null) {
3255 return false; // We are not attached to the view root
3256 }
3257 if (!(parent instanceof View)) {
3258 return true;
3259 }
3260 current = (View) parent;
3261 } while (current != null);
3262
3263 return false;
3264 }
3265
3266 /**
3267 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3268 * is set
3269 *
3270 * @param insets Insets for system windows
3271 *
3272 * @return True if this view applied the insets, false otherwise
3273 */
3274 protected boolean fitSystemWindows(Rect insets) {
3275 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3276 mPaddingLeft = insets.left;
3277 mPaddingTop = insets.top;
3278 mPaddingRight = insets.right;
3279 mPaddingBottom = insets.bottom;
3280 requestLayout();
3281 return true;
3282 }
3283 return false;
3284 }
3285
3286 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003287 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3288 * @return True if window has FITS_SYSTEM_WINDOWS set
3289 *
3290 * @hide
3291 */
3292 public boolean isFitsSystemWindowsFlagSet() {
3293 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3294 }
3295
3296 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 * Returns the visibility status for this view.
3298 *
3299 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3300 * @attr ref android.R.styleable#View_visibility
3301 */
3302 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003303 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3304 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3305 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 })
3307 public int getVisibility() {
3308 return mViewFlags & VISIBILITY_MASK;
3309 }
3310
3311 /**
3312 * Set the enabled state of this view.
3313 *
3314 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3315 * @attr ref android.R.styleable#View_visibility
3316 */
3317 @RemotableViewMethod
3318 public void setVisibility(int visibility) {
3319 setFlags(visibility, VISIBILITY_MASK);
3320 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3321 }
3322
3323 /**
3324 * Returns the enabled status for this view. The interpretation of the
3325 * enabled state varies by subclass.
3326 *
3327 * @return True if this view is enabled, false otherwise.
3328 */
3329 @ViewDebug.ExportedProperty
3330 public boolean isEnabled() {
3331 return (mViewFlags & ENABLED_MASK) == ENABLED;
3332 }
3333
3334 /**
3335 * Set the enabled state of this view. The interpretation of the enabled
3336 * state varies by subclass.
3337 *
3338 * @param enabled True if this view is enabled, false otherwise.
3339 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003340 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003342 if (enabled == isEnabled()) return;
3343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3345
3346 /*
3347 * The View most likely has to change its appearance, so refresh
3348 * the drawable state.
3349 */
3350 refreshDrawableState();
3351
3352 // Invalidate too, since the default behavior for views is to be
3353 // be drawn at 50% alpha rather than to change the drawable.
3354 invalidate();
3355 }
3356
3357 /**
3358 * Set whether this view can receive the focus.
3359 *
3360 * Setting this to false will also ensure that this view is not focusable
3361 * in touch mode.
3362 *
3363 * @param focusable If true, this view can receive the focus.
3364 *
3365 * @see #setFocusableInTouchMode(boolean)
3366 * @attr ref android.R.styleable#View_focusable
3367 */
3368 public void setFocusable(boolean focusable) {
3369 if (!focusable) {
3370 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3371 }
3372 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3373 }
3374
3375 /**
3376 * Set whether this view can receive focus while in touch mode.
3377 *
3378 * Setting this to true will also ensure that this view is focusable.
3379 *
3380 * @param focusableInTouchMode If true, this view can receive the focus while
3381 * in touch mode.
3382 *
3383 * @see #setFocusable(boolean)
3384 * @attr ref android.R.styleable#View_focusableInTouchMode
3385 */
3386 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3387 // Focusable in touch mode should always be set before the focusable flag
3388 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3389 // which, in touch mode, will not successfully request focus on this view
3390 // because the focusable in touch mode flag is not set
3391 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3392 if (focusableInTouchMode) {
3393 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3394 }
3395 }
3396
3397 /**
3398 * Set whether this view should have sound effects enabled for events such as
3399 * clicking and touching.
3400 *
3401 * <p>You may wish to disable sound effects for a view if you already play sounds,
3402 * for instance, a dial key that plays dtmf tones.
3403 *
3404 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3405 * @see #isSoundEffectsEnabled()
3406 * @see #playSoundEffect(int)
3407 * @attr ref android.R.styleable#View_soundEffectsEnabled
3408 */
3409 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3410 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3411 }
3412
3413 /**
3414 * @return whether this view should have sound effects enabled for events such as
3415 * clicking and touching.
3416 *
3417 * @see #setSoundEffectsEnabled(boolean)
3418 * @see #playSoundEffect(int)
3419 * @attr ref android.R.styleable#View_soundEffectsEnabled
3420 */
3421 @ViewDebug.ExportedProperty
3422 public boolean isSoundEffectsEnabled() {
3423 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3424 }
3425
3426 /**
3427 * Set whether this view should have haptic feedback for events such as
3428 * long presses.
3429 *
3430 * <p>You may wish to disable haptic feedback if your view already controls
3431 * its own haptic feedback.
3432 *
3433 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3434 * @see #isHapticFeedbackEnabled()
3435 * @see #performHapticFeedback(int)
3436 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3437 */
3438 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3439 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3440 }
3441
3442 /**
3443 * @return whether this view should have haptic feedback enabled for events
3444 * long presses.
3445 *
3446 * @see #setHapticFeedbackEnabled(boolean)
3447 * @see #performHapticFeedback(int)
3448 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3449 */
3450 @ViewDebug.ExportedProperty
3451 public boolean isHapticFeedbackEnabled() {
3452 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3453 }
3454
3455 /**
3456 * If this view doesn't do any drawing on its own, set this flag to
3457 * allow further optimizations. By default, this flag is not set on
3458 * View, but could be set on some View subclasses such as ViewGroup.
3459 *
3460 * Typically, if you override {@link #onDraw} you should clear this flag.
3461 *
3462 * @param willNotDraw whether or not this View draw on its own
3463 */
3464 public void setWillNotDraw(boolean willNotDraw) {
3465 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3466 }
3467
3468 /**
3469 * Returns whether or not this View draws on its own.
3470 *
3471 * @return true if this view has nothing to draw, false otherwise
3472 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003473 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 public boolean willNotDraw() {
3475 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3476 }
3477
3478 /**
3479 * When a View's drawing cache is enabled, drawing is redirected to an
3480 * offscreen bitmap. Some views, like an ImageView, must be able to
3481 * bypass this mechanism if they already draw a single bitmap, to avoid
3482 * unnecessary usage of the memory.
3483 *
3484 * @param willNotCacheDrawing true if this view does not cache its
3485 * drawing, false otherwise
3486 */
3487 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3488 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3489 }
3490
3491 /**
3492 * Returns whether or not this View can cache its drawing or not.
3493 *
3494 * @return true if this view does not cache its drawing, false otherwise
3495 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003496 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 public boolean willNotCacheDrawing() {
3498 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3499 }
3500
3501 /**
3502 * Indicates whether this view reacts to click events or not.
3503 *
3504 * @return true if the view is clickable, false otherwise
3505 *
3506 * @see #setClickable(boolean)
3507 * @attr ref android.R.styleable#View_clickable
3508 */
3509 @ViewDebug.ExportedProperty
3510 public boolean isClickable() {
3511 return (mViewFlags & CLICKABLE) == CLICKABLE;
3512 }
3513
3514 /**
3515 * Enables or disables click events for this view. When a view
3516 * is clickable it will change its state to "pressed" on every click.
3517 * Subclasses should set the view clickable to visually react to
3518 * user's clicks.
3519 *
3520 * @param clickable true to make the view clickable, false otherwise
3521 *
3522 * @see #isClickable()
3523 * @attr ref android.R.styleable#View_clickable
3524 */
3525 public void setClickable(boolean clickable) {
3526 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3527 }
3528
3529 /**
3530 * Indicates whether this view reacts to long click events or not.
3531 *
3532 * @return true if the view is long clickable, false otherwise
3533 *
3534 * @see #setLongClickable(boolean)
3535 * @attr ref android.R.styleable#View_longClickable
3536 */
3537 public boolean isLongClickable() {
3538 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3539 }
3540
3541 /**
3542 * Enables or disables long click events for this view. When a view is long
3543 * clickable it reacts to the user holding down the button for a longer
3544 * duration than a tap. This event can either launch the listener or a
3545 * context menu.
3546 *
3547 * @param longClickable true to make the view long clickable, false otherwise
3548 * @see #isLongClickable()
3549 * @attr ref android.R.styleable#View_longClickable
3550 */
3551 public void setLongClickable(boolean longClickable) {
3552 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3553 }
3554
3555 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003556 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 *
3558 * @see #isClickable()
3559 * @see #setClickable(boolean)
3560 *
3561 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3562 * the View's internal state from a previously set "pressed" state.
3563 */
3564 public void setPressed(boolean pressed) {
3565 if (pressed) {
3566 mPrivateFlags |= PRESSED;
3567 } else {
3568 mPrivateFlags &= ~PRESSED;
3569 }
3570 refreshDrawableState();
3571 dispatchSetPressed(pressed);
3572 }
3573
3574 /**
3575 * Dispatch setPressed to all of this View's children.
3576 *
3577 * @see #setPressed(boolean)
3578 *
3579 * @param pressed The new pressed state
3580 */
3581 protected void dispatchSetPressed(boolean pressed) {
3582 }
3583
3584 /**
3585 * Indicates whether the view is currently in pressed state. Unless
3586 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3587 * the pressed state.
3588 *
3589 * @see #setPressed
3590 * @see #isClickable()
3591 * @see #setClickable(boolean)
3592 *
3593 * @return true if the view is currently pressed, false otherwise
3594 */
3595 public boolean isPressed() {
3596 return (mPrivateFlags & PRESSED) == PRESSED;
3597 }
3598
3599 /**
3600 * Indicates whether this view will save its state (that is,
3601 * whether its {@link #onSaveInstanceState} method will be called).
3602 *
3603 * @return Returns true if the view state saving is enabled, else false.
3604 *
3605 * @see #setSaveEnabled(boolean)
3606 * @attr ref android.R.styleable#View_saveEnabled
3607 */
3608 public boolean isSaveEnabled() {
3609 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3610 }
3611
3612 /**
3613 * Controls whether the saving of this view's state is
3614 * enabled (that is, whether its {@link #onSaveInstanceState} method
3615 * will be called). Note that even if freezing is enabled, the
3616 * view still must have an id assigned to it (via {@link #setId setId()})
3617 * for its state to be saved. This flag can only disable the
3618 * saving of this view; any child views may still have their state saved.
3619 *
3620 * @param enabled Set to false to <em>disable</em> state saving, or true
3621 * (the default) to allow it.
3622 *
3623 * @see #isSaveEnabled()
3624 * @see #setId(int)
3625 * @see #onSaveInstanceState()
3626 * @attr ref android.R.styleable#View_saveEnabled
3627 */
3628 public void setSaveEnabled(boolean enabled) {
3629 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3630 }
3631
Jeff Brown85a31762010-09-01 17:01:00 -07003632 /**
3633 * Gets whether the framework should discard touches when the view's
3634 * window is obscured by another visible window.
3635 * Refer to the {@link View} security documentation for more details.
3636 *
3637 * @return True if touch filtering is enabled.
3638 *
3639 * @see #setFilterTouchesWhenObscured(boolean)
3640 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3641 */
3642 @ViewDebug.ExportedProperty
3643 public boolean getFilterTouchesWhenObscured() {
3644 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3645 }
3646
3647 /**
3648 * Sets whether the framework should discard touches when the view's
3649 * window is obscured by another visible window.
3650 * Refer to the {@link View} security documentation for more details.
3651 *
3652 * @param enabled True if touch filtering should be enabled.
3653 *
3654 * @see #getFilterTouchesWhenObscured
3655 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3656 */
3657 public void setFilterTouchesWhenObscured(boolean enabled) {
3658 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3659 FILTER_TOUCHES_WHEN_OBSCURED);
3660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661
3662 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003663 * Indicates whether the entire hierarchy under this view will save its
3664 * state when a state saving traversal occurs from its parent. The default
3665 * is true; if false, these views will not be saved unless
3666 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3667 *
3668 * @return Returns true if the view state saving from parent is enabled, else false.
3669 *
3670 * @see #setSaveFromParentEnabled(boolean)
3671 */
3672 public boolean isSaveFromParentEnabled() {
3673 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3674 }
3675
3676 /**
3677 * Controls whether the entire hierarchy under this view will save its
3678 * state when a state saving traversal occurs from its parent. The default
3679 * is true; if false, these views will not be saved unless
3680 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3681 *
3682 * @param enabled Set to false to <em>disable</em> state saving, or true
3683 * (the default) to allow it.
3684 *
3685 * @see #isSaveFromParentEnabled()
3686 * @see #setId(int)
3687 * @see #onSaveInstanceState()
3688 */
3689 public void setSaveFromParentEnabled(boolean enabled) {
3690 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
3691 }
3692
3693
3694 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695 * Returns whether this View is able to take focus.
3696 *
3697 * @return True if this view can take focus, or false otherwise.
3698 * @attr ref android.R.styleable#View_focusable
3699 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003700 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 public final boolean isFocusable() {
3702 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3703 }
3704
3705 /**
3706 * When a view is focusable, it may not want to take focus when in touch mode.
3707 * For example, a button would like focus when the user is navigating via a D-pad
3708 * so that the user can click on it, but once the user starts touching the screen,
3709 * the button shouldn't take focus
3710 * @return Whether the view is focusable in touch mode.
3711 * @attr ref android.R.styleable#View_focusableInTouchMode
3712 */
3713 @ViewDebug.ExportedProperty
3714 public final boolean isFocusableInTouchMode() {
3715 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3716 }
3717
3718 /**
3719 * Find the nearest view in the specified direction that can take focus.
3720 * This does not actually give focus to that view.
3721 *
3722 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3723 *
3724 * @return The nearest focusable in the specified direction, or null if none
3725 * can be found.
3726 */
3727 public View focusSearch(int direction) {
3728 if (mParent != null) {
3729 return mParent.focusSearch(this, direction);
3730 } else {
3731 return null;
3732 }
3733 }
3734
3735 /**
3736 * This method is the last chance for the focused view and its ancestors to
3737 * respond to an arrow key. This is called when the focused view did not
3738 * consume the key internally, nor could the view system find a new view in
3739 * the requested direction to give focus to.
3740 *
3741 * @param focused The currently focused view.
3742 * @param direction The direction focus wants to move. One of FOCUS_UP,
3743 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3744 * @return True if the this view consumed this unhandled move.
3745 */
3746 public boolean dispatchUnhandledMove(View focused, int direction) {
3747 return false;
3748 }
3749
3750 /**
3751 * If a user manually specified the next view id for a particular direction,
3752 * use the root to look up the view. Once a view is found, it is cached
3753 * for future lookups.
3754 * @param root The root view of the hierarchy containing this view.
3755 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3756 * @return The user specified next view, or null if there is none.
3757 */
3758 View findUserSetNextFocus(View root, int direction) {
3759 switch (direction) {
3760 case FOCUS_LEFT:
3761 if (mNextFocusLeftId == View.NO_ID) return null;
3762 return findViewShouldExist(root, mNextFocusLeftId);
3763 case FOCUS_RIGHT:
3764 if (mNextFocusRightId == View.NO_ID) return null;
3765 return findViewShouldExist(root, mNextFocusRightId);
3766 case FOCUS_UP:
3767 if (mNextFocusUpId == View.NO_ID) return null;
3768 return findViewShouldExist(root, mNextFocusUpId);
3769 case FOCUS_DOWN:
3770 if (mNextFocusDownId == View.NO_ID) return null;
3771 return findViewShouldExist(root, mNextFocusDownId);
3772 }
3773 return null;
3774 }
3775
3776 private static View findViewShouldExist(View root, int childViewId) {
3777 View result = root.findViewById(childViewId);
3778 if (result == null) {
3779 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3780 + "by user for id " + childViewId);
3781 }
3782 return result;
3783 }
3784
3785 /**
3786 * Find and return all focusable views that are descendants of this view,
3787 * possibly including this view if it is focusable itself.
3788 *
3789 * @param direction The direction of the focus
3790 * @return A list of focusable views
3791 */
3792 public ArrayList<View> getFocusables(int direction) {
3793 ArrayList<View> result = new ArrayList<View>(24);
3794 addFocusables(result, direction);
3795 return result;
3796 }
3797
3798 /**
3799 * Add any focusable views that are descendants of this view (possibly
3800 * including this view if it is focusable itself) to views. If we are in touch mode,
3801 * only add views that are also focusable in touch mode.
3802 *
3803 * @param views Focusable views found so far
3804 * @param direction The direction of the focus
3805 */
3806 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003807 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809
svetoslavganov75986cf2009-05-14 22:28:01 -07003810 /**
3811 * Adds any focusable views that are descendants of this view (possibly
3812 * including this view if it is focusable itself) to views. This method
3813 * adds all focusable views regardless if we are in touch mode or
3814 * only views focusable in touch mode if we are in touch mode depending on
3815 * the focusable mode paramater.
3816 *
3817 * @param views Focusable views found so far or null if all we are interested is
3818 * the number of focusables.
3819 * @param direction The direction of the focus.
3820 * @param focusableMode The type of focusables to be added.
3821 *
3822 * @see #FOCUSABLES_ALL
3823 * @see #FOCUSABLES_TOUCH_MODE
3824 */
3825 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3826 if (!isFocusable()) {
3827 return;
3828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829
svetoslavganov75986cf2009-05-14 22:28:01 -07003830 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3831 isInTouchMode() && !isFocusableInTouchMode()) {
3832 return;
3833 }
3834
3835 if (views != null) {
3836 views.add(this);
3837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 }
3839
3840 /**
3841 * Find and return all touchable views that are descendants of this view,
3842 * possibly including this view if it is touchable itself.
3843 *
3844 * @return A list of touchable views
3845 */
3846 public ArrayList<View> getTouchables() {
3847 ArrayList<View> result = new ArrayList<View>();
3848 addTouchables(result);
3849 return result;
3850 }
3851
3852 /**
3853 * Add any touchable views that are descendants of this view (possibly
3854 * including this view if it is touchable itself) to views.
3855 *
3856 * @param views Touchable views found so far
3857 */
3858 public void addTouchables(ArrayList<View> views) {
3859 final int viewFlags = mViewFlags;
3860
3861 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
3862 && (viewFlags & ENABLED_MASK) == ENABLED) {
3863 views.add(this);
3864 }
3865 }
3866
3867 /**
3868 * Call this to try to give focus to a specific view or to one of its
3869 * descendants.
3870 *
3871 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3872 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3873 * while the device is in touch mode.
3874 *
3875 * See also {@link #focusSearch}, which is what you call to say that you
3876 * have focus, and you want your parent to look for the next one.
3877 *
3878 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
3879 * {@link #FOCUS_DOWN} and <code>null</code>.
3880 *
3881 * @return Whether this view or one of its descendants actually took focus.
3882 */
3883 public final boolean requestFocus() {
3884 return requestFocus(View.FOCUS_DOWN);
3885 }
3886
3887
3888 /**
3889 * Call this to try to give focus to a specific view or to one of its
3890 * descendants and give it a hint about what direction focus is heading.
3891 *
3892 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3893 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3894 * while the device is in touch mode.
3895 *
3896 * See also {@link #focusSearch}, which is what you call to say that you
3897 * have focus, and you want your parent to look for the next one.
3898 *
3899 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
3900 * <code>null</code> set for the previously focused rectangle.
3901 *
3902 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3903 * @return Whether this view or one of its descendants actually took focus.
3904 */
3905 public final boolean requestFocus(int direction) {
3906 return requestFocus(direction, null);
3907 }
3908
3909 /**
3910 * Call this to try to give focus to a specific view or to one of its descendants
3911 * and give it hints about the direction and a specific rectangle that the focus
3912 * is coming from. The rectangle can help give larger views a finer grained hint
3913 * about where focus is coming from, and therefore, where to show selection, or
3914 * forward focus change internally.
3915 *
3916 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3917 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3918 * while the device is in touch mode.
3919 *
3920 * A View will not take focus if it is not visible.
3921 *
3922 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
3923 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
3924 *
3925 * See also {@link #focusSearch}, which is what you call to say that you
3926 * have focus, and you want your parent to look for the next one.
3927 *
3928 * You may wish to override this method if your custom {@link View} has an internal
3929 * {@link View} that it wishes to forward the request to.
3930 *
3931 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3932 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
3933 * to give a finer grained hint about where focus is coming from. May be null
3934 * if there is no hint.
3935 * @return Whether this view or one of its descendants actually took focus.
3936 */
3937 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
3938 // need to be focusable
3939 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
3940 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3941 return false;
3942 }
3943
3944 // need to be focusable in touch mode if in touch mode
3945 if (isInTouchMode() &&
3946 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
3947 return false;
3948 }
3949
3950 // need to not have any parents blocking us
3951 if (hasAncestorThatBlocksDescendantFocus()) {
3952 return false;
3953 }
3954
3955 handleFocusGainInternal(direction, previouslyFocusedRect);
3956 return true;
3957 }
3958
Christopher Tate2c095f32010-10-04 14:13:40 -07003959 /** Gets the ViewRoot, or null if not attached. */
3960 /*package*/ ViewRoot getViewRoot() {
3961 View root = getRootView();
3962 return root != null ? (ViewRoot)root.getParent() : null;
3963 }
3964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965 /**
3966 * Call this to try to give focus to a specific view or to one of its descendants. This is a
3967 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
3968 * touch mode to request focus when they are touched.
3969 *
3970 * @return Whether this view or one of its descendants actually took focus.
3971 *
3972 * @see #isInTouchMode()
3973 *
3974 */
3975 public final boolean requestFocusFromTouch() {
3976 // Leave touch mode if we need to
3977 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07003978 ViewRoot viewRoot = getViewRoot();
3979 if (viewRoot != null) {
3980 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 }
3982 }
3983 return requestFocus(View.FOCUS_DOWN);
3984 }
3985
3986 /**
3987 * @return Whether any ancestor of this view blocks descendant focus.
3988 */
3989 private boolean hasAncestorThatBlocksDescendantFocus() {
3990 ViewParent ancestor = mParent;
3991 while (ancestor instanceof ViewGroup) {
3992 final ViewGroup vgAncestor = (ViewGroup) ancestor;
3993 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
3994 return true;
3995 } else {
3996 ancestor = vgAncestor.getParent();
3997 }
3998 }
3999 return false;
4000 }
4001
4002 /**
Romain Guya440b002010-02-24 15:57:54 -08004003 * @hide
4004 */
4005 public void dispatchStartTemporaryDetach() {
4006 onStartTemporaryDetach();
4007 }
4008
4009 /**
4010 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4012 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004013 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 */
4015 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004016 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004017 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004018 }
4019
4020 /**
4021 * @hide
4022 */
4023 public void dispatchFinishTemporaryDetach() {
4024 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 }
Romain Guy8506ab42009-06-11 17:35:47 -07004026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 /**
4028 * Called after {@link #onStartTemporaryDetach} when the container is done
4029 * changing the view.
4030 */
4031 public void onFinishTemporaryDetach() {
4032 }
Romain Guy8506ab42009-06-11 17:35:47 -07004033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 /**
4035 * capture information of this view for later analysis: developement only
4036 * check dynamic switch to make sure we only dump view
4037 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4038 */
4039 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004040 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 return;
4042 }
4043 ViewDebug.dumpCapturedView(subTag, v);
4044 }
4045
4046 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004047 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4048 * for this view's window. Returns null if the view is not currently attached
4049 * to the window. Normally you will not need to use this directly, but
4050 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4051 */
4052 public KeyEvent.DispatcherState getKeyDispatcherState() {
4053 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4054 }
4055
4056 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 * Dispatch a key event before it is processed by any input method
4058 * associated with the view hierarchy. This can be used to intercept
4059 * key events in special situations before the IME consumes them; a
4060 * typical example would be handling the BACK key to update the application's
4061 * UI instead of allowing the IME to see it and close itself.
4062 *
4063 * @param event The key event to be dispatched.
4064 * @return True if the event was handled, false otherwise.
4065 */
4066 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4067 return onKeyPreIme(event.getKeyCode(), event);
4068 }
4069
4070 /**
4071 * Dispatch a key event to the next view on the focus path. This path runs
4072 * from the top of the view tree down to the currently focused view. If this
4073 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4074 * the next node down the focus path. This method also fires any key
4075 * listeners.
4076 *
4077 * @param event The key event to be dispatched.
4078 * @return True if the event was handled, false otherwise.
4079 */
4080 public boolean dispatchKeyEvent(KeyEvent event) {
4081 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082
Romain Guyf607bdc2010-09-10 19:20:06 -07004083 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 if (android.util.Config.LOGV) {
4085 captureViewInfo("captureViewKeyEvent", this);
4086 }
4087
Romain Guyf607bdc2010-09-10 19:20:06 -07004088 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4090 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4091 return true;
4092 }
4093
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004094 return event.dispatch(this, mAttachInfo != null
4095 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 }
4097
4098 /**
4099 * Dispatches a key shortcut event.
4100 *
4101 * @param event The key event to be dispatched.
4102 * @return True if the event was handled by the view, false otherwise.
4103 */
4104 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4105 return onKeyShortcut(event.getKeyCode(), event);
4106 }
4107
4108 /**
4109 * Pass the touch screen motion event down to the target view, or this
4110 * view if it is the target.
4111 *
4112 * @param event The motion event to be dispatched.
4113 * @return True if the event was handled by the view, false otherwise.
4114 */
4115 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004116 if (!onFilterTouchEventForSecurity(event)) {
4117 return false;
4118 }
4119
Romain Guyf607bdc2010-09-10 19:20:06 -07004120 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4122 mOnTouchListener.onTouch(this, event)) {
4123 return true;
4124 }
4125 return onTouchEvent(event);
4126 }
4127
4128 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004129 * Filter the touch event to apply security policies.
4130 *
4131 * @param event The motion event to be filtered.
4132 * @return True if the event should be dispatched, false if the event should be dropped.
4133 *
4134 * @see #getFilterTouchesWhenObscured
4135 */
4136 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004137 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004138 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4139 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4140 // Window is obscured, drop this touch.
4141 return false;
4142 }
4143 return true;
4144 }
4145
4146 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147 * Pass a trackball motion event down to the focused view.
4148 *
4149 * @param event The motion event to be dispatched.
4150 * @return True if the event was handled by the view, false otherwise.
4151 */
4152 public boolean dispatchTrackballEvent(MotionEvent event) {
4153 //Log.i("view", "view=" + this + ", " + event.toString());
4154 return onTrackballEvent(event);
4155 }
4156
4157 /**
4158 * Called when the window containing this view gains or loses window focus.
4159 * ViewGroups should override to route to their children.
4160 *
4161 * @param hasFocus True if the window containing this view now has focus,
4162 * false otherwise.
4163 */
4164 public void dispatchWindowFocusChanged(boolean hasFocus) {
4165 onWindowFocusChanged(hasFocus);
4166 }
4167
4168 /**
4169 * Called when the window containing this view gains or loses focus. Note
4170 * that this is separate from view focus: to receive key events, both
4171 * your view and its window must have focus. If a window is displayed
4172 * on top of yours that takes input focus, then your own window will lose
4173 * focus but the view focus will remain unchanged.
4174 *
4175 * @param hasWindowFocus True if the window containing this view now has
4176 * focus, false otherwise.
4177 */
4178 public void onWindowFocusChanged(boolean hasWindowFocus) {
4179 InputMethodManager imm = InputMethodManager.peekInstance();
4180 if (!hasWindowFocus) {
4181 if (isPressed()) {
4182 setPressed(false);
4183 }
4184 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4185 imm.focusOut(this);
4186 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004187 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004188 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004189 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4191 imm.focusIn(this);
4192 }
4193 refreshDrawableState();
4194 }
4195
4196 /**
4197 * Returns true if this view is in a window that currently has window focus.
4198 * Note that this is not the same as the view itself having focus.
4199 *
4200 * @return True if this view is in a window that currently has window focus.
4201 */
4202 public boolean hasWindowFocus() {
4203 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4204 }
4205
4206 /**
Adam Powell326d8082009-12-09 15:10:07 -08004207 * Dispatch a view visibility change down the view hierarchy.
4208 * ViewGroups should override to route to their children.
4209 * @param changedView The view whose visibility changed. Could be 'this' or
4210 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004211 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4212 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004213 */
4214 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4215 onVisibilityChanged(changedView, visibility);
4216 }
4217
4218 /**
4219 * Called when the visibility of the view or an ancestor of the view is changed.
4220 * @param changedView The view whose visibility changed. Could be 'this' or
4221 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004222 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4223 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004224 */
4225 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004226 if (visibility == VISIBLE) {
4227 if (mAttachInfo != null) {
4228 initialAwakenScrollBars();
4229 } else {
4230 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4231 }
4232 }
Adam Powell326d8082009-12-09 15:10:07 -08004233 }
4234
4235 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004236 * Dispatch a hint about whether this view is displayed. For instance, when
4237 * a View moves out of the screen, it might receives a display hint indicating
4238 * the view is not displayed. Applications should not <em>rely</em> on this hint
4239 * as there is no guarantee that they will receive one.
4240 *
4241 * @param hint A hint about whether or not this view is displayed:
4242 * {@link #VISIBLE} or {@link #INVISIBLE}.
4243 */
4244 public void dispatchDisplayHint(int hint) {
4245 onDisplayHint(hint);
4246 }
4247
4248 /**
4249 * Gives this view a hint about whether is displayed or not. For instance, when
4250 * a View moves out of the screen, it might receives a display hint indicating
4251 * the view is not displayed. Applications should not <em>rely</em> on this hint
4252 * as there is no guarantee that they will receive one.
4253 *
4254 * @param hint A hint about whether or not this view is displayed:
4255 * {@link #VISIBLE} or {@link #INVISIBLE}.
4256 */
4257 protected void onDisplayHint(int hint) {
4258 }
4259
4260 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 * Dispatch a window visibility change down the view hierarchy.
4262 * ViewGroups should override to route to their children.
4263 *
4264 * @param visibility The new visibility of the window.
4265 *
4266 * @see #onWindowVisibilityChanged
4267 */
4268 public void dispatchWindowVisibilityChanged(int visibility) {
4269 onWindowVisibilityChanged(visibility);
4270 }
4271
4272 /**
4273 * Called when the window containing has change its visibility
4274 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4275 * that this tells you whether or not your window is being made visible
4276 * to the window manager; this does <em>not</em> tell you whether or not
4277 * your window is obscured by other windows on the screen, even if it
4278 * is itself visible.
4279 *
4280 * @param visibility The new visibility of the window.
4281 */
4282 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004283 if (visibility == VISIBLE) {
4284 initialAwakenScrollBars();
4285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004286 }
4287
4288 /**
4289 * Returns the current visibility of the window this view is attached to
4290 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4291 *
4292 * @return Returns the current visibility of the view's window.
4293 */
4294 public int getWindowVisibility() {
4295 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4296 }
4297
4298 /**
4299 * Retrieve the overall visible display size in which the window this view is
4300 * attached to has been positioned in. This takes into account screen
4301 * decorations above the window, for both cases where the window itself
4302 * is being position inside of them or the window is being placed under
4303 * then and covered insets are used for the window to position its content
4304 * inside. In effect, this tells you the available area where content can
4305 * be placed and remain visible to users.
4306 *
4307 * <p>This function requires an IPC back to the window manager to retrieve
4308 * the requested information, so should not be used in performance critical
4309 * code like drawing.
4310 *
4311 * @param outRect Filled in with the visible display frame. If the view
4312 * is not attached to a window, this is simply the raw display size.
4313 */
4314 public void getWindowVisibleDisplayFrame(Rect outRect) {
4315 if (mAttachInfo != null) {
4316 try {
4317 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4318 } catch (RemoteException e) {
4319 return;
4320 }
4321 // XXX This is really broken, and probably all needs to be done
4322 // in the window manager, and we need to know more about whether
4323 // we want the area behind or in front of the IME.
4324 final Rect insets = mAttachInfo.mVisibleInsets;
4325 outRect.left += insets.left;
4326 outRect.top += insets.top;
4327 outRect.right -= insets.right;
4328 outRect.bottom -= insets.bottom;
4329 return;
4330 }
4331 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4332 outRect.set(0, 0, d.getWidth(), d.getHeight());
4333 }
4334
4335 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004336 * Dispatch a notification about a resource configuration change down
4337 * the view hierarchy.
4338 * ViewGroups should override to route to their children.
4339 *
4340 * @param newConfig The new resource configuration.
4341 *
4342 * @see #onConfigurationChanged
4343 */
4344 public void dispatchConfigurationChanged(Configuration newConfig) {
4345 onConfigurationChanged(newConfig);
4346 }
4347
4348 /**
4349 * Called when the current configuration of the resources being used
4350 * by the application have changed. You can use this to decide when
4351 * to reload resources that can changed based on orientation and other
4352 * configuration characterstics. You only need to use this if you are
4353 * not relying on the normal {@link android.app.Activity} mechanism of
4354 * recreating the activity instance upon a configuration change.
4355 *
4356 * @param newConfig The new resource configuration.
4357 */
4358 protected void onConfigurationChanged(Configuration newConfig) {
4359 }
4360
4361 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 * Private function to aggregate all per-view attributes in to the view
4363 * root.
4364 */
4365 void dispatchCollectViewAttributes(int visibility) {
4366 performCollectViewAttributes(visibility);
4367 }
4368
4369 void performCollectViewAttributes(int visibility) {
4370 //noinspection PointlessBitwiseExpression
4371 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4372 == (VISIBLE | KEEP_SCREEN_ON)) {
4373 mAttachInfo.mKeepScreenOn = true;
4374 }
4375 }
4376
4377 void needGlobalAttributesUpdate(boolean force) {
4378 AttachInfo ai = mAttachInfo;
4379 if (ai != null) {
4380 if (ai.mKeepScreenOn || force) {
4381 ai.mRecomputeGlobalAttributes = true;
4382 }
4383 }
4384 }
4385
4386 /**
4387 * Returns whether the device is currently in touch mode. Touch mode is entered
4388 * once the user begins interacting with the device by touch, and affects various
4389 * things like whether focus is always visible to the user.
4390 *
4391 * @return Whether the device is in touch mode.
4392 */
4393 @ViewDebug.ExportedProperty
4394 public boolean isInTouchMode() {
4395 if (mAttachInfo != null) {
4396 return mAttachInfo.mInTouchMode;
4397 } else {
4398 return ViewRoot.isInTouchMode();
4399 }
4400 }
4401
4402 /**
4403 * Returns the context the view is running in, through which it can
4404 * access the current theme, resources, etc.
4405 *
4406 * @return The view's Context.
4407 */
4408 @ViewDebug.CapturedViewProperty
4409 public final Context getContext() {
4410 return mContext;
4411 }
4412
4413 /**
4414 * Handle a key event before it is processed by any input method
4415 * associated with the view hierarchy. This can be used to intercept
4416 * key events in special situations before the IME consumes them; a
4417 * typical example would be handling the BACK key to update the application's
4418 * UI instead of allowing the IME to see it and close itself.
4419 *
4420 * @param keyCode The value in event.getKeyCode().
4421 * @param event Description of the key event.
4422 * @return If you handled the event, return true. If you want to allow the
4423 * event to be handled by the next receiver, return false.
4424 */
4425 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4426 return false;
4427 }
4428
4429 /**
4430 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4431 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4432 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4433 * is released, if the view is enabled and clickable.
4434 *
4435 * @param keyCode A key code that represents the button pressed, from
4436 * {@link android.view.KeyEvent}.
4437 * @param event The KeyEvent object that defines the button action.
4438 */
4439 public boolean onKeyDown(int keyCode, KeyEvent event) {
4440 boolean result = false;
4441
4442 switch (keyCode) {
4443 case KeyEvent.KEYCODE_DPAD_CENTER:
4444 case KeyEvent.KEYCODE_ENTER: {
4445 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4446 return true;
4447 }
4448 // Long clickable items don't necessarily have to be clickable
4449 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4450 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4451 (event.getRepeatCount() == 0)) {
4452 setPressed(true);
4453 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004454 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 }
4456 return true;
4457 }
4458 break;
4459 }
4460 }
4461 return result;
4462 }
4463
4464 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004465 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4466 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4467 * the event).
4468 */
4469 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4470 return false;
4471 }
4472
4473 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4475 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4476 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4477 * {@link KeyEvent#KEYCODE_ENTER} is released.
4478 *
4479 * @param keyCode A key code that represents the button pressed, from
4480 * {@link android.view.KeyEvent}.
4481 * @param event The KeyEvent object that defines the button action.
4482 */
4483 public boolean onKeyUp(int keyCode, KeyEvent event) {
4484 boolean result = false;
4485
4486 switch (keyCode) {
4487 case KeyEvent.KEYCODE_DPAD_CENTER:
4488 case KeyEvent.KEYCODE_ENTER: {
4489 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4490 return true;
4491 }
4492 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4493 setPressed(false);
4494
4495 if (!mHasPerformedLongPress) {
4496 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004497 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498
4499 result = performClick();
4500 }
4501 }
4502 break;
4503 }
4504 }
4505 return result;
4506 }
4507
4508 /**
4509 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4510 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4511 * the event).
4512 *
4513 * @param keyCode A key code that represents the button pressed, from
4514 * {@link android.view.KeyEvent}.
4515 * @param repeatCount The number of times the action was made.
4516 * @param event The KeyEvent object that defines the button action.
4517 */
4518 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4519 return false;
4520 }
4521
4522 /**
4523 * Called when an unhandled key shortcut event occurs.
4524 *
4525 * @param keyCode The value in event.getKeyCode().
4526 * @param event Description of the key event.
4527 * @return If you handled the event, return true. If you want to allow the
4528 * event to be handled by the next receiver, return false.
4529 */
4530 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4531 return false;
4532 }
4533
4534 /**
4535 * Check whether the called view is a text editor, in which case it
4536 * would make sense to automatically display a soft input window for
4537 * it. Subclasses should override this if they implement
4538 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004539 * a call on that method would return a non-null InputConnection, and
4540 * they are really a first-class editor that the user would normally
4541 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004542 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004543 * <p>The default implementation always returns false. This does
4544 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4545 * will not be called or the user can not otherwise perform edits on your
4546 * view; it is just a hint to the system that this is not the primary
4547 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004548 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004549 * @return Returns true if this view is a text editor, else false.
4550 */
4551 public boolean onCheckIsTextEditor() {
4552 return false;
4553 }
Romain Guy8506ab42009-06-11 17:35:47 -07004554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004555 /**
4556 * Create a new InputConnection for an InputMethod to interact
4557 * with the view. The default implementation returns null, since it doesn't
4558 * support input methods. You can override this to implement such support.
4559 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004560 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 * <p>When implementing this, you probably also want to implement
4562 * {@link #onCheckIsTextEditor()} to indicate you will return a
4563 * non-null InputConnection.
4564 *
4565 * @param outAttrs Fill in with attribute information about the connection.
4566 */
4567 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4568 return null;
4569 }
4570
4571 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004572 * Called by the {@link android.view.inputmethod.InputMethodManager}
4573 * when a view who is not the current
4574 * input connection target is trying to make a call on the manager. The
4575 * default implementation returns false; you can override this to return
4576 * true for certain views if you are performing InputConnection proxying
4577 * to them.
4578 * @param view The View that is making the InputMethodManager call.
4579 * @return Return true to allow the call, false to reject.
4580 */
4581 public boolean checkInputConnectionProxy(View view) {
4582 return false;
4583 }
Romain Guy8506ab42009-06-11 17:35:47 -07004584
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004585 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004586 * Show the context menu for this view. It is not safe to hold on to the
4587 * menu after returning from this method.
4588 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004589 * You should normally not overload this method. Overload
4590 * {@link #onCreateContextMenu(ContextMenu)} or define an
4591 * {@link OnCreateContextMenuListener} to add items to the context menu.
4592 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 * @param menu The context menu to populate
4594 */
4595 public void createContextMenu(ContextMenu menu) {
4596 ContextMenuInfo menuInfo = getContextMenuInfo();
4597
4598 // Sets the current menu info so all items added to menu will have
4599 // my extra info set.
4600 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4601
4602 onCreateContextMenu(menu);
4603 if (mOnCreateContextMenuListener != null) {
4604 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4605 }
4606
4607 // Clear the extra information so subsequent items that aren't mine don't
4608 // have my extra info.
4609 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4610
4611 if (mParent != null) {
4612 mParent.createContextMenu(menu);
4613 }
4614 }
4615
4616 /**
4617 * Views should implement this if they have extra information to associate
4618 * with the context menu. The return result is supplied as a parameter to
4619 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4620 * callback.
4621 *
4622 * @return Extra information about the item for which the context menu
4623 * should be shown. This information will vary across different
4624 * subclasses of View.
4625 */
4626 protected ContextMenuInfo getContextMenuInfo() {
4627 return null;
4628 }
4629
4630 /**
4631 * Views should implement this if the view itself is going to add items to
4632 * the context menu.
4633 *
4634 * @param menu the context menu to populate
4635 */
4636 protected void onCreateContextMenu(ContextMenu menu) {
4637 }
4638
4639 /**
4640 * Implement this method to handle trackball motion events. The
4641 * <em>relative</em> movement of the trackball since the last event
4642 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4643 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4644 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4645 * they will often be fractional values, representing the more fine-grained
4646 * movement information available from a trackball).
4647 *
4648 * @param event The motion event.
4649 * @return True if the event was handled, false otherwise.
4650 */
4651 public boolean onTrackballEvent(MotionEvent event) {
4652 return false;
4653 }
4654
4655 /**
4656 * Implement this method to handle touch screen motion events.
4657 *
4658 * @param event The motion event.
4659 * @return True if the event was handled, false otherwise.
4660 */
4661 public boolean onTouchEvent(MotionEvent event) {
4662 final int viewFlags = mViewFlags;
4663
4664 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4665 // A disabled view that is clickable still consumes the touch
4666 // events, it just doesn't respond to them.
4667 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4668 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4669 }
4670
4671 if (mTouchDelegate != null) {
4672 if (mTouchDelegate.onTouchEvent(event)) {
4673 return true;
4674 }
4675 }
4676
4677 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4678 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4679 switch (event.getAction()) {
4680 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004681 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4682 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004683 // take focus if we don't have it already and we should in
4684 // touch mode.
4685 boolean focusTaken = false;
4686 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4687 focusTaken = requestFocus();
4688 }
4689
4690 if (!mHasPerformedLongPress) {
4691 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004692 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004693
4694 // Only perform take click actions if we were in the pressed state
4695 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004696 // Use a Runnable and post this rather than calling
4697 // performClick directly. This lets other visual state
4698 // of the view update before click actions start.
4699 if (mPerformClick == null) {
4700 mPerformClick = new PerformClick();
4701 }
4702 if (!post(mPerformClick)) {
4703 performClick();
4704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 }
4706 }
4707
4708 if (mUnsetPressedState == null) {
4709 mUnsetPressedState = new UnsetPressedState();
4710 }
4711
Adam Powelle14579b2009-12-16 18:39:52 -08004712 if (prepressed) {
4713 mPrivateFlags |= PRESSED;
4714 refreshDrawableState();
4715 postDelayed(mUnsetPressedState,
4716 ViewConfiguration.getPressedStateDuration());
4717 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004718 // If the post failed, unpress right now
4719 mUnsetPressedState.run();
4720 }
Adam Powelle14579b2009-12-16 18:39:52 -08004721 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004722 }
4723 break;
4724
4725 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004726 if (mPendingCheckForTap == null) {
4727 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004728 }
Adam Powelle14579b2009-12-16 18:39:52 -08004729 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004730 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004731 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004732 break;
4733
4734 case MotionEvent.ACTION_CANCEL:
4735 mPrivateFlags &= ~PRESSED;
4736 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004737 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004738 break;
4739
4740 case MotionEvent.ACTION_MOVE:
4741 final int x = (int) event.getX();
4742 final int y = (int) event.getY();
4743
4744 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004745 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004746 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004747 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004749 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004750 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004751
4752 // Need to switch from pressed to not pressed
4753 mPrivateFlags &= ~PRESSED;
4754 refreshDrawableState();
4755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004756 }
4757 break;
4758 }
4759 return true;
4760 }
4761
4762 return false;
4763 }
4764
4765 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004766 * Remove the longpress detection timer.
4767 */
4768 private void removeLongPressCallback() {
4769 if (mPendingCheckForLongPress != null) {
4770 removeCallbacks(mPendingCheckForLongPress);
4771 }
4772 }
Adam Powelle14579b2009-12-16 18:39:52 -08004773
4774 /**
Romain Guya440b002010-02-24 15:57:54 -08004775 * Remove the prepress detection timer.
4776 */
4777 private void removeUnsetPressCallback() {
4778 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4779 setPressed(false);
4780 removeCallbacks(mUnsetPressedState);
4781 }
4782 }
4783
4784 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004785 * Remove the tap detection timer.
4786 */
4787 private void removeTapCallback() {
4788 if (mPendingCheckForTap != null) {
4789 mPrivateFlags &= ~PREPRESSED;
4790 removeCallbacks(mPendingCheckForTap);
4791 }
4792 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004793
4794 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004795 * Cancels a pending long press. Your subclass can use this if you
4796 * want the context menu to come up if the user presses and holds
4797 * at the same place, but you don't want it to come up if they press
4798 * and then move around enough to cause scrolling.
4799 */
4800 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004801 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004802
4803 /*
4804 * The prepressed state handled by the tap callback is a display
4805 * construct, but the tap callback will post a long press callback
4806 * less its own timeout. Remove it here.
4807 */
4808 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004809 }
4810
4811 /**
4812 * Sets the TouchDelegate for this View.
4813 */
4814 public void setTouchDelegate(TouchDelegate delegate) {
4815 mTouchDelegate = delegate;
4816 }
4817
4818 /**
4819 * Gets the TouchDelegate for this View.
4820 */
4821 public TouchDelegate getTouchDelegate() {
4822 return mTouchDelegate;
4823 }
4824
4825 /**
4826 * Set flags controlling behavior of this view.
4827 *
4828 * @param flags Constant indicating the value which should be set
4829 * @param mask Constant indicating the bit range that should be changed
4830 */
4831 void setFlags(int flags, int mask) {
4832 int old = mViewFlags;
4833 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4834
4835 int changed = mViewFlags ^ old;
4836 if (changed == 0) {
4837 return;
4838 }
4839 int privateFlags = mPrivateFlags;
4840
4841 /* Check if the FOCUSABLE bit has changed */
4842 if (((changed & FOCUSABLE_MASK) != 0) &&
4843 ((privateFlags & HAS_BOUNDS) !=0)) {
4844 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4845 && ((privateFlags & FOCUSED) != 0)) {
4846 /* Give up focus if we are no longer focusable */
4847 clearFocus();
4848 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4849 && ((privateFlags & FOCUSED) == 0)) {
4850 /*
4851 * Tell the view system that we are now available to take focus
4852 * if no one else already has it.
4853 */
4854 if (mParent != null) mParent.focusableViewAvailable(this);
4855 }
4856 }
4857
4858 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4859 if ((changed & VISIBILITY_MASK) != 0) {
4860 /*
4861 * If this view is becoming visible, set the DRAWN flag so that
4862 * the next invalidate() will not be skipped.
4863 */
4864 mPrivateFlags |= DRAWN;
4865
4866 needGlobalAttributesUpdate(true);
4867
4868 // a view becoming visible is worth notifying the parent
4869 // about in case nothing has focus. even if this specific view
4870 // isn't focusable, it may contain something that is, so let
4871 // the root view try to give this focus if nothing else does.
4872 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4873 mParent.focusableViewAvailable(this);
4874 }
4875 }
4876 }
4877
4878 /* Check if the GONE bit has changed */
4879 if ((changed & GONE) != 0) {
4880 needGlobalAttributesUpdate(false);
4881 requestLayout();
4882 invalidate();
4883
Romain Guyecd80ee2009-12-03 17:13:02 -08004884 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
4885 if (hasFocus()) clearFocus();
4886 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004887 }
4888 if (mAttachInfo != null) {
4889 mAttachInfo.mViewVisibilityChanged = true;
4890 }
4891 }
4892
4893 /* Check if the VISIBLE bit has changed */
4894 if ((changed & INVISIBLE) != 0) {
4895 needGlobalAttributesUpdate(false);
4896 invalidate();
4897
4898 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4899 // root view becoming invisible shouldn't clear focus
4900 if (getRootView() != this) {
4901 clearFocus();
4902 }
4903 }
4904 if (mAttachInfo != null) {
4905 mAttachInfo.mViewVisibilityChanged = true;
4906 }
4907 }
4908
Adam Powell326d8082009-12-09 15:10:07 -08004909 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07004910 if (mParent instanceof ViewGroup) {
4911 ((ViewGroup)mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
4912 }
Adam Powell326d8082009-12-09 15:10:07 -08004913 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
4914 }
4915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004916 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4917 destroyDrawingCache();
4918 }
4919
4920 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4921 destroyDrawingCache();
4922 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4923 }
4924
4925 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4926 destroyDrawingCache();
4927 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4928 }
4929
4930 if ((changed & DRAW_MASK) != 0) {
4931 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4932 if (mBGDrawable != null) {
4933 mPrivateFlags &= ~SKIP_DRAW;
4934 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4935 } else {
4936 mPrivateFlags |= SKIP_DRAW;
4937 }
4938 } else {
4939 mPrivateFlags &= ~SKIP_DRAW;
4940 }
4941 requestLayout();
4942 invalidate();
4943 }
4944
4945 if ((changed & KEEP_SCREEN_ON) != 0) {
4946 if (mParent != null) {
4947 mParent.recomputeViewAttributes(this);
4948 }
4949 }
4950 }
4951
4952 /**
4953 * Change the view's z order in the tree, so it's on top of other sibling
4954 * views
4955 */
4956 public void bringToFront() {
4957 if (mParent != null) {
4958 mParent.bringChildToFront(this);
4959 }
4960 }
4961
4962 /**
4963 * This is called in response to an internal scroll in this view (i.e., the
4964 * view scrolled its own contents). This is typically as a result of
4965 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4966 * called.
4967 *
4968 * @param l Current horizontal scroll origin.
4969 * @param t Current vertical scroll origin.
4970 * @param oldl Previous horizontal scroll origin.
4971 * @param oldt Previous vertical scroll origin.
4972 */
4973 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4974 mBackgroundSizeChanged = true;
4975
4976 final AttachInfo ai = mAttachInfo;
4977 if (ai != null) {
4978 ai.mViewScrollChanged = true;
4979 }
4980 }
4981
4982 /**
Chet Haase21cd1382010-09-01 17:42:29 -07004983 * Interface definition for a callback to be invoked when the layout bounds of a view
4984 * changes due to layout processing.
4985 */
4986 public interface OnLayoutChangeListener {
4987 /**
4988 * Called when the focus state of a view has changed.
4989 *
4990 * @param v The view whose state has changed.
4991 * @param left The new value of the view's left property.
4992 * @param top The new value of the view's top property.
4993 * @param right The new value of the view's right property.
4994 * @param bottom The new value of the view's bottom property.
4995 * @param oldLeft The previous value of the view's left property.
4996 * @param oldTop The previous value of the view's top property.
4997 * @param oldRight The previous value of the view's right property.
4998 * @param oldBottom The previous value of the view's bottom property.
4999 */
5000 void onLayoutChange(View v, int left, int top, int right, int bottom,
5001 int oldLeft, int oldTop, int oldRight, int oldBottom);
5002 }
5003
5004 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005005 * This is called during layout when the size of this view has changed. If
5006 * you were just added to the view hierarchy, you're called with the old
5007 * values of 0.
5008 *
5009 * @param w Current width of this view.
5010 * @param h Current height of this view.
5011 * @param oldw Old width of this view.
5012 * @param oldh Old height of this view.
5013 */
5014 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5015 }
5016
5017 /**
5018 * Called by draw to draw the child views. This may be overridden
5019 * by derived classes to gain control just before its children are drawn
5020 * (but after its own view has been drawn).
5021 * @param canvas the canvas on which to draw the view
5022 */
5023 protected void dispatchDraw(Canvas canvas) {
5024 }
5025
5026 /**
5027 * Gets the parent of this view. Note that the parent is a
5028 * ViewParent and not necessarily a View.
5029 *
5030 * @return Parent of this view.
5031 */
5032 public final ViewParent getParent() {
5033 return mParent;
5034 }
5035
5036 /**
5037 * Return the scrolled left position of this view. This is the left edge of
5038 * the displayed part of your view. You do not need to draw any pixels
5039 * farther left, since those are outside of the frame of your view on
5040 * screen.
5041 *
5042 * @return The left edge of the displayed part of your view, in pixels.
5043 */
5044 public final int getScrollX() {
5045 return mScrollX;
5046 }
5047
5048 /**
5049 * Return the scrolled top position of this view. This is the top edge of
5050 * the displayed part of your view. You do not need to draw any pixels above
5051 * it, since those are outside of the frame of your view on screen.
5052 *
5053 * @return The top edge of the displayed part of your view, in pixels.
5054 */
5055 public final int getScrollY() {
5056 return mScrollY;
5057 }
5058
5059 /**
5060 * Return the width of the your view.
5061 *
5062 * @return The width of your view, in pixels.
5063 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005064 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 public final int getWidth() {
5066 return mRight - mLeft;
5067 }
5068
5069 /**
5070 * Return the height of your view.
5071 *
5072 * @return The height of your view, in pixels.
5073 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005074 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005075 public final int getHeight() {
5076 return mBottom - mTop;
5077 }
5078
5079 /**
5080 * Return the visible drawing bounds of your view. Fills in the output
5081 * rectangle with the values from getScrollX(), getScrollY(),
5082 * getWidth(), and getHeight().
5083 *
5084 * @param outRect The (scrolled) drawing bounds of the view.
5085 */
5086 public void getDrawingRect(Rect outRect) {
5087 outRect.left = mScrollX;
5088 outRect.top = mScrollY;
5089 outRect.right = mScrollX + (mRight - mLeft);
5090 outRect.bottom = mScrollY + (mBottom - mTop);
5091 }
5092
5093 /**
5094 * The width of this view as measured in the most recent call to measure().
5095 * This should be used during measurement and layout calculations only. Use
5096 * {@link #getWidth()} to see how wide a view is after layout.
5097 *
5098 * @return The measured width of this view.
5099 */
5100 public final int getMeasuredWidth() {
5101 return mMeasuredWidth;
5102 }
5103
5104 /**
5105 * The height of this view as measured in the most recent call to measure().
5106 * This should be used during measurement and layout calculations only. Use
5107 * {@link #getHeight()} to see how tall a view is after layout.
5108 *
5109 * @return The measured height of this view.
5110 */
5111 public final int getMeasuredHeight() {
5112 return mMeasuredHeight;
5113 }
5114
5115 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005116 * The transform matrix of this view, which is calculated based on the current
5117 * roation, scale, and pivot properties.
5118 *
5119 * @see #getRotation()
5120 * @see #getScaleX()
5121 * @see #getScaleY()
5122 * @see #getPivotX()
5123 * @see #getPivotY()
5124 * @return The current transform matrix for the view
5125 */
5126 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005127 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005128 return mMatrix;
5129 }
5130
5131 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005132 * Utility function to determine if the value is far enough away from zero to be
5133 * considered non-zero.
5134 * @param value A floating point value to check for zero-ness
5135 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5136 */
5137 private static boolean nonzero(float value) {
5138 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5139 }
5140
5141 /**
Jeff Brown86671742010-09-30 20:00:15 -07005142 * Returns true if the transform matrix is the identity matrix.
5143 * Recomputes the matrix if necessary.
Romain Guy33e72ae2010-07-17 12:40:29 -07005144 *
5145 * @return True if the transform matrix is the identity matrix, false otherwise.
5146 */
Jeff Brown86671742010-09-30 20:00:15 -07005147 final boolean hasIdentityMatrix() {
5148 updateMatrix();
5149 return mMatrixIsIdentity;
5150 }
5151
5152 /**
5153 * Recomputes the transform matrix if necessary.
5154 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005155 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005156 if (mMatrixDirty) {
5157 // transform-related properties have changed since the last time someone
5158 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005159
5160 // Figure out if we need to update the pivot point
5161 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5162 if ((mRight - mLeft) != mPrevWidth && (mBottom - mTop) != mPrevHeight) {
5163 mPrevWidth = mRight - mLeft;
5164 mPrevHeight = mBottom - mTop;
5165 mPivotX = (float) mPrevWidth / 2f;
5166 mPivotY = (float) mPrevHeight / 2f;
5167 }
5168 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005169 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005170 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5171 mMatrix.setTranslate(mTranslationX, mTranslationY);
5172 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5173 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5174 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005175 if (mCamera == null) {
5176 mCamera = new Camera();
5177 matrix3D = new Matrix();
5178 }
5179 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005180 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005181 mCamera.rotateX(mRotationX);
5182 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005183 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005184 mCamera.getMatrix(matrix3D);
5185 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005186 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005187 mMatrix.postConcat(matrix3D);
5188 mCamera.restore();
5189 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005190 mMatrixDirty = false;
5191 mMatrixIsIdentity = mMatrix.isIdentity();
5192 mInverseMatrixDirty = true;
5193 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005194 }
5195
5196 /**
5197 * Utility method to retrieve the inverse of the current mMatrix property.
5198 * We cache the matrix to avoid recalculating it when transform properties
5199 * have not changed.
5200 *
5201 * @return The inverse of the current matrix of this view.
5202 */
Jeff Brown86671742010-09-30 20:00:15 -07005203 final Matrix getInverseMatrix() {
5204 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005205 if (mInverseMatrixDirty) {
5206 if (mInverseMatrix == null) {
5207 mInverseMatrix = new Matrix();
5208 }
5209 mMatrix.invert(mInverseMatrix);
5210 mInverseMatrixDirty = false;
5211 }
5212 return mInverseMatrix;
5213 }
5214
5215 /**
5216 * The degrees that the view is rotated around the pivot point.
5217 *
5218 * @see #getPivotX()
5219 * @see #getPivotY()
5220 * @return The degrees of rotation.
5221 */
5222 public float getRotation() {
5223 return mRotation;
5224 }
5225
5226 /**
Chet Haase897247b2010-09-09 14:54:47 -07005227 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5228 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005229 *
5230 * @param rotation The degrees of rotation.
5231 * @see #getPivotX()
5232 * @see #getPivotY()
5233 */
5234 public void setRotation(float rotation) {
5235 if (mRotation != rotation) {
5236 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005237 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005238 mRotation = rotation;
5239 mMatrixDirty = true;
5240 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005241 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005242 }
5243 }
5244
5245 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005246 * The degrees that the view is rotated around the vertical axis through the pivot point.
5247 *
5248 * @see #getPivotX()
5249 * @see #getPivotY()
5250 * @return The degrees of Y rotation.
5251 */
5252 public float getRotationY() {
5253 return mRotationY;
5254 }
5255
5256 /**
Chet Haase897247b2010-09-09 14:54:47 -07005257 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5258 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5259 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005260 *
5261 * @param rotationY The degrees of Y rotation.
5262 * @see #getPivotX()
5263 * @see #getPivotY()
5264 */
5265 public void setRotationY(float rotationY) {
5266 if (mRotationY != rotationY) {
5267 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005268 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005269 mRotationY = rotationY;
5270 mMatrixDirty = true;
5271 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005272 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005273 }
5274 }
5275
5276 /**
5277 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5278 *
5279 * @see #getPivotX()
5280 * @see #getPivotY()
5281 * @return The degrees of X rotation.
5282 */
5283 public float getRotationX() {
5284 return mRotationX;
5285 }
5286
5287 /**
Chet Haase897247b2010-09-09 14:54:47 -07005288 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5289 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5290 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005291 *
5292 * @param rotationX The degrees of X rotation.
5293 * @see #getPivotX()
5294 * @see #getPivotY()
5295 */
5296 public void setRotationX(float rotationX) {
5297 if (mRotationX != rotationX) {
5298 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005299 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005300 mRotationX = rotationX;
5301 mMatrixDirty = true;
5302 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005303 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005304 }
5305 }
5306
5307 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005308 * The amount that the view is scaled in x around the pivot point, as a proportion of
5309 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5310 *
Joe Onorato93162322010-09-16 15:42:01 -04005311 * <p>By default, this is 1.0f.
5312 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005313 * @see #getPivotX()
5314 * @see #getPivotY()
5315 * @return The scaling factor.
5316 */
5317 public float getScaleX() {
5318 return mScaleX;
5319 }
5320
5321 /**
5322 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5323 * the view's unscaled width. A value of 1 means that no scaling is applied.
5324 *
5325 * @param scaleX The scaling factor.
5326 * @see #getPivotX()
5327 * @see #getPivotY()
5328 */
5329 public void setScaleX(float scaleX) {
5330 if (mScaleX != scaleX) {
5331 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005332 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005333 mScaleX = scaleX;
5334 mMatrixDirty = true;
5335 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005336 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005337 }
5338 }
5339
5340 /**
5341 * The amount that the view is scaled in y around the pivot point, as a proportion of
5342 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5343 *
Joe Onorato93162322010-09-16 15:42:01 -04005344 * <p>By default, this is 1.0f.
5345 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005346 * @see #getPivotX()
5347 * @see #getPivotY()
5348 * @return The scaling factor.
5349 */
5350 public float getScaleY() {
5351 return mScaleY;
5352 }
5353
5354 /**
5355 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5356 * the view's unscaled width. A value of 1 means that no scaling is applied.
5357 *
5358 * @param scaleY The scaling factor.
5359 * @see #getPivotX()
5360 * @see #getPivotY()
5361 */
5362 public void setScaleY(float scaleY) {
5363 if (mScaleY != scaleY) {
5364 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005365 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005366 mScaleY = scaleY;
5367 mMatrixDirty = true;
5368 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005369 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005370 }
5371 }
5372
5373 /**
5374 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5375 * and {@link #setScaleX(float) scaled}.
5376 *
5377 * @see #getRotation()
5378 * @see #getScaleX()
5379 * @see #getScaleY()
5380 * @see #getPivotY()
5381 * @return The x location of the pivot point.
5382 */
5383 public float getPivotX() {
5384 return mPivotX;
5385 }
5386
5387 /**
5388 * Sets the x location of the point around which the view is
5389 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005390 * By default, the pivot point is centered on the object.
5391 * Setting this property disables this behavior and causes the view to use only the
5392 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005393 *
5394 * @param pivotX The x location of the pivot point.
5395 * @see #getRotation()
5396 * @see #getScaleX()
5397 * @see #getScaleY()
5398 * @see #getPivotY()
5399 */
5400 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005401 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005402 if (mPivotX != pivotX) {
5403 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005404 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005405 mPivotX = pivotX;
5406 mMatrixDirty = true;
5407 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005408 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005409 }
5410 }
5411
5412 /**
5413 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5414 * and {@link #setScaleY(float) scaled}.
5415 *
5416 * @see #getRotation()
5417 * @see #getScaleX()
5418 * @see #getScaleY()
5419 * @see #getPivotY()
5420 * @return The y location of the pivot point.
5421 */
5422 public float getPivotY() {
5423 return mPivotY;
5424 }
5425
5426 /**
5427 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005428 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5429 * Setting this property disables this behavior and causes the view to use only the
5430 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005431 *
5432 * @param pivotY The y location of the pivot point.
5433 * @see #getRotation()
5434 * @see #getScaleX()
5435 * @see #getScaleY()
5436 * @see #getPivotY()
5437 */
5438 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005439 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005440 if (mPivotY != pivotY) {
5441 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005442 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005443 mPivotY = pivotY;
5444 mMatrixDirty = true;
5445 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005446 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005447 }
5448 }
5449
5450 /**
5451 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5452 * completely transparent and 1 means the view is completely opaque.
5453 *
Joe Onorato93162322010-09-16 15:42:01 -04005454 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005455 * @return The opacity of the view.
5456 */
5457 public float getAlpha() {
5458 return mAlpha;
5459 }
5460
5461 /**
5462 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5463 * completely transparent and 1 means the view is completely opaque.
5464 *
5465 * @param alpha The opacity of the view.
5466 */
5467 public void setAlpha(float alpha) {
5468 mAlpha = alpha;
Chet Haaseed032702010-10-01 14:05:54 -07005469 if (onSetAlpha((int) (alpha * 255))) {
5470 // subclass is handling alpha - don't optimize rendering cache invalidation
5471 invalidate();
5472 } else {
5473 invalidate(false);
5474 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005475 }
5476
5477 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 * Top position of this view relative to its parent.
5479 *
5480 * @return The top of this view, in pixels.
5481 */
5482 @ViewDebug.CapturedViewProperty
5483 public final int getTop() {
5484 return mTop;
5485 }
5486
5487 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005488 * Sets the top position of this view relative to its parent. This method is meant to be called
5489 * by the layout system and should not generally be called otherwise, because the property
5490 * may be changed at any time by the layout.
5491 *
5492 * @param top The top of this view, in pixels.
5493 */
5494 public final void setTop(int top) {
5495 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07005496 updateMatrix();
5497 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005498 final ViewParent p = mParent;
5499 if (p != null && mAttachInfo != null) {
5500 final Rect r = mAttachInfo.mTmpInvalRect;
5501 int minTop;
5502 int yLoc;
5503 if (top < mTop) {
5504 minTop = top;
5505 yLoc = top - mTop;
5506 } else {
5507 minTop = mTop;
5508 yLoc = 0;
5509 }
5510 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5511 p.invalidateChild(this, r);
5512 }
5513 } else {
5514 // Double-invalidation is necessary to capture view's old and new areas
5515 invalidate();
5516 }
5517
Chet Haaseed032702010-10-01 14:05:54 -07005518 int width = mRight - mLeft;
5519 int oldHeight = mBottom - mTop;
5520
Chet Haase21cd1382010-09-01 17:42:29 -07005521 mTop = top;
5522
Chet Haaseed032702010-10-01 14:05:54 -07005523 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5524
Chet Haase21cd1382010-09-01 17:42:29 -07005525 if (!mMatrixIsIdentity) {
5526 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5527 invalidate();
5528 }
5529 }
5530 }
5531
5532 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005533 * Bottom position of this view relative to its parent.
5534 *
5535 * @return The bottom of this view, in pixels.
5536 */
5537 @ViewDebug.CapturedViewProperty
5538 public final int getBottom() {
5539 return mBottom;
5540 }
5541
5542 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005543 * Sets the bottom position of this view relative to its parent. This method is meant to be
5544 * called by the layout system and should not generally be called otherwise, because the
5545 * property may be changed at any time by the layout.
5546 *
5547 * @param bottom The bottom of this view, in pixels.
5548 */
5549 public final void setBottom(int bottom) {
5550 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07005551 updateMatrix();
5552 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005553 final ViewParent p = mParent;
5554 if (p != null && mAttachInfo != null) {
5555 final Rect r = mAttachInfo.mTmpInvalRect;
5556 int maxBottom;
5557 if (bottom < mBottom) {
5558 maxBottom = mBottom;
5559 } else {
5560 maxBottom = bottom;
5561 }
5562 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5563 p.invalidateChild(this, r);
5564 }
5565 } else {
5566 // Double-invalidation is necessary to capture view's old and new areas
5567 invalidate();
5568 }
5569
Chet Haaseed032702010-10-01 14:05:54 -07005570 int width = mRight - mLeft;
5571 int oldHeight = mBottom - mTop;
5572
Chet Haase21cd1382010-09-01 17:42:29 -07005573 mBottom = bottom;
5574
Chet Haaseed032702010-10-01 14:05:54 -07005575 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5576
Chet Haase21cd1382010-09-01 17:42:29 -07005577 if (!mMatrixIsIdentity) {
5578 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5579 invalidate();
5580 }
5581 }
5582 }
5583
5584 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 * Left position of this view relative to its parent.
5586 *
5587 * @return The left edge of this view, in pixels.
5588 */
5589 @ViewDebug.CapturedViewProperty
5590 public final int getLeft() {
5591 return mLeft;
5592 }
5593
5594 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005595 * Sets the left position of this view relative to its parent. This method is meant to be called
5596 * by the layout system and should not generally be called otherwise, because the property
5597 * may be changed at any time by the layout.
5598 *
5599 * @param left The bottom of this view, in pixels.
5600 */
5601 public final void setLeft(int left) {
5602 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07005603 updateMatrix();
5604 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005605 final ViewParent p = mParent;
5606 if (p != null && mAttachInfo != null) {
5607 final Rect r = mAttachInfo.mTmpInvalRect;
5608 int minLeft;
5609 int xLoc;
5610 if (left < mLeft) {
5611 minLeft = left;
5612 xLoc = left - mLeft;
5613 } else {
5614 minLeft = mLeft;
5615 xLoc = 0;
5616 }
5617 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
5618 p.invalidateChild(this, r);
5619 }
5620 } else {
5621 // Double-invalidation is necessary to capture view's old and new areas
5622 invalidate();
5623 }
5624
Chet Haaseed032702010-10-01 14:05:54 -07005625 int oldWidth = mRight - mLeft;
5626 int height = mBottom - mTop;
5627
Chet Haase21cd1382010-09-01 17:42:29 -07005628 mLeft = left;
5629
Chet Haaseed032702010-10-01 14:05:54 -07005630 onSizeChanged(mRight - mLeft, height, oldWidth, height);
5631
Chet Haase21cd1382010-09-01 17:42:29 -07005632 if (!mMatrixIsIdentity) {
5633 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5634 invalidate();
5635 }
Chet Haaseed032702010-10-01 14:05:54 -07005636
Chet Haase21cd1382010-09-01 17:42:29 -07005637 }
5638 }
5639
5640 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 * Right position of this view relative to its parent.
5642 *
5643 * @return The right edge of this view, in pixels.
5644 */
5645 @ViewDebug.CapturedViewProperty
5646 public final int getRight() {
5647 return mRight;
5648 }
5649
5650 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005651 * Sets the right position of this view relative to its parent. This method is meant to be called
5652 * by the layout system and should not generally be called otherwise, because the property
5653 * may be changed at any time by the layout.
5654 *
5655 * @param right The bottom of this view, in pixels.
5656 */
5657 public final void setRight(int right) {
5658 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07005659 updateMatrix();
5660 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005661 final ViewParent p = mParent;
5662 if (p != null && mAttachInfo != null) {
5663 final Rect r = mAttachInfo.mTmpInvalRect;
5664 int maxRight;
5665 if (right < mRight) {
5666 maxRight = mRight;
5667 } else {
5668 maxRight = right;
5669 }
5670 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
5671 p.invalidateChild(this, r);
5672 }
5673 } else {
5674 // Double-invalidation is necessary to capture view's old and new areas
5675 invalidate();
5676 }
5677
Chet Haaseed032702010-10-01 14:05:54 -07005678 int oldWidth = mRight - mLeft;
5679 int height = mBottom - mTop;
5680
Chet Haase21cd1382010-09-01 17:42:29 -07005681 mRight = right;
5682
Chet Haaseed032702010-10-01 14:05:54 -07005683 onSizeChanged(mRight - mLeft, height, oldWidth, height);
5684
Chet Haase21cd1382010-09-01 17:42:29 -07005685 if (!mMatrixIsIdentity) {
5686 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5687 invalidate();
5688 }
5689 }
5690 }
5691
5692 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005693 * The visual x position of this view, in pixels. This is equivalent to the
5694 * {@link #setTranslationX(float) translationX} property plus the current
5695 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07005696 *
Chet Haasedf030d22010-07-30 17:22:38 -07005697 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005698 */
Chet Haasedf030d22010-07-30 17:22:38 -07005699 public float getX() {
5700 return mLeft + mTranslationX;
5701 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005702
Chet Haasedf030d22010-07-30 17:22:38 -07005703 /**
5704 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
5705 * {@link #setTranslationX(float) translationX} property to be the difference between
5706 * the x value passed in and the current {@link #getLeft() left} property.
5707 *
5708 * @param x The visual x position of this view, in pixels.
5709 */
5710 public void setX(float x) {
5711 setTranslationX(x - mLeft);
5712 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005713
Chet Haasedf030d22010-07-30 17:22:38 -07005714 /**
5715 * The visual y position of this view, in pixels. This is equivalent to the
5716 * {@link #setTranslationY(float) translationY} property plus the current
5717 * {@link #getTop() top} property.
5718 *
5719 * @return The visual y position of this view, in pixels.
5720 */
5721 public float getY() {
5722 return mTop + mTranslationY;
5723 }
5724
5725 /**
5726 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
5727 * {@link #setTranslationY(float) translationY} property to be the difference between
5728 * the y value passed in and the current {@link #getTop() top} property.
5729 *
5730 * @param y The visual y position of this view, in pixels.
5731 */
5732 public void setY(float y) {
5733 setTranslationY(y - mTop);
5734 }
5735
5736
5737 /**
5738 * The horizontal location of this view relative to its {@link #getLeft() left} position.
5739 * This position is post-layout, in addition to wherever the object's
5740 * layout placed it.
5741 *
5742 * @return The horizontal position of this view relative to its left position, in pixels.
5743 */
5744 public float getTranslationX() {
5745 return mTranslationX;
5746 }
5747
5748 /**
5749 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
5750 * This effectively positions the object post-layout, in addition to wherever the object's
5751 * layout placed it.
5752 *
5753 * @param translationX The horizontal position of this view relative to its left position,
5754 * in pixels.
5755 */
5756 public void setTranslationX(float translationX) {
5757 if (mTranslationX != translationX) {
5758 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005759 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07005760 mTranslationX = translationX;
5761 mMatrixDirty = true;
5762 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005763 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005764 }
5765 }
5766
5767 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005768 * The horizontal location of this view relative to its {@link #getTop() top} position.
5769 * This position is post-layout, in addition to wherever the object's
5770 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005771 *
Chet Haasedf030d22010-07-30 17:22:38 -07005772 * @return The vertical position of this view relative to its top position,
5773 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005774 */
Chet Haasedf030d22010-07-30 17:22:38 -07005775 public float getTranslationY() {
5776 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07005777 }
5778
5779 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005780 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
5781 * This effectively positions the object post-layout, in addition to wherever the object's
5782 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005783 *
Chet Haasedf030d22010-07-30 17:22:38 -07005784 * @param translationY The vertical position of this view relative to its top position,
5785 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005786 */
Chet Haasedf030d22010-07-30 17:22:38 -07005787 public void setTranslationY(float translationY) {
5788 if (mTranslationY != translationY) {
5789 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005790 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07005791 mTranslationY = translationY;
5792 mMatrixDirty = true;
5793 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005794 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07005795 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005796 }
5797
5798 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 * Hit rectangle in parent's coordinates
5800 *
5801 * @param outRect The hit rectangle of the view.
5802 */
5803 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07005804 updateMatrix();
5805 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005806 outRect.set(mLeft, mTop, mRight, mBottom);
5807 } else {
5808 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07005809 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07005810 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07005811 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
5812 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07005813 }
5814 }
5815
5816 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07005817 * Determines whether the given point, in local coordinates is inside the view.
5818 */
5819 /*package*/ final boolean pointInView(float localX, float localY) {
5820 return localX >= 0 && localX < (mRight - mLeft)
5821 && localY >= 0 && localY < (mBottom - mTop);
5822 }
5823
5824 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005825 * Utility method to determine whether the given point, in local coordinates,
5826 * is inside the view, where the area of the view is expanded by the slop factor.
5827 * This method is called while processing touch-move events to determine if the event
5828 * is still within the view.
5829 */
5830 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07005831 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07005832 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005833 }
5834
5835 /**
5836 * When a view has focus and the user navigates away from it, the next view is searched for
5837 * starting from the rectangle filled in by this method.
5838 *
5839 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
5840 * view maintains some idea of internal selection, such as a cursor, or a selected row
5841 * or column, you should override this method and fill in a more specific rectangle.
5842 *
5843 * @param r The rectangle to fill in, in this view's coordinates.
5844 */
5845 public void getFocusedRect(Rect r) {
5846 getDrawingRect(r);
5847 }
5848
5849 /**
5850 * If some part of this view is not clipped by any of its parents, then
5851 * return that area in r in global (root) coordinates. To convert r to local
5852 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
5853 * -globalOffset.y)) If the view is completely clipped or translated out,
5854 * return false.
5855 *
5856 * @param r If true is returned, r holds the global coordinates of the
5857 * visible portion of this view.
5858 * @param globalOffset If true is returned, globalOffset holds the dx,dy
5859 * between this view and its root. globalOffet may be null.
5860 * @return true if r is non-empty (i.e. part of the view is visible at the
5861 * root level.
5862 */
5863 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
5864 int width = mRight - mLeft;
5865 int height = mBottom - mTop;
5866 if (width > 0 && height > 0) {
5867 r.set(0, 0, width, height);
5868 if (globalOffset != null) {
5869 globalOffset.set(-mScrollX, -mScrollY);
5870 }
5871 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
5872 }
5873 return false;
5874 }
5875
5876 public final boolean getGlobalVisibleRect(Rect r) {
5877 return getGlobalVisibleRect(r, null);
5878 }
5879
5880 public final boolean getLocalVisibleRect(Rect r) {
5881 Point offset = new Point();
5882 if (getGlobalVisibleRect(r, offset)) {
5883 r.offset(-offset.x, -offset.y); // make r local
5884 return true;
5885 }
5886 return false;
5887 }
5888
5889 /**
5890 * Offset this view's vertical location by the specified number of pixels.
5891 *
5892 * @param offset the number of pixels to offset the view by
5893 */
5894 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005895 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07005896 updateMatrix();
5897 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005898 final ViewParent p = mParent;
5899 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005900 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005901 int minTop;
5902 int maxBottom;
5903 int yLoc;
5904 if (offset < 0) {
5905 minTop = mTop + offset;
5906 maxBottom = mBottom;
5907 yLoc = offset;
5908 } else {
5909 minTop = mTop;
5910 maxBottom = mBottom + offset;
5911 yLoc = 0;
5912 }
5913 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
5914 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005915 }
5916 } else {
Chet Haaseed032702010-10-01 14:05:54 -07005917 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005918 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005919
Chet Haasec3aa3612010-06-17 08:50:37 -07005920 mTop += offset;
5921 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005922
Chet Haasec3aa3612010-06-17 08:50:37 -07005923 if (!mMatrixIsIdentity) {
5924 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005925 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005926 }
5927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005928 }
5929
5930 /**
5931 * Offset this view's horizontal location by the specified amount of pixels.
5932 *
5933 * @param offset the numer of pixels to offset the view by
5934 */
5935 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005936 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07005937 updateMatrix();
5938 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005939 final ViewParent p = mParent;
5940 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005941 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005942 int minLeft;
5943 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005944 if (offset < 0) {
5945 minLeft = mLeft + offset;
5946 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005947 } else {
5948 minLeft = mLeft;
5949 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005950 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005951 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07005952 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005953 }
5954 } else {
Chet Haaseed032702010-10-01 14:05:54 -07005955 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005956 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005957
Chet Haasec3aa3612010-06-17 08:50:37 -07005958 mLeft += offset;
5959 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005960
Chet Haasec3aa3612010-06-17 08:50:37 -07005961 if (!mMatrixIsIdentity) {
5962 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005963 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005964 }
5965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 }
5967
5968 /**
5969 * Get the LayoutParams associated with this view. All views should have
5970 * layout parameters. These supply parameters to the <i>parent</i> of this
5971 * view specifying how it should be arranged. There are many subclasses of
5972 * ViewGroup.LayoutParams, and these correspond to the different subclasses
5973 * of ViewGroup that are responsible for arranging their children.
5974 * @return The LayoutParams associated with this view
5975 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07005976 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 public ViewGroup.LayoutParams getLayoutParams() {
5978 return mLayoutParams;
5979 }
5980
5981 /**
5982 * Set the layout parameters associated with this view. These supply
5983 * parameters to the <i>parent</i> of this view specifying how it should be
5984 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
5985 * correspond to the different subclasses of ViewGroup that are responsible
5986 * for arranging their children.
5987 *
5988 * @param params the layout parameters for this view
5989 */
5990 public void setLayoutParams(ViewGroup.LayoutParams params) {
5991 if (params == null) {
5992 throw new NullPointerException("params == null");
5993 }
5994 mLayoutParams = params;
5995 requestLayout();
5996 }
5997
5998 /**
5999 * Set the scrolled position of your view. This will cause a call to
6000 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6001 * invalidated.
6002 * @param x the x position to scroll to
6003 * @param y the y position to scroll to
6004 */
6005 public void scrollTo(int x, int y) {
6006 if (mScrollX != x || mScrollY != y) {
6007 int oldX = mScrollX;
6008 int oldY = mScrollY;
6009 mScrollX = x;
6010 mScrollY = y;
6011 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006012 if (!awakenScrollBars()) {
6013 invalidate();
6014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 }
6016 }
6017
6018 /**
6019 * Move the scrolled position of your view. This will cause a call to
6020 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6021 * invalidated.
6022 * @param x the amount of pixels to scroll by horizontally
6023 * @param y the amount of pixels to scroll by vertically
6024 */
6025 public void scrollBy(int x, int y) {
6026 scrollTo(mScrollX + x, mScrollY + y);
6027 }
6028
6029 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006030 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6031 * animation to fade the scrollbars out after a default delay. If a subclass
6032 * provides animated scrolling, the start delay should equal the duration
6033 * of the scrolling animation.</p>
6034 *
6035 * <p>The animation starts only if at least one of the scrollbars is
6036 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6037 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6038 * this method returns true, and false otherwise. If the animation is
6039 * started, this method calls {@link #invalidate()}; in that case the
6040 * caller should not call {@link #invalidate()}.</p>
6041 *
6042 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006043 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006044 *
6045 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6046 * and {@link #scrollTo(int, int)}.</p>
6047 *
6048 * @return true if the animation is played, false otherwise
6049 *
6050 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006051 * @see #scrollBy(int, int)
6052 * @see #scrollTo(int, int)
6053 * @see #isHorizontalScrollBarEnabled()
6054 * @see #isVerticalScrollBarEnabled()
6055 * @see #setHorizontalScrollBarEnabled(boolean)
6056 * @see #setVerticalScrollBarEnabled(boolean)
6057 */
6058 protected boolean awakenScrollBars() {
6059 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006060 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006061 }
6062
6063 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006064 * Trigger the scrollbars to draw.
6065 * This method differs from awakenScrollBars() only in its default duration.
6066 * initialAwakenScrollBars() will show the scroll bars for longer than
6067 * usual to give the user more of a chance to notice them.
6068 *
6069 * @return true if the animation is played, false otherwise.
6070 */
6071 private boolean initialAwakenScrollBars() {
6072 return mScrollCache != null &&
6073 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6074 }
6075
6076 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006077 * <p>
6078 * Trigger the scrollbars to draw. When invoked this method starts an
6079 * animation to fade the scrollbars out after a fixed delay. If a subclass
6080 * provides animated scrolling, the start delay should equal the duration of
6081 * the scrolling animation.
6082 * </p>
6083 *
6084 * <p>
6085 * The animation starts only if at least one of the scrollbars is enabled,
6086 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6087 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6088 * this method returns true, and false otherwise. If the animation is
6089 * started, this method calls {@link #invalidate()}; in that case the caller
6090 * should not call {@link #invalidate()}.
6091 * </p>
6092 *
6093 * <p>
6094 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006095 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006096 * </p>
6097 *
6098 * @param startDelay the delay, in milliseconds, after which the animation
6099 * should start; when the delay is 0, the animation starts
6100 * immediately
6101 * @return true if the animation is played, false otherwise
6102 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006103 * @see #scrollBy(int, int)
6104 * @see #scrollTo(int, int)
6105 * @see #isHorizontalScrollBarEnabled()
6106 * @see #isVerticalScrollBarEnabled()
6107 * @see #setHorizontalScrollBarEnabled(boolean)
6108 * @see #setVerticalScrollBarEnabled(boolean)
6109 */
6110 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006111 return awakenScrollBars(startDelay, true);
6112 }
6113
6114 /**
6115 * <p>
6116 * Trigger the scrollbars to draw. When invoked this method starts an
6117 * animation to fade the scrollbars out after a fixed delay. If a subclass
6118 * provides animated scrolling, the start delay should equal the duration of
6119 * the scrolling animation.
6120 * </p>
6121 *
6122 * <p>
6123 * The animation starts only if at least one of the scrollbars is enabled,
6124 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6125 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6126 * this method returns true, and false otherwise. If the animation is
6127 * started, this method calls {@link #invalidate()} if the invalidate parameter
6128 * is set to true; in that case the caller
6129 * should not call {@link #invalidate()}.
6130 * </p>
6131 *
6132 * <p>
6133 * This method should be invoked everytime a subclass directly updates the
6134 * scroll parameters.
6135 * </p>
6136 *
6137 * @param startDelay the delay, in milliseconds, after which the animation
6138 * should start; when the delay is 0, the animation starts
6139 * immediately
6140 *
6141 * @param invalidate Wheter this method should call invalidate
6142 *
6143 * @return true if the animation is played, false otherwise
6144 *
6145 * @see #scrollBy(int, int)
6146 * @see #scrollTo(int, int)
6147 * @see #isHorizontalScrollBarEnabled()
6148 * @see #isVerticalScrollBarEnabled()
6149 * @see #setHorizontalScrollBarEnabled(boolean)
6150 * @see #setVerticalScrollBarEnabled(boolean)
6151 */
6152 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006153 final ScrollabilityCache scrollCache = mScrollCache;
6154
6155 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6156 return false;
6157 }
6158
6159 if (scrollCache.scrollBar == null) {
6160 scrollCache.scrollBar = new ScrollBarDrawable();
6161 }
6162
6163 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6164
Mike Cleron290947b2009-09-29 18:34:32 -07006165 if (invalidate) {
6166 // Invalidate to show the scrollbars
6167 invalidate();
6168 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006169
6170 if (scrollCache.state == ScrollabilityCache.OFF) {
6171 // FIXME: this is copied from WindowManagerService.
6172 // We should get this value from the system when it
6173 // is possible to do so.
6174 final int KEY_REPEAT_FIRST_DELAY = 750;
6175 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6176 }
6177
6178 // Tell mScrollCache when we should start fading. This may
6179 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006180 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006181 scrollCache.fadeStartTime = fadeStartTime;
6182 scrollCache.state = ScrollabilityCache.ON;
6183
6184 // Schedule our fader to run, unscheduling any old ones first
6185 if (mAttachInfo != null) {
6186 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6187 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6188 }
6189
6190 return true;
6191 }
6192
6193 return false;
6194 }
6195
6196 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 * Mark the the area defined by dirty as needing to be drawn. If the view is
6198 * visible, {@link #onDraw} will be called at some point in the future.
6199 * This must be called from a UI thread. To call from a non-UI thread, call
6200 * {@link #postInvalidate()}.
6201 *
6202 * WARNING: This method is destructive to dirty.
6203 * @param dirty the rectangle representing the bounds of the dirty region
6204 */
6205 public void invalidate(Rect dirty) {
6206 if (ViewDebug.TRACE_HIERARCHY) {
6207 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6208 }
6209
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006210 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6211 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6213 final ViewParent p = mParent;
6214 final AttachInfo ai = mAttachInfo;
6215 if (p != null && ai != null) {
6216 final int scrollX = mScrollX;
6217 final int scrollY = mScrollY;
6218 final Rect r = ai.mTmpInvalRect;
6219 r.set(dirty.left - scrollX, dirty.top - scrollY,
6220 dirty.right - scrollX, dirty.bottom - scrollY);
6221 mParent.invalidateChild(this, r);
6222 }
6223 }
6224 }
6225
6226 /**
6227 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6228 * The coordinates of the dirty rect are relative to the view.
6229 * If the view is visible, {@link #onDraw} will be called at some point
6230 * in the future. This must be called from a UI thread. To call
6231 * from a non-UI thread, call {@link #postInvalidate()}.
6232 * @param l the left position of the dirty region
6233 * @param t the top position of the dirty region
6234 * @param r the right position of the dirty region
6235 * @param b the bottom position of the dirty region
6236 */
6237 public void invalidate(int l, int t, int r, int b) {
6238 if (ViewDebug.TRACE_HIERARCHY) {
6239 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6240 }
6241
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006242 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6243 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6245 final ViewParent p = mParent;
6246 final AttachInfo ai = mAttachInfo;
6247 if (p != null && ai != null && l < r && t < b) {
6248 final int scrollX = mScrollX;
6249 final int scrollY = mScrollY;
6250 final Rect tmpr = ai.mTmpInvalRect;
6251 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6252 p.invalidateChild(this, tmpr);
6253 }
6254 }
6255 }
6256
6257 /**
6258 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6259 * be called at some point in the future. This must be called from a
6260 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6261 */
6262 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006263 invalidate(true);
6264 }
6265
6266 /**
6267 * This is where the invalidate() work actually happens. A full invalidate()
6268 * causes the drawing cache to be invalidated, but this function can be called with
6269 * invalidateCache set to false to skip that invalidation step for cases that do not
6270 * need it (for example, a component that remains at the same dimensions with the same
6271 * content).
6272 *
6273 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6274 * well. This is usually true for a full invalidate, but may be set to false if the
6275 * View's contents or dimensions have not changed.
6276 */
6277 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 if (ViewDebug.TRACE_HIERARCHY) {
6279 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6280 }
6281
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006282 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6283 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID)) {
Chet Haaseed032702010-10-01 14:05:54 -07006284 mPrivateFlags &= ~DRAWN;
6285 if (invalidateCache) {
6286 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 final ViewParent p = mParent;
6289 final AttachInfo ai = mAttachInfo;
6290 if (p != null && ai != null) {
6291 final Rect r = ai.mTmpInvalRect;
6292 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6293 // Don't call invalidate -- we don't want to internally scroll
6294 // our own bounds
6295 p.invalidateChild(this, r);
6296 }
6297 }
6298 }
6299
6300 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006301 * Indicates whether this View is opaque. An opaque View guarantees that it will
6302 * draw all the pixels overlapping its bounds using a fully opaque color.
6303 *
6304 * Subclasses of View should override this method whenever possible to indicate
6305 * whether an instance is opaque. Opaque Views are treated in a special way by
6306 * the View hierarchy, possibly allowing it to perform optimizations during
6307 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006308 *
Romain Guy24443ea2009-05-11 11:56:30 -07006309 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006310 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006311 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006312 public boolean isOpaque() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006313 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
6314 }
6315
6316 private void computeOpaqueFlags() {
6317 // Opaque if:
6318 // - Has a background
6319 // - Background is opaque
6320 // - Doesn't have scrollbars or scrollbars are inside overlay
6321
6322 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6323 mPrivateFlags |= OPAQUE_BACKGROUND;
6324 } else {
6325 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6326 }
6327
6328 final int flags = mViewFlags;
6329 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6330 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6331 mPrivateFlags |= OPAQUE_SCROLLBARS;
6332 } else {
6333 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6334 }
6335 }
6336
6337 /**
6338 * @hide
6339 */
6340 protected boolean hasOpaqueScrollbars() {
6341 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006342 }
6343
6344 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 * @return A handler associated with the thread running the View. This
6346 * handler can be used to pump events in the UI events queue.
6347 */
6348 public Handler getHandler() {
6349 if (mAttachInfo != null) {
6350 return mAttachInfo.mHandler;
6351 }
6352 return null;
6353 }
6354
6355 /**
6356 * Causes the Runnable to be added to the message queue.
6357 * The runnable will be run on the user interface thread.
6358 *
6359 * @param action The Runnable that will be executed.
6360 *
6361 * @return Returns true if the Runnable was successfully placed in to the
6362 * message queue. Returns false on failure, usually because the
6363 * looper processing the message queue is exiting.
6364 */
6365 public boolean post(Runnable action) {
6366 Handler handler;
6367 if (mAttachInfo != null) {
6368 handler = mAttachInfo.mHandler;
6369 } else {
6370 // Assume that post will succeed later
6371 ViewRoot.getRunQueue().post(action);
6372 return true;
6373 }
6374
6375 return handler.post(action);
6376 }
6377
6378 /**
6379 * Causes the Runnable to be added to the message queue, to be run
6380 * after the specified amount of time elapses.
6381 * The runnable will be run on the user interface thread.
6382 *
6383 * @param action The Runnable that will be executed.
6384 * @param delayMillis The delay (in milliseconds) until the Runnable
6385 * will be executed.
6386 *
6387 * @return true if the Runnable was successfully placed in to the
6388 * message queue. Returns false on failure, usually because the
6389 * looper processing the message queue is exiting. Note that a
6390 * result of true does not mean the Runnable will be processed --
6391 * if the looper is quit before the delivery time of the message
6392 * occurs then the message will be dropped.
6393 */
6394 public boolean postDelayed(Runnable action, long delayMillis) {
6395 Handler handler;
6396 if (mAttachInfo != null) {
6397 handler = mAttachInfo.mHandler;
6398 } else {
6399 // Assume that post will succeed later
6400 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6401 return true;
6402 }
6403
6404 return handler.postDelayed(action, delayMillis);
6405 }
6406
6407 /**
6408 * Removes the specified Runnable from the message queue.
6409 *
6410 * @param action The Runnable to remove from the message handling queue
6411 *
6412 * @return true if this view could ask the Handler to remove the Runnable,
6413 * false otherwise. When the returned value is true, the Runnable
6414 * may or may not have been actually removed from the message queue
6415 * (for instance, if the Runnable was not in the queue already.)
6416 */
6417 public boolean removeCallbacks(Runnable action) {
6418 Handler handler;
6419 if (mAttachInfo != null) {
6420 handler = mAttachInfo.mHandler;
6421 } else {
6422 // Assume that post will succeed later
6423 ViewRoot.getRunQueue().removeCallbacks(action);
6424 return true;
6425 }
6426
6427 handler.removeCallbacks(action);
6428 return true;
6429 }
6430
6431 /**
6432 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6433 * Use this to invalidate the View from a non-UI thread.
6434 *
6435 * @see #invalidate()
6436 */
6437 public void postInvalidate() {
6438 postInvalidateDelayed(0);
6439 }
6440
6441 /**
6442 * Cause an invalidate of the specified area to happen on a subsequent cycle
6443 * through the event loop. Use this to invalidate the View from a non-UI thread.
6444 *
6445 * @param left The left coordinate of the rectangle to invalidate.
6446 * @param top The top coordinate of the rectangle to invalidate.
6447 * @param right The right coordinate of the rectangle to invalidate.
6448 * @param bottom The bottom coordinate of the rectangle to invalidate.
6449 *
6450 * @see #invalidate(int, int, int, int)
6451 * @see #invalidate(Rect)
6452 */
6453 public void postInvalidate(int left, int top, int right, int bottom) {
6454 postInvalidateDelayed(0, left, top, right, bottom);
6455 }
6456
6457 /**
6458 * Cause an invalidate to happen on a subsequent cycle through the event
6459 * loop. Waits for the specified amount of time.
6460 *
6461 * @param delayMilliseconds the duration in milliseconds to delay the
6462 * invalidation by
6463 */
6464 public void postInvalidateDelayed(long delayMilliseconds) {
6465 // We try only with the AttachInfo because there's no point in invalidating
6466 // if we are not attached to our window
6467 if (mAttachInfo != null) {
6468 Message msg = Message.obtain();
6469 msg.what = AttachInfo.INVALIDATE_MSG;
6470 msg.obj = this;
6471 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6472 }
6473 }
6474
6475 /**
6476 * Cause an invalidate of the specified area to happen on a subsequent cycle
6477 * through the event loop. Waits for the specified amount of time.
6478 *
6479 * @param delayMilliseconds the duration in milliseconds to delay the
6480 * invalidation by
6481 * @param left The left coordinate of the rectangle to invalidate.
6482 * @param top The top coordinate of the rectangle to invalidate.
6483 * @param right The right coordinate of the rectangle to invalidate.
6484 * @param bottom The bottom coordinate of the rectangle to invalidate.
6485 */
6486 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6487 int right, int bottom) {
6488
6489 // We try only with the AttachInfo because there's no point in invalidating
6490 // if we are not attached to our window
6491 if (mAttachInfo != null) {
6492 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6493 info.target = this;
6494 info.left = left;
6495 info.top = top;
6496 info.right = right;
6497 info.bottom = bottom;
6498
6499 final Message msg = Message.obtain();
6500 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6501 msg.obj = info;
6502 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6503 }
6504 }
6505
6506 /**
6507 * Called by a parent to request that a child update its values for mScrollX
6508 * and mScrollY if necessary. This will typically be done if the child is
6509 * animating a scroll using a {@link android.widget.Scroller Scroller}
6510 * object.
6511 */
6512 public void computeScroll() {
6513 }
6514
6515 /**
6516 * <p>Indicate whether the horizontal edges are faded when the view is
6517 * scrolled horizontally.</p>
6518 *
6519 * @return true if the horizontal edges should are faded on scroll, false
6520 * otherwise
6521 *
6522 * @see #setHorizontalFadingEdgeEnabled(boolean)
6523 * @attr ref android.R.styleable#View_fadingEdge
6524 */
6525 public boolean isHorizontalFadingEdgeEnabled() {
6526 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6527 }
6528
6529 /**
6530 * <p>Define whether the horizontal edges should be faded when this view
6531 * is scrolled horizontally.</p>
6532 *
6533 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6534 * be faded when the view is scrolled
6535 * horizontally
6536 *
6537 * @see #isHorizontalFadingEdgeEnabled()
6538 * @attr ref android.R.styleable#View_fadingEdge
6539 */
6540 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6541 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6542 if (horizontalFadingEdgeEnabled) {
6543 initScrollCache();
6544 }
6545
6546 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6547 }
6548 }
6549
6550 /**
6551 * <p>Indicate whether the vertical edges are faded when the view is
6552 * scrolled horizontally.</p>
6553 *
6554 * @return true if the vertical edges should are faded on scroll, false
6555 * otherwise
6556 *
6557 * @see #setVerticalFadingEdgeEnabled(boolean)
6558 * @attr ref android.R.styleable#View_fadingEdge
6559 */
6560 public boolean isVerticalFadingEdgeEnabled() {
6561 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6562 }
6563
6564 /**
6565 * <p>Define whether the vertical edges should be faded when this view
6566 * is scrolled vertically.</p>
6567 *
6568 * @param verticalFadingEdgeEnabled true if the vertical edges should
6569 * be faded when the view is scrolled
6570 * vertically
6571 *
6572 * @see #isVerticalFadingEdgeEnabled()
6573 * @attr ref android.R.styleable#View_fadingEdge
6574 */
6575 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6576 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6577 if (verticalFadingEdgeEnabled) {
6578 initScrollCache();
6579 }
6580
6581 mViewFlags ^= FADING_EDGE_VERTICAL;
6582 }
6583 }
6584
6585 /**
6586 * Returns the strength, or intensity, of the top faded edge. The strength is
6587 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6588 * returns 0.0 or 1.0 but no value in between.
6589 *
6590 * Subclasses should override this method to provide a smoother fade transition
6591 * when scrolling occurs.
6592 *
6593 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6594 */
6595 protected float getTopFadingEdgeStrength() {
6596 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6597 }
6598
6599 /**
6600 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6601 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6602 * returns 0.0 or 1.0 but no value in between.
6603 *
6604 * Subclasses should override this method to provide a smoother fade transition
6605 * when scrolling occurs.
6606 *
6607 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6608 */
6609 protected float getBottomFadingEdgeStrength() {
6610 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6611 computeVerticalScrollRange() ? 1.0f : 0.0f;
6612 }
6613
6614 /**
6615 * Returns the strength, or intensity, of the left faded edge. The strength is
6616 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6617 * returns 0.0 or 1.0 but no value in between.
6618 *
6619 * Subclasses should override this method to provide a smoother fade transition
6620 * when scrolling occurs.
6621 *
6622 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6623 */
6624 protected float getLeftFadingEdgeStrength() {
6625 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6626 }
6627
6628 /**
6629 * Returns the strength, or intensity, of the right faded edge. The strength is
6630 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6631 * returns 0.0 or 1.0 but no value in between.
6632 *
6633 * Subclasses should override this method to provide a smoother fade transition
6634 * when scrolling occurs.
6635 *
6636 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6637 */
6638 protected float getRightFadingEdgeStrength() {
6639 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6640 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6641 }
6642
6643 /**
6644 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6645 * scrollbar is not drawn by default.</p>
6646 *
6647 * @return true if the horizontal scrollbar should be painted, false
6648 * otherwise
6649 *
6650 * @see #setHorizontalScrollBarEnabled(boolean)
6651 */
6652 public boolean isHorizontalScrollBarEnabled() {
6653 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6654 }
6655
6656 /**
6657 * <p>Define whether the horizontal scrollbar should be drawn or not. The
6658 * scrollbar is not drawn by default.</p>
6659 *
6660 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
6661 * be painted
6662 *
6663 * @see #isHorizontalScrollBarEnabled()
6664 */
6665 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
6666 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
6667 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006668 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 recomputePadding();
6670 }
6671 }
6672
6673 /**
6674 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
6675 * scrollbar is not drawn by default.</p>
6676 *
6677 * @return true if the vertical scrollbar should be painted, false
6678 * otherwise
6679 *
6680 * @see #setVerticalScrollBarEnabled(boolean)
6681 */
6682 public boolean isVerticalScrollBarEnabled() {
6683 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
6684 }
6685
6686 /**
6687 * <p>Define whether the vertical scrollbar should be drawn or not. The
6688 * scrollbar is not drawn by default.</p>
6689 *
6690 * @param verticalScrollBarEnabled true if the vertical scrollbar should
6691 * be painted
6692 *
6693 * @see #isVerticalScrollBarEnabled()
6694 */
6695 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
6696 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
6697 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006698 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 recomputePadding();
6700 }
6701 }
6702
6703 private void recomputePadding() {
6704 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
6705 }
Mike Cleronfe81d382009-09-28 14:22:16 -07006706
6707 /**
6708 * Define whether scrollbars will fade when the view is not scrolling.
6709 *
6710 * @param fadeScrollbars wheter to enable fading
6711 *
6712 */
6713 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
6714 initScrollCache();
6715 final ScrollabilityCache scrollabilityCache = mScrollCache;
6716 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07006717 if (fadeScrollbars) {
6718 scrollabilityCache.state = ScrollabilityCache.OFF;
6719 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07006720 scrollabilityCache.state = ScrollabilityCache.ON;
6721 }
6722 }
6723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07006725 *
6726 * Returns true if scrollbars will fade when this view is not scrolling
6727 *
6728 * @return true if scrollbar fading is enabled
6729 */
6730 public boolean isScrollbarFadingEnabled() {
6731 return mScrollCache != null && mScrollCache.fadeScrollBars;
6732 }
6733
6734 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
6736 * inset. When inset, they add to the padding of the view. And the scrollbars
6737 * can be drawn inside the padding area or on the edge of the view. For example,
6738 * if a view has a background drawable and you want to draw the scrollbars
6739 * inside the padding specified by the drawable, you can use
6740 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
6741 * appear at the edge of the view, ignoring the padding, then you can use
6742 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
6743 * @param style the style of the scrollbars. Should be one of
6744 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
6745 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
6746 * @see #SCROLLBARS_INSIDE_OVERLAY
6747 * @see #SCROLLBARS_INSIDE_INSET
6748 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6749 * @see #SCROLLBARS_OUTSIDE_INSET
6750 */
6751 public void setScrollBarStyle(int style) {
6752 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
6753 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07006754 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 recomputePadding();
6756 }
6757 }
6758
6759 /**
6760 * <p>Returns the current scrollbar style.</p>
6761 * @return the current scrollbar style
6762 * @see #SCROLLBARS_INSIDE_OVERLAY
6763 * @see #SCROLLBARS_INSIDE_INSET
6764 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6765 * @see #SCROLLBARS_OUTSIDE_INSET
6766 */
6767 public int getScrollBarStyle() {
6768 return mViewFlags & SCROLLBARS_STYLE_MASK;
6769 }
6770
6771 /**
6772 * <p>Compute the horizontal range that the horizontal scrollbar
6773 * represents.</p>
6774 *
6775 * <p>The range is expressed in arbitrary units that must be the same as the
6776 * units used by {@link #computeHorizontalScrollExtent()} and
6777 * {@link #computeHorizontalScrollOffset()}.</p>
6778 *
6779 * <p>The default range is the drawing width of this view.</p>
6780 *
6781 * @return the total horizontal range represented by the horizontal
6782 * scrollbar
6783 *
6784 * @see #computeHorizontalScrollExtent()
6785 * @see #computeHorizontalScrollOffset()
6786 * @see android.widget.ScrollBarDrawable
6787 */
6788 protected int computeHorizontalScrollRange() {
6789 return getWidth();
6790 }
6791
6792 /**
6793 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
6794 * within the horizontal range. This value is used to compute the position
6795 * of the thumb within the scrollbar's track.</p>
6796 *
6797 * <p>The range is expressed in arbitrary units that must be the same as the
6798 * units used by {@link #computeHorizontalScrollRange()} and
6799 * {@link #computeHorizontalScrollExtent()}.</p>
6800 *
6801 * <p>The default offset is the scroll offset of this view.</p>
6802 *
6803 * @return the horizontal offset of the scrollbar's thumb
6804 *
6805 * @see #computeHorizontalScrollRange()
6806 * @see #computeHorizontalScrollExtent()
6807 * @see android.widget.ScrollBarDrawable
6808 */
6809 protected int computeHorizontalScrollOffset() {
6810 return mScrollX;
6811 }
6812
6813 /**
6814 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
6815 * within the horizontal range. This value is used to compute the length
6816 * of the thumb within the scrollbar's track.</p>
6817 *
6818 * <p>The range is expressed in arbitrary units that must be the same as the
6819 * units used by {@link #computeHorizontalScrollRange()} and
6820 * {@link #computeHorizontalScrollOffset()}.</p>
6821 *
6822 * <p>The default extent is the drawing width of this view.</p>
6823 *
6824 * @return the horizontal extent of the scrollbar's thumb
6825 *
6826 * @see #computeHorizontalScrollRange()
6827 * @see #computeHorizontalScrollOffset()
6828 * @see android.widget.ScrollBarDrawable
6829 */
6830 protected int computeHorizontalScrollExtent() {
6831 return getWidth();
6832 }
6833
6834 /**
6835 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
6836 *
6837 * <p>The range is expressed in arbitrary units that must be the same as the
6838 * units used by {@link #computeVerticalScrollExtent()} and
6839 * {@link #computeVerticalScrollOffset()}.</p>
6840 *
6841 * @return the total vertical range represented by the vertical scrollbar
6842 *
6843 * <p>The default range is the drawing height of this view.</p>
6844 *
6845 * @see #computeVerticalScrollExtent()
6846 * @see #computeVerticalScrollOffset()
6847 * @see android.widget.ScrollBarDrawable
6848 */
6849 protected int computeVerticalScrollRange() {
6850 return getHeight();
6851 }
6852
6853 /**
6854 * <p>Compute the vertical offset of the vertical scrollbar's thumb
6855 * within the horizontal range. This value is used to compute the position
6856 * of the thumb within the scrollbar's track.</p>
6857 *
6858 * <p>The range is expressed in arbitrary units that must be the same as the
6859 * units used by {@link #computeVerticalScrollRange()} and
6860 * {@link #computeVerticalScrollExtent()}.</p>
6861 *
6862 * <p>The default offset is the scroll offset of this view.</p>
6863 *
6864 * @return the vertical offset of the scrollbar's thumb
6865 *
6866 * @see #computeVerticalScrollRange()
6867 * @see #computeVerticalScrollExtent()
6868 * @see android.widget.ScrollBarDrawable
6869 */
6870 protected int computeVerticalScrollOffset() {
6871 return mScrollY;
6872 }
6873
6874 /**
6875 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
6876 * within the vertical range. This value is used to compute the length
6877 * of the thumb within the scrollbar's track.</p>
6878 *
6879 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08006880 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006881 * {@link #computeVerticalScrollOffset()}.</p>
6882 *
6883 * <p>The default extent is the drawing height of this view.</p>
6884 *
6885 * @return the vertical extent of the scrollbar's thumb
6886 *
6887 * @see #computeVerticalScrollRange()
6888 * @see #computeVerticalScrollOffset()
6889 * @see android.widget.ScrollBarDrawable
6890 */
6891 protected int computeVerticalScrollExtent() {
6892 return getHeight();
6893 }
6894
6895 /**
6896 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
6897 * scrollbars are painted only if they have been awakened first.</p>
6898 *
6899 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07006900 *
6901 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006902 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08006903 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006904 // scrollbars are drawn only when the animation is running
6905 final ScrollabilityCache cache = mScrollCache;
6906 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006907
6908 int state = cache.state;
6909
6910 if (state == ScrollabilityCache.OFF) {
6911 return;
6912 }
6913
6914 boolean invalidate = false;
6915
6916 if (state == ScrollabilityCache.FADING) {
6917 // We're fading -- get our fade interpolation
6918 if (cache.interpolatorValues == null) {
6919 cache.interpolatorValues = new float[1];
6920 }
6921
6922 float[] values = cache.interpolatorValues;
6923
6924 // Stops the animation if we're done
6925 if (cache.scrollBarInterpolator.timeToValues(values) ==
6926 Interpolator.Result.FREEZE_END) {
6927 cache.state = ScrollabilityCache.OFF;
6928 } else {
6929 cache.scrollBar.setAlpha(Math.round(values[0]));
6930 }
6931
6932 // This will make the scroll bars inval themselves after
6933 // drawing. We only want this when we're fading so that
6934 // we prevent excessive redraws
6935 invalidate = true;
6936 } else {
6937 // We're just on -- but we may have been fading before so
6938 // reset alpha
6939 cache.scrollBar.setAlpha(255);
6940 }
6941
6942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943 final int viewFlags = mViewFlags;
6944
6945 final boolean drawHorizontalScrollBar =
6946 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6947 final boolean drawVerticalScrollBar =
6948 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
6949 && !isVerticalScrollBarHidden();
6950
6951 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
6952 final int width = mRight - mLeft;
6953 final int height = mBottom - mTop;
6954
6955 final ScrollBarDrawable scrollBar = cache.scrollBar;
6956 int size = scrollBar.getSize(false);
6957 if (size <= 0) {
6958 size = cache.scrollBarSize;
6959 }
6960
Mike Reede8853fc2009-09-04 14:01:48 -04006961 final int scrollX = mScrollX;
6962 final int scrollY = mScrollY;
6963 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
6964
Mike Cleronf116bf82009-09-27 19:14:12 -07006965 int left, top, right, bottom;
6966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006968 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04006969 computeHorizontalScrollOffset(),
6970 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04006971 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07006972 getVerticalScrollbarWidth() : 0;
6973 top = scrollY + height - size - (mUserPaddingBottom & inside);
6974 left = scrollX + (mPaddingLeft & inside);
6975 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
6976 bottom = top + size;
6977 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
6978 if (invalidate) {
6979 invalidate(left, top, right, bottom);
6980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006981 }
6982
6983 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04006984 scrollBar.setParameters(computeVerticalScrollRange(),
6985 computeVerticalScrollOffset(),
6986 computeVerticalScrollExtent(), true);
6987 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07006988 left = scrollX + width - size - (mUserPaddingRight & inside);
6989 top = scrollY + (mPaddingTop & inside);
6990 right = left + size;
6991 bottom = scrollY + height - (mUserPaddingBottom & inside);
6992 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
6993 if (invalidate) {
6994 invalidate(left, top, right, bottom);
6995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006996 }
6997 }
6998 }
6999 }
Romain Guy8506ab42009-06-11 17:35:47 -07007000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007001 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007002 * 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 -08007003 * FastScroller is visible.
7004 * @return whether to temporarily hide the vertical scrollbar
7005 * @hide
7006 */
7007 protected boolean isVerticalScrollBarHidden() {
7008 return false;
7009 }
7010
7011 /**
7012 * <p>Draw the horizontal scrollbar if
7013 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7014 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 * @param canvas the canvas on which to draw the scrollbar
7016 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 *
7018 * @see #isHorizontalScrollBarEnabled()
7019 * @see #computeHorizontalScrollRange()
7020 * @see #computeHorizontalScrollExtent()
7021 * @see #computeHorizontalScrollOffset()
7022 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007023 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007024 */
Romain Guy8fb95422010-08-17 18:38:51 -07007025 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7026 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007027 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007028 scrollBar.draw(canvas);
7029 }
Mike Reede8853fc2009-09-04 14:01:48 -04007030
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007031 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007032 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7033 * returns true.</p>
7034 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 * @param canvas the canvas on which to draw the scrollbar
7036 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 *
7038 * @see #isVerticalScrollBarEnabled()
7039 * @see #computeVerticalScrollRange()
7040 * @see #computeVerticalScrollExtent()
7041 * @see #computeVerticalScrollOffset()
7042 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007043 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 */
Romain Guy8fb95422010-08-17 18:38:51 -07007045 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7046 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007047 scrollBar.setBounds(l, t, r, b);
7048 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007049 }
7050
7051 /**
7052 * Implement this to do your drawing.
7053 *
7054 * @param canvas the canvas on which the background will be drawn
7055 */
7056 protected void onDraw(Canvas canvas) {
7057 }
7058
7059 /*
7060 * Caller is responsible for calling requestLayout if necessary.
7061 * (This allows addViewInLayout to not request a new layout.)
7062 */
7063 void assignParent(ViewParent parent) {
7064 if (mParent == null) {
7065 mParent = parent;
7066 } else if (parent == null) {
7067 mParent = null;
7068 } else {
7069 throw new RuntimeException("view " + this + " being added, but"
7070 + " it already has a parent");
7071 }
7072 }
7073
7074 /**
7075 * This is called when the view is attached to a window. At this point it
7076 * has a Surface and will start drawing. Note that this function is
7077 * guaranteed to be called before {@link #onDraw}, however it may be called
7078 * any time before the first onDraw -- including before or after
7079 * {@link #onMeasure}.
7080 *
7081 * @see #onDetachedFromWindow()
7082 */
7083 protected void onAttachedToWindow() {
7084 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7085 mParent.requestTransparentRegion(this);
7086 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007087 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7088 initialAwakenScrollBars();
7089 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007091 }
7092
7093 /**
7094 * This is called when the view is detached from a window. At this point it
7095 * no longer has a surface for drawing.
7096 *
7097 * @see #onAttachedToWindow()
7098 */
7099 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007100 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08007101 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007102 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103 destroyDrawingCache();
7104 }
7105
7106 /**
7107 * @return The number of times this view has been attached to a window
7108 */
7109 protected int getWindowAttachCount() {
7110 return mWindowAttachCount;
7111 }
7112
7113 /**
7114 * Retrieve a unique token identifying the window this view is attached to.
7115 * @return Return the window's token for use in
7116 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7117 */
7118 public IBinder getWindowToken() {
7119 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7120 }
7121
7122 /**
7123 * Retrieve a unique token identifying the top-level "real" window of
7124 * the window that this view is attached to. That is, this is like
7125 * {@link #getWindowToken}, except if the window this view in is a panel
7126 * window (attached to another containing window), then the token of
7127 * the containing window is returned instead.
7128 *
7129 * @return Returns the associated window token, either
7130 * {@link #getWindowToken()} or the containing window's token.
7131 */
7132 public IBinder getApplicationWindowToken() {
7133 AttachInfo ai = mAttachInfo;
7134 if (ai != null) {
7135 IBinder appWindowToken = ai.mPanelParentWindowToken;
7136 if (appWindowToken == null) {
7137 appWindowToken = ai.mWindowToken;
7138 }
7139 return appWindowToken;
7140 }
7141 return null;
7142 }
7143
7144 /**
7145 * Retrieve private session object this view hierarchy is using to
7146 * communicate with the window manager.
7147 * @return the session object to communicate with the window manager
7148 */
7149 /*package*/ IWindowSession getWindowSession() {
7150 return mAttachInfo != null ? mAttachInfo.mSession : null;
7151 }
7152
7153 /**
7154 * @param info the {@link android.view.View.AttachInfo} to associated with
7155 * this view
7156 */
7157 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7158 //System.out.println("Attached! " + this);
7159 mAttachInfo = info;
7160 mWindowAttachCount++;
7161 if (mFloatingTreeObserver != null) {
7162 info.mTreeObserver.merge(mFloatingTreeObserver);
7163 mFloatingTreeObserver = null;
7164 }
7165 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7166 mAttachInfo.mScrollContainers.add(this);
7167 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7168 }
7169 performCollectViewAttributes(visibility);
7170 onAttachedToWindow();
7171 int vis = info.mWindowVisibility;
7172 if (vis != GONE) {
7173 onWindowVisibilityChanged(vis);
7174 }
7175 }
7176
7177 void dispatchDetachedFromWindow() {
7178 //System.out.println("Detached! " + this);
7179 AttachInfo info = mAttachInfo;
7180 if (info != null) {
7181 int vis = info.mWindowVisibility;
7182 if (vis != GONE) {
7183 onWindowVisibilityChanged(GONE);
7184 }
7185 }
7186
7187 onDetachedFromWindow();
7188 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7189 mAttachInfo.mScrollContainers.remove(this);
7190 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7191 }
7192 mAttachInfo = null;
7193 }
7194
7195 /**
7196 * Store this view hierarchy's frozen state into the given container.
7197 *
7198 * @param container The SparseArray in which to save the view's state.
7199 *
7200 * @see #restoreHierarchyState
7201 * @see #dispatchSaveInstanceState
7202 * @see #onSaveInstanceState
7203 */
7204 public void saveHierarchyState(SparseArray<Parcelable> container) {
7205 dispatchSaveInstanceState(container);
7206 }
7207
7208 /**
7209 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7210 * May be overridden to modify how freezing happens to a view's children; for example, some
7211 * views may want to not store state for their children.
7212 *
7213 * @param container The SparseArray in which to save the view's state.
7214 *
7215 * @see #dispatchRestoreInstanceState
7216 * @see #saveHierarchyState
7217 * @see #onSaveInstanceState
7218 */
7219 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7220 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7221 mPrivateFlags &= ~SAVE_STATE_CALLED;
7222 Parcelable state = onSaveInstanceState();
7223 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7224 throw new IllegalStateException(
7225 "Derived class did not call super.onSaveInstanceState()");
7226 }
7227 if (state != null) {
7228 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7229 // + ": " + state);
7230 container.put(mID, state);
7231 }
7232 }
7233 }
7234
7235 /**
7236 * Hook allowing a view to generate a representation of its internal state
7237 * that can later be used to create a new instance with that same state.
7238 * This state should only contain information that is not persistent or can
7239 * not be reconstructed later. For example, you will never store your
7240 * current position on screen because that will be computed again when a
7241 * new instance of the view is placed in its view hierarchy.
7242 * <p>
7243 * Some examples of things you may store here: the current cursor position
7244 * in a text view (but usually not the text itself since that is stored in a
7245 * content provider or other persistent storage), the currently selected
7246 * item in a list view.
7247 *
7248 * @return Returns a Parcelable object containing the view's current dynamic
7249 * state, or null if there is nothing interesting to save. The
7250 * default implementation returns null.
7251 * @see #onRestoreInstanceState
7252 * @see #saveHierarchyState
7253 * @see #dispatchSaveInstanceState
7254 * @see #setSaveEnabled(boolean)
7255 */
7256 protected Parcelable onSaveInstanceState() {
7257 mPrivateFlags |= SAVE_STATE_CALLED;
7258 return BaseSavedState.EMPTY_STATE;
7259 }
7260
7261 /**
7262 * Restore this view hierarchy's frozen state from the given container.
7263 *
7264 * @param container The SparseArray which holds previously frozen states.
7265 *
7266 * @see #saveHierarchyState
7267 * @see #dispatchRestoreInstanceState
7268 * @see #onRestoreInstanceState
7269 */
7270 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7271 dispatchRestoreInstanceState(container);
7272 }
7273
7274 /**
7275 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7276 * children. May be overridden to modify how restoreing happens to a view's children; for
7277 * example, some views may want to not store state for their children.
7278 *
7279 * @param container The SparseArray which holds previously saved state.
7280 *
7281 * @see #dispatchSaveInstanceState
7282 * @see #restoreHierarchyState
7283 * @see #onRestoreInstanceState
7284 */
7285 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7286 if (mID != NO_ID) {
7287 Parcelable state = container.get(mID);
7288 if (state != null) {
7289 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7290 // + ": " + state);
7291 mPrivateFlags &= ~SAVE_STATE_CALLED;
7292 onRestoreInstanceState(state);
7293 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7294 throw new IllegalStateException(
7295 "Derived class did not call super.onRestoreInstanceState()");
7296 }
7297 }
7298 }
7299 }
7300
7301 /**
7302 * Hook allowing a view to re-apply a representation of its internal state that had previously
7303 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7304 * null state.
7305 *
7306 * @param state The frozen state that had previously been returned by
7307 * {@link #onSaveInstanceState}.
7308 *
7309 * @see #onSaveInstanceState
7310 * @see #restoreHierarchyState
7311 * @see #dispatchRestoreInstanceState
7312 */
7313 protected void onRestoreInstanceState(Parcelable state) {
7314 mPrivateFlags |= SAVE_STATE_CALLED;
7315 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007316 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7317 + "received " + state.getClass().toString() + " instead. This usually happens "
7318 + "when two views of different type have the same id in the same hierarchy. "
7319 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7320 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007321 }
7322 }
7323
7324 /**
7325 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7326 *
7327 * @return the drawing start time in milliseconds
7328 */
7329 public long getDrawingTime() {
7330 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7331 }
7332
7333 /**
7334 * <p>Enables or disables the duplication of the parent's state into this view. When
7335 * duplication is enabled, this view gets its drawable state from its parent rather
7336 * than from its own internal properties.</p>
7337 *
7338 * <p>Note: in the current implementation, setting this property to true after the
7339 * view was added to a ViewGroup might have no effect at all. This property should
7340 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7341 *
7342 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7343 * property is enabled, an exception will be thrown.</p>
7344 *
7345 * @param enabled True to enable duplication of the parent's drawable state, false
7346 * to disable it.
7347 *
7348 * @see #getDrawableState()
7349 * @see #isDuplicateParentStateEnabled()
7350 */
7351 public void setDuplicateParentStateEnabled(boolean enabled) {
7352 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7353 }
7354
7355 /**
7356 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7357 *
7358 * @return True if this view's drawable state is duplicated from the parent,
7359 * false otherwise
7360 *
7361 * @see #getDrawableState()
7362 * @see #setDuplicateParentStateEnabled(boolean)
7363 */
7364 public boolean isDuplicateParentStateEnabled() {
7365 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7366 }
7367
7368 /**
7369 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
7370 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
7371 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
7372 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
7373 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
7374 * null.</p>
7375 *
7376 * @param enabled true to enable the drawing cache, false otherwise
7377 *
7378 * @see #isDrawingCacheEnabled()
7379 * @see #getDrawingCache()
7380 * @see #buildDrawingCache()
7381 */
7382 public void setDrawingCacheEnabled(boolean enabled) {
7383 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
7384 }
7385
7386 /**
7387 * <p>Indicates whether the drawing cache is enabled for this view.</p>
7388 *
7389 * @return true if the drawing cache is enabled
7390 *
7391 * @see #setDrawingCacheEnabled(boolean)
7392 * @see #getDrawingCache()
7393 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07007394 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395 public boolean isDrawingCacheEnabled() {
7396 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
7397 }
7398
7399 /**
Romain Guyb051e892010-09-28 19:09:36 -07007400 * <p>Returns a display list that can be used to draw this view again
7401 * without executing its draw method.</p>
7402 *
7403 * @return A DisplayList ready to replay, or null if caching is not enabled.
7404 */
7405 DisplayList getDisplayList() {
7406 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7407 return null;
7408 }
7409
7410 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
7411 return null;
7412 }
7413
7414 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
7415 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mDisplayList == null)) {
7416
7417 if (mDisplayList != null) {
7418 mDisplayList.destroy();
7419 }
7420
7421 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
7422
7423 final HardwareCanvas canvas = mDisplayList.start();
7424 try {
7425 int width = mRight - mLeft;
7426 int height = mBottom - mTop;
7427
7428 canvas.setViewport(width, height);
7429 canvas.onPreDraw();
7430
7431 final int restoreCount = canvas.save();
7432
Romain Guy2fe9a8f2010-10-04 20:17:01 -07007433 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07007434
7435 // Fast path for layouts with no backgrounds
7436 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7437 mPrivateFlags &= ~DIRTY_MASK;
7438 dispatchDraw(canvas);
7439 } else {
7440 draw(canvas);
7441 }
7442
7443 canvas.restoreToCount(restoreCount);
7444 } finally {
7445 canvas.onPostDraw();
7446
7447 mDisplayList.end();
7448
7449 canvas.destroy();
7450 }
7451 }
7452
7453 return mDisplayList;
7454 }
7455
7456 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007457 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
7458 *
7459 * @return A non-scaled bitmap representing this view or null if cache is disabled.
7460 *
7461 * @see #getDrawingCache(boolean)
7462 */
7463 public Bitmap getDrawingCache() {
7464 return getDrawingCache(false);
7465 }
7466
7467 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007468 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
7469 * is null when caching is disabled. If caching is enabled and the cache is not ready,
7470 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
7471 * draw from the cache when the cache is enabled. To benefit from the cache, you must
7472 * request the drawing cache by calling this method and draw it on screen if the
7473 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007474 *
7475 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7476 * this method will create a bitmap of the same size as this view. Because this bitmap
7477 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7478 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7479 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7480 * size than the view. This implies that your application must be able to handle this
7481 * size.</p>
7482 *
7483 * @param autoScale Indicates whether the generated bitmap should be scaled based on
7484 * the current density of the screen when the application is in compatibility
7485 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007486 *
Romain Guyfbd8f692009-06-26 14:51:58 -07007487 * @return A bitmap representing this view or null if cache is disabled.
7488 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 * @see #setDrawingCacheEnabled(boolean)
7490 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07007491 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007492 * @see #destroyDrawingCache()
7493 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007494 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007495 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7496 return null;
7497 }
7498 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007499 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007500 }
Romain Guy02890fd2010-08-06 17:58:44 -07007501 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007502 }
7503
7504 /**
7505 * <p>Frees the resources used by the drawing cache. If you call
7506 * {@link #buildDrawingCache()} manually without calling
7507 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7508 * should cleanup the cache with this method afterwards.</p>
7509 *
7510 * @see #setDrawingCacheEnabled(boolean)
7511 * @see #buildDrawingCache()
7512 * @see #getDrawingCache()
7513 */
7514 public void destroyDrawingCache() {
7515 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007516 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007517 mDrawingCache = null;
7518 }
Romain Guyfbd8f692009-06-26 14:51:58 -07007519 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007520 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07007521 mUnscaledDrawingCache = null;
7522 }
Romain Guyb051e892010-09-28 19:09:36 -07007523 if (mDisplayList != null) {
7524 mDisplayList.destroy();
7525 mDisplayList = null;
7526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007527 }
7528
7529 /**
7530 * Setting a solid background color for the drawing cache's bitmaps will improve
7531 * perfromance and memory usage. Note, though that this should only be used if this
7532 * view will always be drawn on top of a solid color.
7533 *
7534 * @param color The background color to use for the drawing cache's bitmap
7535 *
7536 * @see #setDrawingCacheEnabled(boolean)
7537 * @see #buildDrawingCache()
7538 * @see #getDrawingCache()
7539 */
7540 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08007541 if (color != mDrawingCacheBackgroundColor) {
7542 mDrawingCacheBackgroundColor = color;
7543 mPrivateFlags &= ~DRAWING_CACHE_VALID;
7544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007545 }
7546
7547 /**
7548 * @see #setDrawingCacheBackgroundColor(int)
7549 *
7550 * @return The background color to used for the drawing cache's bitmap
7551 */
7552 public int getDrawingCacheBackgroundColor() {
7553 return mDrawingCacheBackgroundColor;
7554 }
7555
7556 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007557 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
7558 *
7559 * @see #buildDrawingCache(boolean)
7560 */
7561 public void buildDrawingCache() {
7562 buildDrawingCache(false);
7563 }
7564
7565 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007566 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
7567 *
7568 * <p>If you call {@link #buildDrawingCache()} manually without calling
7569 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7570 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007571 *
7572 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7573 * this method will create a bitmap of the same size as this view. Because this bitmap
7574 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7575 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7576 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7577 * size than the view. This implies that your application must be able to handle this
7578 * size.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007579 *
7580 * @see #getDrawingCache()
7581 * @see #destroyDrawingCache()
7582 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007583 public void buildDrawingCache(boolean autoScale) {
7584 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07007585 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007586
7587 if (ViewDebug.TRACE_HIERARCHY) {
7588 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590
Romain Guy8506ab42009-06-11 17:35:47 -07007591 int width = mRight - mLeft;
7592 int height = mBottom - mTop;
7593
7594 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007595 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007596
Romain Guye1123222009-06-29 14:24:56 -07007597 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007598 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7599 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601
7602 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007603 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Romain Guya62e4702009-10-08 10:48:54 -07007604 final boolean translucentWindow = attachInfo != null && attachInfo.mTranslucentWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007605
7606 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007607 // Projected bitmap size in bytes
7608 (width * height * (opaque && !translucentWindow ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007609 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7610 destroyDrawingCache();
7611 return;
7612 }
7613
7614 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07007615 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616
7617 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007618 Bitmap.Config quality;
7619 if (!opaque) {
7620 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7621 case DRAWING_CACHE_QUALITY_AUTO:
7622 quality = Bitmap.Config.ARGB_8888;
7623 break;
7624 case DRAWING_CACHE_QUALITY_LOW:
7625 quality = Bitmap.Config.ARGB_4444;
7626 break;
7627 case DRAWING_CACHE_QUALITY_HIGH:
7628 quality = Bitmap.Config.ARGB_8888;
7629 break;
7630 default:
7631 quality = Bitmap.Config.ARGB_8888;
7632 break;
7633 }
7634 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07007635 // Optimization for translucent windows
7636 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
7637 quality = translucentWindow ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007638 }
7639
7640 // Try to cleanup memory
7641 if (bitmap != null) bitmap.recycle();
7642
7643 try {
7644 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07007645 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07007646 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07007647 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007648 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07007649 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007650 }
Romain Guy35b38ce2009-10-07 13:38:55 -07007651 if (opaque && translucentWindow) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 } catch (OutOfMemoryError e) {
7653 // If there is not enough memory to create the bitmap cache, just
7654 // ignore the issue as bitmap caches are not required to draw the
7655 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07007656 if (autoScale) {
7657 mDrawingCache = null;
7658 } else {
7659 mUnscaledDrawingCache = null;
7660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007661 return;
7662 }
7663
7664 clear = drawingCacheBackgroundColor != 0;
7665 }
7666
7667 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 if (attachInfo != null) {
7669 canvas = attachInfo.mCanvas;
7670 if (canvas == null) {
7671 canvas = new Canvas();
7672 }
7673 canvas.setBitmap(bitmap);
7674 // Temporarily clobber the cached Canvas in case one of our children
7675 // is also using a drawing cache. Without this, the children would
7676 // steal the canvas by attaching their own bitmap to it and bad, bad
7677 // thing would happen (invisible views, corrupted drawings, etc.)
7678 attachInfo.mCanvas = null;
7679 } else {
7680 // This case should hopefully never or seldom happen
7681 canvas = new Canvas(bitmap);
7682 }
7683
7684 if (clear) {
7685 bitmap.eraseColor(drawingCacheBackgroundColor);
7686 }
7687
7688 computeScroll();
7689 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07007690
Romain Guye1123222009-06-29 14:24:56 -07007691 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007692 final float scale = attachInfo.mApplicationScale;
7693 canvas.scale(scale, scale);
7694 }
7695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007696 canvas.translate(-mScrollX, -mScrollY);
7697
Romain Guy5bcdff42009-05-14 21:27:18 -07007698 mPrivateFlags |= DRAWN;
Romain Guyecd80ee2009-12-03 17:13:02 -08007699 mPrivateFlags |= DRAWING_CACHE_VALID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007700
7701 // Fast path for layouts with no backgrounds
7702 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7703 if (ViewDebug.TRACE_HIERARCHY) {
7704 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7705 }
Romain Guy5bcdff42009-05-14 21:27:18 -07007706 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 dispatchDraw(canvas);
7708 } else {
7709 draw(canvas);
7710 }
7711
7712 canvas.restoreToCount(restoreCount);
7713
7714 if (attachInfo != null) {
7715 // Restore the cached Canvas for our siblings
7716 attachInfo.mCanvas = canvas;
7717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 }
7719 }
7720
7721 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007722 * Create a snapshot of the view into a bitmap. We should probably make
7723 * some form of this public, but should think about the API.
7724 */
Romain Guy223ff5c2010-03-02 17:07:47 -08007725 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007726 int width = mRight - mLeft;
7727 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007728
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007729 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07007730 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007731 width = (int) ((width * scale) + 0.5f);
7732 height = (int) ((height * scale) + 0.5f);
7733
Romain Guy8c11e312009-09-14 15:15:30 -07007734 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007735 if (bitmap == null) {
7736 throw new OutOfMemoryError();
7737 }
7738
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007739 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
7740
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007741 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007742 if (attachInfo != null) {
7743 canvas = attachInfo.mCanvas;
7744 if (canvas == null) {
7745 canvas = new Canvas();
7746 }
7747 canvas.setBitmap(bitmap);
7748 // Temporarily clobber the cached Canvas in case one of our children
7749 // is also using a drawing cache. Without this, the children would
7750 // steal the canvas by attaching their own bitmap to it and bad, bad
7751 // things would happen (invisible views, corrupted drawings, etc.)
7752 attachInfo.mCanvas = null;
7753 } else {
7754 // This case should hopefully never or seldom happen
7755 canvas = new Canvas(bitmap);
7756 }
7757
Romain Guy5bcdff42009-05-14 21:27:18 -07007758 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007759 bitmap.eraseColor(backgroundColor);
7760 }
7761
7762 computeScroll();
7763 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007764 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007765 canvas.translate(-mScrollX, -mScrollY);
7766
Romain Guy5bcdff42009-05-14 21:27:18 -07007767 // Temporarily remove the dirty mask
7768 int flags = mPrivateFlags;
7769 mPrivateFlags &= ~DIRTY_MASK;
7770
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007771 // Fast path for layouts with no backgrounds
7772 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7773 dispatchDraw(canvas);
7774 } else {
7775 draw(canvas);
7776 }
7777
Romain Guy5bcdff42009-05-14 21:27:18 -07007778 mPrivateFlags = flags;
7779
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007780 canvas.restoreToCount(restoreCount);
7781
7782 if (attachInfo != null) {
7783 // Restore the cached Canvas for our siblings
7784 attachInfo.mCanvas = canvas;
7785 }
Romain Guy8506ab42009-06-11 17:35:47 -07007786
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007787 return bitmap;
7788 }
7789
7790 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 * Indicates whether this View is currently in edit mode. A View is usually
7792 * in edit mode when displayed within a developer tool. For instance, if
7793 * this View is being drawn by a visual user interface builder, this method
7794 * should return true.
7795 *
7796 * Subclasses should check the return value of this method to provide
7797 * different behaviors if their normal behavior might interfere with the
7798 * host environment. For instance: the class spawns a thread in its
7799 * constructor, the drawing code relies on device-specific features, etc.
7800 *
7801 * This method is usually checked in the drawing code of custom widgets.
7802 *
7803 * @return True if this View is in edit mode, false otherwise.
7804 */
7805 public boolean isInEditMode() {
7806 return false;
7807 }
7808
7809 /**
7810 * If the View draws content inside its padding and enables fading edges,
7811 * it needs to support padding offsets. Padding offsets are added to the
7812 * fading edges to extend the length of the fade so that it covers pixels
7813 * drawn inside the padding.
7814 *
7815 * Subclasses of this class should override this method if they need
7816 * to draw content inside the padding.
7817 *
7818 * @return True if padding offset must be applied, false otherwise.
7819 *
7820 * @see #getLeftPaddingOffset()
7821 * @see #getRightPaddingOffset()
7822 * @see #getTopPaddingOffset()
7823 * @see #getBottomPaddingOffset()
7824 *
7825 * @since CURRENT
7826 */
7827 protected boolean isPaddingOffsetRequired() {
7828 return false;
7829 }
7830
7831 /**
7832 * Amount by which to extend the left fading region. Called only when
7833 * {@link #isPaddingOffsetRequired()} returns true.
7834 *
7835 * @return The left padding offset in pixels.
7836 *
7837 * @see #isPaddingOffsetRequired()
7838 *
7839 * @since CURRENT
7840 */
7841 protected int getLeftPaddingOffset() {
7842 return 0;
7843 }
7844
7845 /**
7846 * Amount by which to extend the right fading region. Called only when
7847 * {@link #isPaddingOffsetRequired()} returns true.
7848 *
7849 * @return The right padding offset in pixels.
7850 *
7851 * @see #isPaddingOffsetRequired()
7852 *
7853 * @since CURRENT
7854 */
7855 protected int getRightPaddingOffset() {
7856 return 0;
7857 }
7858
7859 /**
7860 * Amount by which to extend the top fading region. Called only when
7861 * {@link #isPaddingOffsetRequired()} returns true.
7862 *
7863 * @return The top padding offset in pixels.
7864 *
7865 * @see #isPaddingOffsetRequired()
7866 *
7867 * @since CURRENT
7868 */
7869 protected int getTopPaddingOffset() {
7870 return 0;
7871 }
7872
7873 /**
7874 * Amount by which to extend the bottom fading region. Called only when
7875 * {@link #isPaddingOffsetRequired()} returns true.
7876 *
7877 * @return The bottom padding offset in pixels.
7878 *
7879 * @see #isPaddingOffsetRequired()
7880 *
7881 * @since CURRENT
7882 */
7883 protected int getBottomPaddingOffset() {
7884 return 0;
7885 }
7886
7887 /**
Romain Guy2bffd262010-09-12 17:40:02 -07007888 * <p>Indicates whether this view is attached to an hardware accelerated
7889 * window or not.</p>
7890 *
7891 * <p>Even if this method returns true, it does not mean that every call
7892 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
7893 * accelerated {@link android.graphics.Canvas}. For instance, if this view
7894 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
7895 * window is hardware accelerated,
7896 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
7897 * return false, and this method will return true.</p>
7898 *
7899 * @return True if the view is attached to a window and the window is
7900 * hardware accelerated; false in any other case.
7901 */
7902 public boolean isHardwareAccelerated() {
7903 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
7904 }
7905
7906 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007907 * Manually render this view (and all of its children) to the given Canvas.
7908 * The view must have already done a full layout before this function is
7909 * called. When implementing a view, do not override this method; instead,
7910 * you should implement {@link #onDraw}.
7911 *
7912 * @param canvas The Canvas to which the View is rendered.
7913 */
7914 public void draw(Canvas canvas) {
7915 if (ViewDebug.TRACE_HIERARCHY) {
7916 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7917 }
7918
Romain Guy5bcdff42009-05-14 21:27:18 -07007919 final int privateFlags = mPrivateFlags;
7920 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
7921 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
7922 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07007923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 /*
7925 * Draw traversal performs several drawing steps which must be executed
7926 * in the appropriate order:
7927 *
7928 * 1. Draw the background
7929 * 2. If necessary, save the canvas' layers to prepare for fading
7930 * 3. Draw view's content
7931 * 4. Draw children
7932 * 5. If necessary, draw the fading edges and restore layers
7933 * 6. Draw decorations (scrollbars for instance)
7934 */
7935
7936 // Step 1, draw the background, if needed
7937 int saveCount;
7938
Romain Guy24443ea2009-05-11 11:56:30 -07007939 if (!dirtyOpaque) {
7940 final Drawable background = mBGDrawable;
7941 if (background != null) {
7942 final int scrollX = mScrollX;
7943 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944
Romain Guy24443ea2009-05-11 11:56:30 -07007945 if (mBackgroundSizeChanged) {
7946 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
7947 mBackgroundSizeChanged = false;
7948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007949
Romain Guy24443ea2009-05-11 11:56:30 -07007950 if ((scrollX | scrollY) == 0) {
7951 background.draw(canvas);
7952 } else {
7953 canvas.translate(scrollX, scrollY);
7954 background.draw(canvas);
7955 canvas.translate(-scrollX, -scrollY);
7956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 }
7958 }
7959
7960 // skip step 2 & 5 if possible (common case)
7961 final int viewFlags = mViewFlags;
7962 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
7963 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
7964 if (!verticalEdges && !horizontalEdges) {
7965 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007966 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007967
7968 // Step 4, draw the children
7969 dispatchDraw(canvas);
7970
7971 // Step 6, draw decorations (scrollbars)
7972 onDrawScrollBars(canvas);
7973
7974 // we're done...
7975 return;
7976 }
7977
7978 /*
7979 * Here we do the full fledged routine...
7980 * (this is an uncommon case where speed matters less,
7981 * this is why we repeat some of the tests that have been
7982 * done above)
7983 */
7984
7985 boolean drawTop = false;
7986 boolean drawBottom = false;
7987 boolean drawLeft = false;
7988 boolean drawRight = false;
7989
7990 float topFadeStrength = 0.0f;
7991 float bottomFadeStrength = 0.0f;
7992 float leftFadeStrength = 0.0f;
7993 float rightFadeStrength = 0.0f;
7994
7995 // Step 2, save the canvas' layers
7996 int paddingLeft = mPaddingLeft;
7997 int paddingTop = mPaddingTop;
7998
7999 final boolean offsetRequired = isPaddingOffsetRequired();
8000 if (offsetRequired) {
8001 paddingLeft += getLeftPaddingOffset();
8002 paddingTop += getTopPaddingOffset();
8003 }
8004
8005 int left = mScrollX + paddingLeft;
8006 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8007 int top = mScrollY + paddingTop;
8008 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8009
8010 if (offsetRequired) {
8011 right += getRightPaddingOffset();
8012 bottom += getBottomPaddingOffset();
8013 }
8014
8015 final ScrollabilityCache scrollabilityCache = mScrollCache;
8016 int length = scrollabilityCache.fadingEdgeLength;
8017
8018 // clip the fade length if top and bottom fades overlap
8019 // overlapping fades produce odd-looking artifacts
8020 if (verticalEdges && (top + length > bottom - length)) {
8021 length = (bottom - top) / 2;
8022 }
8023
8024 // also clip horizontal fades if necessary
8025 if (horizontalEdges && (left + length > right - length)) {
8026 length = (right - left) / 2;
8027 }
8028
8029 if (verticalEdges) {
8030 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008031 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008032 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008033 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 }
8035
8036 if (horizontalEdges) {
8037 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008038 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008039 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008040 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008041 }
8042
8043 saveCount = canvas.getSaveCount();
8044
8045 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008046 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008047 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8048
8049 if (drawTop) {
8050 canvas.saveLayer(left, top, right, top + length, null, flags);
8051 }
8052
8053 if (drawBottom) {
8054 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8055 }
8056
8057 if (drawLeft) {
8058 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8059 }
8060
8061 if (drawRight) {
8062 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8063 }
8064 } else {
8065 scrollabilityCache.setFadeColor(solidColor);
8066 }
8067
8068 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008069 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070
8071 // Step 4, draw the children
8072 dispatchDraw(canvas);
8073
8074 // Step 5, draw the fade effect and restore layers
8075 final Paint p = scrollabilityCache.paint;
8076 final Matrix matrix = scrollabilityCache.matrix;
8077 final Shader fade = scrollabilityCache.shader;
8078 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8079
8080 if (drawTop) {
8081 matrix.setScale(1, fadeHeight * topFadeStrength);
8082 matrix.postTranslate(left, top);
8083 fade.setLocalMatrix(matrix);
8084 canvas.drawRect(left, top, right, top + length, p);
8085 }
8086
8087 if (drawBottom) {
8088 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8089 matrix.postRotate(180);
8090 matrix.postTranslate(left, bottom);
8091 fade.setLocalMatrix(matrix);
8092 canvas.drawRect(left, bottom - length, right, bottom, p);
8093 }
8094
8095 if (drawLeft) {
8096 matrix.setScale(1, fadeHeight * leftFadeStrength);
8097 matrix.postRotate(-90);
8098 matrix.postTranslate(left, top);
8099 fade.setLocalMatrix(matrix);
8100 canvas.drawRect(left, top, left + length, bottom, p);
8101 }
8102
8103 if (drawRight) {
8104 matrix.setScale(1, fadeHeight * rightFadeStrength);
8105 matrix.postRotate(90);
8106 matrix.postTranslate(right, top);
8107 fade.setLocalMatrix(matrix);
8108 canvas.drawRect(right - length, top, right, bottom, p);
8109 }
8110
8111 canvas.restoreToCount(saveCount);
8112
8113 // Step 6, draw decorations (scrollbars)
8114 onDrawScrollBars(canvas);
8115 }
8116
8117 /**
8118 * Override this if your view is known to always be drawn on top of a solid color background,
8119 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8120 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8121 * should be set to 0xFF.
8122 *
8123 * @see #setVerticalFadingEdgeEnabled
8124 * @see #setHorizontalFadingEdgeEnabled
8125 *
8126 * @return The known solid color background for this view, or 0 if the color may vary
8127 */
8128 public int getSolidColor() {
8129 return 0;
8130 }
8131
8132 /**
8133 * Build a human readable string representation of the specified view flags.
8134 *
8135 * @param flags the view flags to convert to a string
8136 * @return a String representing the supplied flags
8137 */
8138 private static String printFlags(int flags) {
8139 String output = "";
8140 int numFlags = 0;
8141 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8142 output += "TAKES_FOCUS";
8143 numFlags++;
8144 }
8145
8146 switch (flags & VISIBILITY_MASK) {
8147 case INVISIBLE:
8148 if (numFlags > 0) {
8149 output += " ";
8150 }
8151 output += "INVISIBLE";
8152 // USELESS HERE numFlags++;
8153 break;
8154 case GONE:
8155 if (numFlags > 0) {
8156 output += " ";
8157 }
8158 output += "GONE";
8159 // USELESS HERE numFlags++;
8160 break;
8161 default:
8162 break;
8163 }
8164 return output;
8165 }
8166
8167 /**
8168 * Build a human readable string representation of the specified private
8169 * view flags.
8170 *
8171 * @param privateFlags the private view flags to convert to a string
8172 * @return a String representing the supplied flags
8173 */
8174 private static String printPrivateFlags(int privateFlags) {
8175 String output = "";
8176 int numFlags = 0;
8177
8178 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8179 output += "WANTS_FOCUS";
8180 numFlags++;
8181 }
8182
8183 if ((privateFlags & FOCUSED) == FOCUSED) {
8184 if (numFlags > 0) {
8185 output += " ";
8186 }
8187 output += "FOCUSED";
8188 numFlags++;
8189 }
8190
8191 if ((privateFlags & SELECTED) == SELECTED) {
8192 if (numFlags > 0) {
8193 output += " ";
8194 }
8195 output += "SELECTED";
8196 numFlags++;
8197 }
8198
8199 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8200 if (numFlags > 0) {
8201 output += " ";
8202 }
8203 output += "IS_ROOT_NAMESPACE";
8204 numFlags++;
8205 }
8206
8207 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8208 if (numFlags > 0) {
8209 output += " ";
8210 }
8211 output += "HAS_BOUNDS";
8212 numFlags++;
8213 }
8214
8215 if ((privateFlags & DRAWN) == DRAWN) {
8216 if (numFlags > 0) {
8217 output += " ";
8218 }
8219 output += "DRAWN";
8220 // USELESS HERE numFlags++;
8221 }
8222 return output;
8223 }
8224
8225 /**
8226 * <p>Indicates whether or not this view's layout will be requested during
8227 * the next hierarchy layout pass.</p>
8228 *
8229 * @return true if the layout will be forced during next layout pass
8230 */
8231 public boolean isLayoutRequested() {
8232 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8233 }
8234
8235 /**
8236 * Assign a size and position to a view and all of its
8237 * descendants
8238 *
8239 * <p>This is the second phase of the layout mechanism.
8240 * (The first is measuring). In this phase, each parent calls
8241 * layout on all of its children to position them.
8242 * This is typically done using the child measurements
8243 * that were stored in the measure pass().
8244 *
8245 * Derived classes with children should override
8246 * onLayout. In that method, they should
Chet Haase21cd1382010-09-01 17:42:29 -07008247 * call layout on each of their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008248 *
8249 * @param l Left position, relative to parent
8250 * @param t Top position, relative to parent
8251 * @param r Right position, relative to parent
8252 * @param b Bottom position, relative to parent
8253 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008254 @SuppressWarnings({"unchecked"})
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008255 public final void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008256 int oldL = mLeft;
8257 int oldT = mTop;
8258 int oldB = mBottom;
8259 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008260 boolean changed = setFrame(l, t, r, b);
8261 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8262 if (ViewDebug.TRACE_HIERARCHY) {
8263 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8264 }
8265
8266 onLayout(changed, l, t, r, b);
8267 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008268
8269 if (mOnLayoutChangeListeners != null) {
8270 ArrayList<OnLayoutChangeListener> listenersCopy =
8271 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8272 int numListeners = listenersCopy.size();
8273 for (int i = 0; i < numListeners; ++i) {
8274 listenersCopy.get(i).onLayoutChange(this, l, r, t, b, oldL, oldT, oldR, oldB);
8275 }
8276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008277 }
8278 mPrivateFlags &= ~FORCE_LAYOUT;
8279 }
8280
8281 /**
8282 * Called from layout when this view should
8283 * assign a size and position to each of its children.
8284 *
8285 * Derived classes with children should override
8286 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008287 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008288 * @param changed This is a new size or position for this view
8289 * @param left Left position, relative to parent
8290 * @param top Top position, relative to parent
8291 * @param right Right position, relative to parent
8292 * @param bottom Bottom position, relative to parent
8293 */
8294 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8295 }
8296
8297 /**
8298 * Assign a size and position to this view.
8299 *
8300 * This is called from layout.
8301 *
8302 * @param left Left position, relative to parent
8303 * @param top Top position, relative to parent
8304 * @param right Right position, relative to parent
8305 * @param bottom Bottom position, relative to parent
8306 * @return true if the new size and position are different than the
8307 * previous ones
8308 * {@hide}
8309 */
8310 protected boolean setFrame(int left, int top, int right, int bottom) {
8311 boolean changed = false;
8312
8313 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008314 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008315 + right + "," + bottom + ")");
8316 }
8317
8318 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8319 changed = true;
8320
8321 // Remember our drawn bit
8322 int drawn = mPrivateFlags & DRAWN;
8323
8324 // Invalidate our old position
8325 invalidate();
8326
8327
8328 int oldWidth = mRight - mLeft;
8329 int oldHeight = mBottom - mTop;
8330
8331 mLeft = left;
8332 mTop = top;
8333 mRight = right;
8334 mBottom = bottom;
8335
8336 mPrivateFlags |= HAS_BOUNDS;
8337
8338 int newWidth = right - left;
8339 int newHeight = bottom - top;
8340
8341 if (newWidth != oldWidth || newHeight != oldHeight) {
8342 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8343 }
8344
8345 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8346 // If we are visible, force the DRAWN bit to on so that
8347 // this invalidate will go through (at least to our parent).
8348 // This is because someone may have invalidated this view
8349 // before this call to setFrame came in, therby clearing
8350 // the DRAWN bit.
8351 mPrivateFlags |= DRAWN;
8352 invalidate();
8353 }
8354
8355 // Reset drawn bit to original value (invalidate turns it off)
8356 mPrivateFlags |= drawn;
8357
8358 mBackgroundSizeChanged = true;
8359 }
8360 return changed;
8361 }
8362
8363 /**
8364 * Finalize inflating a view from XML. This is called as the last phase
8365 * of inflation, after all child views have been added.
8366 *
8367 * <p>Even if the subclass overrides onFinishInflate, they should always be
8368 * sure to call the super method, so that we get called.
8369 */
8370 protected void onFinishInflate() {
8371 }
8372
8373 /**
8374 * Returns the resources associated with this view.
8375 *
8376 * @return Resources object.
8377 */
8378 public Resources getResources() {
8379 return mResources;
8380 }
8381
8382 /**
8383 * Invalidates the specified Drawable.
8384 *
8385 * @param drawable the drawable to invalidate
8386 */
8387 public void invalidateDrawable(Drawable drawable) {
8388 if (verifyDrawable(drawable)) {
8389 final Rect dirty = drawable.getBounds();
8390 final int scrollX = mScrollX;
8391 final int scrollY = mScrollY;
8392
8393 invalidate(dirty.left + scrollX, dirty.top + scrollY,
8394 dirty.right + scrollX, dirty.bottom + scrollY);
8395 }
8396 }
8397
8398 /**
8399 * Schedules an action on a drawable to occur at a specified time.
8400 *
8401 * @param who the recipient of the action
8402 * @param what the action to run on the drawable
8403 * @param when the time at which the action must occur. Uses the
8404 * {@link SystemClock#uptimeMillis} timebase.
8405 */
8406 public void scheduleDrawable(Drawable who, Runnable what, long when) {
8407 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8408 mAttachInfo.mHandler.postAtTime(what, who, when);
8409 }
8410 }
8411
8412 /**
8413 * Cancels a scheduled action on a drawable.
8414 *
8415 * @param who the recipient of the action
8416 * @param what the action to cancel
8417 */
8418 public void unscheduleDrawable(Drawable who, Runnable what) {
8419 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8420 mAttachInfo.mHandler.removeCallbacks(what, who);
8421 }
8422 }
8423
8424 /**
8425 * Unschedule any events associated with the given Drawable. This can be
8426 * used when selecting a new Drawable into a view, so that the previous
8427 * one is completely unscheduled.
8428 *
8429 * @param who The Drawable to unschedule.
8430 *
8431 * @see #drawableStateChanged
8432 */
8433 public void unscheduleDrawable(Drawable who) {
8434 if (mAttachInfo != null) {
8435 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
8436 }
8437 }
8438
8439 /**
8440 * If your view subclass is displaying its own Drawable objects, it should
8441 * override this function and return true for any Drawable it is
8442 * displaying. This allows animations for those drawables to be
8443 * scheduled.
8444 *
8445 * <p>Be sure to call through to the super class when overriding this
8446 * function.
8447 *
8448 * @param who The Drawable to verify. Return true if it is one you are
8449 * displaying, else return the result of calling through to the
8450 * super class.
8451 *
8452 * @return boolean If true than the Drawable is being displayed in the
8453 * view; else false and it is not allowed to animate.
8454 *
8455 * @see #unscheduleDrawable
8456 * @see #drawableStateChanged
8457 */
8458 protected boolean verifyDrawable(Drawable who) {
8459 return who == mBGDrawable;
8460 }
8461
8462 /**
8463 * This function is called whenever the state of the view changes in such
8464 * a way that it impacts the state of drawables being shown.
8465 *
8466 * <p>Be sure to call through to the superclass when overriding this
8467 * function.
8468 *
8469 * @see Drawable#setState
8470 */
8471 protected void drawableStateChanged() {
8472 Drawable d = mBGDrawable;
8473 if (d != null && d.isStateful()) {
8474 d.setState(getDrawableState());
8475 }
8476 }
8477
8478 /**
8479 * Call this to force a view to update its drawable state. This will cause
8480 * drawableStateChanged to be called on this view. Views that are interested
8481 * in the new state should call getDrawableState.
8482 *
8483 * @see #drawableStateChanged
8484 * @see #getDrawableState
8485 */
8486 public void refreshDrawableState() {
8487 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
8488 drawableStateChanged();
8489
8490 ViewParent parent = mParent;
8491 if (parent != null) {
8492 parent.childDrawableStateChanged(this);
8493 }
8494 }
8495
8496 /**
8497 * Return an array of resource IDs of the drawable states representing the
8498 * current state of the view.
8499 *
8500 * @return The current drawable state
8501 *
8502 * @see Drawable#setState
8503 * @see #drawableStateChanged
8504 * @see #onCreateDrawableState
8505 */
8506 public final int[] getDrawableState() {
8507 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
8508 return mDrawableState;
8509 } else {
8510 mDrawableState = onCreateDrawableState(0);
8511 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
8512 return mDrawableState;
8513 }
8514 }
8515
8516 /**
8517 * Generate the new {@link android.graphics.drawable.Drawable} state for
8518 * this view. This is called by the view
8519 * system when the cached Drawable state is determined to be invalid. To
8520 * retrieve the current state, you should use {@link #getDrawableState}.
8521 *
8522 * @param extraSpace if non-zero, this is the number of extra entries you
8523 * would like in the returned array in which you can place your own
8524 * states.
8525 *
8526 * @return Returns an array holding the current {@link Drawable} state of
8527 * the view.
8528 *
8529 * @see #mergeDrawableStates
8530 */
8531 protected int[] onCreateDrawableState(int extraSpace) {
8532 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
8533 mParent instanceof View) {
8534 return ((View) mParent).onCreateDrawableState(extraSpace);
8535 }
8536
8537 int[] drawableState;
8538
8539 int privateFlags = mPrivateFlags;
8540
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008541 int viewStateIndex = 0;
8542 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
8543 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
8544 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
8545 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
8546 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
8547 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008548
8549 drawableState = VIEW_STATE_SETS[viewStateIndex];
8550
8551 //noinspection ConstantIfStatement
8552 if (false) {
8553 Log.i("View", "drawableStateIndex=" + viewStateIndex);
8554 Log.i("View", toString()
8555 + " pressed=" + ((privateFlags & PRESSED) != 0)
8556 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
8557 + " fo=" + hasFocus()
8558 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008559 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008560 + ": " + Arrays.toString(drawableState));
8561 }
8562
8563 if (extraSpace == 0) {
8564 return drawableState;
8565 }
8566
8567 final int[] fullState;
8568 if (drawableState != null) {
8569 fullState = new int[drawableState.length + extraSpace];
8570 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
8571 } else {
8572 fullState = new int[extraSpace];
8573 }
8574
8575 return fullState;
8576 }
8577
8578 /**
8579 * Merge your own state values in <var>additionalState</var> into the base
8580 * state values <var>baseState</var> that were returned by
8581 * {@link #onCreateDrawableState}.
8582 *
8583 * @param baseState The base state values returned by
8584 * {@link #onCreateDrawableState}, which will be modified to also hold your
8585 * own additional state values.
8586 *
8587 * @param additionalState The additional state values you would like
8588 * added to <var>baseState</var>; this array is not modified.
8589 *
8590 * @return As a convenience, the <var>baseState</var> array you originally
8591 * passed into the function is returned.
8592 *
8593 * @see #onCreateDrawableState
8594 */
8595 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
8596 final int N = baseState.length;
8597 int i = N - 1;
8598 while (i >= 0 && baseState[i] == 0) {
8599 i--;
8600 }
8601 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
8602 return baseState;
8603 }
8604
8605 /**
8606 * Sets the background color for this view.
8607 * @param color the color of the background
8608 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008609 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008610 public void setBackgroundColor(int color) {
8611 setBackgroundDrawable(new ColorDrawable(color));
8612 }
8613
8614 /**
8615 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07008616 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008617 * @param resid The identifier of the resource.
8618 * @attr ref android.R.styleable#View_background
8619 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008620 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008621 public void setBackgroundResource(int resid) {
8622 if (resid != 0 && resid == mBackgroundResource) {
8623 return;
8624 }
8625
8626 Drawable d= null;
8627 if (resid != 0) {
8628 d = mResources.getDrawable(resid);
8629 }
8630 setBackgroundDrawable(d);
8631
8632 mBackgroundResource = resid;
8633 }
8634
8635 /**
8636 * Set the background to a given Drawable, or remove the background. If the
8637 * background has padding, this View's padding is set to the background's
8638 * padding. However, when a background is removed, this View's padding isn't
8639 * touched. If setting the padding is desired, please use
8640 * {@link #setPadding(int, int, int, int)}.
8641 *
8642 * @param d The Drawable to use as the background, or null to remove the
8643 * background
8644 */
8645 public void setBackgroundDrawable(Drawable d) {
8646 boolean requestLayout = false;
8647
8648 mBackgroundResource = 0;
8649
8650 /*
8651 * Regardless of whether we're setting a new background or not, we want
8652 * to clear the previous drawable.
8653 */
8654 if (mBGDrawable != null) {
8655 mBGDrawable.setCallback(null);
8656 unscheduleDrawable(mBGDrawable);
8657 }
8658
8659 if (d != null) {
8660 Rect padding = sThreadLocal.get();
8661 if (padding == null) {
8662 padding = new Rect();
8663 sThreadLocal.set(padding);
8664 }
8665 if (d.getPadding(padding)) {
8666 setPadding(padding.left, padding.top, padding.right, padding.bottom);
8667 }
8668
8669 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
8670 // if it has a different minimum size, we should layout again
8671 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
8672 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
8673 requestLayout = true;
8674 }
8675
8676 d.setCallback(this);
8677 if (d.isStateful()) {
8678 d.setState(getDrawableState());
8679 }
8680 d.setVisible(getVisibility() == VISIBLE, false);
8681 mBGDrawable = d;
8682
8683 if ((mPrivateFlags & SKIP_DRAW) != 0) {
8684 mPrivateFlags &= ~SKIP_DRAW;
8685 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8686 requestLayout = true;
8687 }
8688 } else {
8689 /* Remove the background */
8690 mBGDrawable = null;
8691
8692 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
8693 /*
8694 * This view ONLY drew the background before and we're removing
8695 * the background, so now it won't draw anything
8696 * (hence we SKIP_DRAW)
8697 */
8698 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
8699 mPrivateFlags |= SKIP_DRAW;
8700 }
8701
8702 /*
8703 * When the background is set, we try to apply its padding to this
8704 * View. When the background is removed, we don't touch this View's
8705 * padding. This is noted in the Javadocs. Hence, we don't need to
8706 * requestLayout(), the invalidate() below is sufficient.
8707 */
8708
8709 // The old background's minimum size could have affected this
8710 // View's layout, so let's requestLayout
8711 requestLayout = true;
8712 }
8713
Romain Guy8f1344f52009-05-15 16:03:59 -07008714 computeOpaqueFlags();
8715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716 if (requestLayout) {
8717 requestLayout();
8718 }
8719
8720 mBackgroundSizeChanged = true;
8721 invalidate();
8722 }
8723
8724 /**
8725 * Gets the background drawable
8726 * @return The drawable used as the background for this view, if any.
8727 */
8728 public Drawable getBackground() {
8729 return mBGDrawable;
8730 }
8731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008732 /**
8733 * Sets the padding. The view may add on the space required to display
8734 * the scrollbars, depending on the style and visibility of the scrollbars.
8735 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
8736 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
8737 * from the values set in this call.
8738 *
8739 * @attr ref android.R.styleable#View_padding
8740 * @attr ref android.R.styleable#View_paddingBottom
8741 * @attr ref android.R.styleable#View_paddingLeft
8742 * @attr ref android.R.styleable#View_paddingRight
8743 * @attr ref android.R.styleable#View_paddingTop
8744 * @param left the left padding in pixels
8745 * @param top the top padding in pixels
8746 * @param right the right padding in pixels
8747 * @param bottom the bottom padding in pixels
8748 */
8749 public void setPadding(int left, int top, int right, int bottom) {
8750 boolean changed = false;
8751
8752 mUserPaddingRight = right;
8753 mUserPaddingBottom = bottom;
8754
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008755 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07008756
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008757 // Common case is there are no scroll bars.
8758 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
8759 // TODO: Deal with RTL languages to adjust left padding instead of right.
8760 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
8761 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8762 ? 0 : getVerticalScrollbarWidth();
8763 }
8764 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
8765 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8766 ? 0 : getHorizontalScrollbarHeight();
8767 }
8768 }
Romain Guy8506ab42009-06-11 17:35:47 -07008769
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008770 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771 changed = true;
8772 mPaddingLeft = left;
8773 }
8774 if (mPaddingTop != top) {
8775 changed = true;
8776 mPaddingTop = top;
8777 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008778 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008780 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008781 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008782 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008783 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008784 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785 }
8786
8787 if (changed) {
8788 requestLayout();
8789 }
8790 }
8791
8792 /**
8793 * Returns the top padding of this view.
8794 *
8795 * @return the top padding in pixels
8796 */
8797 public int getPaddingTop() {
8798 return mPaddingTop;
8799 }
8800
8801 /**
8802 * Returns the bottom padding of this view. If there are inset and enabled
8803 * scrollbars, this value may include the space required to display the
8804 * scrollbars as well.
8805 *
8806 * @return the bottom padding in pixels
8807 */
8808 public int getPaddingBottom() {
8809 return mPaddingBottom;
8810 }
8811
8812 /**
8813 * Returns the left padding of this view. If there are inset and enabled
8814 * scrollbars, this value may include the space required to display the
8815 * scrollbars as well.
8816 *
8817 * @return the left padding in pixels
8818 */
8819 public int getPaddingLeft() {
8820 return mPaddingLeft;
8821 }
8822
8823 /**
8824 * Returns the right padding of this view. If there are inset and enabled
8825 * scrollbars, this value may include the space required to display the
8826 * scrollbars as well.
8827 *
8828 * @return the right padding in pixels
8829 */
8830 public int getPaddingRight() {
8831 return mPaddingRight;
8832 }
8833
8834 /**
8835 * Changes the selection state of this view. A view can be selected or not.
8836 * Note that selection is not the same as focus. Views are typically
8837 * selected in the context of an AdapterView like ListView or GridView;
8838 * the selected view is the view that is highlighted.
8839 *
8840 * @param selected true if the view must be selected, false otherwise
8841 */
8842 public void setSelected(boolean selected) {
8843 if (((mPrivateFlags & SELECTED) != 0) != selected) {
8844 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07008845 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008846 invalidate();
8847 refreshDrawableState();
8848 dispatchSetSelected(selected);
8849 }
8850 }
8851
8852 /**
8853 * Dispatch setSelected to all of this View's children.
8854 *
8855 * @see #setSelected(boolean)
8856 *
8857 * @param selected The new selected state
8858 */
8859 protected void dispatchSetSelected(boolean selected) {
8860 }
8861
8862 /**
8863 * Indicates the selection state of this view.
8864 *
8865 * @return true if the view is selected, false otherwise
8866 */
8867 @ViewDebug.ExportedProperty
8868 public boolean isSelected() {
8869 return (mPrivateFlags & SELECTED) != 0;
8870 }
8871
8872 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008873 * Changes the activated state of this view. A view can be activated or not.
8874 * Note that activation is not the same as selection. Selection is
8875 * a transient property, representing the view (hierarchy) the user is
8876 * currently interacting with. Activation is a longer-term state that the
8877 * user can move views in and out of. For example, in a list view with
8878 * single or multiple selection enabled, the views in the current selection
8879 * set are activated. (Um, yeah, we are deeply sorry about the terminology
8880 * here.) The activated state is propagated down to children of the view it
8881 * is set on.
8882 *
8883 * @param activated true if the view must be activated, false otherwise
8884 */
8885 public void setActivated(boolean activated) {
8886 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
8887 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
8888 invalidate();
8889 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07008890 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008891 }
8892 }
8893
8894 /**
8895 * Dispatch setActivated to all of this View's children.
8896 *
8897 * @see #setActivated(boolean)
8898 *
8899 * @param activated The new activated state
8900 */
8901 protected void dispatchSetActivated(boolean activated) {
8902 }
8903
8904 /**
8905 * Indicates the activation state of this view.
8906 *
8907 * @return true if the view is activated, false otherwise
8908 */
8909 @ViewDebug.ExportedProperty
8910 public boolean isActivated() {
8911 return (mPrivateFlags & ACTIVATED) != 0;
8912 }
8913
8914 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
8916 * observer can be used to get notifications when global events, like
8917 * layout, happen.
8918 *
8919 * The returned ViewTreeObserver observer is not guaranteed to remain
8920 * valid for the lifetime of this View. If the caller of this method keeps
8921 * a long-lived reference to ViewTreeObserver, it should always check for
8922 * the return value of {@link ViewTreeObserver#isAlive()}.
8923 *
8924 * @return The ViewTreeObserver for this view's hierarchy.
8925 */
8926 public ViewTreeObserver getViewTreeObserver() {
8927 if (mAttachInfo != null) {
8928 return mAttachInfo.mTreeObserver;
8929 }
8930 if (mFloatingTreeObserver == null) {
8931 mFloatingTreeObserver = new ViewTreeObserver();
8932 }
8933 return mFloatingTreeObserver;
8934 }
8935
8936 /**
8937 * <p>Finds the topmost view in the current view hierarchy.</p>
8938 *
8939 * @return the topmost view containing this view
8940 */
8941 public View getRootView() {
8942 if (mAttachInfo != null) {
8943 final View v = mAttachInfo.mRootView;
8944 if (v != null) {
8945 return v;
8946 }
8947 }
Romain Guy8506ab42009-06-11 17:35:47 -07008948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 View parent = this;
8950
8951 while (parent.mParent != null && parent.mParent instanceof View) {
8952 parent = (View) parent.mParent;
8953 }
8954
8955 return parent;
8956 }
8957
8958 /**
8959 * <p>Computes the coordinates of this view on the screen. The argument
8960 * must be an array of two integers. After the method returns, the array
8961 * contains the x and y location in that order.</p>
8962 *
8963 * @param location an array of two integers in which to hold the coordinates
8964 */
8965 public void getLocationOnScreen(int[] location) {
8966 getLocationInWindow(location);
8967
8968 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07008969 if (info != null) {
8970 location[0] += info.mWindowLeft;
8971 location[1] += info.mWindowTop;
8972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008973 }
8974
8975 /**
8976 * <p>Computes the coordinates of this view in its window. The argument
8977 * must be an array of two integers. After the method returns, the array
8978 * contains the x and y location in that order.</p>
8979 *
8980 * @param location an array of two integers in which to hold the coordinates
8981 */
8982 public void getLocationInWindow(int[] location) {
8983 if (location == null || location.length < 2) {
8984 throw new IllegalArgumentException("location must be an array of "
8985 + "two integers");
8986 }
8987
8988 location[0] = mLeft;
8989 location[1] = mTop;
8990
8991 ViewParent viewParent = mParent;
8992 while (viewParent instanceof View) {
8993 final View view = (View)viewParent;
8994 location[0] += view.mLeft - view.mScrollX;
8995 location[1] += view.mTop - view.mScrollY;
8996 viewParent = view.mParent;
8997 }
Romain Guy8506ab42009-06-11 17:35:47 -07008998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008999 if (viewParent instanceof ViewRoot) {
9000 // *cough*
9001 final ViewRoot vr = (ViewRoot)viewParent;
9002 location[1] -= vr.mCurScrollY;
9003 }
9004 }
9005
9006 /**
9007 * {@hide}
9008 * @param id the id of the view to be found
9009 * @return the view of the specified id, null if cannot be found
9010 */
9011 protected View findViewTraversal(int id) {
9012 if (id == mID) {
9013 return this;
9014 }
9015 return null;
9016 }
9017
9018 /**
9019 * {@hide}
9020 * @param tag the tag of the view to be found
9021 * @return the view of specified tag, null if cannot be found
9022 */
9023 protected View findViewWithTagTraversal(Object tag) {
9024 if (tag != null && tag.equals(mTag)) {
9025 return this;
9026 }
9027 return null;
9028 }
9029
9030 /**
9031 * Look for a child view with the given id. If this view has the given
9032 * id, return this view.
9033 *
9034 * @param id The id to search for.
9035 * @return The view that has the given id in the hierarchy or null
9036 */
9037 public final View findViewById(int id) {
9038 if (id < 0) {
9039 return null;
9040 }
9041 return findViewTraversal(id);
9042 }
9043
9044 /**
9045 * Look for a child view with the given tag. If this view has the given
9046 * tag, return this view.
9047 *
9048 * @param tag The tag to search for, using "tag.equals(getTag())".
9049 * @return The View that has the given tag in the hierarchy or null
9050 */
9051 public final View findViewWithTag(Object tag) {
9052 if (tag == null) {
9053 return null;
9054 }
9055 return findViewWithTagTraversal(tag);
9056 }
9057
9058 /**
9059 * Sets the identifier for this view. The identifier does not have to be
9060 * unique in this view's hierarchy. The identifier should be a positive
9061 * number.
9062 *
9063 * @see #NO_ID
9064 * @see #getId
9065 * @see #findViewById
9066 *
9067 * @param id a number used to identify the view
9068 *
9069 * @attr ref android.R.styleable#View_id
9070 */
9071 public void setId(int id) {
9072 mID = id;
9073 }
9074
9075 /**
9076 * {@hide}
9077 *
9078 * @param isRoot true if the view belongs to the root namespace, false
9079 * otherwise
9080 */
9081 public void setIsRootNamespace(boolean isRoot) {
9082 if (isRoot) {
9083 mPrivateFlags |= IS_ROOT_NAMESPACE;
9084 } else {
9085 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9086 }
9087 }
9088
9089 /**
9090 * {@hide}
9091 *
9092 * @return true if the view belongs to the root namespace, false otherwise
9093 */
9094 public boolean isRootNamespace() {
9095 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9096 }
9097
9098 /**
9099 * Returns this view's identifier.
9100 *
9101 * @return a positive integer used to identify the view or {@link #NO_ID}
9102 * if the view has no ID
9103 *
9104 * @see #setId
9105 * @see #findViewById
9106 * @attr ref android.R.styleable#View_id
9107 */
9108 @ViewDebug.CapturedViewProperty
9109 public int getId() {
9110 return mID;
9111 }
9112
9113 /**
9114 * Returns this view's tag.
9115 *
9116 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07009117 *
9118 * @see #setTag(Object)
9119 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009120 */
9121 @ViewDebug.ExportedProperty
9122 public Object getTag() {
9123 return mTag;
9124 }
9125
9126 /**
9127 * Sets the tag associated with this view. A tag can be used to mark
9128 * a view in its hierarchy and does not have to be unique within the
9129 * hierarchy. Tags can also be used to store data within a view without
9130 * resorting to another data structure.
9131 *
9132 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07009133 *
9134 * @see #getTag()
9135 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009136 */
9137 public void setTag(final Object tag) {
9138 mTag = tag;
9139 }
9140
9141 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009142 * Returns the tag associated with this view and the specified key.
9143 *
9144 * @param key The key identifying the tag
9145 *
9146 * @return the Object stored in this view as a tag
9147 *
9148 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009149 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009150 */
9151 public Object getTag(int key) {
9152 SparseArray<Object> tags = null;
9153 synchronized (sTagsLock) {
9154 if (sTags != null) {
9155 tags = sTags.get(this);
9156 }
9157 }
9158
9159 if (tags != null) return tags.get(key);
9160 return null;
9161 }
9162
9163 /**
9164 * Sets a tag associated with this view and a key. A tag can be used
9165 * to mark a view in its hierarchy and does not have to be unique within
9166 * the hierarchy. Tags can also be used to store data within a view
9167 * without resorting to another data structure.
9168 *
9169 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009170 * application to ensure it is unique (see the <a
9171 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9172 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009173 * the Android framework or not associated with any package will cause
9174 * an {@link IllegalArgumentException} to be thrown.
9175 *
9176 * @param key The key identifying the tag
9177 * @param tag An Object to tag the view with
9178 *
9179 * @throws IllegalArgumentException If they specified key is not valid
9180 *
9181 * @see #setTag(Object)
9182 * @see #getTag(int)
9183 */
9184 public void setTag(int key, final Object tag) {
9185 // If the package id is 0x00 or 0x01, it's either an undefined package
9186 // or a framework id
9187 if ((key >>> 24) < 2) {
9188 throw new IllegalArgumentException("The key must be an application-specific "
9189 + "resource id.");
9190 }
9191
9192 setTagInternal(this, key, tag);
9193 }
9194
9195 /**
9196 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9197 * framework id.
9198 *
9199 * @hide
9200 */
9201 public void setTagInternal(int key, Object tag) {
9202 if ((key >>> 24) != 0x1) {
9203 throw new IllegalArgumentException("The key must be a framework-specific "
9204 + "resource id.");
9205 }
9206
Romain Guy8506ab42009-06-11 17:35:47 -07009207 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009208 }
9209
9210 private static void setTagInternal(View view, int key, Object tag) {
9211 SparseArray<Object> tags = null;
9212 synchronized (sTagsLock) {
9213 if (sTags == null) {
9214 sTags = new WeakHashMap<View, SparseArray<Object>>();
9215 } else {
9216 tags = sTags.get(view);
9217 }
9218 }
9219
9220 if (tags == null) {
9221 tags = new SparseArray<Object>(2);
9222 synchronized (sTagsLock) {
9223 sTags.put(view, tags);
9224 }
9225 }
9226
9227 tags.put(key, tag);
9228 }
9229
9230 /**
Romain Guy13922e02009-05-12 17:56:14 -07009231 * @param consistency The type of consistency. See ViewDebug for more information.
9232 *
9233 * @hide
9234 */
9235 protected boolean dispatchConsistencyCheck(int consistency) {
9236 return onConsistencyCheck(consistency);
9237 }
9238
9239 /**
9240 * Method that subclasses should implement to check their consistency. The type of
9241 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009242 *
Romain Guy13922e02009-05-12 17:56:14 -07009243 * @param consistency The type of consistency. See ViewDebug for more information.
9244 *
9245 * @throws IllegalStateException if the view is in an inconsistent state.
9246 *
9247 * @hide
9248 */
9249 protected boolean onConsistencyCheck(int consistency) {
9250 boolean result = true;
9251
9252 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9253 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9254
9255 if (checkLayout) {
9256 if (getParent() == null) {
9257 result = false;
9258 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9259 "View " + this + " does not have a parent.");
9260 }
9261
9262 if (mAttachInfo == null) {
9263 result = false;
9264 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9265 "View " + this + " is not attached to a window.");
9266 }
9267 }
9268
9269 if (checkDrawing) {
9270 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9271 // from their draw() method
9272
9273 if ((mPrivateFlags & DRAWN) != DRAWN &&
9274 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9275 result = false;
9276 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9277 "View " + this + " was invalidated but its drawing cache is valid.");
9278 }
9279 }
9280
9281 return result;
9282 }
9283
9284 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009285 * Prints information about this view in the log output, with the tag
9286 * {@link #VIEW_LOG_TAG}.
9287 *
9288 * @hide
9289 */
9290 public void debug() {
9291 debug(0);
9292 }
9293
9294 /**
9295 * Prints information about this view in the log output, with the tag
9296 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
9297 * indentation defined by the <code>depth</code>.
9298 *
9299 * @param depth the indentation level
9300 *
9301 * @hide
9302 */
9303 protected void debug(int depth) {
9304 String output = debugIndent(depth - 1);
9305
9306 output += "+ " + this;
9307 int id = getId();
9308 if (id != -1) {
9309 output += " (id=" + id + ")";
9310 }
9311 Object tag = getTag();
9312 if (tag != null) {
9313 output += " (tag=" + tag + ")";
9314 }
9315 Log.d(VIEW_LOG_TAG, output);
9316
9317 if ((mPrivateFlags & FOCUSED) != 0) {
9318 output = debugIndent(depth) + " FOCUSED";
9319 Log.d(VIEW_LOG_TAG, output);
9320 }
9321
9322 output = debugIndent(depth);
9323 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
9324 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
9325 + "} ";
9326 Log.d(VIEW_LOG_TAG, output);
9327
9328 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
9329 || mPaddingBottom != 0) {
9330 output = debugIndent(depth);
9331 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
9332 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
9333 Log.d(VIEW_LOG_TAG, output);
9334 }
9335
9336 output = debugIndent(depth);
9337 output += "mMeasureWidth=" + mMeasuredWidth +
9338 " mMeasureHeight=" + mMeasuredHeight;
9339 Log.d(VIEW_LOG_TAG, output);
9340
9341 output = debugIndent(depth);
9342 if (mLayoutParams == null) {
9343 output += "BAD! no layout params";
9344 } else {
9345 output = mLayoutParams.debug(output);
9346 }
9347 Log.d(VIEW_LOG_TAG, output);
9348
9349 output = debugIndent(depth);
9350 output += "flags={";
9351 output += View.printFlags(mViewFlags);
9352 output += "}";
9353 Log.d(VIEW_LOG_TAG, output);
9354
9355 output = debugIndent(depth);
9356 output += "privateFlags={";
9357 output += View.printPrivateFlags(mPrivateFlags);
9358 output += "}";
9359 Log.d(VIEW_LOG_TAG, output);
9360 }
9361
9362 /**
9363 * Creates an string of whitespaces used for indentation.
9364 *
9365 * @param depth the indentation level
9366 * @return a String containing (depth * 2 + 3) * 2 white spaces
9367 *
9368 * @hide
9369 */
9370 protected static String debugIndent(int depth) {
9371 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
9372 for (int i = 0; i < (depth * 2) + 3; i++) {
9373 spaces.append(' ').append(' ');
9374 }
9375 return spaces.toString();
9376 }
9377
9378 /**
9379 * <p>Return the offset of the widget's text baseline from the widget's top
9380 * boundary. If this widget does not support baseline alignment, this
9381 * method returns -1. </p>
9382 *
9383 * @return the offset of the baseline within the widget's bounds or -1
9384 * if baseline alignment is not supported
9385 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07009386 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009387 public int getBaseline() {
9388 return -1;
9389 }
9390
9391 /**
9392 * Call this when something has changed which has invalidated the
9393 * layout of this view. This will schedule a layout pass of the view
9394 * tree.
9395 */
9396 public void requestLayout() {
9397 if (ViewDebug.TRACE_HIERARCHY) {
9398 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
9399 }
9400
9401 mPrivateFlags |= FORCE_LAYOUT;
9402
9403 if (mParent != null && !mParent.isLayoutRequested()) {
9404 mParent.requestLayout();
9405 }
9406 }
9407
9408 /**
9409 * Forces this view to be laid out during the next layout pass.
9410 * This method does not call requestLayout() or forceLayout()
9411 * on the parent.
9412 */
9413 public void forceLayout() {
9414 mPrivateFlags |= FORCE_LAYOUT;
9415 }
9416
9417 /**
9418 * <p>
9419 * This is called to find out how big a view should be. The parent
9420 * supplies constraint information in the width and height parameters.
9421 * </p>
9422 *
9423 * <p>
9424 * The actual mesurement work of a view is performed in
9425 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
9426 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
9427 * </p>
9428 *
9429 *
9430 * @param widthMeasureSpec Horizontal space requirements as imposed by the
9431 * parent
9432 * @param heightMeasureSpec Vertical space requirements as imposed by the
9433 * parent
9434 *
9435 * @see #onMeasure(int, int)
9436 */
9437 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
9438 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
9439 widthMeasureSpec != mOldWidthMeasureSpec ||
9440 heightMeasureSpec != mOldHeightMeasureSpec) {
9441
9442 // first clears the measured dimension flag
9443 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9444
9445 if (ViewDebug.TRACE_HIERARCHY) {
9446 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
9447 }
9448
9449 // measure ourselves, this should set the measured dimension flag back
9450 onMeasure(widthMeasureSpec, heightMeasureSpec);
9451
9452 // flag not set, setMeasuredDimension() was not invoked, we raise
9453 // an exception to warn the developer
9454 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9455 throw new IllegalStateException("onMeasure() did not set the"
9456 + " measured dimension by calling"
9457 + " setMeasuredDimension()");
9458 }
9459
9460 mPrivateFlags |= LAYOUT_REQUIRED;
9461 }
9462
9463 mOldWidthMeasureSpec = widthMeasureSpec;
9464 mOldHeightMeasureSpec = heightMeasureSpec;
9465 }
9466
9467 /**
9468 * <p>
9469 * Measure the view and its content to determine the measured width and the
9470 * measured height. This method is invoked by {@link #measure(int, int)} and
9471 * should be overriden by subclasses to provide accurate and efficient
9472 * measurement of their contents.
9473 * </p>
9474 *
9475 * <p>
9476 * <strong>CONTRACT:</strong> When overriding this method, you
9477 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
9478 * measured width and height of this view. Failure to do so will trigger an
9479 * <code>IllegalStateException</code>, thrown by
9480 * {@link #measure(int, int)}. Calling the superclass'
9481 * {@link #onMeasure(int, int)} is a valid use.
9482 * </p>
9483 *
9484 * <p>
9485 * The base class implementation of measure defaults to the background size,
9486 * unless a larger size is allowed by the MeasureSpec. Subclasses should
9487 * override {@link #onMeasure(int, int)} to provide better measurements of
9488 * their content.
9489 * </p>
9490 *
9491 * <p>
9492 * If this method is overridden, it is the subclass's responsibility to make
9493 * sure the measured height and width are at least the view's minimum height
9494 * and width ({@link #getSuggestedMinimumHeight()} and
9495 * {@link #getSuggestedMinimumWidth()}).
9496 * </p>
9497 *
9498 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
9499 * The requirements are encoded with
9500 * {@link android.view.View.MeasureSpec}.
9501 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
9502 * The requirements are encoded with
9503 * {@link android.view.View.MeasureSpec}.
9504 *
9505 * @see #getMeasuredWidth()
9506 * @see #getMeasuredHeight()
9507 * @see #setMeasuredDimension(int, int)
9508 * @see #getSuggestedMinimumHeight()
9509 * @see #getSuggestedMinimumWidth()
9510 * @see android.view.View.MeasureSpec#getMode(int)
9511 * @see android.view.View.MeasureSpec#getSize(int)
9512 */
9513 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9514 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
9515 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
9516 }
9517
9518 /**
9519 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
9520 * measured width and measured height. Failing to do so will trigger an
9521 * exception at measurement time.</p>
9522 *
9523 * @param measuredWidth the measured width of this view
9524 * @param measuredHeight the measured height of this view
9525 */
9526 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
9527 mMeasuredWidth = measuredWidth;
9528 mMeasuredHeight = measuredHeight;
9529
9530 mPrivateFlags |= MEASURED_DIMENSION_SET;
9531 }
9532
9533 /**
9534 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
9535 * Will take the desired size, unless a different size is imposed by the constraints.
9536 *
9537 * @param size How big the view wants to be
9538 * @param measureSpec Constraints imposed by the parent
9539 * @return The size this view should be.
9540 */
9541 public static int resolveSize(int size, int measureSpec) {
9542 int result = size;
9543 int specMode = MeasureSpec.getMode(measureSpec);
9544 int specSize = MeasureSpec.getSize(measureSpec);
9545 switch (specMode) {
9546 case MeasureSpec.UNSPECIFIED:
9547 result = size;
9548 break;
9549 case MeasureSpec.AT_MOST:
9550 result = Math.min(size, specSize);
9551 break;
9552 case MeasureSpec.EXACTLY:
9553 result = specSize;
9554 break;
9555 }
9556 return result;
9557 }
9558
9559 /**
9560 * Utility to return a default size. Uses the supplied size if the
9561 * MeasureSpec imposed no contraints. Will get larger if allowed
9562 * by the MeasureSpec.
9563 *
9564 * @param size Default size for this view
9565 * @param measureSpec Constraints imposed by the parent
9566 * @return The size this view should be.
9567 */
9568 public static int getDefaultSize(int size, int measureSpec) {
9569 int result = size;
9570 int specMode = MeasureSpec.getMode(measureSpec);
9571 int specSize = MeasureSpec.getSize(measureSpec);
9572
9573 switch (specMode) {
9574 case MeasureSpec.UNSPECIFIED:
9575 result = size;
9576 break;
9577 case MeasureSpec.AT_MOST:
9578 case MeasureSpec.EXACTLY:
9579 result = specSize;
9580 break;
9581 }
9582 return result;
9583 }
9584
9585 /**
9586 * Returns the suggested minimum height that the view should use. This
9587 * returns the maximum of the view's minimum height
9588 * and the background's minimum height
9589 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
9590 * <p>
9591 * When being used in {@link #onMeasure(int, int)}, the caller should still
9592 * ensure the returned height is within the requirements of the parent.
9593 *
9594 * @return The suggested minimum height of the view.
9595 */
9596 protected int getSuggestedMinimumHeight() {
9597 int suggestedMinHeight = mMinHeight;
9598
9599 if (mBGDrawable != null) {
9600 final int bgMinHeight = mBGDrawable.getMinimumHeight();
9601 if (suggestedMinHeight < bgMinHeight) {
9602 suggestedMinHeight = bgMinHeight;
9603 }
9604 }
9605
9606 return suggestedMinHeight;
9607 }
9608
9609 /**
9610 * Returns the suggested minimum width that the view should use. This
9611 * returns the maximum of the view's minimum width)
9612 * and the background's minimum width
9613 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
9614 * <p>
9615 * When being used in {@link #onMeasure(int, int)}, the caller should still
9616 * ensure the returned width is within the requirements of the parent.
9617 *
9618 * @return The suggested minimum width of the view.
9619 */
9620 protected int getSuggestedMinimumWidth() {
9621 int suggestedMinWidth = mMinWidth;
9622
9623 if (mBGDrawable != null) {
9624 final int bgMinWidth = mBGDrawable.getMinimumWidth();
9625 if (suggestedMinWidth < bgMinWidth) {
9626 suggestedMinWidth = bgMinWidth;
9627 }
9628 }
9629
9630 return suggestedMinWidth;
9631 }
9632
9633 /**
9634 * Sets the minimum height of the view. It is not guaranteed the view will
9635 * be able to achieve this minimum height (for example, if its parent layout
9636 * constrains it with less available height).
9637 *
9638 * @param minHeight The minimum height the view will try to be.
9639 */
9640 public void setMinimumHeight(int minHeight) {
9641 mMinHeight = minHeight;
9642 }
9643
9644 /**
9645 * Sets the minimum width of the view. It is not guaranteed the view will
9646 * be able to achieve this minimum width (for example, if its parent layout
9647 * constrains it with less available width).
9648 *
9649 * @param minWidth The minimum width the view will try to be.
9650 */
9651 public void setMinimumWidth(int minWidth) {
9652 mMinWidth = minWidth;
9653 }
9654
9655 /**
9656 * Get the animation currently associated with this view.
9657 *
9658 * @return The animation that is currently playing or
9659 * scheduled to play for this view.
9660 */
9661 public Animation getAnimation() {
9662 return mCurrentAnimation;
9663 }
9664
9665 /**
9666 * Start the specified animation now.
9667 *
9668 * @param animation the animation to start now
9669 */
9670 public void startAnimation(Animation animation) {
9671 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
9672 setAnimation(animation);
9673 invalidate();
9674 }
9675
9676 /**
9677 * Cancels any animations for this view.
9678 */
9679 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08009680 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08009681 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08009682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009683 mCurrentAnimation = null;
9684 }
9685
9686 /**
9687 * Sets the next animation to play for this view.
9688 * If you want the animation to play immediately, use
9689 * startAnimation. This method provides allows fine-grained
9690 * control over the start time and invalidation, but you
9691 * must make sure that 1) the animation has a start time set, and
9692 * 2) the view will be invalidated when the animation is supposed to
9693 * start.
9694 *
9695 * @param animation The next animation, or null.
9696 */
9697 public void setAnimation(Animation animation) {
9698 mCurrentAnimation = animation;
9699 if (animation != null) {
9700 animation.reset();
9701 }
9702 }
9703
9704 /**
9705 * Invoked by a parent ViewGroup to notify the start of the animation
9706 * currently associated with this view. If you override this method,
9707 * always call super.onAnimationStart();
9708 *
9709 * @see #setAnimation(android.view.animation.Animation)
9710 * @see #getAnimation()
9711 */
9712 protected void onAnimationStart() {
9713 mPrivateFlags |= ANIMATION_STARTED;
9714 }
9715
9716 /**
9717 * Invoked by a parent ViewGroup to notify the end of the animation
9718 * currently associated with this view. If you override this method,
9719 * always call super.onAnimationEnd();
9720 *
9721 * @see #setAnimation(android.view.animation.Animation)
9722 * @see #getAnimation()
9723 */
9724 protected void onAnimationEnd() {
9725 mPrivateFlags &= ~ANIMATION_STARTED;
9726 }
9727
9728 /**
9729 * Invoked if there is a Transform that involves alpha. Subclass that can
9730 * draw themselves with the specified alpha should return true, and then
9731 * respect that alpha when their onDraw() is called. If this returns false
9732 * then the view may be redirected to draw into an offscreen buffer to
9733 * fulfill the request, which will look fine, but may be slower than if the
9734 * subclass handles it internally. The default implementation returns false.
9735 *
9736 * @param alpha The alpha (0..255) to apply to the view's drawing
9737 * @return true if the view can draw with the specified alpha.
9738 */
9739 protected boolean onSetAlpha(int alpha) {
9740 return false;
9741 }
9742
9743 /**
9744 * This is used by the RootView to perform an optimization when
9745 * the view hierarchy contains one or several SurfaceView.
9746 * SurfaceView is always considered transparent, but its children are not,
9747 * therefore all View objects remove themselves from the global transparent
9748 * region (passed as a parameter to this function).
9749 *
9750 * @param region The transparent region for this ViewRoot (window).
9751 *
9752 * @return Returns true if the effective visibility of the view at this
9753 * point is opaque, regardless of the transparent region; returns false
9754 * if it is possible for underlying windows to be seen behind the view.
9755 *
9756 * {@hide}
9757 */
9758 public boolean gatherTransparentRegion(Region region) {
9759 final AttachInfo attachInfo = mAttachInfo;
9760 if (region != null && attachInfo != null) {
9761 final int pflags = mPrivateFlags;
9762 if ((pflags & SKIP_DRAW) == 0) {
9763 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
9764 // remove it from the transparent region.
9765 final int[] location = attachInfo.mTransparentLocation;
9766 getLocationInWindow(location);
9767 region.op(location[0], location[1], location[0] + mRight - mLeft,
9768 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
9769 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
9770 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
9771 // exists, so we remove the background drawable's non-transparent
9772 // parts from this transparent region.
9773 applyDrawableToTransparentRegion(mBGDrawable, region);
9774 }
9775 }
9776 return true;
9777 }
9778
9779 /**
9780 * Play a sound effect for this view.
9781 *
9782 * <p>The framework will play sound effects for some built in actions, such as
9783 * clicking, but you may wish to play these effects in your widget,
9784 * for instance, for internal navigation.
9785 *
9786 * <p>The sound effect will only be played if sound effects are enabled by the user, and
9787 * {@link #isSoundEffectsEnabled()} is true.
9788 *
9789 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
9790 */
9791 public void playSoundEffect(int soundConstant) {
9792 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
9793 return;
9794 }
9795 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
9796 }
9797
9798 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009799 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009800 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009801 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009802 *
9803 * <p>The framework will provide haptic feedback for some built in actions,
9804 * such as long presses, but you may wish to provide feedback for your
9805 * own widget.
9806 *
9807 * <p>The feedback will only be performed if
9808 * {@link #isHapticFeedbackEnabled()} is true.
9809 *
9810 * @param feedbackConstant One of the constants defined in
9811 * {@link HapticFeedbackConstants}
9812 */
9813 public boolean performHapticFeedback(int feedbackConstant) {
9814 return performHapticFeedback(feedbackConstant, 0);
9815 }
9816
9817 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009818 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009819 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009820 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009821 *
9822 * @param feedbackConstant One of the constants defined in
9823 * {@link HapticFeedbackConstants}
9824 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
9825 */
9826 public boolean performHapticFeedback(int feedbackConstant, int flags) {
9827 if (mAttachInfo == null) {
9828 return false;
9829 }
Romain Guyf607bdc2010-09-10 19:20:06 -07009830 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -07009831 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 && !isHapticFeedbackEnabled()) {
9833 return false;
9834 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009835 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
9836 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009837 }
9838
9839 /**
Christopher Tate2c095f32010-10-04 14:13:40 -07009840 * !!! TODO: real docs
9841 *
9842 * The base class implementation makes the thumbnail the same size and appearance
9843 * as the view itself, and positions it with its center at the touch point.
9844 */
9845 public class DragThumbnailBuilder {
9846 private View mView;
9847
9848 /**
9849 * Construct a thumbnail builder object for use with the given view.
9850 * @param view
9851 */
9852 public DragThumbnailBuilder(View view) {
9853 mView = view;
9854 }
9855
9856 /**
9857 * Provide the draggable-thumbnail metrics for the operation: the dimensions of
9858 * the thumbnail image itself, and the point within that thumbnail that should
9859 * be centered under the touch location while dragging.
9860 * <p>
9861 * The default implementation sets the dimensions of the thumbnail to be the
9862 * same as the dimensions of the View itself and centers the thumbnail under
9863 * the touch point.
9864 *
9865 * @param thumbnailSize The application should set the {@code x} member of this
9866 * parameter to the desired thumbnail width, and the {@code y} member to
9867 * the desired height.
9868 * @param thumbnailTouchPoint The application should set this point to be the
9869 * location within the thumbnail that should track directly underneath
9870 * the touch point on the screen during a drag.
9871 */
9872 public void onProvideThumbnailMetrics(Point thumbnailSize, Point thumbnailTouchPoint) {
9873 thumbnailSize.set(mView.getWidth(), mView.getHeight());
9874 thumbnailTouchPoint.set(thumbnailSize.x / 2, thumbnailSize.y / 2);
9875 }
9876
9877 /**
9878 * Draw the thumbnail image for the upcoming drag. The thumbnail canvas was
9879 * created with the dimensions supplied by the onProvideThumbnailMetrics()
9880 * callback.
9881 *
9882 * @param canvas
9883 */
9884 public void onDrawThumbnail(Canvas canvas) {
9885 mView.draw(canvas);
9886 }
9887 }
9888
9889 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07009890 * Drag and drop. App calls startDrag(), then callbacks to onMeasureDragThumbnail()
9891 * and onDrawDragThumbnail() happen, then the drag operation is handed over to the
9892 * OS.
9893 * !!! TODO: real docs
9894 * @hide
9895 */
Christopher Tate2c095f32010-10-04 14:13:40 -07009896 public final boolean startDrag(ClipData data, DragThumbnailBuilder thumbBuilder,
9897 boolean myWindowOnly) {
9898 if (ViewDebug.DEBUG_DRAG) {
9899 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " local=" + myWindowOnly);
Christopher Tatea53146c2010-09-07 11:57:52 -07009900 }
9901 boolean okay = false;
9902
Christopher Tate2c095f32010-10-04 14:13:40 -07009903 Point thumbSize = new Point();
9904 Point thumbTouchPoint = new Point();
9905 thumbBuilder.onProvideThumbnailMetrics(thumbSize, thumbTouchPoint);
9906
9907 if ((thumbSize.x < 0) || (thumbSize.y < 0) ||
9908 (thumbTouchPoint.x < 0) || (thumbTouchPoint.y < 0)) {
9909 throw new IllegalStateException("Drag thumb dimensions must not be negative");
9910 }
Christopher Tatea53146c2010-09-07 11:57:52 -07009911
9912 Surface surface = new Surface();
9913 try {
9914 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
9915 myWindowOnly, mThumbnailWidth, mThumbnailHeight, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -07009916 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -07009917 + " surface=" + surface);
9918 if (token != null) {
9919 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -07009920 try {
Christopher Tate2c095f32010-10-04 14:13:40 -07009921 thumbBuilder.onDrawThumbnail(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -07009922 } finally {
9923 surface.unlockCanvasAndPost(canvas);
9924 }
Christopher Tatea53146c2010-09-07 11:57:52 -07009925
Christopher Tate2c095f32010-10-04 14:13:40 -07009926 // repurpose 'thumbSize' for the last touch point
9927 getViewRoot().getLastTouchPoint(thumbSize);
9928
Christopher Tatea53146c2010-09-07 11:57:52 -07009929 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate2c095f32010-10-04 14:13:40 -07009930 (float) thumbSize.x, (float) thumbSize.y,
9931 (float) thumbTouchPoint.x, (float) thumbTouchPoint.y, data);
9932 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -07009933 }
9934 } catch (Exception e) {
9935 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
9936 surface.destroy();
9937 }
9938
9939 return okay;
9940 }
9941
9942 private void measureThumbnail() {
9943 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9944
9945 onMeasureDragThumbnail();
9946
9947 // flag not set, setDragThumbnailDimension() was not invoked, we raise
9948 // an exception to warn the developer
9949 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9950 throw new IllegalStateException("onMeasureDragThumbnail() did not set the"
9951 + " measured dimension by calling setDragThumbnailDimension()");
9952 }
9953
Christopher Tate2c095f32010-10-04 14:13:40 -07009954 if (ViewDebug.DEBUG_DRAG) {
Christopher Tatea53146c2010-09-07 11:57:52 -07009955 Log.d(VIEW_LOG_TAG, "Drag thumb measured: w=" + mThumbnailWidth
9956 + " h=" + mThumbnailHeight);
9957 }
9958 }
9959
9960 /**
9961 * The View must call this method from onMeasureDragThumbnail() in order to
9962 * specify the dimensions of the drag thumbnail image.
9963 *
Romain Guy0bb56672010-10-01 00:25:02 -07009964 * @param width The desired thumbnail width.
9965 * @param height The desired thumbnail height.
Christopher Tatea53146c2010-09-07 11:57:52 -07009966 */
9967 protected final void setDragThumbnailDimension(int width, int height) {
9968 mPrivateFlags |= MEASURED_DIMENSION_SET;
9969 mThumbnailWidth = width;
9970 mThumbnailHeight = height;
9971 }
9972
9973 /**
9974 * The default implementation specifies a drag thumbnail that matches the
9975 * View's current size and appearance.
9976 */
9977 protected void onMeasureDragThumbnail() {
9978 setDragThumbnailDimension(getWidth(), getHeight());
9979 }
9980
9981 /**
9982 * The default implementation just draws the current View appearance as the thumbnail
9983 * @param canvas
9984 */
9985 protected void onDrawDragThumbnail(Canvas canvas) {
9986 draw(canvas);
9987 }
9988
9989 /**
9990 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
9991 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
9992 *
9993 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
9994 * being dragged. onDragEvent() should return 'true' if the view can handle
9995 * a drop of that content. A view that returns 'false' here will receive no
9996 * further calls to onDragEvent() about the drag/drop operation.
9997 *
9998 * For DRAG_ENTERED, event.getClipDescription() describes the content being
9999 * dragged. This will be the same content description passed in the
10000 * DRAG_STARTED_EVENT invocation.
10001 *
10002 * For DRAG_EXITED, event.getClipDescription() describes the content being
10003 * dragged. This will be the same content description passed in the
10004 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
10005 * drag-acceptance visual state.
10006 *
10007 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10008 * coordinates of the current drag point. The view must return 'true' if it
10009 * can accept a drop of the current drag content, false otherwise.
10010 *
10011 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10012 * within the view; also, event.getClipData() returns the full data payload
10013 * being dropped. The view should return 'true' if it consumed the dropped
10014 * content, 'false' if it did not.
10015 *
10016 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
10017 * to its normal visual state.
10018 */
10019 protected boolean onDragEvent(DragEvent event) {
10020 return false;
10021 }
10022
10023 /**
10024 * Views typically don't need to override dispatchDragEvent(); it just calls
10025 * onDragEvent(what, event) and passes the result up appropriately.
10026 *
10027 */
10028 public boolean dispatchDragEvent(DragEvent event) {
10029 return onDragEvent(event);
10030 }
10031
10032 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070010033 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
10034 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070010035 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070010036 */
10037 public void onCloseSystemDialogs(String reason) {
10038 }
10039
10040 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010041 * Given a Drawable whose bounds have been set to draw into this view,
10042 * update a Region being computed for {@link #gatherTransparentRegion} so
10043 * that any non-transparent parts of the Drawable are removed from the
10044 * given transparent region.
10045 *
10046 * @param dr The Drawable whose transparency is to be applied to the region.
10047 * @param region A Region holding the current transparency information,
10048 * where any parts of the region that are set are considered to be
10049 * transparent. On return, this region will be modified to have the
10050 * transparency information reduced by the corresponding parts of the
10051 * Drawable that are not transparent.
10052 * {@hide}
10053 */
10054 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
10055 if (DBG) {
10056 Log.i("View", "Getting transparent region for: " + this);
10057 }
10058 final Region r = dr.getTransparentRegion();
10059 final Rect db = dr.getBounds();
10060 final AttachInfo attachInfo = mAttachInfo;
10061 if (r != null && attachInfo != null) {
10062 final int w = getRight()-getLeft();
10063 final int h = getBottom()-getTop();
10064 if (db.left > 0) {
10065 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
10066 r.op(0, 0, db.left, h, Region.Op.UNION);
10067 }
10068 if (db.right < w) {
10069 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
10070 r.op(db.right, 0, w, h, Region.Op.UNION);
10071 }
10072 if (db.top > 0) {
10073 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
10074 r.op(0, 0, w, db.top, Region.Op.UNION);
10075 }
10076 if (db.bottom < h) {
10077 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
10078 r.op(0, db.bottom, w, h, Region.Op.UNION);
10079 }
10080 final int[] location = attachInfo.mTransparentLocation;
10081 getLocationInWindow(location);
10082 r.translate(location[0], location[1]);
10083 region.op(r, Region.Op.INTERSECT);
10084 } else {
10085 region.op(db, Region.Op.DIFFERENCE);
10086 }
10087 }
10088
Adam Powelle14579b2009-12-16 18:39:52 -080010089 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010090 mHasPerformedLongPress = false;
10091
10092 if (mPendingCheckForLongPress == null) {
10093 mPendingCheckForLongPress = new CheckForLongPress();
10094 }
10095 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080010096 postDelayed(mPendingCheckForLongPress,
10097 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010098 }
10099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010100 /**
10101 * Inflate a view from an XML resource. This convenience method wraps the {@link
10102 * LayoutInflater} class, which provides a full range of options for view inflation.
10103 *
10104 * @param context The Context object for your activity or application.
10105 * @param resource The resource ID to inflate
10106 * @param root A view group that will be the parent. Used to properly inflate the
10107 * layout_* parameters.
10108 * @see LayoutInflater
10109 */
10110 public static View inflate(Context context, int resource, ViewGroup root) {
10111 LayoutInflater factory = LayoutInflater.from(context);
10112 return factory.inflate(resource, root);
10113 }
Romain Guy33e72ae2010-07-17 12:40:29 -070010114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010115 /**
10116 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
10117 * Each MeasureSpec represents a requirement for either the width or the height.
10118 * A MeasureSpec is comprised of a size and a mode. There are three possible
10119 * modes:
10120 * <dl>
10121 * <dt>UNSPECIFIED</dt>
10122 * <dd>
10123 * The parent has not imposed any constraint on the child. It can be whatever size
10124 * it wants.
10125 * </dd>
10126 *
10127 * <dt>EXACTLY</dt>
10128 * <dd>
10129 * The parent has determined an exact size for the child. The child is going to be
10130 * given those bounds regardless of how big it wants to be.
10131 * </dd>
10132 *
10133 * <dt>AT_MOST</dt>
10134 * <dd>
10135 * The child can be as large as it wants up to the specified size.
10136 * </dd>
10137 * </dl>
10138 *
10139 * MeasureSpecs are implemented as ints to reduce object allocation. This class
10140 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
10141 */
10142 public static class MeasureSpec {
10143 private static final int MODE_SHIFT = 30;
10144 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
10145
10146 /**
10147 * Measure specification mode: The parent has not imposed any constraint
10148 * on the child. It can be whatever size it wants.
10149 */
10150 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
10151
10152 /**
10153 * Measure specification mode: The parent has determined an exact size
10154 * for the child. The child is going to be given those bounds regardless
10155 * of how big it wants to be.
10156 */
10157 public static final int EXACTLY = 1 << MODE_SHIFT;
10158
10159 /**
10160 * Measure specification mode: The child can be as large as it wants up
10161 * to the specified size.
10162 */
10163 public static final int AT_MOST = 2 << MODE_SHIFT;
10164
10165 /**
10166 * Creates a measure specification based on the supplied size and mode.
10167 *
10168 * The mode must always be one of the following:
10169 * <ul>
10170 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
10171 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
10172 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
10173 * </ul>
10174 *
10175 * @param size the size of the measure specification
10176 * @param mode the mode of the measure specification
10177 * @return the measure specification based on size and mode
10178 */
10179 public static int makeMeasureSpec(int size, int mode) {
10180 return size + mode;
10181 }
10182
10183 /**
10184 * Extracts the mode from the supplied measure specification.
10185 *
10186 * @param measureSpec the measure specification to extract the mode from
10187 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
10188 * {@link android.view.View.MeasureSpec#AT_MOST} or
10189 * {@link android.view.View.MeasureSpec#EXACTLY}
10190 */
10191 public static int getMode(int measureSpec) {
10192 return (measureSpec & MODE_MASK);
10193 }
10194
10195 /**
10196 * Extracts the size from the supplied measure specification.
10197 *
10198 * @param measureSpec the measure specification to extract the size from
10199 * @return the size in pixels defined in the supplied measure specification
10200 */
10201 public static int getSize(int measureSpec) {
10202 return (measureSpec & ~MODE_MASK);
10203 }
10204
10205 /**
10206 * Returns a String representation of the specified measure
10207 * specification.
10208 *
10209 * @param measureSpec the measure specification to convert to a String
10210 * @return a String with the following format: "MeasureSpec: MODE SIZE"
10211 */
10212 public static String toString(int measureSpec) {
10213 int mode = getMode(measureSpec);
10214 int size = getSize(measureSpec);
10215
10216 StringBuilder sb = new StringBuilder("MeasureSpec: ");
10217
10218 if (mode == UNSPECIFIED)
10219 sb.append("UNSPECIFIED ");
10220 else if (mode == EXACTLY)
10221 sb.append("EXACTLY ");
10222 else if (mode == AT_MOST)
10223 sb.append("AT_MOST ");
10224 else
10225 sb.append(mode).append(" ");
10226
10227 sb.append(size);
10228 return sb.toString();
10229 }
10230 }
10231
10232 class CheckForLongPress implements Runnable {
10233
10234 private int mOriginalWindowAttachCount;
10235
10236 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070010237 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010238 && mOriginalWindowAttachCount == mWindowAttachCount) {
10239 if (performLongClick()) {
10240 mHasPerformedLongPress = true;
10241 }
10242 }
10243 }
10244
10245 public void rememberWindowAttachCount() {
10246 mOriginalWindowAttachCount = mWindowAttachCount;
10247 }
10248 }
Adam Powelle14579b2009-12-16 18:39:52 -080010249
10250 private final class CheckForTap implements Runnable {
10251 public void run() {
10252 mPrivateFlags &= ~PREPRESSED;
10253 mPrivateFlags |= PRESSED;
10254 refreshDrawableState();
10255 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
10256 postCheckForLongClick(ViewConfiguration.getTapTimeout());
10257 }
10258 }
10259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010260
Adam Powella35d7682010-03-12 14:48:13 -080010261 private final class PerformClick implements Runnable {
10262 public void run() {
10263 performClick();
10264 }
10265 }
10266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010267 /**
10268 * Interface definition for a callback to be invoked when a key event is
10269 * dispatched to this view. The callback will be invoked before the key
10270 * event is given to the view.
10271 */
10272 public interface OnKeyListener {
10273 /**
10274 * Called when a key is dispatched to a view. This allows listeners to
10275 * get a chance to respond before the target view.
10276 *
10277 * @param v The view the key has been dispatched to.
10278 * @param keyCode The code for the physical key that was pressed
10279 * @param event The KeyEvent object containing full information about
10280 * the event.
10281 * @return True if the listener has consumed the event, false otherwise.
10282 */
10283 boolean onKey(View v, int keyCode, KeyEvent event);
10284 }
10285
10286 /**
10287 * Interface definition for a callback to be invoked when a touch event is
10288 * dispatched to this view. The callback will be invoked before the touch
10289 * event is given to the view.
10290 */
10291 public interface OnTouchListener {
10292 /**
10293 * Called when a touch event is dispatched to a view. This allows listeners to
10294 * get a chance to respond before the target view.
10295 *
10296 * @param v The view the touch event has been dispatched to.
10297 * @param event The MotionEvent object containing full information about
10298 * the event.
10299 * @return True if the listener has consumed the event, false otherwise.
10300 */
10301 boolean onTouch(View v, MotionEvent event);
10302 }
10303
10304 /**
10305 * Interface definition for a callback to be invoked when a view has been clicked and held.
10306 */
10307 public interface OnLongClickListener {
10308 /**
10309 * Called when a view has been clicked and held.
10310 *
10311 * @param v The view that was clicked and held.
10312 *
10313 * return True if the callback consumed the long click, false otherwise
10314 */
10315 boolean onLongClick(View v);
10316 }
10317
10318 /**
10319 * Interface definition for a callback to be invoked when the focus state of
10320 * a view changed.
10321 */
10322 public interface OnFocusChangeListener {
10323 /**
10324 * Called when the focus state of a view has changed.
10325 *
10326 * @param v The view whose state has changed.
10327 * @param hasFocus The new focus state of v.
10328 */
10329 void onFocusChange(View v, boolean hasFocus);
10330 }
10331
10332 /**
10333 * Interface definition for a callback to be invoked when a view is clicked.
10334 */
10335 public interface OnClickListener {
10336 /**
10337 * Called when a view has been clicked.
10338 *
10339 * @param v The view that was clicked.
10340 */
10341 void onClick(View v);
10342 }
10343
10344 /**
10345 * Interface definition for a callback to be invoked when the context menu
10346 * for this view is being built.
10347 */
10348 public interface OnCreateContextMenuListener {
10349 /**
10350 * Called when the context menu for this view is being built. It is not
10351 * safe to hold onto the menu after this method returns.
10352 *
10353 * @param menu The context menu that is being built
10354 * @param v The view for which the context menu is being built
10355 * @param menuInfo Extra information about the item for which the
10356 * context menu should be shown. This information will vary
10357 * depending on the class of v.
10358 */
10359 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
10360 }
10361
10362 private final class UnsetPressedState implements Runnable {
10363 public void run() {
10364 setPressed(false);
10365 }
10366 }
10367
10368 /**
10369 * Base class for derived classes that want to save and restore their own
10370 * state in {@link android.view.View#onSaveInstanceState()}.
10371 */
10372 public static class BaseSavedState extends AbsSavedState {
10373 /**
10374 * Constructor used when reading from a parcel. Reads the state of the superclass.
10375 *
10376 * @param source
10377 */
10378 public BaseSavedState(Parcel source) {
10379 super(source);
10380 }
10381
10382 /**
10383 * Constructor called by derived classes when creating their SavedState objects
10384 *
10385 * @param superState The state of the superclass of this view
10386 */
10387 public BaseSavedState(Parcelable superState) {
10388 super(superState);
10389 }
10390
10391 public static final Parcelable.Creator<BaseSavedState> CREATOR =
10392 new Parcelable.Creator<BaseSavedState>() {
10393 public BaseSavedState createFromParcel(Parcel in) {
10394 return new BaseSavedState(in);
10395 }
10396
10397 public BaseSavedState[] newArray(int size) {
10398 return new BaseSavedState[size];
10399 }
10400 };
10401 }
10402
10403 /**
10404 * A set of information given to a view when it is attached to its parent
10405 * window.
10406 */
10407 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010408 interface Callbacks {
10409 void playSoundEffect(int effectId);
10410 boolean performHapticFeedback(int effectId, boolean always);
10411 }
10412
10413 /**
10414 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
10415 * to a Handler. This class contains the target (View) to invalidate and
10416 * the coordinates of the dirty rectangle.
10417 *
10418 * For performance purposes, this class also implements a pool of up to
10419 * POOL_LIMIT objects that get reused. This reduces memory allocations
10420 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010421 */
Romain Guyd928d682009-03-31 17:52:16 -070010422 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010423 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070010424 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
10425 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070010426 public InvalidateInfo newInstance() {
10427 return new InvalidateInfo();
10428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010429
Romain Guyd928d682009-03-31 17:52:16 -070010430 public void onAcquired(InvalidateInfo element) {
10431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010432
Romain Guyd928d682009-03-31 17:52:16 -070010433 public void onReleased(InvalidateInfo element) {
10434 }
10435 }, POOL_LIMIT)
10436 );
10437
10438 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010439
10440 View target;
10441
10442 int left;
10443 int top;
10444 int right;
10445 int bottom;
10446
Romain Guyd928d682009-03-31 17:52:16 -070010447 public void setNextPoolable(InvalidateInfo element) {
10448 mNext = element;
10449 }
10450
10451 public InvalidateInfo getNextPoolable() {
10452 return mNext;
10453 }
10454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010455 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070010456 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010457 }
10458
10459 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070010460 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010461 }
10462 }
10463
10464 final IWindowSession mSession;
10465
10466 final IWindow mWindow;
10467
10468 final IBinder mWindowToken;
10469
10470 final Callbacks mRootCallbacks;
10471
10472 /**
10473 * The top view of the hierarchy.
10474 */
10475 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070010476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010477 IBinder mPanelParentWindowToken;
10478 Surface mSurface;
10479
Romain Guyb051e892010-09-28 19:09:36 -070010480 boolean mHardwareAccelerated;
10481 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070010482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010483 /**
Romain Guy8506ab42009-06-11 17:35:47 -070010484 * Scale factor used by the compatibility mode
10485 */
10486 float mApplicationScale;
10487
10488 /**
10489 * Indicates whether the application is in compatibility mode
10490 */
10491 boolean mScalingRequired;
10492
10493 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010494 * Left position of this view's window
10495 */
10496 int mWindowLeft;
10497
10498 /**
10499 * Top position of this view's window
10500 */
10501 int mWindowTop;
10502
10503 /**
Romain Guy35b38ce2009-10-07 13:38:55 -070010504 * Indicates whether the window is translucent/transparent
10505 */
10506 boolean mTranslucentWindow;
10507
10508 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010509 * For windows that are full-screen but using insets to layout inside
10510 * of the screen decorations, these are the current insets for the
10511 * content of the window.
10512 */
10513 final Rect mContentInsets = new Rect();
10514
10515 /**
10516 * For windows that are full-screen but using insets to layout inside
10517 * of the screen decorations, these are the current insets for the
10518 * actual visible parts of the window.
10519 */
10520 final Rect mVisibleInsets = new Rect();
10521
10522 /**
10523 * The internal insets given by this window. This value is
10524 * supplied by the client (through
10525 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
10526 * be given to the window manager when changed to be used in laying
10527 * out windows behind it.
10528 */
10529 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
10530 = new ViewTreeObserver.InternalInsetsInfo();
10531
10532 /**
10533 * All views in the window's hierarchy that serve as scroll containers,
10534 * used to determine if the window can be resized or must be panned
10535 * to adjust for a soft input area.
10536 */
10537 final ArrayList<View> mScrollContainers = new ArrayList<View>();
10538
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070010539 final KeyEvent.DispatcherState mKeyDispatchState
10540 = new KeyEvent.DispatcherState();
10541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 /**
10543 * Indicates whether the view's window currently has the focus.
10544 */
10545 boolean mHasWindowFocus;
10546
10547 /**
10548 * The current visibility of the window.
10549 */
10550 int mWindowVisibility;
10551
10552 /**
10553 * Indicates the time at which drawing started to occur.
10554 */
10555 long mDrawingTime;
10556
10557 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070010558 * Indicates whether or not ignoring the DIRTY_MASK flags.
10559 */
10560 boolean mIgnoreDirtyState;
10561
10562 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010563 * Indicates whether the view's window is currently in touch mode.
10564 */
10565 boolean mInTouchMode;
10566
10567 /**
10568 * Indicates that ViewRoot should trigger a global layout change
10569 * the next time it performs a traversal
10570 */
10571 boolean mRecomputeGlobalAttributes;
10572
10573 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010574 * Set during a traveral if any views want to keep the screen on.
10575 */
10576 boolean mKeepScreenOn;
10577
10578 /**
10579 * Set if the visibility of any views has changed.
10580 */
10581 boolean mViewVisibilityChanged;
10582
10583 /**
10584 * Set to true if a view has been scrolled.
10585 */
10586 boolean mViewScrollChanged;
10587
10588 /**
10589 * Global to the view hierarchy used as a temporary for dealing with
10590 * x/y points in the transparent region computations.
10591 */
10592 final int[] mTransparentLocation = new int[2];
10593
10594 /**
10595 * Global to the view hierarchy used as a temporary for dealing with
10596 * x/y points in the ViewGroup.invalidateChild implementation.
10597 */
10598 final int[] mInvalidateChildLocation = new int[2];
10599
Chet Haasec3aa3612010-06-17 08:50:37 -070010600
10601 /**
10602 * Global to the view hierarchy used as a temporary for dealing with
10603 * x/y location when view is transformed.
10604 */
10605 final float[] mTmpTransformLocation = new float[2];
10606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010607 /**
10608 * The view tree observer used to dispatch global events like
10609 * layout, pre-draw, touch mode change, etc.
10610 */
10611 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
10612
10613 /**
10614 * A Canvas used by the view hierarchy to perform bitmap caching.
10615 */
10616 Canvas mCanvas;
10617
10618 /**
10619 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
10620 * handler can be used to pump events in the UI events queue.
10621 */
10622 final Handler mHandler;
10623
10624 /**
10625 * Identifier for messages requesting the view to be invalidated.
10626 * Such messages should be sent to {@link #mHandler}.
10627 */
10628 static final int INVALIDATE_MSG = 0x1;
10629
10630 /**
10631 * Identifier for messages requesting the view to invalidate a region.
10632 * Such messages should be sent to {@link #mHandler}.
10633 */
10634 static final int INVALIDATE_RECT_MSG = 0x2;
10635
10636 /**
10637 * Temporary for use in computing invalidate rectangles while
10638 * calling up the hierarchy.
10639 */
10640 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070010641
10642 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070010643 * Temporary for use in computing hit areas with transformed views
10644 */
10645 final RectF mTmpTransformRect = new RectF();
10646
10647 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070010648 * Temporary list for use in collecting focusable descendents of a view.
10649 */
10650 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
10651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010652 /**
10653 * Creates a new set of attachment information with the specified
10654 * events handler and thread.
10655 *
10656 * @param handler the events handler the view must use
10657 */
10658 AttachInfo(IWindowSession session, IWindow window,
10659 Handler handler, Callbacks effectPlayer) {
10660 mSession = session;
10661 mWindow = window;
10662 mWindowToken = window.asBinder();
10663 mHandler = handler;
10664 mRootCallbacks = effectPlayer;
10665 }
10666 }
10667
10668 /**
10669 * <p>ScrollabilityCache holds various fields used by a View when scrolling
10670 * is supported. This avoids keeping too many unused fields in most
10671 * instances of View.</p>
10672 */
Mike Cleronf116bf82009-09-27 19:14:12 -070010673 private static class ScrollabilityCache implements Runnable {
10674
10675 /**
10676 * Scrollbars are not visible
10677 */
10678 public static final int OFF = 0;
10679
10680 /**
10681 * Scrollbars are visible
10682 */
10683 public static final int ON = 1;
10684
10685 /**
10686 * Scrollbars are fading away
10687 */
10688 public static final int FADING = 2;
10689
10690 public boolean fadeScrollBars;
10691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010692 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070010693 public int scrollBarDefaultDelayBeforeFade;
10694 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010695
10696 public int scrollBarSize;
10697 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070010698 public float[] interpolatorValues;
10699 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010700
10701 public final Paint paint;
10702 public final Matrix matrix;
10703 public Shader shader;
10704
Mike Cleronf116bf82009-09-27 19:14:12 -070010705 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
10706
Romain Guy8fb95422010-08-17 18:38:51 -070010707 private final float[] mOpaque = { 255.0f };
10708 private final float[] mTransparent = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070010709
10710 /**
10711 * When fading should start. This time moves into the future every time
10712 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
10713 */
10714 public long fadeStartTime;
10715
10716
10717 /**
10718 * The current state of the scrollbars: ON, OFF, or FADING
10719 */
10720 public int state = OFF;
10721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010722 private int mLastColor;
10723
Mike Cleronf116bf82009-09-27 19:14:12 -070010724 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010725 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
10726 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070010727 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
10728 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010729
10730 paint = new Paint();
10731 matrix = new Matrix();
10732 // use use a height of 1, and then wack the matrix each time we
10733 // actually use it.
10734 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010736 paint.setShader(shader);
10737 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070010738 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010739 }
Romain Guy8506ab42009-06-11 17:35:47 -070010740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010741 public void setFadeColor(int color) {
10742 if (color != 0 && color != mLastColor) {
10743 mLastColor = color;
10744 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070010745
Romain Guye55e1a72009-08-27 10:42:26 -070010746 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
10747 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010749 paint.setShader(shader);
10750 // Restore the default transfer mode (src_over)
10751 paint.setXfermode(null);
10752 }
10753 }
Mike Cleronf116bf82009-09-27 19:14:12 -070010754
10755 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070010756 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070010757 if (now >= fadeStartTime) {
10758
10759 // the animation fades the scrollbars out by changing
10760 // the opacity (alpha) from fully opaque to fully
10761 // transparent
10762 int nextFrame = (int) now;
10763 int framesCount = 0;
10764
10765 Interpolator interpolator = scrollBarInterpolator;
10766
10767 // Start opaque
10768 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
10769
10770 // End transparent
10771 nextFrame += scrollBarFadeDuration;
10772 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
10773
10774 state = FADING;
10775
10776 // Kick off the fade animation
10777 host.invalidate();
10778 }
10779 }
10780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010781 }
10782}