blob: 00324a854dfdfe63a1ffb62981a5c1f73a2c7be9 [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;
Christopher Tatea53146c2010-09-07 11:57:52 -0700618 static final boolean DEBUG_DRAG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619
620 /**
621 * The logging tag used by this class with android.util.Log.
622 */
623 protected static final String VIEW_LOG_TAG = "View";
624
625 /**
626 * Used to mark a View that has no ID.
627 */
628 public static final int NO_ID = -1;
629
630 /**
631 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
632 * calling setFlags.
633 */
634 private static final int NOT_FOCUSABLE = 0x00000000;
635
636 /**
637 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
638 * setFlags.
639 */
640 private static final int FOCUSABLE = 0x00000001;
641
642 /**
643 * Mask for use with setFlags indicating bits used for focus.
644 */
645 private static final int FOCUSABLE_MASK = 0x00000001;
646
647 /**
648 * This view will adjust its padding to fit sytem windows (e.g. status bar)
649 */
650 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
651
652 /**
653 * This view is visible. Use with {@link #setVisibility}.
654 */
655 public static final int VISIBLE = 0x00000000;
656
657 /**
658 * This view is invisible, but it still takes up space for layout purposes.
659 * Use with {@link #setVisibility}.
660 */
661 public static final int INVISIBLE = 0x00000004;
662
663 /**
664 * This view is invisible, and it doesn't take any space for layout
665 * purposes. Use with {@link #setVisibility}.
666 */
667 public static final int GONE = 0x00000008;
668
669 /**
670 * Mask for use with setFlags indicating bits used for visibility.
671 * {@hide}
672 */
673 static final int VISIBILITY_MASK = 0x0000000C;
674
675 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
676
677 /**
678 * This view is enabled. Intrepretation varies by subclass.
679 * Use with ENABLED_MASK when calling setFlags.
680 * {@hide}
681 */
682 static final int ENABLED = 0x00000000;
683
684 /**
685 * This view is disabled. Intrepretation varies by subclass.
686 * Use with ENABLED_MASK when calling setFlags.
687 * {@hide}
688 */
689 static final int DISABLED = 0x00000020;
690
691 /**
692 * Mask for use with setFlags indicating bits used for indicating whether
693 * this view is enabled
694 * {@hide}
695 */
696 static final int ENABLED_MASK = 0x00000020;
697
698 /**
699 * This view won't draw. {@link #onDraw} won't be called and further
700 * optimizations
701 * will be performed. It is okay to have this flag set and a background.
702 * Use with DRAW_MASK when calling setFlags.
703 * {@hide}
704 */
705 static final int WILL_NOT_DRAW = 0x00000080;
706
707 /**
708 * Mask for use with setFlags indicating bits used for indicating whether
709 * this view is will draw
710 * {@hide}
711 */
712 static final int DRAW_MASK = 0x00000080;
713
714 /**
715 * <p>This view doesn't show scrollbars.</p>
716 * {@hide}
717 */
718 static final int SCROLLBARS_NONE = 0x00000000;
719
720 /**
721 * <p>This view shows horizontal scrollbars.</p>
722 * {@hide}
723 */
724 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
725
726 /**
727 * <p>This view shows vertical scrollbars.</p>
728 * {@hide}
729 */
730 static final int SCROLLBARS_VERTICAL = 0x00000200;
731
732 /**
733 * <p>Mask for use with setFlags indicating bits used for indicating which
734 * scrollbars are enabled.</p>
735 * {@hide}
736 */
737 static final int SCROLLBARS_MASK = 0x00000300;
738
Jeff Brown85a31762010-09-01 17:01:00 -0700739 /**
740 * Indicates that the view should filter touches when its window is obscured.
741 * Refer to the class comments for more information about this security feature.
742 * {@hide}
743 */
744 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
745
746 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747
748 /**
749 * <p>This view doesn't show fading edges.</p>
750 * {@hide}
751 */
752 static final int FADING_EDGE_NONE = 0x00000000;
753
754 /**
755 * <p>This view shows horizontal fading edges.</p>
756 * {@hide}
757 */
758 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
759
760 /**
761 * <p>This view shows vertical fading edges.</p>
762 * {@hide}
763 */
764 static final int FADING_EDGE_VERTICAL = 0x00002000;
765
766 /**
767 * <p>Mask for use with setFlags indicating bits used for indicating which
768 * fading edges are enabled.</p>
769 * {@hide}
770 */
771 static final int FADING_EDGE_MASK = 0x00003000;
772
773 /**
774 * <p>Indicates this view can be clicked. When clickable, a View reacts
775 * to clicks by notifying the OnClickListener.<p>
776 * {@hide}
777 */
778 static final int CLICKABLE = 0x00004000;
779
780 /**
781 * <p>Indicates this view is caching its drawing into a bitmap.</p>
782 * {@hide}
783 */
784 static final int DRAWING_CACHE_ENABLED = 0x00008000;
785
786 /**
787 * <p>Indicates that no icicle should be saved for this view.<p>
788 * {@hide}
789 */
790 static final int SAVE_DISABLED = 0x000010000;
791
792 /**
793 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
794 * property.</p>
795 * {@hide}
796 */
797 static final int SAVE_DISABLED_MASK = 0x000010000;
798
799 /**
800 * <p>Indicates that no drawing cache should ever be created for this view.<p>
801 * {@hide}
802 */
803 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
804
805 /**
806 * <p>Indicates this view can take / keep focus when int touch mode.</p>
807 * {@hide}
808 */
809 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
810
811 /**
812 * <p>Enables low quality mode for the drawing cache.</p>
813 */
814 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
815
816 /**
817 * <p>Enables high quality mode for the drawing cache.</p>
818 */
819 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
820
821 /**
822 * <p>Enables automatic quality mode for the drawing cache.</p>
823 */
824 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
825
826 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
827 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
828 };
829
830 /**
831 * <p>Mask for use with setFlags indicating bits used for the cache
832 * quality property.</p>
833 * {@hide}
834 */
835 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
836
837 /**
838 * <p>
839 * Indicates this view can be long clicked. When long clickable, a View
840 * reacts to long clicks by notifying the OnLongClickListener or showing a
841 * context menu.
842 * </p>
843 * {@hide}
844 */
845 static final int LONG_CLICKABLE = 0x00200000;
846
847 /**
848 * <p>Indicates that this view gets its drawable states from its direct parent
849 * and ignores its original internal states.</p>
850 *
851 * @hide
852 */
853 static final int DUPLICATE_PARENT_STATE = 0x00400000;
854
855 /**
856 * The scrollbar style to display the scrollbars inside the content area,
857 * without increasing the padding. The scrollbars will be overlaid with
858 * translucency on the view's content.
859 */
860 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
861
862 /**
863 * The scrollbar style to display the scrollbars inside the padded area,
864 * increasing the padding of the view. The scrollbars will not overlap the
865 * content area of the view.
866 */
867 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
868
869 /**
870 * The scrollbar style to display the scrollbars at the edge of the view,
871 * without increasing the padding. The scrollbars will be overlaid with
872 * translucency.
873 */
874 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
875
876 /**
877 * The scrollbar style to display the scrollbars at the edge of the view,
878 * increasing the padding of the view. The scrollbars will only overlap the
879 * background, if any.
880 */
881 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
882
883 /**
884 * Mask to check if the scrollbar style is overlay or inset.
885 * {@hide}
886 */
887 static final int SCROLLBARS_INSET_MASK = 0x01000000;
888
889 /**
890 * Mask to check if the scrollbar style is inside or outside.
891 * {@hide}
892 */
893 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
894
895 /**
896 * Mask for scrollbar style.
897 * {@hide}
898 */
899 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
900
901 /**
902 * View flag indicating that the screen should remain on while the
903 * window containing this view is visible to the user. This effectively
904 * takes care of automatically setting the WindowManager's
905 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
906 */
907 public static final int KEEP_SCREEN_ON = 0x04000000;
908
909 /**
910 * View flag indicating whether this view should have sound effects enabled
911 * for events such as clicking and touching.
912 */
913 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
914
915 /**
916 * View flag indicating whether this view should have haptic feedback
917 * enabled for events such as long presses.
918 */
919 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
920
921 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700922 * <p>Indicates that the view hierarchy should stop saving state when
923 * it reaches this view. If state saving is initiated immediately at
924 * the view, it will be allowed.
925 * {@hide}
926 */
927 static final int PARENT_SAVE_DISABLED = 0x20000000;
928
929 /**
930 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
931 * {@hide}
932 */
933 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
934
935 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700936 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
937 * should add all focusable Views regardless if they are focusable in touch mode.
938 */
939 public static final int FOCUSABLES_ALL = 0x00000000;
940
941 /**
942 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
943 * should add only Views focusable in touch mode.
944 */
945 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
946
947 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 * Use with {@link #focusSearch}. Move focus to the previous selectable
949 * item.
950 */
951 public static final int FOCUS_BACKWARD = 0x00000001;
952
953 /**
954 * Use with {@link #focusSearch}. Move focus to the next selectable
955 * item.
956 */
957 public static final int FOCUS_FORWARD = 0x00000002;
958
959 /**
960 * Use with {@link #focusSearch}. Move focus to the left.
961 */
962 public static final int FOCUS_LEFT = 0x00000011;
963
964 /**
965 * Use with {@link #focusSearch}. Move focus up.
966 */
967 public static final int FOCUS_UP = 0x00000021;
968
969 /**
970 * Use with {@link #focusSearch}. Move focus to the right.
971 */
972 public static final int FOCUS_RIGHT = 0x00000042;
973
974 /**
975 * Use with {@link #focusSearch}. Move focus down.
976 */
977 public static final int FOCUS_DOWN = 0x00000082;
978
979 /**
980 * Base View state sets
981 */
982 // Singles
983 /**
984 * Indicates the view has no states set. States are used with
985 * {@link android.graphics.drawable.Drawable} to change the drawing of the
986 * view depending on its state.
987 *
988 * @see android.graphics.drawable.Drawable
989 * @see #getDrawableState()
990 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -0700991 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 /**
993 * Indicates the view is enabled. States are used with
994 * {@link android.graphics.drawable.Drawable} to change the drawing of the
995 * view depending on its state.
996 *
997 * @see android.graphics.drawable.Drawable
998 * @see #getDrawableState()
999 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001000 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 /**
1002 * Indicates the view is focused. States are used with
1003 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1004 * view depending on its state.
1005 *
1006 * @see android.graphics.drawable.Drawable
1007 * @see #getDrawableState()
1008 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001009 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 /**
1011 * Indicates the view is selected. States are used with
1012 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1013 * view depending on its state.
1014 *
1015 * @see android.graphics.drawable.Drawable
1016 * @see #getDrawableState()
1017 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001018 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 /**
1020 * Indicates the view is pressed. States are used with
1021 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1022 * view depending on its state.
1023 *
1024 * @see android.graphics.drawable.Drawable
1025 * @see #getDrawableState()
1026 * @hide
1027 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001028 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 /**
1030 * Indicates the view's window has focus. States are used with
1031 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1032 * view depending on its state.
1033 *
1034 * @see android.graphics.drawable.Drawable
1035 * @see #getDrawableState()
1036 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001037 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 // Doubles
1039 /**
1040 * Indicates the view is enabled and has the focus.
1041 *
1042 * @see #ENABLED_STATE_SET
1043 * @see #FOCUSED_STATE_SET
1044 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001045 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 /**
1047 * Indicates the view is enabled and selected.
1048 *
1049 * @see #ENABLED_STATE_SET
1050 * @see #SELECTED_STATE_SET
1051 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001052 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 /**
1054 * Indicates the view is enabled and that its window has focus.
1055 *
1056 * @see #ENABLED_STATE_SET
1057 * @see #WINDOW_FOCUSED_STATE_SET
1058 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001059 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 /**
1061 * Indicates the view is focused and selected.
1062 *
1063 * @see #FOCUSED_STATE_SET
1064 * @see #SELECTED_STATE_SET
1065 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001066 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 /**
1068 * Indicates the view has the focus and that its window has the focus.
1069 *
1070 * @see #FOCUSED_STATE_SET
1071 * @see #WINDOW_FOCUSED_STATE_SET
1072 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001073 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 /**
1075 * Indicates the view is selected and that its window has the focus.
1076 *
1077 * @see #SELECTED_STATE_SET
1078 * @see #WINDOW_FOCUSED_STATE_SET
1079 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001080 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 // Triples
1082 /**
1083 * Indicates the view is enabled, focused and selected.
1084 *
1085 * @see #ENABLED_STATE_SET
1086 * @see #FOCUSED_STATE_SET
1087 * @see #SELECTED_STATE_SET
1088 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001089 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 /**
1091 * Indicates the view is enabled, focused and its window has the focus.
1092 *
1093 * @see #ENABLED_STATE_SET
1094 * @see #FOCUSED_STATE_SET
1095 * @see #WINDOW_FOCUSED_STATE_SET
1096 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001097 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 /**
1099 * Indicates the view is enabled, selected and its window has the focus.
1100 *
1101 * @see #ENABLED_STATE_SET
1102 * @see #SELECTED_STATE_SET
1103 * @see #WINDOW_FOCUSED_STATE_SET
1104 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001105 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 /**
1107 * Indicates the view is focused, selected and its window has the focus.
1108 *
1109 * @see #FOCUSED_STATE_SET
1110 * @see #SELECTED_STATE_SET
1111 * @see #WINDOW_FOCUSED_STATE_SET
1112 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001113 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 /**
1115 * Indicates the view is enabled, focused, selected and its window
1116 * has the focus.
1117 *
1118 * @see #ENABLED_STATE_SET
1119 * @see #FOCUSED_STATE_SET
1120 * @see #SELECTED_STATE_SET
1121 * @see #WINDOW_FOCUSED_STATE_SET
1122 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001123 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 /**
1125 * Indicates the view is pressed and its window has the focus.
1126 *
1127 * @see #PRESSED_STATE_SET
1128 * @see #WINDOW_FOCUSED_STATE_SET
1129 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001130 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 /**
1132 * Indicates the view is pressed and selected.
1133 *
1134 * @see #PRESSED_STATE_SET
1135 * @see #SELECTED_STATE_SET
1136 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001137 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 /**
1139 * Indicates the view is pressed, selected and its window has the focus.
1140 *
1141 * @see #PRESSED_STATE_SET
1142 * @see #SELECTED_STATE_SET
1143 * @see #WINDOW_FOCUSED_STATE_SET
1144 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001145 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 /**
1147 * Indicates the view is pressed and focused.
1148 *
1149 * @see #PRESSED_STATE_SET
1150 * @see #FOCUSED_STATE_SET
1151 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001152 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 /**
1154 * Indicates the view is pressed, focused and its window has the focus.
1155 *
1156 * @see #PRESSED_STATE_SET
1157 * @see #FOCUSED_STATE_SET
1158 * @see #WINDOW_FOCUSED_STATE_SET
1159 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001160 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 /**
1162 * Indicates the view is pressed, focused and selected.
1163 *
1164 * @see #PRESSED_STATE_SET
1165 * @see #SELECTED_STATE_SET
1166 * @see #FOCUSED_STATE_SET
1167 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001168 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 /**
1170 * Indicates the view is pressed, focused, selected and its window has the focus.
1171 *
1172 * @see #PRESSED_STATE_SET
1173 * @see #FOCUSED_STATE_SET
1174 * @see #SELECTED_STATE_SET
1175 * @see #WINDOW_FOCUSED_STATE_SET
1176 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001177 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 /**
1179 * Indicates the view is pressed and enabled.
1180 *
1181 * @see #PRESSED_STATE_SET
1182 * @see #ENABLED_STATE_SET
1183 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001184 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 /**
1186 * Indicates the view is pressed, enabled and its window has the focus.
1187 *
1188 * @see #PRESSED_STATE_SET
1189 * @see #ENABLED_STATE_SET
1190 * @see #WINDOW_FOCUSED_STATE_SET
1191 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001192 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 /**
1194 * Indicates the view is pressed, enabled and selected.
1195 *
1196 * @see #PRESSED_STATE_SET
1197 * @see #ENABLED_STATE_SET
1198 * @see #SELECTED_STATE_SET
1199 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001200 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 /**
1202 * Indicates the view is pressed, enabled, selected and its window has the
1203 * focus.
1204 *
1205 * @see #PRESSED_STATE_SET
1206 * @see #ENABLED_STATE_SET
1207 * @see #SELECTED_STATE_SET
1208 * @see #WINDOW_FOCUSED_STATE_SET
1209 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001210 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 /**
1212 * Indicates the view is pressed, enabled and focused.
1213 *
1214 * @see #PRESSED_STATE_SET
1215 * @see #ENABLED_STATE_SET
1216 * @see #FOCUSED_STATE_SET
1217 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001218 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 /**
1220 * Indicates the view is pressed, enabled, focused and its window has the
1221 * focus.
1222 *
1223 * @see #PRESSED_STATE_SET
1224 * @see #ENABLED_STATE_SET
1225 * @see #FOCUSED_STATE_SET
1226 * @see #WINDOW_FOCUSED_STATE_SET
1227 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001228 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 /**
1230 * Indicates the view is pressed, enabled, focused and selected.
1231 *
1232 * @see #PRESSED_STATE_SET
1233 * @see #ENABLED_STATE_SET
1234 * @see #SELECTED_STATE_SET
1235 * @see #FOCUSED_STATE_SET
1236 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001237 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 /**
1239 * Indicates the view is pressed, enabled, focused, selected and its window
1240 * has the focus.
1241 *
1242 * @see #PRESSED_STATE_SET
1243 * @see #ENABLED_STATE_SET
1244 * @see #SELECTED_STATE_SET
1245 * @see #FOCUSED_STATE_SET
1246 * @see #WINDOW_FOCUSED_STATE_SET
1247 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001248 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249
1250 /**
1251 * The order here is very important to {@link #getDrawableState()}
1252 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001253 private static final int[][] VIEW_STATE_SETS;
1254
Romain Guyb051e892010-09-28 19:09:36 -07001255 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1256 static final int VIEW_STATE_SELECTED = 1 << 1;
1257 static final int VIEW_STATE_FOCUSED = 1 << 2;
1258 static final int VIEW_STATE_ENABLED = 1 << 3;
1259 static final int VIEW_STATE_PRESSED = 1 << 4;
1260 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001261
1262 static final int[] VIEW_STATE_IDS = new int[] {
1263 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1264 R.attr.state_selected, VIEW_STATE_SELECTED,
1265 R.attr.state_focused, VIEW_STATE_FOCUSED,
1266 R.attr.state_enabled, VIEW_STATE_ENABLED,
1267 R.attr.state_pressed, VIEW_STATE_PRESSED,
1268 R.attr.state_activated, VIEW_STATE_ACTIVATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 };
1270
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001271 static {
1272 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001273 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001274 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001275 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001276 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001277 orderedIds[i * 2] = viewState;
1278 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001279 }
1280 }
1281 }
Romain Guyb051e892010-09-28 19:09:36 -07001282 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1283 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1284 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001285 int numBits = Integer.bitCount(i);
1286 int[] set = new int[numBits];
1287 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001288 for (int j = 0; j < orderedIds.length; j += 2) {
1289 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001290 set[pos++] = orderedIds[j];
1291 }
1292 }
1293 VIEW_STATE_SETS[i] = set;
1294 }
1295
1296 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1297 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1298 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1299 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1300 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1301 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1302 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1303 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1304 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1305 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1306 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1307 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1308 | VIEW_STATE_FOCUSED];
1309 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1310 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1311 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1312 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1313 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1314 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1315 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1316 | VIEW_STATE_ENABLED];
1317 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1318 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1319 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1320 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1321 | VIEW_STATE_ENABLED];
1322 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1323 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1324 | VIEW_STATE_ENABLED];
1325 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1326 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1327 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1328
1329 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1330 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1331 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1332 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1333 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1334 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1335 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1336 | VIEW_STATE_PRESSED];
1337 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1338 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1339 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1340 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1341 | VIEW_STATE_PRESSED];
1342 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1343 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1344 | VIEW_STATE_PRESSED];
1345 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1346 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1347 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1348 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1349 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1350 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1351 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1352 | VIEW_STATE_PRESSED];
1353 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1354 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1355 | VIEW_STATE_PRESSED];
1356 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1357 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1358 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1359 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1360 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1361 | VIEW_STATE_PRESSED];
1362 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1363 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1364 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1365 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1366 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1367 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1368 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1369 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1370 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1371 | VIEW_STATE_PRESSED];
1372 }
1373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 /**
1375 * Used by views that contain lists of items. This state indicates that
1376 * the view is showing the last item.
1377 * @hide
1378 */
1379 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1380 /**
1381 * Used by views that contain lists of items. This state indicates that
1382 * the view is showing the first item.
1383 * @hide
1384 */
1385 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1386 /**
1387 * Used by views that contain lists of items. This state indicates that
1388 * the view is showing the middle item.
1389 * @hide
1390 */
1391 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1392 /**
1393 * Used by views that contain lists of items. This state indicates that
1394 * the view is showing only one item.
1395 * @hide
1396 */
1397 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1398 /**
1399 * Used by views that contain lists of items. This state indicates that
1400 * the view is pressed and showing the last item.
1401 * @hide
1402 */
1403 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1404 /**
1405 * Used by views that contain lists of items. This state indicates that
1406 * the view is pressed and showing the first item.
1407 * @hide
1408 */
1409 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1410 /**
1411 * Used by views that contain lists of items. This state indicates that
1412 * the view is pressed and showing the middle item.
1413 * @hide
1414 */
1415 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1416 /**
1417 * Used by views that contain lists of items. This state indicates that
1418 * the view is pressed and showing only one item.
1419 * @hide
1420 */
1421 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1422
1423 /**
1424 * Temporary Rect currently for use in setBackground(). This will probably
1425 * be extended in the future to hold our own class with more than just
1426 * a Rect. :)
1427 */
1428 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001429
1430 /**
1431 * Map used to store views' tags.
1432 */
1433 private static WeakHashMap<View, SparseArray<Object>> sTags;
1434
1435 /**
1436 * Lock used to access sTags.
1437 */
1438 private static final Object sTagsLock = new Object();
1439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 /**
1441 * The animation currently associated with this view.
1442 * @hide
1443 */
1444 protected Animation mCurrentAnimation = null;
1445
1446 /**
1447 * Width as measured during measure pass.
1448 * {@hide}
1449 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001450 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 protected int mMeasuredWidth;
1452
1453 /**
1454 * Height as measured during measure pass.
1455 * {@hide}
1456 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001457 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 protected int mMeasuredHeight;
1459
1460 /**
1461 * The view's identifier.
1462 * {@hide}
1463 *
1464 * @see #setId(int)
1465 * @see #getId()
1466 */
1467 @ViewDebug.ExportedProperty(resolveId = true)
1468 int mID = NO_ID;
1469
1470 /**
1471 * The view's tag.
1472 * {@hide}
1473 *
1474 * @see #setTag(Object)
1475 * @see #getTag()
1476 */
1477 protected Object mTag;
1478
1479 // for mPrivateFlags:
1480 /** {@hide} */
1481 static final int WANTS_FOCUS = 0x00000001;
1482 /** {@hide} */
1483 static final int FOCUSED = 0x00000002;
1484 /** {@hide} */
1485 static final int SELECTED = 0x00000004;
1486 /** {@hide} */
1487 static final int IS_ROOT_NAMESPACE = 0x00000008;
1488 /** {@hide} */
1489 static final int HAS_BOUNDS = 0x00000010;
1490 /** {@hide} */
1491 static final int DRAWN = 0x00000020;
1492 /**
1493 * When this flag is set, this view is running an animation on behalf of its
1494 * children and should therefore not cancel invalidate requests, even if they
1495 * lie outside of this view's bounds.
1496 *
1497 * {@hide}
1498 */
1499 static final int DRAW_ANIMATION = 0x00000040;
1500 /** {@hide} */
1501 static final int SKIP_DRAW = 0x00000080;
1502 /** {@hide} */
1503 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1504 /** {@hide} */
1505 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1506 /** {@hide} */
1507 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1508 /** {@hide} */
1509 static final int MEASURED_DIMENSION_SET = 0x00000800;
1510 /** {@hide} */
1511 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001512 /** {@hide} */
1513 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514
1515 private static final int PRESSED = 0x00004000;
1516
1517 /** {@hide} */
1518 static final int DRAWING_CACHE_VALID = 0x00008000;
1519 /**
1520 * Flag used to indicate that this view should be drawn once more (and only once
1521 * more) after its animation has completed.
1522 * {@hide}
1523 */
1524 static final int ANIMATION_STARTED = 0x00010000;
1525
1526 private static final int SAVE_STATE_CALLED = 0x00020000;
1527
1528 /**
1529 * Indicates that the View returned true when onSetAlpha() was called and that
1530 * the alpha must be restored.
1531 * {@hide}
1532 */
1533 static final int ALPHA_SET = 0x00040000;
1534
1535 /**
1536 * Set by {@link #setScrollContainer(boolean)}.
1537 */
1538 static final int SCROLL_CONTAINER = 0x00080000;
1539
1540 /**
1541 * Set by {@link #setScrollContainer(boolean)}.
1542 */
1543 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1544
1545 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001546 * View flag indicating whether this view was invalidated (fully or partially.)
1547 *
1548 * @hide
1549 */
1550 static final int DIRTY = 0x00200000;
1551
1552 /**
1553 * View flag indicating whether this view was invalidated by an opaque
1554 * invalidate request.
1555 *
1556 * @hide
1557 */
1558 static final int DIRTY_OPAQUE = 0x00400000;
1559
1560 /**
1561 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1562 *
1563 * @hide
1564 */
1565 static final int DIRTY_MASK = 0x00600000;
1566
1567 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001568 * Indicates whether the background is opaque.
1569 *
1570 * @hide
1571 */
1572 static final int OPAQUE_BACKGROUND = 0x00800000;
1573
1574 /**
1575 * Indicates whether the scrollbars are opaque.
1576 *
1577 * @hide
1578 */
1579 static final int OPAQUE_SCROLLBARS = 0x01000000;
1580
1581 /**
1582 * Indicates whether the view is opaque.
1583 *
1584 * @hide
1585 */
1586 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001587
1588 /**
1589 * Indicates a prepressed state;
1590 * the short time between ACTION_DOWN and recognizing
1591 * a 'real' press. Prepressed is used to recognize quick taps
1592 * even when they are shorter than ViewConfiguration.getTapTimeout().
1593 *
1594 * @hide
1595 */
1596 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001597
1598 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001599 * Indicates whether the view is temporarily detached.
1600 *
1601 * @hide
1602 */
1603 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001604
1605 /**
1606 * Indicates that we should awaken scroll bars once attached
1607 *
1608 * @hide
1609 */
1610 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001611
1612 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001613 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1614 * for transform operations
1615 *
1616 * @hide
1617 */
Adam Powellf37df072010-09-17 16:22:49 -07001618 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001619
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001620 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001621 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001622
Chet Haasefd2b0022010-08-06 13:08:56 -07001623 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 * The parent this view is attached to.
1625 * {@hide}
1626 *
1627 * @see #getParent()
1628 */
1629 protected ViewParent mParent;
1630
1631 /**
1632 * {@hide}
1633 */
1634 AttachInfo mAttachInfo;
1635
1636 /**
1637 * {@hide}
1638 */
Romain Guy809a7f62009-05-14 15:44:42 -07001639 @ViewDebug.ExportedProperty(flagMapping = {
1640 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1641 name = "FORCE_LAYOUT"),
1642 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1643 name = "LAYOUT_REQUIRED"),
1644 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001645 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001646 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1647 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1648 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1649 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1650 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 int mPrivateFlags;
1652
1653 /**
1654 * Count of how many windows this view has been attached to.
1655 */
1656 int mWindowAttachCount;
1657
1658 /**
1659 * The layout parameters associated with this view and used by the parent
1660 * {@link android.view.ViewGroup} to determine how this view should be
1661 * laid out.
1662 * {@hide}
1663 */
1664 protected ViewGroup.LayoutParams mLayoutParams;
1665
1666 /**
1667 * The view flags hold various views states.
1668 * {@hide}
1669 */
1670 @ViewDebug.ExportedProperty
1671 int mViewFlags;
1672
1673 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001674 * The transform matrix for the View. This transform is calculated internally
1675 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1676 * is used by default. Do *not* use this variable directly; instead call
1677 * getMatrix(), which will automatically recalculate the matrix if necessary
1678 * to get the correct matrix based on the latest rotation and scale properties.
1679 */
1680 private final Matrix mMatrix = new Matrix();
1681
1682 /**
1683 * The transform matrix for the View. This transform is calculated internally
1684 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1685 * is used by default. Do *not* use this variable directly; instead call
1686 * getMatrix(), which will automatically recalculate the matrix if necessary
1687 * to get the correct matrix based on the latest rotation and scale properties.
1688 */
1689 private Matrix mInverseMatrix;
1690
1691 /**
1692 * An internal variable that tracks whether we need to recalculate the
1693 * transform matrix, based on whether the rotation or scaleX/Y properties
1694 * have changed since the matrix was last calculated.
1695 */
1696 private boolean mMatrixDirty = false;
1697
1698 /**
1699 * An internal variable that tracks whether we need to recalculate the
1700 * transform matrix, based on whether the rotation or scaleX/Y properties
1701 * have changed since the matrix was last calculated.
1702 */
1703 private boolean mInverseMatrixDirty = true;
1704
1705 /**
1706 * A variable that tracks whether we need to recalculate the
1707 * transform matrix, based on whether the rotation or scaleX/Y properties
1708 * have changed since the matrix was last calculated. This variable
1709 * is only valid after a call to getMatrix().
1710 */
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
3959 /**
3960 * Call this to try to give focus to a specific view or to one of its descendants. This is a
3961 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
3962 * touch mode to request focus when they are touched.
3963 *
3964 * @return Whether this view or one of its descendants actually took focus.
3965 *
3966 * @see #isInTouchMode()
3967 *
3968 */
3969 public final boolean requestFocusFromTouch() {
3970 // Leave touch mode if we need to
3971 if (isInTouchMode()) {
3972 View root = getRootView();
3973 if (root != null) {
3974 ViewRoot viewRoot = (ViewRoot)root.getParent();
3975 if (viewRoot != null) {
3976 viewRoot.ensureTouchMode(false);
3977 }
3978 }
3979 }
3980 return requestFocus(View.FOCUS_DOWN);
3981 }
3982
3983 /**
3984 * @return Whether any ancestor of this view blocks descendant focus.
3985 */
3986 private boolean hasAncestorThatBlocksDescendantFocus() {
3987 ViewParent ancestor = mParent;
3988 while (ancestor instanceof ViewGroup) {
3989 final ViewGroup vgAncestor = (ViewGroup) ancestor;
3990 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
3991 return true;
3992 } else {
3993 ancestor = vgAncestor.getParent();
3994 }
3995 }
3996 return false;
3997 }
3998
3999 /**
Romain Guya440b002010-02-24 15:57:54 -08004000 * @hide
4001 */
4002 public void dispatchStartTemporaryDetach() {
4003 onStartTemporaryDetach();
4004 }
4005
4006 /**
4007 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4009 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004010 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 */
4012 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004013 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004014 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004015 }
4016
4017 /**
4018 * @hide
4019 */
4020 public void dispatchFinishTemporaryDetach() {
4021 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 }
Romain Guy8506ab42009-06-11 17:35:47 -07004023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 /**
4025 * Called after {@link #onStartTemporaryDetach} when the container is done
4026 * changing the view.
4027 */
4028 public void onFinishTemporaryDetach() {
4029 }
Romain Guy8506ab42009-06-11 17:35:47 -07004030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 /**
4032 * capture information of this view for later analysis: developement only
4033 * check dynamic switch to make sure we only dump view
4034 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4035 */
4036 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004037 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 return;
4039 }
4040 ViewDebug.dumpCapturedView(subTag, v);
4041 }
4042
4043 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004044 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4045 * for this view's window. Returns null if the view is not currently attached
4046 * to the window. Normally you will not need to use this directly, but
4047 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4048 */
4049 public KeyEvent.DispatcherState getKeyDispatcherState() {
4050 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4051 }
4052
4053 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 * Dispatch a key event before it is processed by any input method
4055 * associated with the view hierarchy. This can be used to intercept
4056 * key events in special situations before the IME consumes them; a
4057 * typical example would be handling the BACK key to update the application's
4058 * UI instead of allowing the IME to see it and close itself.
4059 *
4060 * @param event The key event to be dispatched.
4061 * @return True if the event was handled, false otherwise.
4062 */
4063 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4064 return onKeyPreIme(event.getKeyCode(), event);
4065 }
4066
4067 /**
4068 * Dispatch a key event to the next view on the focus path. This path runs
4069 * from the top of the view tree down to the currently focused view. If this
4070 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4071 * the next node down the focus path. This method also fires any key
4072 * listeners.
4073 *
4074 * @param event The key event to be dispatched.
4075 * @return True if the event was handled, false otherwise.
4076 */
4077 public boolean dispatchKeyEvent(KeyEvent event) {
4078 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079
Romain Guyf607bdc2010-09-10 19:20:06 -07004080 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004081 if (android.util.Config.LOGV) {
4082 captureViewInfo("captureViewKeyEvent", this);
4083 }
4084
Romain Guyf607bdc2010-09-10 19:20:06 -07004085 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4087 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4088 return true;
4089 }
4090
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004091 return event.dispatch(this, mAttachInfo != null
4092 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 }
4094
4095 /**
4096 * Dispatches a key shortcut event.
4097 *
4098 * @param event The key event to be dispatched.
4099 * @return True if the event was handled by the view, false otherwise.
4100 */
4101 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4102 return onKeyShortcut(event.getKeyCode(), event);
4103 }
4104
4105 /**
4106 * Pass the touch screen motion event down to the target view, or this
4107 * view if it is the target.
4108 *
4109 * @param event The motion event to be dispatched.
4110 * @return True if the event was handled by the view, false otherwise.
4111 */
4112 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004113 if (!onFilterTouchEventForSecurity(event)) {
4114 return false;
4115 }
4116
Romain Guyf607bdc2010-09-10 19:20:06 -07004117 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4119 mOnTouchListener.onTouch(this, event)) {
4120 return true;
4121 }
4122 return onTouchEvent(event);
4123 }
4124
4125 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004126 * Filter the touch event to apply security policies.
4127 *
4128 * @param event The motion event to be filtered.
4129 * @return True if the event should be dispatched, false if the event should be dropped.
4130 *
4131 * @see #getFilterTouchesWhenObscured
4132 */
4133 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004134 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004135 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4136 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4137 // Window is obscured, drop this touch.
4138 return false;
4139 }
4140 return true;
4141 }
4142
4143 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 * Pass a trackball motion event down to the focused view.
4145 *
4146 * @param event The motion event to be dispatched.
4147 * @return True if the event was handled by the view, false otherwise.
4148 */
4149 public boolean dispatchTrackballEvent(MotionEvent event) {
4150 //Log.i("view", "view=" + this + ", " + event.toString());
4151 return onTrackballEvent(event);
4152 }
4153
4154 /**
4155 * Called when the window containing this view gains or loses window focus.
4156 * ViewGroups should override to route to their children.
4157 *
4158 * @param hasFocus True if the window containing this view now has focus,
4159 * false otherwise.
4160 */
4161 public void dispatchWindowFocusChanged(boolean hasFocus) {
4162 onWindowFocusChanged(hasFocus);
4163 }
4164
4165 /**
4166 * Called when the window containing this view gains or loses focus. Note
4167 * that this is separate from view focus: to receive key events, both
4168 * your view and its window must have focus. If a window is displayed
4169 * on top of yours that takes input focus, then your own window will lose
4170 * focus but the view focus will remain unchanged.
4171 *
4172 * @param hasWindowFocus True if the window containing this view now has
4173 * focus, false otherwise.
4174 */
4175 public void onWindowFocusChanged(boolean hasWindowFocus) {
4176 InputMethodManager imm = InputMethodManager.peekInstance();
4177 if (!hasWindowFocus) {
4178 if (isPressed()) {
4179 setPressed(false);
4180 }
4181 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4182 imm.focusOut(this);
4183 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004184 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004185 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004186 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4188 imm.focusIn(this);
4189 }
4190 refreshDrawableState();
4191 }
4192
4193 /**
4194 * Returns true if this view is in a window that currently has window focus.
4195 * Note that this is not the same as the view itself having focus.
4196 *
4197 * @return True if this view is in a window that currently has window focus.
4198 */
4199 public boolean hasWindowFocus() {
4200 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4201 }
4202
4203 /**
Adam Powell326d8082009-12-09 15:10:07 -08004204 * Dispatch a view visibility change down the view hierarchy.
4205 * ViewGroups should override to route to their children.
4206 * @param changedView The view whose visibility changed. Could be 'this' or
4207 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004208 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4209 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004210 */
4211 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4212 onVisibilityChanged(changedView, visibility);
4213 }
4214
4215 /**
4216 * Called when the visibility of the view or an ancestor of the view is changed.
4217 * @param changedView The view whose visibility changed. Could be 'this' or
4218 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004219 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4220 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004221 */
4222 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004223 if (visibility == VISIBLE) {
4224 if (mAttachInfo != null) {
4225 initialAwakenScrollBars();
4226 } else {
4227 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4228 }
4229 }
Adam Powell326d8082009-12-09 15:10:07 -08004230 }
4231
4232 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004233 * Dispatch a hint about whether this view is displayed. For instance, when
4234 * a View moves out of the screen, it might receives a display hint indicating
4235 * the view is not displayed. Applications should not <em>rely</em> on this hint
4236 * as there is no guarantee that they will receive one.
4237 *
4238 * @param hint A hint about whether or not this view is displayed:
4239 * {@link #VISIBLE} or {@link #INVISIBLE}.
4240 */
4241 public void dispatchDisplayHint(int hint) {
4242 onDisplayHint(hint);
4243 }
4244
4245 /**
4246 * Gives this view a hint about whether is displayed or not. For instance, when
4247 * a View moves out of the screen, it might receives a display hint indicating
4248 * the view is not displayed. Applications should not <em>rely</em> on this hint
4249 * as there is no guarantee that they will receive one.
4250 *
4251 * @param hint A hint about whether or not this view is displayed:
4252 * {@link #VISIBLE} or {@link #INVISIBLE}.
4253 */
4254 protected void onDisplayHint(int hint) {
4255 }
4256
4257 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 * Dispatch a window visibility change down the view hierarchy.
4259 * ViewGroups should override to route to their children.
4260 *
4261 * @param visibility The new visibility of the window.
4262 *
4263 * @see #onWindowVisibilityChanged
4264 */
4265 public void dispatchWindowVisibilityChanged(int visibility) {
4266 onWindowVisibilityChanged(visibility);
4267 }
4268
4269 /**
4270 * Called when the window containing has change its visibility
4271 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4272 * that this tells you whether or not your window is being made visible
4273 * to the window manager; this does <em>not</em> tell you whether or not
4274 * your window is obscured by other windows on the screen, even if it
4275 * is itself visible.
4276 *
4277 * @param visibility The new visibility of the window.
4278 */
4279 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004280 if (visibility == VISIBLE) {
4281 initialAwakenScrollBars();
4282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 }
4284
4285 /**
4286 * Returns the current visibility of the window this view is attached to
4287 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4288 *
4289 * @return Returns the current visibility of the view's window.
4290 */
4291 public int getWindowVisibility() {
4292 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4293 }
4294
4295 /**
4296 * Retrieve the overall visible display size in which the window this view is
4297 * attached to has been positioned in. This takes into account screen
4298 * decorations above the window, for both cases where the window itself
4299 * is being position inside of them or the window is being placed under
4300 * then and covered insets are used for the window to position its content
4301 * inside. In effect, this tells you the available area where content can
4302 * be placed and remain visible to users.
4303 *
4304 * <p>This function requires an IPC back to the window manager to retrieve
4305 * the requested information, so should not be used in performance critical
4306 * code like drawing.
4307 *
4308 * @param outRect Filled in with the visible display frame. If the view
4309 * is not attached to a window, this is simply the raw display size.
4310 */
4311 public void getWindowVisibleDisplayFrame(Rect outRect) {
4312 if (mAttachInfo != null) {
4313 try {
4314 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4315 } catch (RemoteException e) {
4316 return;
4317 }
4318 // XXX This is really broken, and probably all needs to be done
4319 // in the window manager, and we need to know more about whether
4320 // we want the area behind or in front of the IME.
4321 final Rect insets = mAttachInfo.mVisibleInsets;
4322 outRect.left += insets.left;
4323 outRect.top += insets.top;
4324 outRect.right -= insets.right;
4325 outRect.bottom -= insets.bottom;
4326 return;
4327 }
4328 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4329 outRect.set(0, 0, d.getWidth(), d.getHeight());
4330 }
4331
4332 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004333 * Dispatch a notification about a resource configuration change down
4334 * the view hierarchy.
4335 * ViewGroups should override to route to their children.
4336 *
4337 * @param newConfig The new resource configuration.
4338 *
4339 * @see #onConfigurationChanged
4340 */
4341 public void dispatchConfigurationChanged(Configuration newConfig) {
4342 onConfigurationChanged(newConfig);
4343 }
4344
4345 /**
4346 * Called when the current configuration of the resources being used
4347 * by the application have changed. You can use this to decide when
4348 * to reload resources that can changed based on orientation and other
4349 * configuration characterstics. You only need to use this if you are
4350 * not relying on the normal {@link android.app.Activity} mechanism of
4351 * recreating the activity instance upon a configuration change.
4352 *
4353 * @param newConfig The new resource configuration.
4354 */
4355 protected void onConfigurationChanged(Configuration newConfig) {
4356 }
4357
4358 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 * Private function to aggregate all per-view attributes in to the view
4360 * root.
4361 */
4362 void dispatchCollectViewAttributes(int visibility) {
4363 performCollectViewAttributes(visibility);
4364 }
4365
4366 void performCollectViewAttributes(int visibility) {
4367 //noinspection PointlessBitwiseExpression
4368 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4369 == (VISIBLE | KEEP_SCREEN_ON)) {
4370 mAttachInfo.mKeepScreenOn = true;
4371 }
4372 }
4373
4374 void needGlobalAttributesUpdate(boolean force) {
4375 AttachInfo ai = mAttachInfo;
4376 if (ai != null) {
4377 if (ai.mKeepScreenOn || force) {
4378 ai.mRecomputeGlobalAttributes = true;
4379 }
4380 }
4381 }
4382
4383 /**
4384 * Returns whether the device is currently in touch mode. Touch mode is entered
4385 * once the user begins interacting with the device by touch, and affects various
4386 * things like whether focus is always visible to the user.
4387 *
4388 * @return Whether the device is in touch mode.
4389 */
4390 @ViewDebug.ExportedProperty
4391 public boolean isInTouchMode() {
4392 if (mAttachInfo != null) {
4393 return mAttachInfo.mInTouchMode;
4394 } else {
4395 return ViewRoot.isInTouchMode();
4396 }
4397 }
4398
4399 /**
4400 * Returns the context the view is running in, through which it can
4401 * access the current theme, resources, etc.
4402 *
4403 * @return The view's Context.
4404 */
4405 @ViewDebug.CapturedViewProperty
4406 public final Context getContext() {
4407 return mContext;
4408 }
4409
4410 /**
4411 * Handle a key event before it is processed by any input method
4412 * associated with the view hierarchy. This can be used to intercept
4413 * key events in special situations before the IME consumes them; a
4414 * typical example would be handling the BACK key to update the application's
4415 * UI instead of allowing the IME to see it and close itself.
4416 *
4417 * @param keyCode The value in event.getKeyCode().
4418 * @param event Description of the key event.
4419 * @return If you handled the event, return true. If you want to allow the
4420 * event to be handled by the next receiver, return false.
4421 */
4422 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4423 return false;
4424 }
4425
4426 /**
4427 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4428 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4429 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4430 * is released, if the view is enabled and clickable.
4431 *
4432 * @param keyCode A key code that represents the button pressed, from
4433 * {@link android.view.KeyEvent}.
4434 * @param event The KeyEvent object that defines the button action.
4435 */
4436 public boolean onKeyDown(int keyCode, KeyEvent event) {
4437 boolean result = false;
4438
4439 switch (keyCode) {
4440 case KeyEvent.KEYCODE_DPAD_CENTER:
4441 case KeyEvent.KEYCODE_ENTER: {
4442 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4443 return true;
4444 }
4445 // Long clickable items don't necessarily have to be clickable
4446 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4447 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4448 (event.getRepeatCount() == 0)) {
4449 setPressed(true);
4450 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004451 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 }
4453 return true;
4454 }
4455 break;
4456 }
4457 }
4458 return result;
4459 }
4460
4461 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004462 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4463 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4464 * the event).
4465 */
4466 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4467 return false;
4468 }
4469
4470 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004471 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4472 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4473 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4474 * {@link KeyEvent#KEYCODE_ENTER} is released.
4475 *
4476 * @param keyCode A key code that represents the button pressed, from
4477 * {@link android.view.KeyEvent}.
4478 * @param event The KeyEvent object that defines the button action.
4479 */
4480 public boolean onKeyUp(int keyCode, KeyEvent event) {
4481 boolean result = false;
4482
4483 switch (keyCode) {
4484 case KeyEvent.KEYCODE_DPAD_CENTER:
4485 case KeyEvent.KEYCODE_ENTER: {
4486 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4487 return true;
4488 }
4489 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4490 setPressed(false);
4491
4492 if (!mHasPerformedLongPress) {
4493 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004494 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495
4496 result = performClick();
4497 }
4498 }
4499 break;
4500 }
4501 }
4502 return result;
4503 }
4504
4505 /**
4506 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4507 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4508 * the event).
4509 *
4510 * @param keyCode A key code that represents the button pressed, from
4511 * {@link android.view.KeyEvent}.
4512 * @param repeatCount The number of times the action was made.
4513 * @param event The KeyEvent object that defines the button action.
4514 */
4515 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4516 return false;
4517 }
4518
4519 /**
4520 * Called when an unhandled key shortcut event occurs.
4521 *
4522 * @param keyCode The value in event.getKeyCode().
4523 * @param event Description of the key event.
4524 * @return If you handled the event, return true. If you want to allow the
4525 * event to be handled by the next receiver, return false.
4526 */
4527 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4528 return false;
4529 }
4530
4531 /**
4532 * Check whether the called view is a text editor, in which case it
4533 * would make sense to automatically display a soft input window for
4534 * it. Subclasses should override this if they implement
4535 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004536 * a call on that method would return a non-null InputConnection, and
4537 * they are really a first-class editor that the user would normally
4538 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004539 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004540 * <p>The default implementation always returns false. This does
4541 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4542 * will not be called or the user can not otherwise perform edits on your
4543 * view; it is just a hint to the system that this is not the primary
4544 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004545 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004546 * @return Returns true if this view is a text editor, else false.
4547 */
4548 public boolean onCheckIsTextEditor() {
4549 return false;
4550 }
Romain Guy8506ab42009-06-11 17:35:47 -07004551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 /**
4553 * Create a new InputConnection for an InputMethod to interact
4554 * with the view. The default implementation returns null, since it doesn't
4555 * support input methods. You can override this to implement such support.
4556 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004557 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004558 * <p>When implementing this, you probably also want to implement
4559 * {@link #onCheckIsTextEditor()} to indicate you will return a
4560 * non-null InputConnection.
4561 *
4562 * @param outAttrs Fill in with attribute information about the connection.
4563 */
4564 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4565 return null;
4566 }
4567
4568 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004569 * Called by the {@link android.view.inputmethod.InputMethodManager}
4570 * when a view who is not the current
4571 * input connection target is trying to make a call on the manager. The
4572 * default implementation returns false; you can override this to return
4573 * true for certain views if you are performing InputConnection proxying
4574 * to them.
4575 * @param view The View that is making the InputMethodManager call.
4576 * @return Return true to allow the call, false to reject.
4577 */
4578 public boolean checkInputConnectionProxy(View view) {
4579 return false;
4580 }
Romain Guy8506ab42009-06-11 17:35:47 -07004581
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004582 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 * Show the context menu for this view. It is not safe to hold on to the
4584 * menu after returning from this method.
4585 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004586 * You should normally not overload this method. Overload
4587 * {@link #onCreateContextMenu(ContextMenu)} or define an
4588 * {@link OnCreateContextMenuListener} to add items to the context menu.
4589 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 * @param menu The context menu to populate
4591 */
4592 public void createContextMenu(ContextMenu menu) {
4593 ContextMenuInfo menuInfo = getContextMenuInfo();
4594
4595 // Sets the current menu info so all items added to menu will have
4596 // my extra info set.
4597 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4598
4599 onCreateContextMenu(menu);
4600 if (mOnCreateContextMenuListener != null) {
4601 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4602 }
4603
4604 // Clear the extra information so subsequent items that aren't mine don't
4605 // have my extra info.
4606 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4607
4608 if (mParent != null) {
4609 mParent.createContextMenu(menu);
4610 }
4611 }
4612
4613 /**
4614 * Views should implement this if they have extra information to associate
4615 * with the context menu. The return result is supplied as a parameter to
4616 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4617 * callback.
4618 *
4619 * @return Extra information about the item for which the context menu
4620 * should be shown. This information will vary across different
4621 * subclasses of View.
4622 */
4623 protected ContextMenuInfo getContextMenuInfo() {
4624 return null;
4625 }
4626
4627 /**
4628 * Views should implement this if the view itself is going to add items to
4629 * the context menu.
4630 *
4631 * @param menu the context menu to populate
4632 */
4633 protected void onCreateContextMenu(ContextMenu menu) {
4634 }
4635
4636 /**
4637 * Implement this method to handle trackball motion events. The
4638 * <em>relative</em> movement of the trackball since the last event
4639 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4640 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4641 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4642 * they will often be fractional values, representing the more fine-grained
4643 * movement information available from a trackball).
4644 *
4645 * @param event The motion event.
4646 * @return True if the event was handled, false otherwise.
4647 */
4648 public boolean onTrackballEvent(MotionEvent event) {
4649 return false;
4650 }
4651
4652 /**
4653 * Implement this method to handle touch screen motion events.
4654 *
4655 * @param event The motion event.
4656 * @return True if the event was handled, false otherwise.
4657 */
4658 public boolean onTouchEvent(MotionEvent event) {
4659 final int viewFlags = mViewFlags;
4660
4661 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4662 // A disabled view that is clickable still consumes the touch
4663 // events, it just doesn't respond to them.
4664 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4665 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4666 }
4667
4668 if (mTouchDelegate != null) {
4669 if (mTouchDelegate.onTouchEvent(event)) {
4670 return true;
4671 }
4672 }
4673
4674 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4675 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4676 switch (event.getAction()) {
4677 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004678 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4679 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004680 // take focus if we don't have it already and we should in
4681 // touch mode.
4682 boolean focusTaken = false;
4683 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4684 focusTaken = requestFocus();
4685 }
4686
4687 if (!mHasPerformedLongPress) {
4688 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004689 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004690
4691 // Only perform take click actions if we were in the pressed state
4692 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004693 // Use a Runnable and post this rather than calling
4694 // performClick directly. This lets other visual state
4695 // of the view update before click actions start.
4696 if (mPerformClick == null) {
4697 mPerformClick = new PerformClick();
4698 }
4699 if (!post(mPerformClick)) {
4700 performClick();
4701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004702 }
4703 }
4704
4705 if (mUnsetPressedState == null) {
4706 mUnsetPressedState = new UnsetPressedState();
4707 }
4708
Adam Powelle14579b2009-12-16 18:39:52 -08004709 if (prepressed) {
4710 mPrivateFlags |= PRESSED;
4711 refreshDrawableState();
4712 postDelayed(mUnsetPressedState,
4713 ViewConfiguration.getPressedStateDuration());
4714 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 // If the post failed, unpress right now
4716 mUnsetPressedState.run();
4717 }
Adam Powelle14579b2009-12-16 18:39:52 -08004718 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004719 }
4720 break;
4721
4722 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004723 if (mPendingCheckForTap == null) {
4724 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004725 }
Adam Powelle14579b2009-12-16 18:39:52 -08004726 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004727 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004728 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 break;
4730
4731 case MotionEvent.ACTION_CANCEL:
4732 mPrivateFlags &= ~PRESSED;
4733 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004734 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 break;
4736
4737 case MotionEvent.ACTION_MOVE:
4738 final int x = (int) event.getX();
4739 final int y = (int) event.getY();
4740
4741 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004742 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004743 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004744 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004746 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004747 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748
4749 // Need to switch from pressed to not pressed
4750 mPrivateFlags &= ~PRESSED;
4751 refreshDrawableState();
4752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753 }
4754 break;
4755 }
4756 return true;
4757 }
4758
4759 return false;
4760 }
4761
4762 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004763 * Remove the longpress detection timer.
4764 */
4765 private void removeLongPressCallback() {
4766 if (mPendingCheckForLongPress != null) {
4767 removeCallbacks(mPendingCheckForLongPress);
4768 }
4769 }
Adam Powelle14579b2009-12-16 18:39:52 -08004770
4771 /**
Romain Guya440b002010-02-24 15:57:54 -08004772 * Remove the prepress detection timer.
4773 */
4774 private void removeUnsetPressCallback() {
4775 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4776 setPressed(false);
4777 removeCallbacks(mUnsetPressedState);
4778 }
4779 }
4780
4781 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004782 * Remove the tap detection timer.
4783 */
4784 private void removeTapCallback() {
4785 if (mPendingCheckForTap != null) {
4786 mPrivateFlags &= ~PREPRESSED;
4787 removeCallbacks(mPendingCheckForTap);
4788 }
4789 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004790
4791 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004792 * Cancels a pending long press. Your subclass can use this if you
4793 * want the context menu to come up if the user presses and holds
4794 * at the same place, but you don't want it to come up if they press
4795 * and then move around enough to cause scrolling.
4796 */
4797 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004798 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004799
4800 /*
4801 * The prepressed state handled by the tap callback is a display
4802 * construct, but the tap callback will post a long press callback
4803 * less its own timeout. Remove it here.
4804 */
4805 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004806 }
4807
4808 /**
4809 * Sets the TouchDelegate for this View.
4810 */
4811 public void setTouchDelegate(TouchDelegate delegate) {
4812 mTouchDelegate = delegate;
4813 }
4814
4815 /**
4816 * Gets the TouchDelegate for this View.
4817 */
4818 public TouchDelegate getTouchDelegate() {
4819 return mTouchDelegate;
4820 }
4821
4822 /**
4823 * Set flags controlling behavior of this view.
4824 *
4825 * @param flags Constant indicating the value which should be set
4826 * @param mask Constant indicating the bit range that should be changed
4827 */
4828 void setFlags(int flags, int mask) {
4829 int old = mViewFlags;
4830 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4831
4832 int changed = mViewFlags ^ old;
4833 if (changed == 0) {
4834 return;
4835 }
4836 int privateFlags = mPrivateFlags;
4837
4838 /* Check if the FOCUSABLE bit has changed */
4839 if (((changed & FOCUSABLE_MASK) != 0) &&
4840 ((privateFlags & HAS_BOUNDS) !=0)) {
4841 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4842 && ((privateFlags & FOCUSED) != 0)) {
4843 /* Give up focus if we are no longer focusable */
4844 clearFocus();
4845 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4846 && ((privateFlags & FOCUSED) == 0)) {
4847 /*
4848 * Tell the view system that we are now available to take focus
4849 * if no one else already has it.
4850 */
4851 if (mParent != null) mParent.focusableViewAvailable(this);
4852 }
4853 }
4854
4855 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4856 if ((changed & VISIBILITY_MASK) != 0) {
4857 /*
4858 * If this view is becoming visible, set the DRAWN flag so that
4859 * the next invalidate() will not be skipped.
4860 */
4861 mPrivateFlags |= DRAWN;
4862
4863 needGlobalAttributesUpdate(true);
4864
4865 // a view becoming visible is worth notifying the parent
4866 // about in case nothing has focus. even if this specific view
4867 // isn't focusable, it may contain something that is, so let
4868 // the root view try to give this focus if nothing else does.
4869 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4870 mParent.focusableViewAvailable(this);
4871 }
4872 }
4873 }
4874
4875 /* Check if the GONE bit has changed */
4876 if ((changed & GONE) != 0) {
4877 needGlobalAttributesUpdate(false);
4878 requestLayout();
4879 invalidate();
4880
Romain Guyecd80ee2009-12-03 17:13:02 -08004881 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
4882 if (hasFocus()) clearFocus();
4883 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 }
4885 if (mAttachInfo != null) {
4886 mAttachInfo.mViewVisibilityChanged = true;
4887 }
4888 }
4889
4890 /* Check if the VISIBLE bit has changed */
4891 if ((changed & INVISIBLE) != 0) {
4892 needGlobalAttributesUpdate(false);
4893 invalidate();
4894
4895 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4896 // root view becoming invisible shouldn't clear focus
4897 if (getRootView() != this) {
4898 clearFocus();
4899 }
4900 }
4901 if (mAttachInfo != null) {
4902 mAttachInfo.mViewVisibilityChanged = true;
4903 }
4904 }
4905
Adam Powell326d8082009-12-09 15:10:07 -08004906 if ((changed & VISIBILITY_MASK) != 0) {
4907 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
4908 }
4909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004910 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4911 destroyDrawingCache();
4912 }
4913
4914 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4915 destroyDrawingCache();
4916 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4917 }
4918
4919 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4920 destroyDrawingCache();
4921 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4922 }
4923
4924 if ((changed & DRAW_MASK) != 0) {
4925 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4926 if (mBGDrawable != null) {
4927 mPrivateFlags &= ~SKIP_DRAW;
4928 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4929 } else {
4930 mPrivateFlags |= SKIP_DRAW;
4931 }
4932 } else {
4933 mPrivateFlags &= ~SKIP_DRAW;
4934 }
4935 requestLayout();
4936 invalidate();
4937 }
4938
4939 if ((changed & KEEP_SCREEN_ON) != 0) {
4940 if (mParent != null) {
4941 mParent.recomputeViewAttributes(this);
4942 }
4943 }
4944 }
4945
4946 /**
4947 * Change the view's z order in the tree, so it's on top of other sibling
4948 * views
4949 */
4950 public void bringToFront() {
4951 if (mParent != null) {
4952 mParent.bringChildToFront(this);
4953 }
4954 }
4955
4956 /**
4957 * This is called in response to an internal scroll in this view (i.e., the
4958 * view scrolled its own contents). This is typically as a result of
4959 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4960 * called.
4961 *
4962 * @param l Current horizontal scroll origin.
4963 * @param t Current vertical scroll origin.
4964 * @param oldl Previous horizontal scroll origin.
4965 * @param oldt Previous vertical scroll origin.
4966 */
4967 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4968 mBackgroundSizeChanged = true;
4969
4970 final AttachInfo ai = mAttachInfo;
4971 if (ai != null) {
4972 ai.mViewScrollChanged = true;
4973 }
4974 }
4975
4976 /**
Chet Haase21cd1382010-09-01 17:42:29 -07004977 * Interface definition for a callback to be invoked when the layout bounds of a view
4978 * changes due to layout processing.
4979 */
4980 public interface OnLayoutChangeListener {
4981 /**
4982 * Called when the focus state of a view has changed.
4983 *
4984 * @param v The view whose state has changed.
4985 * @param left The new value of the view's left property.
4986 * @param top The new value of the view's top property.
4987 * @param right The new value of the view's right property.
4988 * @param bottom The new value of the view's bottom property.
4989 * @param oldLeft The previous value of the view's left property.
4990 * @param oldTop The previous value of the view's top property.
4991 * @param oldRight The previous value of the view's right property.
4992 * @param oldBottom The previous value of the view's bottom property.
4993 */
4994 void onLayoutChange(View v, int left, int top, int right, int bottom,
4995 int oldLeft, int oldTop, int oldRight, int oldBottom);
4996 }
4997
4998 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004999 * This is called during layout when the size of this view has changed. If
5000 * you were just added to the view hierarchy, you're called with the old
5001 * values of 0.
5002 *
5003 * @param w Current width of this view.
5004 * @param h Current height of this view.
5005 * @param oldw Old width of this view.
5006 * @param oldh Old height of this view.
5007 */
5008 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5009 }
5010
5011 /**
5012 * Called by draw to draw the child views. This may be overridden
5013 * by derived classes to gain control just before its children are drawn
5014 * (but after its own view has been drawn).
5015 * @param canvas the canvas on which to draw the view
5016 */
5017 protected void dispatchDraw(Canvas canvas) {
5018 }
5019
5020 /**
5021 * Gets the parent of this view. Note that the parent is a
5022 * ViewParent and not necessarily a View.
5023 *
5024 * @return Parent of this view.
5025 */
5026 public final ViewParent getParent() {
5027 return mParent;
5028 }
5029
5030 /**
5031 * Return the scrolled left position of this view. This is the left edge of
5032 * the displayed part of your view. You do not need to draw any pixels
5033 * farther left, since those are outside of the frame of your view on
5034 * screen.
5035 *
5036 * @return The left edge of the displayed part of your view, in pixels.
5037 */
5038 public final int getScrollX() {
5039 return mScrollX;
5040 }
5041
5042 /**
5043 * Return the scrolled top position of this view. This is the top edge of
5044 * the displayed part of your view. You do not need to draw any pixels above
5045 * it, since those are outside of the frame of your view on screen.
5046 *
5047 * @return The top edge of the displayed part of your view, in pixels.
5048 */
5049 public final int getScrollY() {
5050 return mScrollY;
5051 }
5052
5053 /**
5054 * Return the width of the your view.
5055 *
5056 * @return The width of your view, in pixels.
5057 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005058 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 public final int getWidth() {
5060 return mRight - mLeft;
5061 }
5062
5063 /**
5064 * Return the height of your view.
5065 *
5066 * @return The height of your view, in pixels.
5067 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005068 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 public final int getHeight() {
5070 return mBottom - mTop;
5071 }
5072
5073 /**
5074 * Return the visible drawing bounds of your view. Fills in the output
5075 * rectangle with the values from getScrollX(), getScrollY(),
5076 * getWidth(), and getHeight().
5077 *
5078 * @param outRect The (scrolled) drawing bounds of the view.
5079 */
5080 public void getDrawingRect(Rect outRect) {
5081 outRect.left = mScrollX;
5082 outRect.top = mScrollY;
5083 outRect.right = mScrollX + (mRight - mLeft);
5084 outRect.bottom = mScrollY + (mBottom - mTop);
5085 }
5086
5087 /**
5088 * The width of this view as measured in the most recent call to measure().
5089 * This should be used during measurement and layout calculations only. Use
5090 * {@link #getWidth()} to see how wide a view is after layout.
5091 *
5092 * @return The measured width of this view.
5093 */
5094 public final int getMeasuredWidth() {
5095 return mMeasuredWidth;
5096 }
5097
5098 /**
5099 * The height of this view as measured in the most recent call to measure().
5100 * This should be used during measurement and layout calculations only. Use
5101 * {@link #getHeight()} to see how tall a view is after layout.
5102 *
5103 * @return The measured height of this view.
5104 */
5105 public final int getMeasuredHeight() {
5106 return mMeasuredHeight;
5107 }
5108
5109 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005110 * The transform matrix of this view, which is calculated based on the current
5111 * roation, scale, and pivot properties.
5112 *
5113 * @see #getRotation()
5114 * @see #getScaleX()
5115 * @see #getScaleY()
5116 * @see #getPivotX()
5117 * @see #getPivotY()
5118 * @return The current transform matrix for the view
5119 */
5120 public Matrix getMatrix() {
Romain Guy33e72ae2010-07-17 12:40:29 -07005121 hasIdentityMatrix();
5122 return mMatrix;
5123 }
5124
5125 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005126 * Utility function to determine if the value is far enough away from zero to be
5127 * considered non-zero.
5128 * @param value A floating point value to check for zero-ness
5129 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5130 */
5131 private static boolean nonzero(float value) {
5132 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5133 }
5134
5135 /**
Romain Guy33e72ae2010-07-17 12:40:29 -07005136 * Recomputes the transform matrix if necessary.
5137 *
5138 * @return True if the transform matrix is the identity matrix, false otherwise.
5139 */
5140 boolean hasIdentityMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005141 if (mMatrixDirty) {
5142 // transform-related properties have changed since the last time someone
5143 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005144
5145 // Figure out if we need to update the pivot point
5146 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5147 if ((mRight - mLeft) != mPrevWidth && (mBottom - mTop) != mPrevHeight) {
5148 mPrevWidth = mRight - mLeft;
5149 mPrevHeight = mBottom - mTop;
5150 mPivotX = (float) mPrevWidth / 2f;
5151 mPivotY = (float) mPrevHeight / 2f;
5152 }
5153 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005154 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005155 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5156 mMatrix.setTranslate(mTranslationX, mTranslationY);
5157 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5158 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5159 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005160 if (mCamera == null) {
5161 mCamera = new Camera();
5162 matrix3D = new Matrix();
5163 }
5164 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005165 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005166 mCamera.rotateX(mRotationX);
5167 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005168 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005169 mCamera.getMatrix(matrix3D);
5170 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005171 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005172 mMatrix.postConcat(matrix3D);
5173 mCamera.restore();
5174 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005175 mMatrixDirty = false;
5176 mMatrixIsIdentity = mMatrix.isIdentity();
5177 mInverseMatrixDirty = true;
5178 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005179 return mMatrixIsIdentity;
Chet Haasec3aa3612010-06-17 08:50:37 -07005180 }
5181
5182 /**
5183 * Utility method to retrieve the inverse of the current mMatrix property.
5184 * We cache the matrix to avoid recalculating it when transform properties
5185 * have not changed.
5186 *
5187 * @return The inverse of the current matrix of this view.
5188 */
5189 Matrix getInverseMatrix() {
5190 if (mInverseMatrixDirty) {
5191 if (mInverseMatrix == null) {
5192 mInverseMatrix = new Matrix();
5193 }
5194 mMatrix.invert(mInverseMatrix);
5195 mInverseMatrixDirty = false;
5196 }
5197 return mInverseMatrix;
5198 }
5199
5200 /**
5201 * The degrees that the view is rotated around the pivot point.
5202 *
5203 * @see #getPivotX()
5204 * @see #getPivotY()
5205 * @return The degrees of rotation.
5206 */
5207 public float getRotation() {
5208 return mRotation;
5209 }
5210
5211 /**
Chet Haase897247b2010-09-09 14:54:47 -07005212 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5213 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005214 *
5215 * @param rotation The degrees of rotation.
5216 * @see #getPivotX()
5217 * @see #getPivotY()
5218 */
5219 public void setRotation(float rotation) {
5220 if (mRotation != rotation) {
5221 // Double-invalidation is necessary to capture view's old and new areas
5222 invalidate();
5223 mRotation = rotation;
5224 mMatrixDirty = true;
5225 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5226 invalidate();
5227 }
5228 }
5229
5230 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005231 * The degrees that the view is rotated around the vertical axis through the pivot point.
5232 *
5233 * @see #getPivotX()
5234 * @see #getPivotY()
5235 * @return The degrees of Y rotation.
5236 */
5237 public float getRotationY() {
5238 return mRotationY;
5239 }
5240
5241 /**
Chet Haase897247b2010-09-09 14:54:47 -07005242 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5243 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5244 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005245 *
5246 * @param rotationY The degrees of Y rotation.
5247 * @see #getPivotX()
5248 * @see #getPivotY()
5249 */
5250 public void setRotationY(float rotationY) {
5251 if (mRotationY != rotationY) {
5252 // Double-invalidation is necessary to capture view's old and new areas
5253 invalidate();
5254 mRotationY = rotationY;
5255 mMatrixDirty = true;
5256 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5257 invalidate();
5258 }
5259 }
5260
5261 /**
5262 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5263 *
5264 * @see #getPivotX()
5265 * @see #getPivotY()
5266 * @return The degrees of X rotation.
5267 */
5268 public float getRotationX() {
5269 return mRotationX;
5270 }
5271
5272 /**
Chet Haase897247b2010-09-09 14:54:47 -07005273 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5274 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5275 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005276 *
5277 * @param rotationX The degrees of X rotation.
5278 * @see #getPivotX()
5279 * @see #getPivotY()
5280 */
5281 public void setRotationX(float rotationX) {
5282 if (mRotationX != rotationX) {
5283 // Double-invalidation is necessary to capture view's old and new areas
5284 invalidate();
5285 mRotationX = rotationX;
5286 mMatrixDirty = true;
5287 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5288 invalidate();
5289 }
5290 }
5291
5292 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005293 * The amount that the view is scaled in x around the pivot point, as a proportion of
5294 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5295 *
Joe Onorato93162322010-09-16 15:42:01 -04005296 * <p>By default, this is 1.0f.
5297 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005298 * @see #getPivotX()
5299 * @see #getPivotY()
5300 * @return The scaling factor.
5301 */
5302 public float getScaleX() {
5303 return mScaleX;
5304 }
5305
5306 /**
5307 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5308 * the view's unscaled width. A value of 1 means that no scaling is applied.
5309 *
5310 * @param scaleX The scaling factor.
5311 * @see #getPivotX()
5312 * @see #getPivotY()
5313 */
5314 public void setScaleX(float scaleX) {
5315 if (mScaleX != scaleX) {
5316 // Double-invalidation is necessary to capture view's old and new areas
5317 invalidate();
5318 mScaleX = scaleX;
5319 mMatrixDirty = true;
5320 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5321 invalidate();
5322 }
5323 }
5324
5325 /**
5326 * The amount that the view is scaled in y around the pivot point, as a proportion of
5327 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5328 *
Joe Onorato93162322010-09-16 15:42:01 -04005329 * <p>By default, this is 1.0f.
5330 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005331 * @see #getPivotX()
5332 * @see #getPivotY()
5333 * @return The scaling factor.
5334 */
5335 public float getScaleY() {
5336 return mScaleY;
5337 }
5338
5339 /**
5340 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5341 * the view's unscaled width. A value of 1 means that no scaling is applied.
5342 *
5343 * @param scaleY The scaling factor.
5344 * @see #getPivotX()
5345 * @see #getPivotY()
5346 */
5347 public void setScaleY(float scaleY) {
5348 if (mScaleY != scaleY) {
5349 // Double-invalidation is necessary to capture view's old and new areas
5350 invalidate();
5351 mScaleY = scaleY;
5352 mMatrixDirty = true;
5353 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5354 invalidate();
5355 }
5356 }
5357
5358 /**
5359 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5360 * and {@link #setScaleX(float) scaled}.
5361 *
5362 * @see #getRotation()
5363 * @see #getScaleX()
5364 * @see #getScaleY()
5365 * @see #getPivotY()
5366 * @return The x location of the pivot point.
5367 */
5368 public float getPivotX() {
5369 return mPivotX;
5370 }
5371
5372 /**
5373 * Sets the x location of the point around which the view is
5374 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005375 * By default, the pivot point is centered on the object.
5376 * Setting this property disables this behavior and causes the view to use only the
5377 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005378 *
5379 * @param pivotX The x location of the pivot point.
5380 * @see #getRotation()
5381 * @see #getScaleX()
5382 * @see #getScaleY()
5383 * @see #getPivotY()
5384 */
5385 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005386 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005387 if (mPivotX != pivotX) {
5388 // Double-invalidation is necessary to capture view's old and new areas
5389 invalidate();
5390 mPivotX = pivotX;
5391 mMatrixDirty = true;
5392 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5393 invalidate();
5394 }
5395 }
5396
5397 /**
5398 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5399 * and {@link #setScaleY(float) scaled}.
5400 *
5401 * @see #getRotation()
5402 * @see #getScaleX()
5403 * @see #getScaleY()
5404 * @see #getPivotY()
5405 * @return The y location of the pivot point.
5406 */
5407 public float getPivotY() {
5408 return mPivotY;
5409 }
5410
5411 /**
5412 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005413 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5414 * Setting this property disables this behavior and causes the view to use only the
5415 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005416 *
5417 * @param pivotY The y location of the pivot point.
5418 * @see #getRotation()
5419 * @see #getScaleX()
5420 * @see #getScaleY()
5421 * @see #getPivotY()
5422 */
5423 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005424 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005425 if (mPivotY != pivotY) {
5426 // Double-invalidation is necessary to capture view's old and new areas
5427 invalidate();
5428 mPivotY = pivotY;
5429 mMatrixDirty = true;
5430 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5431 invalidate();
5432 }
5433 }
5434
5435 /**
5436 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5437 * completely transparent and 1 means the view is completely opaque.
5438 *
Joe Onorato93162322010-09-16 15:42:01 -04005439 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005440 * @return The opacity of the view.
5441 */
5442 public float getAlpha() {
5443 return mAlpha;
5444 }
5445
5446 /**
5447 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5448 * completely transparent and 1 means the view is completely opaque.
5449 *
5450 * @param alpha The opacity of the view.
5451 */
5452 public void setAlpha(float alpha) {
5453 mAlpha = alpha;
Romain Guy9b34d452010-09-02 11:45:04 -07005454 onSetAlpha((int) (alpha * 255));
Chet Haasec3aa3612010-06-17 08:50:37 -07005455 invalidate();
5456 }
5457
5458 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 * Top position of this view relative to its parent.
5460 *
5461 * @return The top of this view, in pixels.
5462 */
5463 @ViewDebug.CapturedViewProperty
5464 public final int getTop() {
5465 return mTop;
5466 }
5467
5468 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005469 * Sets the top position of this view relative to its parent. This method is meant to be called
5470 * by the layout system and should not generally be called otherwise, because the property
5471 * may be changed at any time by the layout.
5472 *
5473 * @param top The top of this view, in pixels.
5474 */
5475 public final void setTop(int top) {
5476 if (top != mTop) {
5477 if (hasIdentityMatrix()) {
5478 final ViewParent p = mParent;
5479 if (p != null && mAttachInfo != null) {
5480 final Rect r = mAttachInfo.mTmpInvalRect;
5481 int minTop;
5482 int yLoc;
5483 if (top < mTop) {
5484 minTop = top;
5485 yLoc = top - mTop;
5486 } else {
5487 minTop = mTop;
5488 yLoc = 0;
5489 }
5490 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5491 p.invalidateChild(this, r);
5492 }
5493 } else {
5494 // Double-invalidation is necessary to capture view's old and new areas
5495 invalidate();
5496 }
5497
5498 mTop = top;
5499
5500 if (!mMatrixIsIdentity) {
5501 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5502 invalidate();
5503 }
5504 }
5505 }
5506
5507 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 * Bottom position of this view relative to its parent.
5509 *
5510 * @return The bottom of this view, in pixels.
5511 */
5512 @ViewDebug.CapturedViewProperty
5513 public final int getBottom() {
5514 return mBottom;
5515 }
5516
5517 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005518 * Sets the bottom position of this view relative to its parent. This method is meant to be
5519 * called by the layout system and should not generally be called otherwise, because the
5520 * property may be changed at any time by the layout.
5521 *
5522 * @param bottom The bottom of this view, in pixels.
5523 */
5524 public final void setBottom(int bottom) {
5525 if (bottom != mBottom) {
5526 if (hasIdentityMatrix()) {
5527 final ViewParent p = mParent;
5528 if (p != null && mAttachInfo != null) {
5529 final Rect r = mAttachInfo.mTmpInvalRect;
5530 int maxBottom;
5531 if (bottom < mBottom) {
5532 maxBottom = mBottom;
5533 } else {
5534 maxBottom = bottom;
5535 }
5536 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5537 p.invalidateChild(this, r);
5538 }
5539 } else {
5540 // Double-invalidation is necessary to capture view's old and new areas
5541 invalidate();
5542 }
5543
5544 mBottom = bottom;
5545
5546 if (!mMatrixIsIdentity) {
5547 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5548 invalidate();
5549 }
5550 }
5551 }
5552
5553 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005554 * Left position of this view relative to its parent.
5555 *
5556 * @return The left edge of this view, in pixels.
5557 */
5558 @ViewDebug.CapturedViewProperty
5559 public final int getLeft() {
5560 return mLeft;
5561 }
5562
5563 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005564 * Sets the left position of this view relative to its parent. This method is meant to be called
5565 * by the layout system and should not generally be called otherwise, because the property
5566 * may be changed at any time by the layout.
5567 *
5568 * @param left The bottom of this view, in pixels.
5569 */
5570 public final void setLeft(int left) {
5571 if (left != mLeft) {
5572 System.out.println("view " + this + " left = " + left);
5573 if (hasIdentityMatrix()) {
5574 final ViewParent p = mParent;
5575 if (p != null && mAttachInfo != null) {
5576 final Rect r = mAttachInfo.mTmpInvalRect;
5577 int minLeft;
5578 int xLoc;
5579 if (left < mLeft) {
5580 minLeft = left;
5581 xLoc = left - mLeft;
5582 } else {
5583 minLeft = mLeft;
5584 xLoc = 0;
5585 }
5586 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
5587 p.invalidateChild(this, r);
5588 }
5589 } else {
5590 // Double-invalidation is necessary to capture view's old and new areas
5591 invalidate();
5592 }
5593
5594 mLeft = left;
5595
5596 if (!mMatrixIsIdentity) {
5597 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5598 invalidate();
5599 }
5600 }
5601 }
5602
5603 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005604 * Right position of this view relative to its parent.
5605 *
5606 * @return The right edge of this view, in pixels.
5607 */
5608 @ViewDebug.CapturedViewProperty
5609 public final int getRight() {
5610 return mRight;
5611 }
5612
5613 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005614 * Sets the right position of this view relative to its parent. This method is meant to be called
5615 * by the layout system and should not generally be called otherwise, because the property
5616 * may be changed at any time by the layout.
5617 *
5618 * @param right The bottom of this view, in pixels.
5619 */
5620 public final void setRight(int right) {
5621 if (right != mRight) {
5622 if (hasIdentityMatrix()) {
5623 final ViewParent p = mParent;
5624 if (p != null && mAttachInfo != null) {
5625 final Rect r = mAttachInfo.mTmpInvalRect;
5626 int maxRight;
5627 if (right < mRight) {
5628 maxRight = mRight;
5629 } else {
5630 maxRight = right;
5631 }
5632 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
5633 p.invalidateChild(this, r);
5634 }
5635 } else {
5636 // Double-invalidation is necessary to capture view's old and new areas
5637 invalidate();
5638 }
5639
5640 mRight = right;
5641
5642 if (!mMatrixIsIdentity) {
5643 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5644 invalidate();
5645 }
5646 }
5647 }
5648
5649 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005650 * The visual x position of this view, in pixels. This is equivalent to the
5651 * {@link #setTranslationX(float) translationX} property plus the current
5652 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07005653 *
Chet Haasedf030d22010-07-30 17:22:38 -07005654 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005655 */
Chet Haasedf030d22010-07-30 17:22:38 -07005656 public float getX() {
5657 return mLeft + mTranslationX;
5658 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005659
Chet Haasedf030d22010-07-30 17:22:38 -07005660 /**
5661 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
5662 * {@link #setTranslationX(float) translationX} property to be the difference between
5663 * the x value passed in and the current {@link #getLeft() left} property.
5664 *
5665 * @param x The visual x position of this view, in pixels.
5666 */
5667 public void setX(float x) {
5668 setTranslationX(x - mLeft);
5669 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005670
Chet Haasedf030d22010-07-30 17:22:38 -07005671 /**
5672 * The visual y position of this view, in pixels. This is equivalent to the
5673 * {@link #setTranslationY(float) translationY} property plus the current
5674 * {@link #getTop() top} property.
5675 *
5676 * @return The visual y position of this view, in pixels.
5677 */
5678 public float getY() {
5679 return mTop + mTranslationY;
5680 }
5681
5682 /**
5683 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
5684 * {@link #setTranslationY(float) translationY} property to be the difference between
5685 * the y value passed in and the current {@link #getTop() top} property.
5686 *
5687 * @param y The visual y position of this view, in pixels.
5688 */
5689 public void setY(float y) {
5690 setTranslationY(y - mTop);
5691 }
5692
5693
5694 /**
5695 * The horizontal location of this view relative to its {@link #getLeft() left} position.
5696 * This position is post-layout, in addition to wherever the object's
5697 * layout placed it.
5698 *
5699 * @return The horizontal position of this view relative to its left position, in pixels.
5700 */
5701 public float getTranslationX() {
5702 return mTranslationX;
5703 }
5704
5705 /**
5706 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
5707 * This effectively positions the object post-layout, in addition to wherever the object's
5708 * layout placed it.
5709 *
5710 * @param translationX The horizontal position of this view relative to its left position,
5711 * in pixels.
5712 */
5713 public void setTranslationX(float translationX) {
5714 if (mTranslationX != translationX) {
5715 // Double-invalidation is necessary to capture view's old and new areas
5716 invalidate();
5717 mTranslationX = translationX;
5718 mMatrixDirty = true;
5719 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5720 invalidate();
Chet Haasec3aa3612010-06-17 08:50:37 -07005721 }
5722 }
5723
5724 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005725 * The horizontal location of this view relative to its {@link #getTop() top} position.
5726 * This position is post-layout, in addition to wherever the object's
5727 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005728 *
Chet Haasedf030d22010-07-30 17:22:38 -07005729 * @return The vertical position of this view relative to its top position,
5730 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005731 */
Chet Haasedf030d22010-07-30 17:22:38 -07005732 public float getTranslationY() {
5733 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07005734 }
5735
5736 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005737 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
5738 * This effectively positions the object post-layout, in addition to wherever the object's
5739 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005740 *
Chet Haasedf030d22010-07-30 17:22:38 -07005741 * @param translationY The vertical position of this view relative to its top position,
5742 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005743 */
Chet Haasedf030d22010-07-30 17:22:38 -07005744 public void setTranslationY(float translationY) {
5745 if (mTranslationY != translationY) {
5746 // Double-invalidation is necessary to capture view's old and new areas
5747 invalidate();
5748 mTranslationY = translationY;
5749 mMatrixDirty = true;
5750 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5751 invalidate();
5752 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005753 }
5754
5755 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 * Hit rectangle in parent's coordinates
5757 *
5758 * @param outRect The hit rectangle of the view.
5759 */
5760 public void getHitRect(Rect outRect) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005761 if (hasIdentityMatrix() || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005762 outRect.set(mLeft, mTop, mRight, mBottom);
5763 } else {
Adam Powellb5de9f32010-07-17 01:00:53 -07005764 Matrix m = getMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005765 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07005766 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Chet Haasec3aa3612010-06-17 08:50:37 -07005767 m.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07005768 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
5769 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07005770 }
5771 }
5772
5773 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07005774 * Determines whether the given point, in local coordinates is inside the view.
5775 */
5776 /*package*/ final boolean pointInView(float localX, float localY) {
5777 return localX >= 0 && localX < (mRight - mLeft)
5778 && localY >= 0 && localY < (mBottom - mTop);
5779 }
5780
5781 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005782 * Utility method to determine whether the given point, in local coordinates,
5783 * is inside the view, where the area of the view is expanded by the slop factor.
5784 * This method is called while processing touch-move events to determine if the event
5785 * is still within the view.
5786 */
5787 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07005788 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07005789 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 }
5791
5792 /**
5793 * When a view has focus and the user navigates away from it, the next view is searched for
5794 * starting from the rectangle filled in by this method.
5795 *
5796 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
5797 * view maintains some idea of internal selection, such as a cursor, or a selected row
5798 * or column, you should override this method and fill in a more specific rectangle.
5799 *
5800 * @param r The rectangle to fill in, in this view's coordinates.
5801 */
5802 public void getFocusedRect(Rect r) {
5803 getDrawingRect(r);
5804 }
5805
5806 /**
5807 * If some part of this view is not clipped by any of its parents, then
5808 * return that area in r in global (root) coordinates. To convert r to local
5809 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
5810 * -globalOffset.y)) If the view is completely clipped or translated out,
5811 * return false.
5812 *
5813 * @param r If true is returned, r holds the global coordinates of the
5814 * visible portion of this view.
5815 * @param globalOffset If true is returned, globalOffset holds the dx,dy
5816 * between this view and its root. globalOffet may be null.
5817 * @return true if r is non-empty (i.e. part of the view is visible at the
5818 * root level.
5819 */
5820 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
5821 int width = mRight - mLeft;
5822 int height = mBottom - mTop;
5823 if (width > 0 && height > 0) {
5824 r.set(0, 0, width, height);
5825 if (globalOffset != null) {
5826 globalOffset.set(-mScrollX, -mScrollY);
5827 }
5828 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
5829 }
5830 return false;
5831 }
5832
5833 public final boolean getGlobalVisibleRect(Rect r) {
5834 return getGlobalVisibleRect(r, null);
5835 }
5836
5837 public final boolean getLocalVisibleRect(Rect r) {
5838 Point offset = new Point();
5839 if (getGlobalVisibleRect(r, offset)) {
5840 r.offset(-offset.x, -offset.y); // make r local
5841 return true;
5842 }
5843 return false;
5844 }
5845
5846 /**
5847 * Offset this view's vertical location by the specified number of pixels.
5848 *
5849 * @param offset the number of pixels to offset the view by
5850 */
5851 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005852 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005853 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005854 final ViewParent p = mParent;
5855 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005856 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005857 int minTop;
5858 int maxBottom;
5859 int yLoc;
5860 if (offset < 0) {
5861 minTop = mTop + offset;
5862 maxBottom = mBottom;
5863 yLoc = offset;
5864 } else {
5865 minTop = mTop;
5866 maxBottom = mBottom + offset;
5867 yLoc = 0;
5868 }
5869 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
5870 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005871 }
5872 } else {
5873 invalidate();
5874 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005875
Chet Haasec3aa3612010-06-17 08:50:37 -07005876 mTop += offset;
5877 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005878
Chet Haasec3aa3612010-06-17 08:50:37 -07005879 if (!mMatrixIsIdentity) {
5880 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5881 invalidate();
5882 }
5883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005884 }
5885
5886 /**
5887 * Offset this view's horizontal location by the specified amount of pixels.
5888 *
5889 * @param offset the numer of pixels to offset the view by
5890 */
5891 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005892 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005893 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005894 final ViewParent p = mParent;
5895 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005896 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005897 int minLeft;
5898 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005899 if (offset < 0) {
5900 minLeft = mLeft + offset;
5901 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005902 } else {
5903 minLeft = mLeft;
5904 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005905 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005906 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07005907 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005908 }
5909 } else {
5910 invalidate();
5911 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005912
Chet Haasec3aa3612010-06-17 08:50:37 -07005913 mLeft += offset;
5914 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005915
Chet Haasec3aa3612010-06-17 08:50:37 -07005916 if (!mMatrixIsIdentity) {
5917 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5918 invalidate();
5919 }
5920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 }
5922
5923 /**
5924 * Get the LayoutParams associated with this view. All views should have
5925 * layout parameters. These supply parameters to the <i>parent</i> of this
5926 * view specifying how it should be arranged. There are many subclasses of
5927 * ViewGroup.LayoutParams, and these correspond to the different subclasses
5928 * of ViewGroup that are responsible for arranging their children.
5929 * @return The LayoutParams associated with this view
5930 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07005931 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005932 public ViewGroup.LayoutParams getLayoutParams() {
5933 return mLayoutParams;
5934 }
5935
5936 /**
5937 * Set the layout parameters associated with this view. These supply
5938 * parameters to the <i>parent</i> of this view specifying how it should be
5939 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
5940 * correspond to the different subclasses of ViewGroup that are responsible
5941 * for arranging their children.
5942 *
5943 * @param params the layout parameters for this view
5944 */
5945 public void setLayoutParams(ViewGroup.LayoutParams params) {
5946 if (params == null) {
5947 throw new NullPointerException("params == null");
5948 }
5949 mLayoutParams = params;
5950 requestLayout();
5951 }
5952
5953 /**
5954 * Set the scrolled position of your view. This will cause a call to
5955 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5956 * invalidated.
5957 * @param x the x position to scroll to
5958 * @param y the y position to scroll to
5959 */
5960 public void scrollTo(int x, int y) {
5961 if (mScrollX != x || mScrollY != y) {
5962 int oldX = mScrollX;
5963 int oldY = mScrollY;
5964 mScrollX = x;
5965 mScrollY = y;
5966 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07005967 if (!awakenScrollBars()) {
5968 invalidate();
5969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 }
5971 }
5972
5973 /**
5974 * Move the scrolled position of your view. This will cause a call to
5975 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5976 * invalidated.
5977 * @param x the amount of pixels to scroll by horizontally
5978 * @param y the amount of pixels to scroll by vertically
5979 */
5980 public void scrollBy(int x, int y) {
5981 scrollTo(mScrollX + x, mScrollY + y);
5982 }
5983
5984 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07005985 * <p>Trigger the scrollbars to draw. When invoked this method starts an
5986 * animation to fade the scrollbars out after a default delay. If a subclass
5987 * provides animated scrolling, the start delay should equal the duration
5988 * of the scrolling animation.</p>
5989 *
5990 * <p>The animation starts only if at least one of the scrollbars is
5991 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
5992 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5993 * this method returns true, and false otherwise. If the animation is
5994 * started, this method calls {@link #invalidate()}; in that case the
5995 * caller should not call {@link #invalidate()}.</p>
5996 *
5997 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07005998 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07005999 *
6000 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6001 * and {@link #scrollTo(int, int)}.</p>
6002 *
6003 * @return true if the animation is played, false otherwise
6004 *
6005 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006006 * @see #scrollBy(int, int)
6007 * @see #scrollTo(int, int)
6008 * @see #isHorizontalScrollBarEnabled()
6009 * @see #isVerticalScrollBarEnabled()
6010 * @see #setHorizontalScrollBarEnabled(boolean)
6011 * @see #setVerticalScrollBarEnabled(boolean)
6012 */
6013 protected boolean awakenScrollBars() {
6014 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006015 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006016 }
6017
6018 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006019 * Trigger the scrollbars to draw.
6020 * This method differs from awakenScrollBars() only in its default duration.
6021 * initialAwakenScrollBars() will show the scroll bars for longer than
6022 * usual to give the user more of a chance to notice them.
6023 *
6024 * @return true if the animation is played, false otherwise.
6025 */
6026 private boolean initialAwakenScrollBars() {
6027 return mScrollCache != null &&
6028 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6029 }
6030
6031 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006032 * <p>
6033 * Trigger the scrollbars to draw. When invoked this method starts an
6034 * animation to fade the scrollbars out after a fixed delay. If a subclass
6035 * provides animated scrolling, the start delay should equal the duration of
6036 * the scrolling animation.
6037 * </p>
6038 *
6039 * <p>
6040 * The animation starts only if at least one of the scrollbars is enabled,
6041 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6042 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6043 * this method returns true, and false otherwise. If the animation is
6044 * started, this method calls {@link #invalidate()}; in that case the caller
6045 * should not call {@link #invalidate()}.
6046 * </p>
6047 *
6048 * <p>
6049 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006050 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006051 * </p>
6052 *
6053 * @param startDelay the delay, in milliseconds, after which the animation
6054 * should start; when the delay is 0, the animation starts
6055 * immediately
6056 * @return true if the animation is played, false otherwise
6057 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006058 * @see #scrollBy(int, int)
6059 * @see #scrollTo(int, int)
6060 * @see #isHorizontalScrollBarEnabled()
6061 * @see #isVerticalScrollBarEnabled()
6062 * @see #setHorizontalScrollBarEnabled(boolean)
6063 * @see #setVerticalScrollBarEnabled(boolean)
6064 */
6065 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006066 return awakenScrollBars(startDelay, true);
6067 }
6068
6069 /**
6070 * <p>
6071 * Trigger the scrollbars to draw. When invoked this method starts an
6072 * animation to fade the scrollbars out after a fixed delay. If a subclass
6073 * provides animated scrolling, the start delay should equal the duration of
6074 * the scrolling animation.
6075 * </p>
6076 *
6077 * <p>
6078 * The animation starts only if at least one of the scrollbars is enabled,
6079 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6080 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6081 * this method returns true, and false otherwise. If the animation is
6082 * started, this method calls {@link #invalidate()} if the invalidate parameter
6083 * is set to true; in that case the caller
6084 * should not call {@link #invalidate()}.
6085 * </p>
6086 *
6087 * <p>
6088 * This method should be invoked everytime a subclass directly updates the
6089 * scroll parameters.
6090 * </p>
6091 *
6092 * @param startDelay the delay, in milliseconds, after which the animation
6093 * should start; when the delay is 0, the animation starts
6094 * immediately
6095 *
6096 * @param invalidate Wheter this method should call invalidate
6097 *
6098 * @return true if the animation is played, false otherwise
6099 *
6100 * @see #scrollBy(int, int)
6101 * @see #scrollTo(int, int)
6102 * @see #isHorizontalScrollBarEnabled()
6103 * @see #isVerticalScrollBarEnabled()
6104 * @see #setHorizontalScrollBarEnabled(boolean)
6105 * @see #setVerticalScrollBarEnabled(boolean)
6106 */
6107 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006108 final ScrollabilityCache scrollCache = mScrollCache;
6109
6110 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6111 return false;
6112 }
6113
6114 if (scrollCache.scrollBar == null) {
6115 scrollCache.scrollBar = new ScrollBarDrawable();
6116 }
6117
6118 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6119
Mike Cleron290947b2009-09-29 18:34:32 -07006120 if (invalidate) {
6121 // Invalidate to show the scrollbars
6122 invalidate();
6123 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006124
6125 if (scrollCache.state == ScrollabilityCache.OFF) {
6126 // FIXME: this is copied from WindowManagerService.
6127 // We should get this value from the system when it
6128 // is possible to do so.
6129 final int KEY_REPEAT_FIRST_DELAY = 750;
6130 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6131 }
6132
6133 // Tell mScrollCache when we should start fading. This may
6134 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006135 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006136 scrollCache.fadeStartTime = fadeStartTime;
6137 scrollCache.state = ScrollabilityCache.ON;
6138
6139 // Schedule our fader to run, unscheduling any old ones first
6140 if (mAttachInfo != null) {
6141 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6142 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6143 }
6144
6145 return true;
6146 }
6147
6148 return false;
6149 }
6150
6151 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 * Mark the the area defined by dirty as needing to be drawn. If the view is
6153 * visible, {@link #onDraw} will be called at some point in the future.
6154 * This must be called from a UI thread. To call from a non-UI thread, call
6155 * {@link #postInvalidate()}.
6156 *
6157 * WARNING: This method is destructive to dirty.
6158 * @param dirty the rectangle representing the bounds of the dirty region
6159 */
6160 public void invalidate(Rect dirty) {
6161 if (ViewDebug.TRACE_HIERARCHY) {
6162 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6163 }
6164
6165 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6166 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6167 final ViewParent p = mParent;
6168 final AttachInfo ai = mAttachInfo;
6169 if (p != null && ai != null) {
6170 final int scrollX = mScrollX;
6171 final int scrollY = mScrollY;
6172 final Rect r = ai.mTmpInvalRect;
6173 r.set(dirty.left - scrollX, dirty.top - scrollY,
6174 dirty.right - scrollX, dirty.bottom - scrollY);
6175 mParent.invalidateChild(this, r);
6176 }
6177 }
6178 }
6179
6180 /**
6181 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6182 * The coordinates of the dirty rect are relative to the view.
6183 * If the view is visible, {@link #onDraw} will be called at some point
6184 * in the future. This must be called from a UI thread. To call
6185 * from a non-UI thread, call {@link #postInvalidate()}.
6186 * @param l the left position of the dirty region
6187 * @param t the top position of the dirty region
6188 * @param r the right position of the dirty region
6189 * @param b the bottom position of the dirty region
6190 */
6191 public void invalidate(int l, int t, int r, int b) {
6192 if (ViewDebug.TRACE_HIERARCHY) {
6193 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6194 }
6195
6196 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6197 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6198 final ViewParent p = mParent;
6199 final AttachInfo ai = mAttachInfo;
6200 if (p != null && ai != null && l < r && t < b) {
6201 final int scrollX = mScrollX;
6202 final int scrollY = mScrollY;
6203 final Rect tmpr = ai.mTmpInvalRect;
6204 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6205 p.invalidateChild(this, tmpr);
6206 }
6207 }
6208 }
6209
6210 /**
6211 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6212 * be called at some point in the future. This must be called from a
6213 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6214 */
6215 public void invalidate() {
6216 if (ViewDebug.TRACE_HIERARCHY) {
6217 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6218 }
6219
6220 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6221 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
6222 final ViewParent p = mParent;
6223 final AttachInfo ai = mAttachInfo;
6224 if (p != null && ai != null) {
6225 final Rect r = ai.mTmpInvalRect;
6226 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6227 // Don't call invalidate -- we don't want to internally scroll
6228 // our own bounds
6229 p.invalidateChild(this, r);
6230 }
6231 }
6232 }
6233
6234 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006235 * Indicates whether this View is opaque. An opaque View guarantees that it will
6236 * draw all the pixels overlapping its bounds using a fully opaque color.
6237 *
6238 * Subclasses of View should override this method whenever possible to indicate
6239 * whether an instance is opaque. Opaque Views are treated in a special way by
6240 * the View hierarchy, possibly allowing it to perform optimizations during
6241 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006242 *
Romain Guy24443ea2009-05-11 11:56:30 -07006243 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006244 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006245 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006246 public boolean isOpaque() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006247 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
6248 }
6249
6250 private void computeOpaqueFlags() {
6251 // Opaque if:
6252 // - Has a background
6253 // - Background is opaque
6254 // - Doesn't have scrollbars or scrollbars are inside overlay
6255
6256 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6257 mPrivateFlags |= OPAQUE_BACKGROUND;
6258 } else {
6259 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6260 }
6261
6262 final int flags = mViewFlags;
6263 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6264 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6265 mPrivateFlags |= OPAQUE_SCROLLBARS;
6266 } else {
6267 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6268 }
6269 }
6270
6271 /**
6272 * @hide
6273 */
6274 protected boolean hasOpaqueScrollbars() {
6275 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006276 }
6277
6278 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 * @return A handler associated with the thread running the View. This
6280 * handler can be used to pump events in the UI events queue.
6281 */
6282 public Handler getHandler() {
6283 if (mAttachInfo != null) {
6284 return mAttachInfo.mHandler;
6285 }
6286 return null;
6287 }
6288
6289 /**
6290 * Causes the Runnable to be added to the message queue.
6291 * The runnable will be run on the user interface thread.
6292 *
6293 * @param action The Runnable that will be executed.
6294 *
6295 * @return Returns true if the Runnable was successfully placed in to the
6296 * message queue. Returns false on failure, usually because the
6297 * looper processing the message queue is exiting.
6298 */
6299 public boolean post(Runnable action) {
6300 Handler handler;
6301 if (mAttachInfo != null) {
6302 handler = mAttachInfo.mHandler;
6303 } else {
6304 // Assume that post will succeed later
6305 ViewRoot.getRunQueue().post(action);
6306 return true;
6307 }
6308
6309 return handler.post(action);
6310 }
6311
6312 /**
6313 * Causes the Runnable to be added to the message queue, to be run
6314 * after the specified amount of time elapses.
6315 * The runnable will be run on the user interface thread.
6316 *
6317 * @param action The Runnable that will be executed.
6318 * @param delayMillis The delay (in milliseconds) until the Runnable
6319 * will be executed.
6320 *
6321 * @return true if the Runnable was successfully placed in to the
6322 * message queue. Returns false on failure, usually because the
6323 * looper processing the message queue is exiting. Note that a
6324 * result of true does not mean the Runnable will be processed --
6325 * if the looper is quit before the delivery time of the message
6326 * occurs then the message will be dropped.
6327 */
6328 public boolean postDelayed(Runnable action, long delayMillis) {
6329 Handler handler;
6330 if (mAttachInfo != null) {
6331 handler = mAttachInfo.mHandler;
6332 } else {
6333 // Assume that post will succeed later
6334 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6335 return true;
6336 }
6337
6338 return handler.postDelayed(action, delayMillis);
6339 }
6340
6341 /**
6342 * Removes the specified Runnable from the message queue.
6343 *
6344 * @param action The Runnable to remove from the message handling queue
6345 *
6346 * @return true if this view could ask the Handler to remove the Runnable,
6347 * false otherwise. When the returned value is true, the Runnable
6348 * may or may not have been actually removed from the message queue
6349 * (for instance, if the Runnable was not in the queue already.)
6350 */
6351 public boolean removeCallbacks(Runnable action) {
6352 Handler handler;
6353 if (mAttachInfo != null) {
6354 handler = mAttachInfo.mHandler;
6355 } else {
6356 // Assume that post will succeed later
6357 ViewRoot.getRunQueue().removeCallbacks(action);
6358 return true;
6359 }
6360
6361 handler.removeCallbacks(action);
6362 return true;
6363 }
6364
6365 /**
6366 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6367 * Use this to invalidate the View from a non-UI thread.
6368 *
6369 * @see #invalidate()
6370 */
6371 public void postInvalidate() {
6372 postInvalidateDelayed(0);
6373 }
6374
6375 /**
6376 * Cause an invalidate of the specified area to happen on a subsequent cycle
6377 * through the event loop. Use this to invalidate the View from a non-UI thread.
6378 *
6379 * @param left The left coordinate of the rectangle to invalidate.
6380 * @param top The top coordinate of the rectangle to invalidate.
6381 * @param right The right coordinate of the rectangle to invalidate.
6382 * @param bottom The bottom coordinate of the rectangle to invalidate.
6383 *
6384 * @see #invalidate(int, int, int, int)
6385 * @see #invalidate(Rect)
6386 */
6387 public void postInvalidate(int left, int top, int right, int bottom) {
6388 postInvalidateDelayed(0, left, top, right, bottom);
6389 }
6390
6391 /**
6392 * Cause an invalidate to happen on a subsequent cycle through the event
6393 * loop. Waits for the specified amount of time.
6394 *
6395 * @param delayMilliseconds the duration in milliseconds to delay the
6396 * invalidation by
6397 */
6398 public void postInvalidateDelayed(long delayMilliseconds) {
6399 // We try only with the AttachInfo because there's no point in invalidating
6400 // if we are not attached to our window
6401 if (mAttachInfo != null) {
6402 Message msg = Message.obtain();
6403 msg.what = AttachInfo.INVALIDATE_MSG;
6404 msg.obj = this;
6405 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6406 }
6407 }
6408
6409 /**
6410 * Cause an invalidate of the specified area to happen on a subsequent cycle
6411 * through the event loop. Waits for the specified amount of time.
6412 *
6413 * @param delayMilliseconds the duration in milliseconds to delay the
6414 * invalidation by
6415 * @param left The left coordinate of the rectangle to invalidate.
6416 * @param top The top coordinate of the rectangle to invalidate.
6417 * @param right The right coordinate of the rectangle to invalidate.
6418 * @param bottom The bottom coordinate of the rectangle to invalidate.
6419 */
6420 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6421 int right, int bottom) {
6422
6423 // We try only with the AttachInfo because there's no point in invalidating
6424 // if we are not attached to our window
6425 if (mAttachInfo != null) {
6426 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6427 info.target = this;
6428 info.left = left;
6429 info.top = top;
6430 info.right = right;
6431 info.bottom = bottom;
6432
6433 final Message msg = Message.obtain();
6434 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6435 msg.obj = info;
6436 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6437 }
6438 }
6439
6440 /**
6441 * Called by a parent to request that a child update its values for mScrollX
6442 * and mScrollY if necessary. This will typically be done if the child is
6443 * animating a scroll using a {@link android.widget.Scroller Scroller}
6444 * object.
6445 */
6446 public void computeScroll() {
6447 }
6448
6449 /**
6450 * <p>Indicate whether the horizontal edges are faded when the view is
6451 * scrolled horizontally.</p>
6452 *
6453 * @return true if the horizontal edges should are faded on scroll, false
6454 * otherwise
6455 *
6456 * @see #setHorizontalFadingEdgeEnabled(boolean)
6457 * @attr ref android.R.styleable#View_fadingEdge
6458 */
6459 public boolean isHorizontalFadingEdgeEnabled() {
6460 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6461 }
6462
6463 /**
6464 * <p>Define whether the horizontal edges should be faded when this view
6465 * is scrolled horizontally.</p>
6466 *
6467 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6468 * be faded when the view is scrolled
6469 * horizontally
6470 *
6471 * @see #isHorizontalFadingEdgeEnabled()
6472 * @attr ref android.R.styleable#View_fadingEdge
6473 */
6474 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6475 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6476 if (horizontalFadingEdgeEnabled) {
6477 initScrollCache();
6478 }
6479
6480 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6481 }
6482 }
6483
6484 /**
6485 * <p>Indicate whether the vertical edges are faded when the view is
6486 * scrolled horizontally.</p>
6487 *
6488 * @return true if the vertical edges should are faded on scroll, false
6489 * otherwise
6490 *
6491 * @see #setVerticalFadingEdgeEnabled(boolean)
6492 * @attr ref android.R.styleable#View_fadingEdge
6493 */
6494 public boolean isVerticalFadingEdgeEnabled() {
6495 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6496 }
6497
6498 /**
6499 * <p>Define whether the vertical edges should be faded when this view
6500 * is scrolled vertically.</p>
6501 *
6502 * @param verticalFadingEdgeEnabled true if the vertical edges should
6503 * be faded when the view is scrolled
6504 * vertically
6505 *
6506 * @see #isVerticalFadingEdgeEnabled()
6507 * @attr ref android.R.styleable#View_fadingEdge
6508 */
6509 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6510 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6511 if (verticalFadingEdgeEnabled) {
6512 initScrollCache();
6513 }
6514
6515 mViewFlags ^= FADING_EDGE_VERTICAL;
6516 }
6517 }
6518
6519 /**
6520 * Returns the strength, or intensity, of the top faded edge. The strength is
6521 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6522 * returns 0.0 or 1.0 but no value in between.
6523 *
6524 * Subclasses should override this method to provide a smoother fade transition
6525 * when scrolling occurs.
6526 *
6527 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6528 */
6529 protected float getTopFadingEdgeStrength() {
6530 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6531 }
6532
6533 /**
6534 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6535 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6536 * returns 0.0 or 1.0 but no value in between.
6537 *
6538 * Subclasses should override this method to provide a smoother fade transition
6539 * when scrolling occurs.
6540 *
6541 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6542 */
6543 protected float getBottomFadingEdgeStrength() {
6544 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6545 computeVerticalScrollRange() ? 1.0f : 0.0f;
6546 }
6547
6548 /**
6549 * Returns the strength, or intensity, of the left faded edge. The strength is
6550 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6551 * returns 0.0 or 1.0 but no value in between.
6552 *
6553 * Subclasses should override this method to provide a smoother fade transition
6554 * when scrolling occurs.
6555 *
6556 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6557 */
6558 protected float getLeftFadingEdgeStrength() {
6559 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6560 }
6561
6562 /**
6563 * Returns the strength, or intensity, of the right faded edge. The strength is
6564 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6565 * returns 0.0 or 1.0 but no value in between.
6566 *
6567 * Subclasses should override this method to provide a smoother fade transition
6568 * when scrolling occurs.
6569 *
6570 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6571 */
6572 protected float getRightFadingEdgeStrength() {
6573 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6574 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6575 }
6576
6577 /**
6578 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6579 * scrollbar is not drawn by default.</p>
6580 *
6581 * @return true if the horizontal scrollbar should be painted, false
6582 * otherwise
6583 *
6584 * @see #setHorizontalScrollBarEnabled(boolean)
6585 */
6586 public boolean isHorizontalScrollBarEnabled() {
6587 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6588 }
6589
6590 /**
6591 * <p>Define whether the horizontal scrollbar should be drawn or not. The
6592 * scrollbar is not drawn by default.</p>
6593 *
6594 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
6595 * be painted
6596 *
6597 * @see #isHorizontalScrollBarEnabled()
6598 */
6599 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
6600 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
6601 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006602 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006603 recomputePadding();
6604 }
6605 }
6606
6607 /**
6608 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
6609 * scrollbar is not drawn by default.</p>
6610 *
6611 * @return true if the vertical scrollbar should be painted, false
6612 * otherwise
6613 *
6614 * @see #setVerticalScrollBarEnabled(boolean)
6615 */
6616 public boolean isVerticalScrollBarEnabled() {
6617 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
6618 }
6619
6620 /**
6621 * <p>Define whether the vertical scrollbar should be drawn or not. The
6622 * scrollbar is not drawn by default.</p>
6623 *
6624 * @param verticalScrollBarEnabled true if the vertical scrollbar should
6625 * be painted
6626 *
6627 * @see #isVerticalScrollBarEnabled()
6628 */
6629 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
6630 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
6631 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006632 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 recomputePadding();
6634 }
6635 }
6636
6637 private void recomputePadding() {
6638 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
6639 }
Mike Cleronfe81d382009-09-28 14:22:16 -07006640
6641 /**
6642 * Define whether scrollbars will fade when the view is not scrolling.
6643 *
6644 * @param fadeScrollbars wheter to enable fading
6645 *
6646 */
6647 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
6648 initScrollCache();
6649 final ScrollabilityCache scrollabilityCache = mScrollCache;
6650 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07006651 if (fadeScrollbars) {
6652 scrollabilityCache.state = ScrollabilityCache.OFF;
6653 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07006654 scrollabilityCache.state = ScrollabilityCache.ON;
6655 }
6656 }
6657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07006659 *
6660 * Returns true if scrollbars will fade when this view is not scrolling
6661 *
6662 * @return true if scrollbar fading is enabled
6663 */
6664 public boolean isScrollbarFadingEnabled() {
6665 return mScrollCache != null && mScrollCache.fadeScrollBars;
6666 }
6667
6668 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
6670 * inset. When inset, they add to the padding of the view. And the scrollbars
6671 * can be drawn inside the padding area or on the edge of the view. For example,
6672 * if a view has a background drawable and you want to draw the scrollbars
6673 * inside the padding specified by the drawable, you can use
6674 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
6675 * appear at the edge of the view, ignoring the padding, then you can use
6676 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
6677 * @param style the style of the scrollbars. Should be one of
6678 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
6679 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
6680 * @see #SCROLLBARS_INSIDE_OVERLAY
6681 * @see #SCROLLBARS_INSIDE_INSET
6682 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6683 * @see #SCROLLBARS_OUTSIDE_INSET
6684 */
6685 public void setScrollBarStyle(int style) {
6686 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
6687 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07006688 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 recomputePadding();
6690 }
6691 }
6692
6693 /**
6694 * <p>Returns the current scrollbar style.</p>
6695 * @return the current scrollbar style
6696 * @see #SCROLLBARS_INSIDE_OVERLAY
6697 * @see #SCROLLBARS_INSIDE_INSET
6698 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6699 * @see #SCROLLBARS_OUTSIDE_INSET
6700 */
6701 public int getScrollBarStyle() {
6702 return mViewFlags & SCROLLBARS_STYLE_MASK;
6703 }
6704
6705 /**
6706 * <p>Compute the horizontal range that the horizontal scrollbar
6707 * represents.</p>
6708 *
6709 * <p>The range is expressed in arbitrary units that must be the same as the
6710 * units used by {@link #computeHorizontalScrollExtent()} and
6711 * {@link #computeHorizontalScrollOffset()}.</p>
6712 *
6713 * <p>The default range is the drawing width of this view.</p>
6714 *
6715 * @return the total horizontal range represented by the horizontal
6716 * scrollbar
6717 *
6718 * @see #computeHorizontalScrollExtent()
6719 * @see #computeHorizontalScrollOffset()
6720 * @see android.widget.ScrollBarDrawable
6721 */
6722 protected int computeHorizontalScrollRange() {
6723 return getWidth();
6724 }
6725
6726 /**
6727 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
6728 * within the horizontal range. This value is used to compute the position
6729 * of the thumb within the scrollbar's track.</p>
6730 *
6731 * <p>The range is expressed in arbitrary units that must be the same as the
6732 * units used by {@link #computeHorizontalScrollRange()} and
6733 * {@link #computeHorizontalScrollExtent()}.</p>
6734 *
6735 * <p>The default offset is the scroll offset of this view.</p>
6736 *
6737 * @return the horizontal offset of the scrollbar's thumb
6738 *
6739 * @see #computeHorizontalScrollRange()
6740 * @see #computeHorizontalScrollExtent()
6741 * @see android.widget.ScrollBarDrawable
6742 */
6743 protected int computeHorizontalScrollOffset() {
6744 return mScrollX;
6745 }
6746
6747 /**
6748 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
6749 * within the horizontal range. This value is used to compute the length
6750 * of the thumb within the scrollbar's track.</p>
6751 *
6752 * <p>The range is expressed in arbitrary units that must be the same as the
6753 * units used by {@link #computeHorizontalScrollRange()} and
6754 * {@link #computeHorizontalScrollOffset()}.</p>
6755 *
6756 * <p>The default extent is the drawing width of this view.</p>
6757 *
6758 * @return the horizontal extent of the scrollbar's thumb
6759 *
6760 * @see #computeHorizontalScrollRange()
6761 * @see #computeHorizontalScrollOffset()
6762 * @see android.widget.ScrollBarDrawable
6763 */
6764 protected int computeHorizontalScrollExtent() {
6765 return getWidth();
6766 }
6767
6768 /**
6769 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
6770 *
6771 * <p>The range is expressed in arbitrary units that must be the same as the
6772 * units used by {@link #computeVerticalScrollExtent()} and
6773 * {@link #computeVerticalScrollOffset()}.</p>
6774 *
6775 * @return the total vertical range represented by the vertical scrollbar
6776 *
6777 * <p>The default range is the drawing height of this view.</p>
6778 *
6779 * @see #computeVerticalScrollExtent()
6780 * @see #computeVerticalScrollOffset()
6781 * @see android.widget.ScrollBarDrawable
6782 */
6783 protected int computeVerticalScrollRange() {
6784 return getHeight();
6785 }
6786
6787 /**
6788 * <p>Compute the vertical offset of the vertical scrollbar's thumb
6789 * within the horizontal range. This value is used to compute the position
6790 * of the thumb within the scrollbar's track.</p>
6791 *
6792 * <p>The range is expressed in arbitrary units that must be the same as the
6793 * units used by {@link #computeVerticalScrollRange()} and
6794 * {@link #computeVerticalScrollExtent()}.</p>
6795 *
6796 * <p>The default offset is the scroll offset of this view.</p>
6797 *
6798 * @return the vertical offset of the scrollbar's thumb
6799 *
6800 * @see #computeVerticalScrollRange()
6801 * @see #computeVerticalScrollExtent()
6802 * @see android.widget.ScrollBarDrawable
6803 */
6804 protected int computeVerticalScrollOffset() {
6805 return mScrollY;
6806 }
6807
6808 /**
6809 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
6810 * within the vertical range. This value is used to compute the length
6811 * of the thumb within the scrollbar's track.</p>
6812 *
6813 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08006814 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 * {@link #computeVerticalScrollOffset()}.</p>
6816 *
6817 * <p>The default extent is the drawing height of this view.</p>
6818 *
6819 * @return the vertical extent of the scrollbar's thumb
6820 *
6821 * @see #computeVerticalScrollRange()
6822 * @see #computeVerticalScrollOffset()
6823 * @see android.widget.ScrollBarDrawable
6824 */
6825 protected int computeVerticalScrollExtent() {
6826 return getHeight();
6827 }
6828
6829 /**
6830 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
6831 * scrollbars are painted only if they have been awakened first.</p>
6832 *
6833 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07006834 *
6835 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08006837 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 // scrollbars are drawn only when the animation is running
6839 final ScrollabilityCache cache = mScrollCache;
6840 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006841
6842 int state = cache.state;
6843
6844 if (state == ScrollabilityCache.OFF) {
6845 return;
6846 }
6847
6848 boolean invalidate = false;
6849
6850 if (state == ScrollabilityCache.FADING) {
6851 // We're fading -- get our fade interpolation
6852 if (cache.interpolatorValues == null) {
6853 cache.interpolatorValues = new float[1];
6854 }
6855
6856 float[] values = cache.interpolatorValues;
6857
6858 // Stops the animation if we're done
6859 if (cache.scrollBarInterpolator.timeToValues(values) ==
6860 Interpolator.Result.FREEZE_END) {
6861 cache.state = ScrollabilityCache.OFF;
6862 } else {
6863 cache.scrollBar.setAlpha(Math.round(values[0]));
6864 }
6865
6866 // This will make the scroll bars inval themselves after
6867 // drawing. We only want this when we're fading so that
6868 // we prevent excessive redraws
6869 invalidate = true;
6870 } else {
6871 // We're just on -- but we may have been fading before so
6872 // reset alpha
6873 cache.scrollBar.setAlpha(255);
6874 }
6875
6876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006877 final int viewFlags = mViewFlags;
6878
6879 final boolean drawHorizontalScrollBar =
6880 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6881 final boolean drawVerticalScrollBar =
6882 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
6883 && !isVerticalScrollBarHidden();
6884
6885 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
6886 final int width = mRight - mLeft;
6887 final int height = mBottom - mTop;
6888
6889 final ScrollBarDrawable scrollBar = cache.scrollBar;
6890 int size = scrollBar.getSize(false);
6891 if (size <= 0) {
6892 size = cache.scrollBarSize;
6893 }
6894
Mike Reede8853fc2009-09-04 14:01:48 -04006895 final int scrollX = mScrollX;
6896 final int scrollY = mScrollY;
6897 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
6898
Mike Cleronf116bf82009-09-27 19:14:12 -07006899 int left, top, right, bottom;
6900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006901 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006902 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04006903 computeHorizontalScrollOffset(),
6904 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04006905 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07006906 getVerticalScrollbarWidth() : 0;
6907 top = scrollY + height - size - (mUserPaddingBottom & inside);
6908 left = scrollX + (mPaddingLeft & inside);
6909 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
6910 bottom = top + size;
6911 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
6912 if (invalidate) {
6913 invalidate(left, top, right, bottom);
6914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006915 }
6916
6917 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04006918 scrollBar.setParameters(computeVerticalScrollRange(),
6919 computeVerticalScrollOffset(),
6920 computeVerticalScrollExtent(), true);
6921 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07006922 left = scrollX + width - size - (mUserPaddingRight & inside);
6923 top = scrollY + (mPaddingTop & inside);
6924 right = left + size;
6925 bottom = scrollY + height - (mUserPaddingBottom & inside);
6926 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
6927 if (invalidate) {
6928 invalidate(left, top, right, bottom);
6929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006930 }
6931 }
6932 }
6933 }
Romain Guy8506ab42009-06-11 17:35:47 -07006934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006935 /**
Romain Guy8506ab42009-06-11 17:35:47 -07006936 * 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 -08006937 * FastScroller is visible.
6938 * @return whether to temporarily hide the vertical scrollbar
6939 * @hide
6940 */
6941 protected boolean isVerticalScrollBarHidden() {
6942 return false;
6943 }
6944
6945 /**
6946 * <p>Draw the horizontal scrollbar if
6947 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
6948 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006949 * @param canvas the canvas on which to draw the scrollbar
6950 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 *
6952 * @see #isHorizontalScrollBarEnabled()
6953 * @see #computeHorizontalScrollRange()
6954 * @see #computeHorizontalScrollExtent()
6955 * @see #computeHorizontalScrollOffset()
6956 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07006957 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006958 */
Romain Guy8fb95422010-08-17 18:38:51 -07006959 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
6960 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006961 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006962 scrollBar.draw(canvas);
6963 }
Mike Reede8853fc2009-09-04 14:01:48 -04006964
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006965 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006966 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
6967 * returns true.</p>
6968 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 * @param canvas the canvas on which to draw the scrollbar
6970 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006971 *
6972 * @see #isVerticalScrollBarEnabled()
6973 * @see #computeVerticalScrollRange()
6974 * @see #computeVerticalScrollExtent()
6975 * @see #computeVerticalScrollOffset()
6976 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04006977 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 */
Romain Guy8fb95422010-08-17 18:38:51 -07006979 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
6980 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04006981 scrollBar.setBounds(l, t, r, b);
6982 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006983 }
6984
6985 /**
6986 * Implement this to do your drawing.
6987 *
6988 * @param canvas the canvas on which the background will be drawn
6989 */
6990 protected void onDraw(Canvas canvas) {
6991 }
6992
6993 /*
6994 * Caller is responsible for calling requestLayout if necessary.
6995 * (This allows addViewInLayout to not request a new layout.)
6996 */
6997 void assignParent(ViewParent parent) {
6998 if (mParent == null) {
6999 mParent = parent;
7000 } else if (parent == null) {
7001 mParent = null;
7002 } else {
7003 throw new RuntimeException("view " + this + " being added, but"
7004 + " it already has a parent");
7005 }
7006 }
7007
7008 /**
7009 * This is called when the view is attached to a window. At this point it
7010 * has a Surface and will start drawing. Note that this function is
7011 * guaranteed to be called before {@link #onDraw}, however it may be called
7012 * any time before the first onDraw -- including before or after
7013 * {@link #onMeasure}.
7014 *
7015 * @see #onDetachedFromWindow()
7016 */
7017 protected void onAttachedToWindow() {
7018 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7019 mParent.requestTransparentRegion(this);
7020 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007021 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7022 initialAwakenScrollBars();
7023 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007025 }
7026
7027 /**
7028 * This is called when the view is detached from a window. At this point it
7029 * no longer has a surface for drawing.
7030 *
7031 * @see #onAttachedToWindow()
7032 */
7033 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007034 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08007035 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007036 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 destroyDrawingCache();
7038 }
7039
7040 /**
7041 * @return The number of times this view has been attached to a window
7042 */
7043 protected int getWindowAttachCount() {
7044 return mWindowAttachCount;
7045 }
7046
7047 /**
7048 * Retrieve a unique token identifying the window this view is attached to.
7049 * @return Return the window's token for use in
7050 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7051 */
7052 public IBinder getWindowToken() {
7053 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7054 }
7055
7056 /**
7057 * Retrieve a unique token identifying the top-level "real" window of
7058 * the window that this view is attached to. That is, this is like
7059 * {@link #getWindowToken}, except if the window this view in is a panel
7060 * window (attached to another containing window), then the token of
7061 * the containing window is returned instead.
7062 *
7063 * @return Returns the associated window token, either
7064 * {@link #getWindowToken()} or the containing window's token.
7065 */
7066 public IBinder getApplicationWindowToken() {
7067 AttachInfo ai = mAttachInfo;
7068 if (ai != null) {
7069 IBinder appWindowToken = ai.mPanelParentWindowToken;
7070 if (appWindowToken == null) {
7071 appWindowToken = ai.mWindowToken;
7072 }
7073 return appWindowToken;
7074 }
7075 return null;
7076 }
7077
7078 /**
7079 * Retrieve private session object this view hierarchy is using to
7080 * communicate with the window manager.
7081 * @return the session object to communicate with the window manager
7082 */
7083 /*package*/ IWindowSession getWindowSession() {
7084 return mAttachInfo != null ? mAttachInfo.mSession : null;
7085 }
7086
7087 /**
7088 * @param info the {@link android.view.View.AttachInfo} to associated with
7089 * this view
7090 */
7091 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7092 //System.out.println("Attached! " + this);
7093 mAttachInfo = info;
7094 mWindowAttachCount++;
7095 if (mFloatingTreeObserver != null) {
7096 info.mTreeObserver.merge(mFloatingTreeObserver);
7097 mFloatingTreeObserver = null;
7098 }
7099 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7100 mAttachInfo.mScrollContainers.add(this);
7101 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7102 }
7103 performCollectViewAttributes(visibility);
7104 onAttachedToWindow();
7105 int vis = info.mWindowVisibility;
7106 if (vis != GONE) {
7107 onWindowVisibilityChanged(vis);
7108 }
7109 }
7110
7111 void dispatchDetachedFromWindow() {
7112 //System.out.println("Detached! " + this);
7113 AttachInfo info = mAttachInfo;
7114 if (info != null) {
7115 int vis = info.mWindowVisibility;
7116 if (vis != GONE) {
7117 onWindowVisibilityChanged(GONE);
7118 }
7119 }
7120
7121 onDetachedFromWindow();
7122 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7123 mAttachInfo.mScrollContainers.remove(this);
7124 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7125 }
7126 mAttachInfo = null;
7127 }
7128
7129 /**
7130 * Store this view hierarchy's frozen state into the given container.
7131 *
7132 * @param container The SparseArray in which to save the view's state.
7133 *
7134 * @see #restoreHierarchyState
7135 * @see #dispatchSaveInstanceState
7136 * @see #onSaveInstanceState
7137 */
7138 public void saveHierarchyState(SparseArray<Parcelable> container) {
7139 dispatchSaveInstanceState(container);
7140 }
7141
7142 /**
7143 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7144 * May be overridden to modify how freezing happens to a view's children; for example, some
7145 * views may want to not store state for their children.
7146 *
7147 * @param container The SparseArray in which to save the view's state.
7148 *
7149 * @see #dispatchRestoreInstanceState
7150 * @see #saveHierarchyState
7151 * @see #onSaveInstanceState
7152 */
7153 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7154 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7155 mPrivateFlags &= ~SAVE_STATE_CALLED;
7156 Parcelable state = onSaveInstanceState();
7157 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7158 throw new IllegalStateException(
7159 "Derived class did not call super.onSaveInstanceState()");
7160 }
7161 if (state != null) {
7162 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7163 // + ": " + state);
7164 container.put(mID, state);
7165 }
7166 }
7167 }
7168
7169 /**
7170 * Hook allowing a view to generate a representation of its internal state
7171 * that can later be used to create a new instance with that same state.
7172 * This state should only contain information that is not persistent or can
7173 * not be reconstructed later. For example, you will never store your
7174 * current position on screen because that will be computed again when a
7175 * new instance of the view is placed in its view hierarchy.
7176 * <p>
7177 * Some examples of things you may store here: the current cursor position
7178 * in a text view (but usually not the text itself since that is stored in a
7179 * content provider or other persistent storage), the currently selected
7180 * item in a list view.
7181 *
7182 * @return Returns a Parcelable object containing the view's current dynamic
7183 * state, or null if there is nothing interesting to save. The
7184 * default implementation returns null.
7185 * @see #onRestoreInstanceState
7186 * @see #saveHierarchyState
7187 * @see #dispatchSaveInstanceState
7188 * @see #setSaveEnabled(boolean)
7189 */
7190 protected Parcelable onSaveInstanceState() {
7191 mPrivateFlags |= SAVE_STATE_CALLED;
7192 return BaseSavedState.EMPTY_STATE;
7193 }
7194
7195 /**
7196 * Restore this view hierarchy's frozen state from the given container.
7197 *
7198 * @param container The SparseArray which holds previously frozen states.
7199 *
7200 * @see #saveHierarchyState
7201 * @see #dispatchRestoreInstanceState
7202 * @see #onRestoreInstanceState
7203 */
7204 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7205 dispatchRestoreInstanceState(container);
7206 }
7207
7208 /**
7209 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7210 * children. May be overridden to modify how restoreing happens to a view's children; for
7211 * example, some views may want to not store state for their children.
7212 *
7213 * @param container The SparseArray which holds previously saved state.
7214 *
7215 * @see #dispatchSaveInstanceState
7216 * @see #restoreHierarchyState
7217 * @see #onRestoreInstanceState
7218 */
7219 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7220 if (mID != NO_ID) {
7221 Parcelable state = container.get(mID);
7222 if (state != null) {
7223 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7224 // + ": " + state);
7225 mPrivateFlags &= ~SAVE_STATE_CALLED;
7226 onRestoreInstanceState(state);
7227 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7228 throw new IllegalStateException(
7229 "Derived class did not call super.onRestoreInstanceState()");
7230 }
7231 }
7232 }
7233 }
7234
7235 /**
7236 * Hook allowing a view to re-apply a representation of its internal state that had previously
7237 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7238 * null state.
7239 *
7240 * @param state The frozen state that had previously been returned by
7241 * {@link #onSaveInstanceState}.
7242 *
7243 * @see #onSaveInstanceState
7244 * @see #restoreHierarchyState
7245 * @see #dispatchRestoreInstanceState
7246 */
7247 protected void onRestoreInstanceState(Parcelable state) {
7248 mPrivateFlags |= SAVE_STATE_CALLED;
7249 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007250 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7251 + "received " + state.getClass().toString() + " instead. This usually happens "
7252 + "when two views of different type have the same id in the same hierarchy. "
7253 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7254 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 }
7256 }
7257
7258 /**
7259 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7260 *
7261 * @return the drawing start time in milliseconds
7262 */
7263 public long getDrawingTime() {
7264 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7265 }
7266
7267 /**
7268 * <p>Enables or disables the duplication of the parent's state into this view. When
7269 * duplication is enabled, this view gets its drawable state from its parent rather
7270 * than from its own internal properties.</p>
7271 *
7272 * <p>Note: in the current implementation, setting this property to true after the
7273 * view was added to a ViewGroup might have no effect at all. This property should
7274 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7275 *
7276 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7277 * property is enabled, an exception will be thrown.</p>
7278 *
7279 * @param enabled True to enable duplication of the parent's drawable state, false
7280 * to disable it.
7281 *
7282 * @see #getDrawableState()
7283 * @see #isDuplicateParentStateEnabled()
7284 */
7285 public void setDuplicateParentStateEnabled(boolean enabled) {
7286 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7287 }
7288
7289 /**
7290 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7291 *
7292 * @return True if this view's drawable state is duplicated from the parent,
7293 * false otherwise
7294 *
7295 * @see #getDrawableState()
7296 * @see #setDuplicateParentStateEnabled(boolean)
7297 */
7298 public boolean isDuplicateParentStateEnabled() {
7299 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7300 }
7301
7302 /**
7303 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
7304 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
7305 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
7306 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
7307 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
7308 * null.</p>
7309 *
7310 * @param enabled true to enable the drawing cache, false otherwise
7311 *
7312 * @see #isDrawingCacheEnabled()
7313 * @see #getDrawingCache()
7314 * @see #buildDrawingCache()
7315 */
7316 public void setDrawingCacheEnabled(boolean enabled) {
7317 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
7318 }
7319
7320 /**
7321 * <p>Indicates whether the drawing cache is enabled for this view.</p>
7322 *
7323 * @return true if the drawing cache is enabled
7324 *
7325 * @see #setDrawingCacheEnabled(boolean)
7326 * @see #getDrawingCache()
7327 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07007328 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329 public boolean isDrawingCacheEnabled() {
7330 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
7331 }
7332
7333 /**
Romain Guyb051e892010-09-28 19:09:36 -07007334 * <p>Returns a display list that can be used to draw this view again
7335 * without executing its draw method.</p>
7336 *
7337 * @return A DisplayList ready to replay, or null if caching is not enabled.
7338 */
7339 DisplayList getDisplayList() {
7340 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7341 return null;
7342 }
7343
7344 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
7345 return null;
7346 }
7347
7348 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
7349 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mDisplayList == null)) {
7350
7351 if (mDisplayList != null) {
7352 mDisplayList.destroy();
7353 }
7354
7355 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
7356
7357 final HardwareCanvas canvas = mDisplayList.start();
7358 try {
7359 int width = mRight - mLeft;
7360 int height = mBottom - mTop;
7361
7362 canvas.setViewport(width, height);
7363 canvas.onPreDraw();
7364
7365 final int restoreCount = canvas.save();
7366
7367 mPrivateFlags |= DRAWN;
7368 mPrivateFlags |= DRAWING_CACHE_VALID;
7369
7370 // Fast path for layouts with no backgrounds
7371 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7372 mPrivateFlags &= ~DIRTY_MASK;
7373 dispatchDraw(canvas);
7374 } else {
7375 draw(canvas);
7376 }
7377
7378 canvas.restoreToCount(restoreCount);
7379 } finally {
7380 canvas.onPostDraw();
7381
7382 mDisplayList.end();
7383
7384 canvas.destroy();
7385 }
7386 }
7387
7388 return mDisplayList;
7389 }
7390
7391 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007392 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
7393 *
7394 * @return A non-scaled bitmap representing this view or null if cache is disabled.
7395 *
7396 * @see #getDrawingCache(boolean)
7397 */
7398 public Bitmap getDrawingCache() {
7399 return getDrawingCache(false);
7400 }
7401
7402 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007403 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
7404 * is null when caching is disabled. If caching is enabled and the cache is not ready,
7405 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
7406 * draw from the cache when the cache is enabled. To benefit from the cache, you must
7407 * request the drawing cache by calling this method and draw it on screen if the
7408 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007409 *
7410 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7411 * this method will create a bitmap of the same size as this view. Because this bitmap
7412 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7413 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7414 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7415 * size than the view. This implies that your application must be able to handle this
7416 * size.</p>
7417 *
7418 * @param autoScale Indicates whether the generated bitmap should be scaled based on
7419 * the current density of the screen when the application is in compatibility
7420 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 *
Romain Guyfbd8f692009-06-26 14:51:58 -07007422 * @return A bitmap representing this view or null if cache is disabled.
7423 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007424 * @see #setDrawingCacheEnabled(boolean)
7425 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07007426 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007427 * @see #destroyDrawingCache()
7428 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007429 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007430 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7431 return null;
7432 }
7433 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007434 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007435 }
Romain Guy02890fd2010-08-06 17:58:44 -07007436 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007437 }
7438
7439 /**
7440 * <p>Frees the resources used by the drawing cache. If you call
7441 * {@link #buildDrawingCache()} manually without calling
7442 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7443 * should cleanup the cache with this method afterwards.</p>
7444 *
7445 * @see #setDrawingCacheEnabled(boolean)
7446 * @see #buildDrawingCache()
7447 * @see #getDrawingCache()
7448 */
7449 public void destroyDrawingCache() {
7450 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007451 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007452 mDrawingCache = null;
7453 }
Romain Guyfbd8f692009-06-26 14:51:58 -07007454 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007455 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07007456 mUnscaledDrawingCache = null;
7457 }
Romain Guyb051e892010-09-28 19:09:36 -07007458 if (mDisplayList != null) {
7459 mDisplayList.destroy();
7460 mDisplayList = null;
7461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007462 }
7463
7464 /**
7465 * Setting a solid background color for the drawing cache's bitmaps will improve
7466 * perfromance and memory usage. Note, though that this should only be used if this
7467 * view will always be drawn on top of a solid color.
7468 *
7469 * @param color The background color to use for the drawing cache's bitmap
7470 *
7471 * @see #setDrawingCacheEnabled(boolean)
7472 * @see #buildDrawingCache()
7473 * @see #getDrawingCache()
7474 */
7475 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08007476 if (color != mDrawingCacheBackgroundColor) {
7477 mDrawingCacheBackgroundColor = color;
7478 mPrivateFlags &= ~DRAWING_CACHE_VALID;
7479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 }
7481
7482 /**
7483 * @see #setDrawingCacheBackgroundColor(int)
7484 *
7485 * @return The background color to used for the drawing cache's bitmap
7486 */
7487 public int getDrawingCacheBackgroundColor() {
7488 return mDrawingCacheBackgroundColor;
7489 }
7490
7491 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007492 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
7493 *
7494 * @see #buildDrawingCache(boolean)
7495 */
7496 public void buildDrawingCache() {
7497 buildDrawingCache(false);
7498 }
7499
7500 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007501 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
7502 *
7503 * <p>If you call {@link #buildDrawingCache()} manually without calling
7504 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7505 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007506 *
7507 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7508 * this method will create a bitmap of the same size as this view. Because this bitmap
7509 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7510 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7511 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7512 * size than the view. This implies that your application must be able to handle this
7513 * size.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007514 *
7515 * @see #getDrawingCache()
7516 * @see #destroyDrawingCache()
7517 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007518 public void buildDrawingCache(boolean autoScale) {
7519 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07007520 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007521
7522 if (ViewDebug.TRACE_HIERARCHY) {
7523 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007525
Romain Guy8506ab42009-06-11 17:35:47 -07007526 int width = mRight - mLeft;
7527 int height = mBottom - mTop;
7528
7529 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007530 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007531
Romain Guye1123222009-06-29 14:24:56 -07007532 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007533 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7534 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536
7537 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007538 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Romain Guya62e4702009-10-08 10:48:54 -07007539 final boolean translucentWindow = attachInfo != null && attachInfo.mTranslucentWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007540
7541 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007542 // Projected bitmap size in bytes
7543 (width * height * (opaque && !translucentWindow ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007544 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7545 destroyDrawingCache();
7546 return;
7547 }
7548
7549 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07007550 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007551
7552 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007553 Bitmap.Config quality;
7554 if (!opaque) {
7555 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7556 case DRAWING_CACHE_QUALITY_AUTO:
7557 quality = Bitmap.Config.ARGB_8888;
7558 break;
7559 case DRAWING_CACHE_QUALITY_LOW:
7560 quality = Bitmap.Config.ARGB_4444;
7561 break;
7562 case DRAWING_CACHE_QUALITY_HIGH:
7563 quality = Bitmap.Config.ARGB_8888;
7564 break;
7565 default:
7566 quality = Bitmap.Config.ARGB_8888;
7567 break;
7568 }
7569 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07007570 // Optimization for translucent windows
7571 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
7572 quality = translucentWindow ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 }
7574
7575 // Try to cleanup memory
7576 if (bitmap != null) bitmap.recycle();
7577
7578 try {
7579 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07007580 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07007581 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07007582 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007583 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07007584 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007585 }
Romain Guy35b38ce2009-10-07 13:38:55 -07007586 if (opaque && translucentWindow) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 } catch (OutOfMemoryError e) {
7588 // If there is not enough memory to create the bitmap cache, just
7589 // ignore the issue as bitmap caches are not required to draw the
7590 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07007591 if (autoScale) {
7592 mDrawingCache = null;
7593 } else {
7594 mUnscaledDrawingCache = null;
7595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 return;
7597 }
7598
7599 clear = drawingCacheBackgroundColor != 0;
7600 }
7601
7602 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603 if (attachInfo != null) {
7604 canvas = attachInfo.mCanvas;
7605 if (canvas == null) {
7606 canvas = new Canvas();
7607 }
7608 canvas.setBitmap(bitmap);
7609 // Temporarily clobber the cached Canvas in case one of our children
7610 // is also using a drawing cache. Without this, the children would
7611 // steal the canvas by attaching their own bitmap to it and bad, bad
7612 // thing would happen (invisible views, corrupted drawings, etc.)
7613 attachInfo.mCanvas = null;
7614 } else {
7615 // This case should hopefully never or seldom happen
7616 canvas = new Canvas(bitmap);
7617 }
7618
7619 if (clear) {
7620 bitmap.eraseColor(drawingCacheBackgroundColor);
7621 }
7622
7623 computeScroll();
7624 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07007625
Romain Guye1123222009-06-29 14:24:56 -07007626 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007627 final float scale = attachInfo.mApplicationScale;
7628 canvas.scale(scale, scale);
7629 }
7630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007631 canvas.translate(-mScrollX, -mScrollY);
7632
Romain Guy5bcdff42009-05-14 21:27:18 -07007633 mPrivateFlags |= DRAWN;
Romain Guyecd80ee2009-12-03 17:13:02 -08007634 mPrivateFlags |= DRAWING_CACHE_VALID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007635
7636 // Fast path for layouts with no backgrounds
7637 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7638 if (ViewDebug.TRACE_HIERARCHY) {
7639 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7640 }
Romain Guy5bcdff42009-05-14 21:27:18 -07007641 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007642 dispatchDraw(canvas);
7643 } else {
7644 draw(canvas);
7645 }
7646
7647 canvas.restoreToCount(restoreCount);
7648
7649 if (attachInfo != null) {
7650 // Restore the cached Canvas for our siblings
7651 attachInfo.mCanvas = canvas;
7652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653 }
7654 }
7655
7656 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007657 * Create a snapshot of the view into a bitmap. We should probably make
7658 * some form of this public, but should think about the API.
7659 */
Romain Guy223ff5c2010-03-02 17:07:47 -08007660 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007661 int width = mRight - mLeft;
7662 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007663
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007664 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07007665 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007666 width = (int) ((width * scale) + 0.5f);
7667 height = (int) ((height * scale) + 0.5f);
7668
Romain Guy8c11e312009-09-14 15:15:30 -07007669 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007670 if (bitmap == null) {
7671 throw new OutOfMemoryError();
7672 }
7673
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007674 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
7675
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007676 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007677 if (attachInfo != null) {
7678 canvas = attachInfo.mCanvas;
7679 if (canvas == null) {
7680 canvas = new Canvas();
7681 }
7682 canvas.setBitmap(bitmap);
7683 // Temporarily clobber the cached Canvas in case one of our children
7684 // is also using a drawing cache. Without this, the children would
7685 // steal the canvas by attaching their own bitmap to it and bad, bad
7686 // things would happen (invisible views, corrupted drawings, etc.)
7687 attachInfo.mCanvas = null;
7688 } else {
7689 // This case should hopefully never or seldom happen
7690 canvas = new Canvas(bitmap);
7691 }
7692
Romain Guy5bcdff42009-05-14 21:27:18 -07007693 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007694 bitmap.eraseColor(backgroundColor);
7695 }
7696
7697 computeScroll();
7698 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007699 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007700 canvas.translate(-mScrollX, -mScrollY);
7701
Romain Guy5bcdff42009-05-14 21:27:18 -07007702 // Temporarily remove the dirty mask
7703 int flags = mPrivateFlags;
7704 mPrivateFlags &= ~DIRTY_MASK;
7705
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007706 // Fast path for layouts with no backgrounds
7707 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7708 dispatchDraw(canvas);
7709 } else {
7710 draw(canvas);
7711 }
7712
Romain Guy5bcdff42009-05-14 21:27:18 -07007713 mPrivateFlags = flags;
7714
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007715 canvas.restoreToCount(restoreCount);
7716
7717 if (attachInfo != null) {
7718 // Restore the cached Canvas for our siblings
7719 attachInfo.mCanvas = canvas;
7720 }
Romain Guy8506ab42009-06-11 17:35:47 -07007721
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007722 return bitmap;
7723 }
7724
7725 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 * Indicates whether this View is currently in edit mode. A View is usually
7727 * in edit mode when displayed within a developer tool. For instance, if
7728 * this View is being drawn by a visual user interface builder, this method
7729 * should return true.
7730 *
7731 * Subclasses should check the return value of this method to provide
7732 * different behaviors if their normal behavior might interfere with the
7733 * host environment. For instance: the class spawns a thread in its
7734 * constructor, the drawing code relies on device-specific features, etc.
7735 *
7736 * This method is usually checked in the drawing code of custom widgets.
7737 *
7738 * @return True if this View is in edit mode, false otherwise.
7739 */
7740 public boolean isInEditMode() {
7741 return false;
7742 }
7743
7744 /**
7745 * If the View draws content inside its padding and enables fading edges,
7746 * it needs to support padding offsets. Padding offsets are added to the
7747 * fading edges to extend the length of the fade so that it covers pixels
7748 * drawn inside the padding.
7749 *
7750 * Subclasses of this class should override this method if they need
7751 * to draw content inside the padding.
7752 *
7753 * @return True if padding offset must be applied, false otherwise.
7754 *
7755 * @see #getLeftPaddingOffset()
7756 * @see #getRightPaddingOffset()
7757 * @see #getTopPaddingOffset()
7758 * @see #getBottomPaddingOffset()
7759 *
7760 * @since CURRENT
7761 */
7762 protected boolean isPaddingOffsetRequired() {
7763 return false;
7764 }
7765
7766 /**
7767 * Amount by which to extend the left fading region. Called only when
7768 * {@link #isPaddingOffsetRequired()} returns true.
7769 *
7770 * @return The left padding offset in pixels.
7771 *
7772 * @see #isPaddingOffsetRequired()
7773 *
7774 * @since CURRENT
7775 */
7776 protected int getLeftPaddingOffset() {
7777 return 0;
7778 }
7779
7780 /**
7781 * Amount by which to extend the right fading region. Called only when
7782 * {@link #isPaddingOffsetRequired()} returns true.
7783 *
7784 * @return The right padding offset in pixels.
7785 *
7786 * @see #isPaddingOffsetRequired()
7787 *
7788 * @since CURRENT
7789 */
7790 protected int getRightPaddingOffset() {
7791 return 0;
7792 }
7793
7794 /**
7795 * Amount by which to extend the top fading region. Called only when
7796 * {@link #isPaddingOffsetRequired()} returns true.
7797 *
7798 * @return The top padding offset in pixels.
7799 *
7800 * @see #isPaddingOffsetRequired()
7801 *
7802 * @since CURRENT
7803 */
7804 protected int getTopPaddingOffset() {
7805 return 0;
7806 }
7807
7808 /**
7809 * Amount by which to extend the bottom fading region. Called only when
7810 * {@link #isPaddingOffsetRequired()} returns true.
7811 *
7812 * @return The bottom padding offset in pixels.
7813 *
7814 * @see #isPaddingOffsetRequired()
7815 *
7816 * @since CURRENT
7817 */
7818 protected int getBottomPaddingOffset() {
7819 return 0;
7820 }
7821
7822 /**
Romain Guy2bffd262010-09-12 17:40:02 -07007823 * <p>Indicates whether this view is attached to an hardware accelerated
7824 * window or not.</p>
7825 *
7826 * <p>Even if this method returns true, it does not mean that every call
7827 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
7828 * accelerated {@link android.graphics.Canvas}. For instance, if this view
7829 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
7830 * window is hardware accelerated,
7831 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
7832 * return false, and this method will return true.</p>
7833 *
7834 * @return True if the view is attached to a window and the window is
7835 * hardware accelerated; false in any other case.
7836 */
7837 public boolean isHardwareAccelerated() {
7838 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
7839 }
7840
7841 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 * Manually render this view (and all of its children) to the given Canvas.
7843 * The view must have already done a full layout before this function is
7844 * called. When implementing a view, do not override this method; instead,
7845 * you should implement {@link #onDraw}.
7846 *
7847 * @param canvas The Canvas to which the View is rendered.
7848 */
7849 public void draw(Canvas canvas) {
7850 if (ViewDebug.TRACE_HIERARCHY) {
7851 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7852 }
7853
Romain Guy5bcdff42009-05-14 21:27:18 -07007854 final int privateFlags = mPrivateFlags;
7855 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
7856 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
7857 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07007858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007859 /*
7860 * Draw traversal performs several drawing steps which must be executed
7861 * in the appropriate order:
7862 *
7863 * 1. Draw the background
7864 * 2. If necessary, save the canvas' layers to prepare for fading
7865 * 3. Draw view's content
7866 * 4. Draw children
7867 * 5. If necessary, draw the fading edges and restore layers
7868 * 6. Draw decorations (scrollbars for instance)
7869 */
7870
7871 // Step 1, draw the background, if needed
7872 int saveCount;
7873
Romain Guy24443ea2009-05-11 11:56:30 -07007874 if (!dirtyOpaque) {
7875 final Drawable background = mBGDrawable;
7876 if (background != null) {
7877 final int scrollX = mScrollX;
7878 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879
Romain Guy24443ea2009-05-11 11:56:30 -07007880 if (mBackgroundSizeChanged) {
7881 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
7882 mBackgroundSizeChanged = false;
7883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884
Romain Guy24443ea2009-05-11 11:56:30 -07007885 if ((scrollX | scrollY) == 0) {
7886 background.draw(canvas);
7887 } else {
7888 canvas.translate(scrollX, scrollY);
7889 background.draw(canvas);
7890 canvas.translate(-scrollX, -scrollY);
7891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 }
7893 }
7894
7895 // skip step 2 & 5 if possible (common case)
7896 final int viewFlags = mViewFlags;
7897 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
7898 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
7899 if (!verticalEdges && !horizontalEdges) {
7900 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007901 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007902
7903 // Step 4, draw the children
7904 dispatchDraw(canvas);
7905
7906 // Step 6, draw decorations (scrollbars)
7907 onDrawScrollBars(canvas);
7908
7909 // we're done...
7910 return;
7911 }
7912
7913 /*
7914 * Here we do the full fledged routine...
7915 * (this is an uncommon case where speed matters less,
7916 * this is why we repeat some of the tests that have been
7917 * done above)
7918 */
7919
7920 boolean drawTop = false;
7921 boolean drawBottom = false;
7922 boolean drawLeft = false;
7923 boolean drawRight = false;
7924
7925 float topFadeStrength = 0.0f;
7926 float bottomFadeStrength = 0.0f;
7927 float leftFadeStrength = 0.0f;
7928 float rightFadeStrength = 0.0f;
7929
7930 // Step 2, save the canvas' layers
7931 int paddingLeft = mPaddingLeft;
7932 int paddingTop = mPaddingTop;
7933
7934 final boolean offsetRequired = isPaddingOffsetRequired();
7935 if (offsetRequired) {
7936 paddingLeft += getLeftPaddingOffset();
7937 paddingTop += getTopPaddingOffset();
7938 }
7939
7940 int left = mScrollX + paddingLeft;
7941 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
7942 int top = mScrollY + paddingTop;
7943 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
7944
7945 if (offsetRequired) {
7946 right += getRightPaddingOffset();
7947 bottom += getBottomPaddingOffset();
7948 }
7949
7950 final ScrollabilityCache scrollabilityCache = mScrollCache;
7951 int length = scrollabilityCache.fadingEdgeLength;
7952
7953 // clip the fade length if top and bottom fades overlap
7954 // overlapping fades produce odd-looking artifacts
7955 if (verticalEdges && (top + length > bottom - length)) {
7956 length = (bottom - top) / 2;
7957 }
7958
7959 // also clip horizontal fades if necessary
7960 if (horizontalEdges && (left + length > right - length)) {
7961 length = (right - left) / 2;
7962 }
7963
7964 if (verticalEdges) {
7965 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007966 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007967 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007968 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007969 }
7970
7971 if (horizontalEdges) {
7972 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007973 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007975 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007976 }
7977
7978 saveCount = canvas.getSaveCount();
7979
7980 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07007981 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
7983
7984 if (drawTop) {
7985 canvas.saveLayer(left, top, right, top + length, null, flags);
7986 }
7987
7988 if (drawBottom) {
7989 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
7990 }
7991
7992 if (drawLeft) {
7993 canvas.saveLayer(left, top, left + length, bottom, null, flags);
7994 }
7995
7996 if (drawRight) {
7997 canvas.saveLayer(right - length, top, right, bottom, null, flags);
7998 }
7999 } else {
8000 scrollabilityCache.setFadeColor(solidColor);
8001 }
8002
8003 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008004 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005
8006 // Step 4, draw the children
8007 dispatchDraw(canvas);
8008
8009 // Step 5, draw the fade effect and restore layers
8010 final Paint p = scrollabilityCache.paint;
8011 final Matrix matrix = scrollabilityCache.matrix;
8012 final Shader fade = scrollabilityCache.shader;
8013 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8014
8015 if (drawTop) {
8016 matrix.setScale(1, fadeHeight * topFadeStrength);
8017 matrix.postTranslate(left, top);
8018 fade.setLocalMatrix(matrix);
8019 canvas.drawRect(left, top, right, top + length, p);
8020 }
8021
8022 if (drawBottom) {
8023 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8024 matrix.postRotate(180);
8025 matrix.postTranslate(left, bottom);
8026 fade.setLocalMatrix(matrix);
8027 canvas.drawRect(left, bottom - length, right, bottom, p);
8028 }
8029
8030 if (drawLeft) {
8031 matrix.setScale(1, fadeHeight * leftFadeStrength);
8032 matrix.postRotate(-90);
8033 matrix.postTranslate(left, top);
8034 fade.setLocalMatrix(matrix);
8035 canvas.drawRect(left, top, left + length, bottom, p);
8036 }
8037
8038 if (drawRight) {
8039 matrix.setScale(1, fadeHeight * rightFadeStrength);
8040 matrix.postRotate(90);
8041 matrix.postTranslate(right, top);
8042 fade.setLocalMatrix(matrix);
8043 canvas.drawRect(right - length, top, right, bottom, p);
8044 }
8045
8046 canvas.restoreToCount(saveCount);
8047
8048 // Step 6, draw decorations (scrollbars)
8049 onDrawScrollBars(canvas);
8050 }
8051
8052 /**
8053 * Override this if your view is known to always be drawn on top of a solid color background,
8054 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8055 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8056 * should be set to 0xFF.
8057 *
8058 * @see #setVerticalFadingEdgeEnabled
8059 * @see #setHorizontalFadingEdgeEnabled
8060 *
8061 * @return The known solid color background for this view, or 0 if the color may vary
8062 */
8063 public int getSolidColor() {
8064 return 0;
8065 }
8066
8067 /**
8068 * Build a human readable string representation of the specified view flags.
8069 *
8070 * @param flags the view flags to convert to a string
8071 * @return a String representing the supplied flags
8072 */
8073 private static String printFlags(int flags) {
8074 String output = "";
8075 int numFlags = 0;
8076 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8077 output += "TAKES_FOCUS";
8078 numFlags++;
8079 }
8080
8081 switch (flags & VISIBILITY_MASK) {
8082 case INVISIBLE:
8083 if (numFlags > 0) {
8084 output += " ";
8085 }
8086 output += "INVISIBLE";
8087 // USELESS HERE numFlags++;
8088 break;
8089 case GONE:
8090 if (numFlags > 0) {
8091 output += " ";
8092 }
8093 output += "GONE";
8094 // USELESS HERE numFlags++;
8095 break;
8096 default:
8097 break;
8098 }
8099 return output;
8100 }
8101
8102 /**
8103 * Build a human readable string representation of the specified private
8104 * view flags.
8105 *
8106 * @param privateFlags the private view flags to convert to a string
8107 * @return a String representing the supplied flags
8108 */
8109 private static String printPrivateFlags(int privateFlags) {
8110 String output = "";
8111 int numFlags = 0;
8112
8113 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8114 output += "WANTS_FOCUS";
8115 numFlags++;
8116 }
8117
8118 if ((privateFlags & FOCUSED) == FOCUSED) {
8119 if (numFlags > 0) {
8120 output += " ";
8121 }
8122 output += "FOCUSED";
8123 numFlags++;
8124 }
8125
8126 if ((privateFlags & SELECTED) == SELECTED) {
8127 if (numFlags > 0) {
8128 output += " ";
8129 }
8130 output += "SELECTED";
8131 numFlags++;
8132 }
8133
8134 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8135 if (numFlags > 0) {
8136 output += " ";
8137 }
8138 output += "IS_ROOT_NAMESPACE";
8139 numFlags++;
8140 }
8141
8142 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8143 if (numFlags > 0) {
8144 output += " ";
8145 }
8146 output += "HAS_BOUNDS";
8147 numFlags++;
8148 }
8149
8150 if ((privateFlags & DRAWN) == DRAWN) {
8151 if (numFlags > 0) {
8152 output += " ";
8153 }
8154 output += "DRAWN";
8155 // USELESS HERE numFlags++;
8156 }
8157 return output;
8158 }
8159
8160 /**
8161 * <p>Indicates whether or not this view's layout will be requested during
8162 * the next hierarchy layout pass.</p>
8163 *
8164 * @return true if the layout will be forced during next layout pass
8165 */
8166 public boolean isLayoutRequested() {
8167 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8168 }
8169
8170 /**
8171 * Assign a size and position to a view and all of its
8172 * descendants
8173 *
8174 * <p>This is the second phase of the layout mechanism.
8175 * (The first is measuring). In this phase, each parent calls
8176 * layout on all of its children to position them.
8177 * This is typically done using the child measurements
8178 * that were stored in the measure pass().
8179 *
8180 * Derived classes with children should override
8181 * onLayout. In that method, they should
Chet Haase21cd1382010-09-01 17:42:29 -07008182 * call layout on each of their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008183 *
8184 * @param l Left position, relative to parent
8185 * @param t Top position, relative to parent
8186 * @param r Right position, relative to parent
8187 * @param b Bottom position, relative to parent
8188 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008189 @SuppressWarnings({"unchecked"})
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190 public final void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008191 int oldL = mLeft;
8192 int oldT = mTop;
8193 int oldB = mBottom;
8194 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008195 boolean changed = setFrame(l, t, r, b);
8196 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8197 if (ViewDebug.TRACE_HIERARCHY) {
8198 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8199 }
8200
8201 onLayout(changed, l, t, r, b);
8202 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008203
8204 if (mOnLayoutChangeListeners != null) {
8205 ArrayList<OnLayoutChangeListener> listenersCopy =
8206 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8207 int numListeners = listenersCopy.size();
8208 for (int i = 0; i < numListeners; ++i) {
8209 listenersCopy.get(i).onLayoutChange(this, l, r, t, b, oldL, oldT, oldR, oldB);
8210 }
8211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008212 }
8213 mPrivateFlags &= ~FORCE_LAYOUT;
8214 }
8215
8216 /**
8217 * Called from layout when this view should
8218 * assign a size and position to each of its children.
8219 *
8220 * Derived classes with children should override
8221 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008222 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008223 * @param changed This is a new size or position for this view
8224 * @param left Left position, relative to parent
8225 * @param top Top position, relative to parent
8226 * @param right Right position, relative to parent
8227 * @param bottom Bottom position, relative to parent
8228 */
8229 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8230 }
8231
8232 /**
8233 * Assign a size and position to this view.
8234 *
8235 * This is called from layout.
8236 *
8237 * @param left Left position, relative to parent
8238 * @param top Top position, relative to parent
8239 * @param right Right position, relative to parent
8240 * @param bottom Bottom position, relative to parent
8241 * @return true if the new size and position are different than the
8242 * previous ones
8243 * {@hide}
8244 */
8245 protected boolean setFrame(int left, int top, int right, int bottom) {
8246 boolean changed = false;
8247
8248 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008249 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008250 + right + "," + bottom + ")");
8251 }
8252
8253 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8254 changed = true;
8255
8256 // Remember our drawn bit
8257 int drawn = mPrivateFlags & DRAWN;
8258
8259 // Invalidate our old position
8260 invalidate();
8261
8262
8263 int oldWidth = mRight - mLeft;
8264 int oldHeight = mBottom - mTop;
8265
8266 mLeft = left;
8267 mTop = top;
8268 mRight = right;
8269 mBottom = bottom;
8270
8271 mPrivateFlags |= HAS_BOUNDS;
8272
8273 int newWidth = right - left;
8274 int newHeight = bottom - top;
8275
8276 if (newWidth != oldWidth || newHeight != oldHeight) {
8277 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8278 }
8279
8280 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8281 // If we are visible, force the DRAWN bit to on so that
8282 // this invalidate will go through (at least to our parent).
8283 // This is because someone may have invalidated this view
8284 // before this call to setFrame came in, therby clearing
8285 // the DRAWN bit.
8286 mPrivateFlags |= DRAWN;
8287 invalidate();
8288 }
8289
8290 // Reset drawn bit to original value (invalidate turns it off)
8291 mPrivateFlags |= drawn;
8292
8293 mBackgroundSizeChanged = true;
8294 }
8295 return changed;
8296 }
8297
8298 /**
8299 * Finalize inflating a view from XML. This is called as the last phase
8300 * of inflation, after all child views have been added.
8301 *
8302 * <p>Even if the subclass overrides onFinishInflate, they should always be
8303 * sure to call the super method, so that we get called.
8304 */
8305 protected void onFinishInflate() {
8306 }
8307
8308 /**
8309 * Returns the resources associated with this view.
8310 *
8311 * @return Resources object.
8312 */
8313 public Resources getResources() {
8314 return mResources;
8315 }
8316
8317 /**
8318 * Invalidates the specified Drawable.
8319 *
8320 * @param drawable the drawable to invalidate
8321 */
8322 public void invalidateDrawable(Drawable drawable) {
8323 if (verifyDrawable(drawable)) {
8324 final Rect dirty = drawable.getBounds();
8325 final int scrollX = mScrollX;
8326 final int scrollY = mScrollY;
8327
8328 invalidate(dirty.left + scrollX, dirty.top + scrollY,
8329 dirty.right + scrollX, dirty.bottom + scrollY);
8330 }
8331 }
8332
8333 /**
8334 * Schedules an action on a drawable to occur at a specified time.
8335 *
8336 * @param who the recipient of the action
8337 * @param what the action to run on the drawable
8338 * @param when the time at which the action must occur. Uses the
8339 * {@link SystemClock#uptimeMillis} timebase.
8340 */
8341 public void scheduleDrawable(Drawable who, Runnable what, long when) {
8342 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8343 mAttachInfo.mHandler.postAtTime(what, who, when);
8344 }
8345 }
8346
8347 /**
8348 * Cancels a scheduled action on a drawable.
8349 *
8350 * @param who the recipient of the action
8351 * @param what the action to cancel
8352 */
8353 public void unscheduleDrawable(Drawable who, Runnable what) {
8354 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8355 mAttachInfo.mHandler.removeCallbacks(what, who);
8356 }
8357 }
8358
8359 /**
8360 * Unschedule any events associated with the given Drawable. This can be
8361 * used when selecting a new Drawable into a view, so that the previous
8362 * one is completely unscheduled.
8363 *
8364 * @param who The Drawable to unschedule.
8365 *
8366 * @see #drawableStateChanged
8367 */
8368 public void unscheduleDrawable(Drawable who) {
8369 if (mAttachInfo != null) {
8370 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
8371 }
8372 }
8373
8374 /**
8375 * If your view subclass is displaying its own Drawable objects, it should
8376 * override this function and return true for any Drawable it is
8377 * displaying. This allows animations for those drawables to be
8378 * scheduled.
8379 *
8380 * <p>Be sure to call through to the super class when overriding this
8381 * function.
8382 *
8383 * @param who The Drawable to verify. Return true if it is one you are
8384 * displaying, else return the result of calling through to the
8385 * super class.
8386 *
8387 * @return boolean If true than the Drawable is being displayed in the
8388 * view; else false and it is not allowed to animate.
8389 *
8390 * @see #unscheduleDrawable
8391 * @see #drawableStateChanged
8392 */
8393 protected boolean verifyDrawable(Drawable who) {
8394 return who == mBGDrawable;
8395 }
8396
8397 /**
8398 * This function is called whenever the state of the view changes in such
8399 * a way that it impacts the state of drawables being shown.
8400 *
8401 * <p>Be sure to call through to the superclass when overriding this
8402 * function.
8403 *
8404 * @see Drawable#setState
8405 */
8406 protected void drawableStateChanged() {
8407 Drawable d = mBGDrawable;
8408 if (d != null && d.isStateful()) {
8409 d.setState(getDrawableState());
8410 }
8411 }
8412
8413 /**
8414 * Call this to force a view to update its drawable state. This will cause
8415 * drawableStateChanged to be called on this view. Views that are interested
8416 * in the new state should call getDrawableState.
8417 *
8418 * @see #drawableStateChanged
8419 * @see #getDrawableState
8420 */
8421 public void refreshDrawableState() {
8422 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
8423 drawableStateChanged();
8424
8425 ViewParent parent = mParent;
8426 if (parent != null) {
8427 parent.childDrawableStateChanged(this);
8428 }
8429 }
8430
8431 /**
8432 * Return an array of resource IDs of the drawable states representing the
8433 * current state of the view.
8434 *
8435 * @return The current drawable state
8436 *
8437 * @see Drawable#setState
8438 * @see #drawableStateChanged
8439 * @see #onCreateDrawableState
8440 */
8441 public final int[] getDrawableState() {
8442 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
8443 return mDrawableState;
8444 } else {
8445 mDrawableState = onCreateDrawableState(0);
8446 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
8447 return mDrawableState;
8448 }
8449 }
8450
8451 /**
8452 * Generate the new {@link android.graphics.drawable.Drawable} state for
8453 * this view. This is called by the view
8454 * system when the cached Drawable state is determined to be invalid. To
8455 * retrieve the current state, you should use {@link #getDrawableState}.
8456 *
8457 * @param extraSpace if non-zero, this is the number of extra entries you
8458 * would like in the returned array in which you can place your own
8459 * states.
8460 *
8461 * @return Returns an array holding the current {@link Drawable} state of
8462 * the view.
8463 *
8464 * @see #mergeDrawableStates
8465 */
8466 protected int[] onCreateDrawableState(int extraSpace) {
8467 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
8468 mParent instanceof View) {
8469 return ((View) mParent).onCreateDrawableState(extraSpace);
8470 }
8471
8472 int[] drawableState;
8473
8474 int privateFlags = mPrivateFlags;
8475
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008476 int viewStateIndex = 0;
8477 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
8478 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
8479 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
8480 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
8481 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
8482 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008483
8484 drawableState = VIEW_STATE_SETS[viewStateIndex];
8485
8486 //noinspection ConstantIfStatement
8487 if (false) {
8488 Log.i("View", "drawableStateIndex=" + viewStateIndex);
8489 Log.i("View", toString()
8490 + " pressed=" + ((privateFlags & PRESSED) != 0)
8491 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
8492 + " fo=" + hasFocus()
8493 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008494 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008495 + ": " + Arrays.toString(drawableState));
8496 }
8497
8498 if (extraSpace == 0) {
8499 return drawableState;
8500 }
8501
8502 final int[] fullState;
8503 if (drawableState != null) {
8504 fullState = new int[drawableState.length + extraSpace];
8505 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
8506 } else {
8507 fullState = new int[extraSpace];
8508 }
8509
8510 return fullState;
8511 }
8512
8513 /**
8514 * Merge your own state values in <var>additionalState</var> into the base
8515 * state values <var>baseState</var> that were returned by
8516 * {@link #onCreateDrawableState}.
8517 *
8518 * @param baseState The base state values returned by
8519 * {@link #onCreateDrawableState}, which will be modified to also hold your
8520 * own additional state values.
8521 *
8522 * @param additionalState The additional state values you would like
8523 * added to <var>baseState</var>; this array is not modified.
8524 *
8525 * @return As a convenience, the <var>baseState</var> array you originally
8526 * passed into the function is returned.
8527 *
8528 * @see #onCreateDrawableState
8529 */
8530 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
8531 final int N = baseState.length;
8532 int i = N - 1;
8533 while (i >= 0 && baseState[i] == 0) {
8534 i--;
8535 }
8536 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
8537 return baseState;
8538 }
8539
8540 /**
8541 * Sets the background color for this view.
8542 * @param color the color of the background
8543 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008544 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008545 public void setBackgroundColor(int color) {
8546 setBackgroundDrawable(new ColorDrawable(color));
8547 }
8548
8549 /**
8550 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07008551 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552 * @param resid The identifier of the resource.
8553 * @attr ref android.R.styleable#View_background
8554 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008555 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 public void setBackgroundResource(int resid) {
8557 if (resid != 0 && resid == mBackgroundResource) {
8558 return;
8559 }
8560
8561 Drawable d= null;
8562 if (resid != 0) {
8563 d = mResources.getDrawable(resid);
8564 }
8565 setBackgroundDrawable(d);
8566
8567 mBackgroundResource = resid;
8568 }
8569
8570 /**
8571 * Set the background to a given Drawable, or remove the background. If the
8572 * background has padding, this View's padding is set to the background's
8573 * padding. However, when a background is removed, this View's padding isn't
8574 * touched. If setting the padding is desired, please use
8575 * {@link #setPadding(int, int, int, int)}.
8576 *
8577 * @param d The Drawable to use as the background, or null to remove the
8578 * background
8579 */
8580 public void setBackgroundDrawable(Drawable d) {
8581 boolean requestLayout = false;
8582
8583 mBackgroundResource = 0;
8584
8585 /*
8586 * Regardless of whether we're setting a new background or not, we want
8587 * to clear the previous drawable.
8588 */
8589 if (mBGDrawable != null) {
8590 mBGDrawable.setCallback(null);
8591 unscheduleDrawable(mBGDrawable);
8592 }
8593
8594 if (d != null) {
8595 Rect padding = sThreadLocal.get();
8596 if (padding == null) {
8597 padding = new Rect();
8598 sThreadLocal.set(padding);
8599 }
8600 if (d.getPadding(padding)) {
8601 setPadding(padding.left, padding.top, padding.right, padding.bottom);
8602 }
8603
8604 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
8605 // if it has a different minimum size, we should layout again
8606 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
8607 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
8608 requestLayout = true;
8609 }
8610
8611 d.setCallback(this);
8612 if (d.isStateful()) {
8613 d.setState(getDrawableState());
8614 }
8615 d.setVisible(getVisibility() == VISIBLE, false);
8616 mBGDrawable = d;
8617
8618 if ((mPrivateFlags & SKIP_DRAW) != 0) {
8619 mPrivateFlags &= ~SKIP_DRAW;
8620 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8621 requestLayout = true;
8622 }
8623 } else {
8624 /* Remove the background */
8625 mBGDrawable = null;
8626
8627 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
8628 /*
8629 * This view ONLY drew the background before and we're removing
8630 * the background, so now it won't draw anything
8631 * (hence we SKIP_DRAW)
8632 */
8633 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
8634 mPrivateFlags |= SKIP_DRAW;
8635 }
8636
8637 /*
8638 * When the background is set, we try to apply its padding to this
8639 * View. When the background is removed, we don't touch this View's
8640 * padding. This is noted in the Javadocs. Hence, we don't need to
8641 * requestLayout(), the invalidate() below is sufficient.
8642 */
8643
8644 // The old background's minimum size could have affected this
8645 // View's layout, so let's requestLayout
8646 requestLayout = true;
8647 }
8648
Romain Guy8f1344f52009-05-15 16:03:59 -07008649 computeOpaqueFlags();
8650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651 if (requestLayout) {
8652 requestLayout();
8653 }
8654
8655 mBackgroundSizeChanged = true;
8656 invalidate();
8657 }
8658
8659 /**
8660 * Gets the background drawable
8661 * @return The drawable used as the background for this view, if any.
8662 */
8663 public Drawable getBackground() {
8664 return mBGDrawable;
8665 }
8666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008667 /**
8668 * Sets the padding. The view may add on the space required to display
8669 * the scrollbars, depending on the style and visibility of the scrollbars.
8670 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
8671 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
8672 * from the values set in this call.
8673 *
8674 * @attr ref android.R.styleable#View_padding
8675 * @attr ref android.R.styleable#View_paddingBottom
8676 * @attr ref android.R.styleable#View_paddingLeft
8677 * @attr ref android.R.styleable#View_paddingRight
8678 * @attr ref android.R.styleable#View_paddingTop
8679 * @param left the left padding in pixels
8680 * @param top the top padding in pixels
8681 * @param right the right padding in pixels
8682 * @param bottom the bottom padding in pixels
8683 */
8684 public void setPadding(int left, int top, int right, int bottom) {
8685 boolean changed = false;
8686
8687 mUserPaddingRight = right;
8688 mUserPaddingBottom = bottom;
8689
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008690 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07008691
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008692 // Common case is there are no scroll bars.
8693 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
8694 // TODO: Deal with RTL languages to adjust left padding instead of right.
8695 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
8696 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8697 ? 0 : getVerticalScrollbarWidth();
8698 }
8699 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
8700 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8701 ? 0 : getHorizontalScrollbarHeight();
8702 }
8703 }
Romain Guy8506ab42009-06-11 17:35:47 -07008704
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008705 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 changed = true;
8707 mPaddingLeft = left;
8708 }
8709 if (mPaddingTop != top) {
8710 changed = true;
8711 mPaddingTop = top;
8712 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008713 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008715 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008717 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008719 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 }
8721
8722 if (changed) {
8723 requestLayout();
8724 }
8725 }
8726
8727 /**
8728 * Returns the top padding of this view.
8729 *
8730 * @return the top padding in pixels
8731 */
8732 public int getPaddingTop() {
8733 return mPaddingTop;
8734 }
8735
8736 /**
8737 * Returns the bottom padding of this view. If there are inset and enabled
8738 * scrollbars, this value may include the space required to display the
8739 * scrollbars as well.
8740 *
8741 * @return the bottom padding in pixels
8742 */
8743 public int getPaddingBottom() {
8744 return mPaddingBottom;
8745 }
8746
8747 /**
8748 * Returns the left padding of this view. If there are inset and enabled
8749 * scrollbars, this value may include the space required to display the
8750 * scrollbars as well.
8751 *
8752 * @return the left padding in pixels
8753 */
8754 public int getPaddingLeft() {
8755 return mPaddingLeft;
8756 }
8757
8758 /**
8759 * Returns the right padding of this view. If there are inset and enabled
8760 * scrollbars, this value may include the space required to display the
8761 * scrollbars as well.
8762 *
8763 * @return the right padding in pixels
8764 */
8765 public int getPaddingRight() {
8766 return mPaddingRight;
8767 }
8768
8769 /**
8770 * Changes the selection state of this view. A view can be selected or not.
8771 * Note that selection is not the same as focus. Views are typically
8772 * selected in the context of an AdapterView like ListView or GridView;
8773 * the selected view is the view that is highlighted.
8774 *
8775 * @param selected true if the view must be selected, false otherwise
8776 */
8777 public void setSelected(boolean selected) {
8778 if (((mPrivateFlags & SELECTED) != 0) != selected) {
8779 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07008780 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008781 invalidate();
8782 refreshDrawableState();
8783 dispatchSetSelected(selected);
8784 }
8785 }
8786
8787 /**
8788 * Dispatch setSelected to all of this View's children.
8789 *
8790 * @see #setSelected(boolean)
8791 *
8792 * @param selected The new selected state
8793 */
8794 protected void dispatchSetSelected(boolean selected) {
8795 }
8796
8797 /**
8798 * Indicates the selection state of this view.
8799 *
8800 * @return true if the view is selected, false otherwise
8801 */
8802 @ViewDebug.ExportedProperty
8803 public boolean isSelected() {
8804 return (mPrivateFlags & SELECTED) != 0;
8805 }
8806
8807 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008808 * Changes the activated state of this view. A view can be activated or not.
8809 * Note that activation is not the same as selection. Selection is
8810 * a transient property, representing the view (hierarchy) the user is
8811 * currently interacting with. Activation is a longer-term state that the
8812 * user can move views in and out of. For example, in a list view with
8813 * single or multiple selection enabled, the views in the current selection
8814 * set are activated. (Um, yeah, we are deeply sorry about the terminology
8815 * here.) The activated state is propagated down to children of the view it
8816 * is set on.
8817 *
8818 * @param activated true if the view must be activated, false otherwise
8819 */
8820 public void setActivated(boolean activated) {
8821 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
8822 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
8823 invalidate();
8824 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07008825 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008826 }
8827 }
8828
8829 /**
8830 * Dispatch setActivated to all of this View's children.
8831 *
8832 * @see #setActivated(boolean)
8833 *
8834 * @param activated The new activated state
8835 */
8836 protected void dispatchSetActivated(boolean activated) {
8837 }
8838
8839 /**
8840 * Indicates the activation state of this view.
8841 *
8842 * @return true if the view is activated, false otherwise
8843 */
8844 @ViewDebug.ExportedProperty
8845 public boolean isActivated() {
8846 return (mPrivateFlags & ACTIVATED) != 0;
8847 }
8848
8849 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
8851 * observer can be used to get notifications when global events, like
8852 * layout, happen.
8853 *
8854 * The returned ViewTreeObserver observer is not guaranteed to remain
8855 * valid for the lifetime of this View. If the caller of this method keeps
8856 * a long-lived reference to ViewTreeObserver, it should always check for
8857 * the return value of {@link ViewTreeObserver#isAlive()}.
8858 *
8859 * @return The ViewTreeObserver for this view's hierarchy.
8860 */
8861 public ViewTreeObserver getViewTreeObserver() {
8862 if (mAttachInfo != null) {
8863 return mAttachInfo.mTreeObserver;
8864 }
8865 if (mFloatingTreeObserver == null) {
8866 mFloatingTreeObserver = new ViewTreeObserver();
8867 }
8868 return mFloatingTreeObserver;
8869 }
8870
8871 /**
8872 * <p>Finds the topmost view in the current view hierarchy.</p>
8873 *
8874 * @return the topmost view containing this view
8875 */
8876 public View getRootView() {
8877 if (mAttachInfo != null) {
8878 final View v = mAttachInfo.mRootView;
8879 if (v != null) {
8880 return v;
8881 }
8882 }
Romain Guy8506ab42009-06-11 17:35:47 -07008883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884 View parent = this;
8885
8886 while (parent.mParent != null && parent.mParent instanceof View) {
8887 parent = (View) parent.mParent;
8888 }
8889
8890 return parent;
8891 }
8892
8893 /**
8894 * <p>Computes the coordinates of this view on the screen. The argument
8895 * must be an array of two integers. After the method returns, the array
8896 * contains the x and y location in that order.</p>
8897 *
8898 * @param location an array of two integers in which to hold the coordinates
8899 */
8900 public void getLocationOnScreen(int[] location) {
8901 getLocationInWindow(location);
8902
8903 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07008904 if (info != null) {
8905 location[0] += info.mWindowLeft;
8906 location[1] += info.mWindowTop;
8907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008908 }
8909
8910 /**
8911 * <p>Computes the coordinates of this view in its window. The argument
8912 * must be an array of two integers. After the method returns, the array
8913 * contains the x and y location in that order.</p>
8914 *
8915 * @param location an array of two integers in which to hold the coordinates
8916 */
8917 public void getLocationInWindow(int[] location) {
8918 if (location == null || location.length < 2) {
8919 throw new IllegalArgumentException("location must be an array of "
8920 + "two integers");
8921 }
8922
8923 location[0] = mLeft;
8924 location[1] = mTop;
8925
8926 ViewParent viewParent = mParent;
8927 while (viewParent instanceof View) {
8928 final View view = (View)viewParent;
8929 location[0] += view.mLeft - view.mScrollX;
8930 location[1] += view.mTop - view.mScrollY;
8931 viewParent = view.mParent;
8932 }
Romain Guy8506ab42009-06-11 17:35:47 -07008933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 if (viewParent instanceof ViewRoot) {
8935 // *cough*
8936 final ViewRoot vr = (ViewRoot)viewParent;
8937 location[1] -= vr.mCurScrollY;
8938 }
8939 }
8940
8941 /**
8942 * {@hide}
8943 * @param id the id of the view to be found
8944 * @return the view of the specified id, null if cannot be found
8945 */
8946 protected View findViewTraversal(int id) {
8947 if (id == mID) {
8948 return this;
8949 }
8950 return null;
8951 }
8952
8953 /**
8954 * {@hide}
8955 * @param tag the tag of the view to be found
8956 * @return the view of specified tag, null if cannot be found
8957 */
8958 protected View findViewWithTagTraversal(Object tag) {
8959 if (tag != null && tag.equals(mTag)) {
8960 return this;
8961 }
8962 return null;
8963 }
8964
8965 /**
8966 * Look for a child view with the given id. If this view has the given
8967 * id, return this view.
8968 *
8969 * @param id The id to search for.
8970 * @return The view that has the given id in the hierarchy or null
8971 */
8972 public final View findViewById(int id) {
8973 if (id < 0) {
8974 return null;
8975 }
8976 return findViewTraversal(id);
8977 }
8978
8979 /**
8980 * Look for a child view with the given tag. If this view has the given
8981 * tag, return this view.
8982 *
8983 * @param tag The tag to search for, using "tag.equals(getTag())".
8984 * @return The View that has the given tag in the hierarchy or null
8985 */
8986 public final View findViewWithTag(Object tag) {
8987 if (tag == null) {
8988 return null;
8989 }
8990 return findViewWithTagTraversal(tag);
8991 }
8992
8993 /**
8994 * Sets the identifier for this view. The identifier does not have to be
8995 * unique in this view's hierarchy. The identifier should be a positive
8996 * number.
8997 *
8998 * @see #NO_ID
8999 * @see #getId
9000 * @see #findViewById
9001 *
9002 * @param id a number used to identify the view
9003 *
9004 * @attr ref android.R.styleable#View_id
9005 */
9006 public void setId(int id) {
9007 mID = id;
9008 }
9009
9010 /**
9011 * {@hide}
9012 *
9013 * @param isRoot true if the view belongs to the root namespace, false
9014 * otherwise
9015 */
9016 public void setIsRootNamespace(boolean isRoot) {
9017 if (isRoot) {
9018 mPrivateFlags |= IS_ROOT_NAMESPACE;
9019 } else {
9020 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9021 }
9022 }
9023
9024 /**
9025 * {@hide}
9026 *
9027 * @return true if the view belongs to the root namespace, false otherwise
9028 */
9029 public boolean isRootNamespace() {
9030 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9031 }
9032
9033 /**
9034 * Returns this view's identifier.
9035 *
9036 * @return a positive integer used to identify the view or {@link #NO_ID}
9037 * if the view has no ID
9038 *
9039 * @see #setId
9040 * @see #findViewById
9041 * @attr ref android.R.styleable#View_id
9042 */
9043 @ViewDebug.CapturedViewProperty
9044 public int getId() {
9045 return mID;
9046 }
9047
9048 /**
9049 * Returns this view's tag.
9050 *
9051 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07009052 *
9053 * @see #setTag(Object)
9054 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009055 */
9056 @ViewDebug.ExportedProperty
9057 public Object getTag() {
9058 return mTag;
9059 }
9060
9061 /**
9062 * Sets the tag associated with this view. A tag can be used to mark
9063 * a view in its hierarchy and does not have to be unique within the
9064 * hierarchy. Tags can also be used to store data within a view without
9065 * resorting to another data structure.
9066 *
9067 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07009068 *
9069 * @see #getTag()
9070 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009071 */
9072 public void setTag(final Object tag) {
9073 mTag = tag;
9074 }
9075
9076 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009077 * Returns the tag associated with this view and the specified key.
9078 *
9079 * @param key The key identifying the tag
9080 *
9081 * @return the Object stored in this view as a tag
9082 *
9083 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009084 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009085 */
9086 public Object getTag(int key) {
9087 SparseArray<Object> tags = null;
9088 synchronized (sTagsLock) {
9089 if (sTags != null) {
9090 tags = sTags.get(this);
9091 }
9092 }
9093
9094 if (tags != null) return tags.get(key);
9095 return null;
9096 }
9097
9098 /**
9099 * Sets a tag associated with this view and a key. A tag can be used
9100 * to mark a view in its hierarchy and does not have to be unique within
9101 * the hierarchy. Tags can also be used to store data within a view
9102 * without resorting to another data structure.
9103 *
9104 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009105 * application to ensure it is unique (see the <a
9106 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9107 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009108 * the Android framework or not associated with any package will cause
9109 * an {@link IllegalArgumentException} to be thrown.
9110 *
9111 * @param key The key identifying the tag
9112 * @param tag An Object to tag the view with
9113 *
9114 * @throws IllegalArgumentException If they specified key is not valid
9115 *
9116 * @see #setTag(Object)
9117 * @see #getTag(int)
9118 */
9119 public void setTag(int key, final Object tag) {
9120 // If the package id is 0x00 or 0x01, it's either an undefined package
9121 // or a framework id
9122 if ((key >>> 24) < 2) {
9123 throw new IllegalArgumentException("The key must be an application-specific "
9124 + "resource id.");
9125 }
9126
9127 setTagInternal(this, key, tag);
9128 }
9129
9130 /**
9131 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9132 * framework id.
9133 *
9134 * @hide
9135 */
9136 public void setTagInternal(int key, Object tag) {
9137 if ((key >>> 24) != 0x1) {
9138 throw new IllegalArgumentException("The key must be a framework-specific "
9139 + "resource id.");
9140 }
9141
Romain Guy8506ab42009-06-11 17:35:47 -07009142 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009143 }
9144
9145 private static void setTagInternal(View view, int key, Object tag) {
9146 SparseArray<Object> tags = null;
9147 synchronized (sTagsLock) {
9148 if (sTags == null) {
9149 sTags = new WeakHashMap<View, SparseArray<Object>>();
9150 } else {
9151 tags = sTags.get(view);
9152 }
9153 }
9154
9155 if (tags == null) {
9156 tags = new SparseArray<Object>(2);
9157 synchronized (sTagsLock) {
9158 sTags.put(view, tags);
9159 }
9160 }
9161
9162 tags.put(key, tag);
9163 }
9164
9165 /**
Romain Guy13922e02009-05-12 17:56:14 -07009166 * @param consistency The type of consistency. See ViewDebug for more information.
9167 *
9168 * @hide
9169 */
9170 protected boolean dispatchConsistencyCheck(int consistency) {
9171 return onConsistencyCheck(consistency);
9172 }
9173
9174 /**
9175 * Method that subclasses should implement to check their consistency. The type of
9176 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009177 *
Romain Guy13922e02009-05-12 17:56:14 -07009178 * @param consistency The type of consistency. See ViewDebug for more information.
9179 *
9180 * @throws IllegalStateException if the view is in an inconsistent state.
9181 *
9182 * @hide
9183 */
9184 protected boolean onConsistencyCheck(int consistency) {
9185 boolean result = true;
9186
9187 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9188 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9189
9190 if (checkLayout) {
9191 if (getParent() == null) {
9192 result = false;
9193 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9194 "View " + this + " does not have a parent.");
9195 }
9196
9197 if (mAttachInfo == null) {
9198 result = false;
9199 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9200 "View " + this + " is not attached to a window.");
9201 }
9202 }
9203
9204 if (checkDrawing) {
9205 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9206 // from their draw() method
9207
9208 if ((mPrivateFlags & DRAWN) != DRAWN &&
9209 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9210 result = false;
9211 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9212 "View " + this + " was invalidated but its drawing cache is valid.");
9213 }
9214 }
9215
9216 return result;
9217 }
9218
9219 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009220 * Prints information about this view in the log output, with the tag
9221 * {@link #VIEW_LOG_TAG}.
9222 *
9223 * @hide
9224 */
9225 public void debug() {
9226 debug(0);
9227 }
9228
9229 /**
9230 * Prints information about this view in the log output, with the tag
9231 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
9232 * indentation defined by the <code>depth</code>.
9233 *
9234 * @param depth the indentation level
9235 *
9236 * @hide
9237 */
9238 protected void debug(int depth) {
9239 String output = debugIndent(depth - 1);
9240
9241 output += "+ " + this;
9242 int id = getId();
9243 if (id != -1) {
9244 output += " (id=" + id + ")";
9245 }
9246 Object tag = getTag();
9247 if (tag != null) {
9248 output += " (tag=" + tag + ")";
9249 }
9250 Log.d(VIEW_LOG_TAG, output);
9251
9252 if ((mPrivateFlags & FOCUSED) != 0) {
9253 output = debugIndent(depth) + " FOCUSED";
9254 Log.d(VIEW_LOG_TAG, output);
9255 }
9256
9257 output = debugIndent(depth);
9258 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
9259 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
9260 + "} ";
9261 Log.d(VIEW_LOG_TAG, output);
9262
9263 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
9264 || mPaddingBottom != 0) {
9265 output = debugIndent(depth);
9266 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
9267 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
9268 Log.d(VIEW_LOG_TAG, output);
9269 }
9270
9271 output = debugIndent(depth);
9272 output += "mMeasureWidth=" + mMeasuredWidth +
9273 " mMeasureHeight=" + mMeasuredHeight;
9274 Log.d(VIEW_LOG_TAG, output);
9275
9276 output = debugIndent(depth);
9277 if (mLayoutParams == null) {
9278 output += "BAD! no layout params";
9279 } else {
9280 output = mLayoutParams.debug(output);
9281 }
9282 Log.d(VIEW_LOG_TAG, output);
9283
9284 output = debugIndent(depth);
9285 output += "flags={";
9286 output += View.printFlags(mViewFlags);
9287 output += "}";
9288 Log.d(VIEW_LOG_TAG, output);
9289
9290 output = debugIndent(depth);
9291 output += "privateFlags={";
9292 output += View.printPrivateFlags(mPrivateFlags);
9293 output += "}";
9294 Log.d(VIEW_LOG_TAG, output);
9295 }
9296
9297 /**
9298 * Creates an string of whitespaces used for indentation.
9299 *
9300 * @param depth the indentation level
9301 * @return a String containing (depth * 2 + 3) * 2 white spaces
9302 *
9303 * @hide
9304 */
9305 protected static String debugIndent(int depth) {
9306 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
9307 for (int i = 0; i < (depth * 2) + 3; i++) {
9308 spaces.append(' ').append(' ');
9309 }
9310 return spaces.toString();
9311 }
9312
9313 /**
9314 * <p>Return the offset of the widget's text baseline from the widget's top
9315 * boundary. If this widget does not support baseline alignment, this
9316 * method returns -1. </p>
9317 *
9318 * @return the offset of the baseline within the widget's bounds or -1
9319 * if baseline alignment is not supported
9320 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07009321 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009322 public int getBaseline() {
9323 return -1;
9324 }
9325
9326 /**
9327 * Call this when something has changed which has invalidated the
9328 * layout of this view. This will schedule a layout pass of the view
9329 * tree.
9330 */
9331 public void requestLayout() {
9332 if (ViewDebug.TRACE_HIERARCHY) {
9333 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
9334 }
9335
9336 mPrivateFlags |= FORCE_LAYOUT;
9337
9338 if (mParent != null && !mParent.isLayoutRequested()) {
9339 mParent.requestLayout();
9340 }
9341 }
9342
9343 /**
9344 * Forces this view to be laid out during the next layout pass.
9345 * This method does not call requestLayout() or forceLayout()
9346 * on the parent.
9347 */
9348 public void forceLayout() {
9349 mPrivateFlags |= FORCE_LAYOUT;
9350 }
9351
9352 /**
9353 * <p>
9354 * This is called to find out how big a view should be. The parent
9355 * supplies constraint information in the width and height parameters.
9356 * </p>
9357 *
9358 * <p>
9359 * The actual mesurement work of a view is performed in
9360 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
9361 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
9362 * </p>
9363 *
9364 *
9365 * @param widthMeasureSpec Horizontal space requirements as imposed by the
9366 * parent
9367 * @param heightMeasureSpec Vertical space requirements as imposed by the
9368 * parent
9369 *
9370 * @see #onMeasure(int, int)
9371 */
9372 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
9373 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
9374 widthMeasureSpec != mOldWidthMeasureSpec ||
9375 heightMeasureSpec != mOldHeightMeasureSpec) {
9376
9377 // first clears the measured dimension flag
9378 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9379
9380 if (ViewDebug.TRACE_HIERARCHY) {
9381 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
9382 }
9383
9384 // measure ourselves, this should set the measured dimension flag back
9385 onMeasure(widthMeasureSpec, heightMeasureSpec);
9386
9387 // flag not set, setMeasuredDimension() was not invoked, we raise
9388 // an exception to warn the developer
9389 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9390 throw new IllegalStateException("onMeasure() did not set the"
9391 + " measured dimension by calling"
9392 + " setMeasuredDimension()");
9393 }
9394
9395 mPrivateFlags |= LAYOUT_REQUIRED;
9396 }
9397
9398 mOldWidthMeasureSpec = widthMeasureSpec;
9399 mOldHeightMeasureSpec = heightMeasureSpec;
9400 }
9401
9402 /**
9403 * <p>
9404 * Measure the view and its content to determine the measured width and the
9405 * measured height. This method is invoked by {@link #measure(int, int)} and
9406 * should be overriden by subclasses to provide accurate and efficient
9407 * measurement of their contents.
9408 * </p>
9409 *
9410 * <p>
9411 * <strong>CONTRACT:</strong> When overriding this method, you
9412 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
9413 * measured width and height of this view. Failure to do so will trigger an
9414 * <code>IllegalStateException</code>, thrown by
9415 * {@link #measure(int, int)}. Calling the superclass'
9416 * {@link #onMeasure(int, int)} is a valid use.
9417 * </p>
9418 *
9419 * <p>
9420 * The base class implementation of measure defaults to the background size,
9421 * unless a larger size is allowed by the MeasureSpec. Subclasses should
9422 * override {@link #onMeasure(int, int)} to provide better measurements of
9423 * their content.
9424 * </p>
9425 *
9426 * <p>
9427 * If this method is overridden, it is the subclass's responsibility to make
9428 * sure the measured height and width are at least the view's minimum height
9429 * and width ({@link #getSuggestedMinimumHeight()} and
9430 * {@link #getSuggestedMinimumWidth()}).
9431 * </p>
9432 *
9433 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
9434 * The requirements are encoded with
9435 * {@link android.view.View.MeasureSpec}.
9436 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
9437 * The requirements are encoded with
9438 * {@link android.view.View.MeasureSpec}.
9439 *
9440 * @see #getMeasuredWidth()
9441 * @see #getMeasuredHeight()
9442 * @see #setMeasuredDimension(int, int)
9443 * @see #getSuggestedMinimumHeight()
9444 * @see #getSuggestedMinimumWidth()
9445 * @see android.view.View.MeasureSpec#getMode(int)
9446 * @see android.view.View.MeasureSpec#getSize(int)
9447 */
9448 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9449 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
9450 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
9451 }
9452
9453 /**
9454 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
9455 * measured width and measured height. Failing to do so will trigger an
9456 * exception at measurement time.</p>
9457 *
9458 * @param measuredWidth the measured width of this view
9459 * @param measuredHeight the measured height of this view
9460 */
9461 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
9462 mMeasuredWidth = measuredWidth;
9463 mMeasuredHeight = measuredHeight;
9464
9465 mPrivateFlags |= MEASURED_DIMENSION_SET;
9466 }
9467
9468 /**
9469 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
9470 * Will take the desired size, unless a different size is imposed by the constraints.
9471 *
9472 * @param size How big the view wants to be
9473 * @param measureSpec Constraints imposed by the parent
9474 * @return The size this view should be.
9475 */
9476 public static int resolveSize(int size, int measureSpec) {
9477 int result = size;
9478 int specMode = MeasureSpec.getMode(measureSpec);
9479 int specSize = MeasureSpec.getSize(measureSpec);
9480 switch (specMode) {
9481 case MeasureSpec.UNSPECIFIED:
9482 result = size;
9483 break;
9484 case MeasureSpec.AT_MOST:
9485 result = Math.min(size, specSize);
9486 break;
9487 case MeasureSpec.EXACTLY:
9488 result = specSize;
9489 break;
9490 }
9491 return result;
9492 }
9493
9494 /**
9495 * Utility to return a default size. Uses the supplied size if the
9496 * MeasureSpec imposed no contraints. Will get larger if allowed
9497 * by the MeasureSpec.
9498 *
9499 * @param size Default size for this view
9500 * @param measureSpec Constraints imposed by the parent
9501 * @return The size this view should be.
9502 */
9503 public static int getDefaultSize(int size, int measureSpec) {
9504 int result = size;
9505 int specMode = MeasureSpec.getMode(measureSpec);
9506 int specSize = MeasureSpec.getSize(measureSpec);
9507
9508 switch (specMode) {
9509 case MeasureSpec.UNSPECIFIED:
9510 result = size;
9511 break;
9512 case MeasureSpec.AT_MOST:
9513 case MeasureSpec.EXACTLY:
9514 result = specSize;
9515 break;
9516 }
9517 return result;
9518 }
9519
9520 /**
9521 * Returns the suggested minimum height that the view should use. This
9522 * returns the maximum of the view's minimum height
9523 * and the background's minimum height
9524 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
9525 * <p>
9526 * When being used in {@link #onMeasure(int, int)}, the caller should still
9527 * ensure the returned height is within the requirements of the parent.
9528 *
9529 * @return The suggested minimum height of the view.
9530 */
9531 protected int getSuggestedMinimumHeight() {
9532 int suggestedMinHeight = mMinHeight;
9533
9534 if (mBGDrawable != null) {
9535 final int bgMinHeight = mBGDrawable.getMinimumHeight();
9536 if (suggestedMinHeight < bgMinHeight) {
9537 suggestedMinHeight = bgMinHeight;
9538 }
9539 }
9540
9541 return suggestedMinHeight;
9542 }
9543
9544 /**
9545 * Returns the suggested minimum width that the view should use. This
9546 * returns the maximum of the view's minimum width)
9547 * and the background's minimum width
9548 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
9549 * <p>
9550 * When being used in {@link #onMeasure(int, int)}, the caller should still
9551 * ensure the returned width is within the requirements of the parent.
9552 *
9553 * @return The suggested minimum width of the view.
9554 */
9555 protected int getSuggestedMinimumWidth() {
9556 int suggestedMinWidth = mMinWidth;
9557
9558 if (mBGDrawable != null) {
9559 final int bgMinWidth = mBGDrawable.getMinimumWidth();
9560 if (suggestedMinWidth < bgMinWidth) {
9561 suggestedMinWidth = bgMinWidth;
9562 }
9563 }
9564
9565 return suggestedMinWidth;
9566 }
9567
9568 /**
9569 * Sets the minimum height of the view. It is not guaranteed the view will
9570 * be able to achieve this minimum height (for example, if its parent layout
9571 * constrains it with less available height).
9572 *
9573 * @param minHeight The minimum height the view will try to be.
9574 */
9575 public void setMinimumHeight(int minHeight) {
9576 mMinHeight = minHeight;
9577 }
9578
9579 /**
9580 * Sets the minimum width of the view. It is not guaranteed the view will
9581 * be able to achieve this minimum width (for example, if its parent layout
9582 * constrains it with less available width).
9583 *
9584 * @param minWidth The minimum width the view will try to be.
9585 */
9586 public void setMinimumWidth(int minWidth) {
9587 mMinWidth = minWidth;
9588 }
9589
9590 /**
9591 * Get the animation currently associated with this view.
9592 *
9593 * @return The animation that is currently playing or
9594 * scheduled to play for this view.
9595 */
9596 public Animation getAnimation() {
9597 return mCurrentAnimation;
9598 }
9599
9600 /**
9601 * Start the specified animation now.
9602 *
9603 * @param animation the animation to start now
9604 */
9605 public void startAnimation(Animation animation) {
9606 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
9607 setAnimation(animation);
9608 invalidate();
9609 }
9610
9611 /**
9612 * Cancels any animations for this view.
9613 */
9614 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08009615 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08009616 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08009617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009618 mCurrentAnimation = null;
9619 }
9620
9621 /**
9622 * Sets the next animation to play for this view.
9623 * If you want the animation to play immediately, use
9624 * startAnimation. This method provides allows fine-grained
9625 * control over the start time and invalidation, but you
9626 * must make sure that 1) the animation has a start time set, and
9627 * 2) the view will be invalidated when the animation is supposed to
9628 * start.
9629 *
9630 * @param animation The next animation, or null.
9631 */
9632 public void setAnimation(Animation animation) {
9633 mCurrentAnimation = animation;
9634 if (animation != null) {
9635 animation.reset();
9636 }
9637 }
9638
9639 /**
9640 * Invoked by a parent ViewGroup to notify the start of the animation
9641 * currently associated with this view. If you override this method,
9642 * always call super.onAnimationStart();
9643 *
9644 * @see #setAnimation(android.view.animation.Animation)
9645 * @see #getAnimation()
9646 */
9647 protected void onAnimationStart() {
9648 mPrivateFlags |= ANIMATION_STARTED;
9649 }
9650
9651 /**
9652 * Invoked by a parent ViewGroup to notify the end of the animation
9653 * currently associated with this view. If you override this method,
9654 * always call super.onAnimationEnd();
9655 *
9656 * @see #setAnimation(android.view.animation.Animation)
9657 * @see #getAnimation()
9658 */
9659 protected void onAnimationEnd() {
9660 mPrivateFlags &= ~ANIMATION_STARTED;
9661 }
9662
9663 /**
9664 * Invoked if there is a Transform that involves alpha. Subclass that can
9665 * draw themselves with the specified alpha should return true, and then
9666 * respect that alpha when their onDraw() is called. If this returns false
9667 * then the view may be redirected to draw into an offscreen buffer to
9668 * fulfill the request, which will look fine, but may be slower than if the
9669 * subclass handles it internally. The default implementation returns false.
9670 *
9671 * @param alpha The alpha (0..255) to apply to the view's drawing
9672 * @return true if the view can draw with the specified alpha.
9673 */
9674 protected boolean onSetAlpha(int alpha) {
9675 return false;
9676 }
9677
9678 /**
9679 * This is used by the RootView to perform an optimization when
9680 * the view hierarchy contains one or several SurfaceView.
9681 * SurfaceView is always considered transparent, but its children are not,
9682 * therefore all View objects remove themselves from the global transparent
9683 * region (passed as a parameter to this function).
9684 *
9685 * @param region The transparent region for this ViewRoot (window).
9686 *
9687 * @return Returns true if the effective visibility of the view at this
9688 * point is opaque, regardless of the transparent region; returns false
9689 * if it is possible for underlying windows to be seen behind the view.
9690 *
9691 * {@hide}
9692 */
9693 public boolean gatherTransparentRegion(Region region) {
9694 final AttachInfo attachInfo = mAttachInfo;
9695 if (region != null && attachInfo != null) {
9696 final int pflags = mPrivateFlags;
9697 if ((pflags & SKIP_DRAW) == 0) {
9698 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
9699 // remove it from the transparent region.
9700 final int[] location = attachInfo.mTransparentLocation;
9701 getLocationInWindow(location);
9702 region.op(location[0], location[1], location[0] + mRight - mLeft,
9703 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
9704 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
9705 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
9706 // exists, so we remove the background drawable's non-transparent
9707 // parts from this transparent region.
9708 applyDrawableToTransparentRegion(mBGDrawable, region);
9709 }
9710 }
9711 return true;
9712 }
9713
9714 /**
9715 * Play a sound effect for this view.
9716 *
9717 * <p>The framework will play sound effects for some built in actions, such as
9718 * clicking, but you may wish to play these effects in your widget,
9719 * for instance, for internal navigation.
9720 *
9721 * <p>The sound effect will only be played if sound effects are enabled by the user, and
9722 * {@link #isSoundEffectsEnabled()} is true.
9723 *
9724 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
9725 */
9726 public void playSoundEffect(int soundConstant) {
9727 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
9728 return;
9729 }
9730 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
9731 }
9732
9733 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009734 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009735 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009736 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009737 *
9738 * <p>The framework will provide haptic feedback for some built in actions,
9739 * such as long presses, but you may wish to provide feedback for your
9740 * own widget.
9741 *
9742 * <p>The feedback will only be performed if
9743 * {@link #isHapticFeedbackEnabled()} is true.
9744 *
9745 * @param feedbackConstant One of the constants defined in
9746 * {@link HapticFeedbackConstants}
9747 */
9748 public boolean performHapticFeedback(int feedbackConstant) {
9749 return performHapticFeedback(feedbackConstant, 0);
9750 }
9751
9752 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009753 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009754 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009755 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009756 *
9757 * @param feedbackConstant One of the constants defined in
9758 * {@link HapticFeedbackConstants}
9759 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
9760 */
9761 public boolean performHapticFeedback(int feedbackConstant, int flags) {
9762 if (mAttachInfo == null) {
9763 return false;
9764 }
Romain Guyf607bdc2010-09-10 19:20:06 -07009765 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -07009766 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009767 && !isHapticFeedbackEnabled()) {
9768 return false;
9769 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009770 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
9771 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009772 }
9773
9774 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07009775 * Drag and drop. App calls startDrag(), then callbacks to onMeasureDragThumbnail()
9776 * and onDrawDragThumbnail() happen, then the drag operation is handed over to the
9777 * OS.
9778 * !!! TODO: real docs
9779 * @hide
9780 */
9781 public final boolean startDrag(ClipData data, float touchX, float touchY,
9782 float thumbnailTouchX, float thumbnailTouchY, boolean myWindowOnly) {
9783 if (DEBUG_DRAG) {
9784 Log.d(VIEW_LOG_TAG, "startDrag: touch=(" + touchX + "," + touchY
9785 + ") thumb=(" + thumbnailTouchX + "," + thumbnailTouchY
9786 + ") data=" + data + " local=" + myWindowOnly);
9787 }
9788 boolean okay = false;
9789
9790 measureThumbnail(); // throws if the view fails to specify dimensions
9791
9792 Surface surface = new Surface();
9793 try {
9794 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
9795 myWindowOnly, mThumbnailWidth, mThumbnailHeight, surface);
9796 if (DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
9797 + " surface=" + surface);
9798 if (token != null) {
9799 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -07009800 try {
9801 onDrawDragThumbnail(canvas);
9802 } finally {
9803 surface.unlockCanvasAndPost(canvas);
9804 }
Christopher Tatea53146c2010-09-07 11:57:52 -07009805
9806 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Romain Guy0bb56672010-10-01 00:25:02 -07009807 touchX, touchY, thumbnailTouchX, thumbnailTouchY, data);
Christopher Tatea53146c2010-09-07 11:57:52 -07009808 if (DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
9809 }
9810 } catch (Exception e) {
9811 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
9812 surface.destroy();
9813 }
9814
9815 return okay;
9816 }
9817
9818 private void measureThumbnail() {
9819 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9820
9821 onMeasureDragThumbnail();
9822
9823 // flag not set, setDragThumbnailDimension() was not invoked, we raise
9824 // an exception to warn the developer
9825 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9826 throw new IllegalStateException("onMeasureDragThumbnail() did not set the"
9827 + " measured dimension by calling setDragThumbnailDimension()");
9828 }
9829
9830 if (DEBUG_DRAG) {
9831 Log.d(VIEW_LOG_TAG, "Drag thumb measured: w=" + mThumbnailWidth
9832 + " h=" + mThumbnailHeight);
9833 }
9834 }
9835
9836 /**
9837 * The View must call this method from onMeasureDragThumbnail() in order to
9838 * specify the dimensions of the drag thumbnail image.
9839 *
Romain Guy0bb56672010-10-01 00:25:02 -07009840 * @param width The desired thumbnail width.
9841 * @param height The desired thumbnail height.
Christopher Tatea53146c2010-09-07 11:57:52 -07009842 */
9843 protected final void setDragThumbnailDimension(int width, int height) {
9844 mPrivateFlags |= MEASURED_DIMENSION_SET;
9845 mThumbnailWidth = width;
9846 mThumbnailHeight = height;
9847 }
9848
9849 /**
9850 * The default implementation specifies a drag thumbnail that matches the
9851 * View's current size and appearance.
9852 */
9853 protected void onMeasureDragThumbnail() {
9854 setDragThumbnailDimension(getWidth(), getHeight());
9855 }
9856
9857 /**
9858 * The default implementation just draws the current View appearance as the thumbnail
9859 * @param canvas
9860 */
9861 protected void onDrawDragThumbnail(Canvas canvas) {
9862 draw(canvas);
9863 }
9864
9865 /**
9866 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
9867 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
9868 *
9869 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
9870 * being dragged. onDragEvent() should return 'true' if the view can handle
9871 * a drop of that content. A view that returns 'false' here will receive no
9872 * further calls to onDragEvent() about the drag/drop operation.
9873 *
9874 * For DRAG_ENTERED, event.getClipDescription() describes the content being
9875 * dragged. This will be the same content description passed in the
9876 * DRAG_STARTED_EVENT invocation.
9877 *
9878 * For DRAG_EXITED, event.getClipDescription() describes the content being
9879 * dragged. This will be the same content description passed in the
9880 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
9881 * drag-acceptance visual state.
9882 *
9883 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
9884 * coordinates of the current drag point. The view must return 'true' if it
9885 * can accept a drop of the current drag content, false otherwise.
9886 *
9887 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
9888 * within the view; also, event.getClipData() returns the full data payload
9889 * being dropped. The view should return 'true' if it consumed the dropped
9890 * content, 'false' if it did not.
9891 *
9892 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
9893 * to its normal visual state.
9894 */
9895 protected boolean onDragEvent(DragEvent event) {
9896 return false;
9897 }
9898
9899 /**
9900 * Views typically don't need to override dispatchDragEvent(); it just calls
9901 * onDragEvent(what, event) and passes the result up appropriately.
9902 *
9903 */
9904 public boolean dispatchDragEvent(DragEvent event) {
9905 return onDragEvent(event);
9906 }
9907
9908 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -07009909 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
9910 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -07009911 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -07009912 */
9913 public void onCloseSystemDialogs(String reason) {
9914 }
9915
9916 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009917 * Given a Drawable whose bounds have been set to draw into this view,
9918 * update a Region being computed for {@link #gatherTransparentRegion} so
9919 * that any non-transparent parts of the Drawable are removed from the
9920 * given transparent region.
9921 *
9922 * @param dr The Drawable whose transparency is to be applied to the region.
9923 * @param region A Region holding the current transparency information,
9924 * where any parts of the region that are set are considered to be
9925 * transparent. On return, this region will be modified to have the
9926 * transparency information reduced by the corresponding parts of the
9927 * Drawable that are not transparent.
9928 * {@hide}
9929 */
9930 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
9931 if (DBG) {
9932 Log.i("View", "Getting transparent region for: " + this);
9933 }
9934 final Region r = dr.getTransparentRegion();
9935 final Rect db = dr.getBounds();
9936 final AttachInfo attachInfo = mAttachInfo;
9937 if (r != null && attachInfo != null) {
9938 final int w = getRight()-getLeft();
9939 final int h = getBottom()-getTop();
9940 if (db.left > 0) {
9941 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
9942 r.op(0, 0, db.left, h, Region.Op.UNION);
9943 }
9944 if (db.right < w) {
9945 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
9946 r.op(db.right, 0, w, h, Region.Op.UNION);
9947 }
9948 if (db.top > 0) {
9949 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
9950 r.op(0, 0, w, db.top, Region.Op.UNION);
9951 }
9952 if (db.bottom < h) {
9953 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
9954 r.op(0, db.bottom, w, h, Region.Op.UNION);
9955 }
9956 final int[] location = attachInfo.mTransparentLocation;
9957 getLocationInWindow(location);
9958 r.translate(location[0], location[1]);
9959 region.op(r, Region.Op.INTERSECT);
9960 } else {
9961 region.op(db, Region.Op.DIFFERENCE);
9962 }
9963 }
9964
Adam Powelle14579b2009-12-16 18:39:52 -08009965 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009966 mHasPerformedLongPress = false;
9967
9968 if (mPendingCheckForLongPress == null) {
9969 mPendingCheckForLongPress = new CheckForLongPress();
9970 }
9971 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -08009972 postDelayed(mPendingCheckForLongPress,
9973 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009974 }
9975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009976 /**
9977 * Inflate a view from an XML resource. This convenience method wraps the {@link
9978 * LayoutInflater} class, which provides a full range of options for view inflation.
9979 *
9980 * @param context The Context object for your activity or application.
9981 * @param resource The resource ID to inflate
9982 * @param root A view group that will be the parent. Used to properly inflate the
9983 * layout_* parameters.
9984 * @see LayoutInflater
9985 */
9986 public static View inflate(Context context, int resource, ViewGroup root) {
9987 LayoutInflater factory = LayoutInflater.from(context);
9988 return factory.inflate(resource, root);
9989 }
Romain Guy33e72ae2010-07-17 12:40:29 -07009990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009991 /**
9992 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
9993 * Each MeasureSpec represents a requirement for either the width or the height.
9994 * A MeasureSpec is comprised of a size and a mode. There are three possible
9995 * modes:
9996 * <dl>
9997 * <dt>UNSPECIFIED</dt>
9998 * <dd>
9999 * The parent has not imposed any constraint on the child. It can be whatever size
10000 * it wants.
10001 * </dd>
10002 *
10003 * <dt>EXACTLY</dt>
10004 * <dd>
10005 * The parent has determined an exact size for the child. The child is going to be
10006 * given those bounds regardless of how big it wants to be.
10007 * </dd>
10008 *
10009 * <dt>AT_MOST</dt>
10010 * <dd>
10011 * The child can be as large as it wants up to the specified size.
10012 * </dd>
10013 * </dl>
10014 *
10015 * MeasureSpecs are implemented as ints to reduce object allocation. This class
10016 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
10017 */
10018 public static class MeasureSpec {
10019 private static final int MODE_SHIFT = 30;
10020 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
10021
10022 /**
10023 * Measure specification mode: The parent has not imposed any constraint
10024 * on the child. It can be whatever size it wants.
10025 */
10026 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
10027
10028 /**
10029 * Measure specification mode: The parent has determined an exact size
10030 * for the child. The child is going to be given those bounds regardless
10031 * of how big it wants to be.
10032 */
10033 public static final int EXACTLY = 1 << MODE_SHIFT;
10034
10035 /**
10036 * Measure specification mode: The child can be as large as it wants up
10037 * to the specified size.
10038 */
10039 public static final int AT_MOST = 2 << MODE_SHIFT;
10040
10041 /**
10042 * Creates a measure specification based on the supplied size and mode.
10043 *
10044 * The mode must always be one of the following:
10045 * <ul>
10046 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
10047 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
10048 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
10049 * </ul>
10050 *
10051 * @param size the size of the measure specification
10052 * @param mode the mode of the measure specification
10053 * @return the measure specification based on size and mode
10054 */
10055 public static int makeMeasureSpec(int size, int mode) {
10056 return size + mode;
10057 }
10058
10059 /**
10060 * Extracts the mode from the supplied measure specification.
10061 *
10062 * @param measureSpec the measure specification to extract the mode from
10063 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
10064 * {@link android.view.View.MeasureSpec#AT_MOST} or
10065 * {@link android.view.View.MeasureSpec#EXACTLY}
10066 */
10067 public static int getMode(int measureSpec) {
10068 return (measureSpec & MODE_MASK);
10069 }
10070
10071 /**
10072 * Extracts the size from the supplied measure specification.
10073 *
10074 * @param measureSpec the measure specification to extract the size from
10075 * @return the size in pixels defined in the supplied measure specification
10076 */
10077 public static int getSize(int measureSpec) {
10078 return (measureSpec & ~MODE_MASK);
10079 }
10080
10081 /**
10082 * Returns a String representation of the specified measure
10083 * specification.
10084 *
10085 * @param measureSpec the measure specification to convert to a String
10086 * @return a String with the following format: "MeasureSpec: MODE SIZE"
10087 */
10088 public static String toString(int measureSpec) {
10089 int mode = getMode(measureSpec);
10090 int size = getSize(measureSpec);
10091
10092 StringBuilder sb = new StringBuilder("MeasureSpec: ");
10093
10094 if (mode == UNSPECIFIED)
10095 sb.append("UNSPECIFIED ");
10096 else if (mode == EXACTLY)
10097 sb.append("EXACTLY ");
10098 else if (mode == AT_MOST)
10099 sb.append("AT_MOST ");
10100 else
10101 sb.append(mode).append(" ");
10102
10103 sb.append(size);
10104 return sb.toString();
10105 }
10106 }
10107
10108 class CheckForLongPress implements Runnable {
10109
10110 private int mOriginalWindowAttachCount;
10111
10112 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070010113 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010114 && mOriginalWindowAttachCount == mWindowAttachCount) {
10115 if (performLongClick()) {
10116 mHasPerformedLongPress = true;
10117 }
10118 }
10119 }
10120
10121 public void rememberWindowAttachCount() {
10122 mOriginalWindowAttachCount = mWindowAttachCount;
10123 }
10124 }
Adam Powelle14579b2009-12-16 18:39:52 -080010125
10126 private final class CheckForTap implements Runnable {
10127 public void run() {
10128 mPrivateFlags &= ~PREPRESSED;
10129 mPrivateFlags |= PRESSED;
10130 refreshDrawableState();
10131 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
10132 postCheckForLongClick(ViewConfiguration.getTapTimeout());
10133 }
10134 }
10135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010136
Adam Powella35d7682010-03-12 14:48:13 -080010137 private final class PerformClick implements Runnable {
10138 public void run() {
10139 performClick();
10140 }
10141 }
10142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010143 /**
10144 * Interface definition for a callback to be invoked when a key event is
10145 * dispatched to this view. The callback will be invoked before the key
10146 * event is given to the view.
10147 */
10148 public interface OnKeyListener {
10149 /**
10150 * Called when a key is dispatched to a view. This allows listeners to
10151 * get a chance to respond before the target view.
10152 *
10153 * @param v The view the key has been dispatched to.
10154 * @param keyCode The code for the physical key that was pressed
10155 * @param event The KeyEvent object containing full information about
10156 * the event.
10157 * @return True if the listener has consumed the event, false otherwise.
10158 */
10159 boolean onKey(View v, int keyCode, KeyEvent event);
10160 }
10161
10162 /**
10163 * Interface definition for a callback to be invoked when a touch event is
10164 * dispatched to this view. The callback will be invoked before the touch
10165 * event is given to the view.
10166 */
10167 public interface OnTouchListener {
10168 /**
10169 * Called when a touch event is dispatched to a view. This allows listeners to
10170 * get a chance to respond before the target view.
10171 *
10172 * @param v The view the touch event has been dispatched to.
10173 * @param event The MotionEvent object containing full information about
10174 * the event.
10175 * @return True if the listener has consumed the event, false otherwise.
10176 */
10177 boolean onTouch(View v, MotionEvent event);
10178 }
10179
10180 /**
10181 * Interface definition for a callback to be invoked when a view has been clicked and held.
10182 */
10183 public interface OnLongClickListener {
10184 /**
10185 * Called when a view has been clicked and held.
10186 *
10187 * @param v The view that was clicked and held.
10188 *
10189 * return True if the callback consumed the long click, false otherwise
10190 */
10191 boolean onLongClick(View v);
10192 }
10193
10194 /**
10195 * Interface definition for a callback to be invoked when the focus state of
10196 * a view changed.
10197 */
10198 public interface OnFocusChangeListener {
10199 /**
10200 * Called when the focus state of a view has changed.
10201 *
10202 * @param v The view whose state has changed.
10203 * @param hasFocus The new focus state of v.
10204 */
10205 void onFocusChange(View v, boolean hasFocus);
10206 }
10207
10208 /**
10209 * Interface definition for a callback to be invoked when a view is clicked.
10210 */
10211 public interface OnClickListener {
10212 /**
10213 * Called when a view has been clicked.
10214 *
10215 * @param v The view that was clicked.
10216 */
10217 void onClick(View v);
10218 }
10219
10220 /**
10221 * Interface definition for a callback to be invoked when the context menu
10222 * for this view is being built.
10223 */
10224 public interface OnCreateContextMenuListener {
10225 /**
10226 * Called when the context menu for this view is being built. It is not
10227 * safe to hold onto the menu after this method returns.
10228 *
10229 * @param menu The context menu that is being built
10230 * @param v The view for which the context menu is being built
10231 * @param menuInfo Extra information about the item for which the
10232 * context menu should be shown. This information will vary
10233 * depending on the class of v.
10234 */
10235 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
10236 }
10237
10238 private final class UnsetPressedState implements Runnable {
10239 public void run() {
10240 setPressed(false);
10241 }
10242 }
10243
10244 /**
10245 * Base class for derived classes that want to save and restore their own
10246 * state in {@link android.view.View#onSaveInstanceState()}.
10247 */
10248 public static class BaseSavedState extends AbsSavedState {
10249 /**
10250 * Constructor used when reading from a parcel. Reads the state of the superclass.
10251 *
10252 * @param source
10253 */
10254 public BaseSavedState(Parcel source) {
10255 super(source);
10256 }
10257
10258 /**
10259 * Constructor called by derived classes when creating their SavedState objects
10260 *
10261 * @param superState The state of the superclass of this view
10262 */
10263 public BaseSavedState(Parcelable superState) {
10264 super(superState);
10265 }
10266
10267 public static final Parcelable.Creator<BaseSavedState> CREATOR =
10268 new Parcelable.Creator<BaseSavedState>() {
10269 public BaseSavedState createFromParcel(Parcel in) {
10270 return new BaseSavedState(in);
10271 }
10272
10273 public BaseSavedState[] newArray(int size) {
10274 return new BaseSavedState[size];
10275 }
10276 };
10277 }
10278
10279 /**
10280 * A set of information given to a view when it is attached to its parent
10281 * window.
10282 */
10283 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010284 interface Callbacks {
10285 void playSoundEffect(int effectId);
10286 boolean performHapticFeedback(int effectId, boolean always);
10287 }
10288
10289 /**
10290 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
10291 * to a Handler. This class contains the target (View) to invalidate and
10292 * the coordinates of the dirty rectangle.
10293 *
10294 * For performance purposes, this class also implements a pool of up to
10295 * POOL_LIMIT objects that get reused. This reduces memory allocations
10296 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010297 */
Romain Guyd928d682009-03-31 17:52:16 -070010298 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010299 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070010300 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
10301 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070010302 public InvalidateInfo newInstance() {
10303 return new InvalidateInfo();
10304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010305
Romain Guyd928d682009-03-31 17:52:16 -070010306 public void onAcquired(InvalidateInfo element) {
10307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010308
Romain Guyd928d682009-03-31 17:52:16 -070010309 public void onReleased(InvalidateInfo element) {
10310 }
10311 }, POOL_LIMIT)
10312 );
10313
10314 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010315
10316 View target;
10317
10318 int left;
10319 int top;
10320 int right;
10321 int bottom;
10322
Romain Guyd928d682009-03-31 17:52:16 -070010323 public void setNextPoolable(InvalidateInfo element) {
10324 mNext = element;
10325 }
10326
10327 public InvalidateInfo getNextPoolable() {
10328 return mNext;
10329 }
10330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010331 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070010332 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010333 }
10334
10335 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070010336 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010337 }
10338 }
10339
10340 final IWindowSession mSession;
10341
10342 final IWindow mWindow;
10343
10344 final IBinder mWindowToken;
10345
10346 final Callbacks mRootCallbacks;
10347
10348 /**
10349 * The top view of the hierarchy.
10350 */
10351 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070010352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010353 IBinder mPanelParentWindowToken;
10354 Surface mSurface;
10355
Romain Guyb051e892010-09-28 19:09:36 -070010356 boolean mHardwareAccelerated;
10357 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070010358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010359 /**
Romain Guy8506ab42009-06-11 17:35:47 -070010360 * Scale factor used by the compatibility mode
10361 */
10362 float mApplicationScale;
10363
10364 /**
10365 * Indicates whether the application is in compatibility mode
10366 */
10367 boolean mScalingRequired;
10368
10369 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010370 * Left position of this view's window
10371 */
10372 int mWindowLeft;
10373
10374 /**
10375 * Top position of this view's window
10376 */
10377 int mWindowTop;
10378
10379 /**
Romain Guy35b38ce2009-10-07 13:38:55 -070010380 * Indicates whether the window is translucent/transparent
10381 */
10382 boolean mTranslucentWindow;
10383
10384 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010385 * For windows that are full-screen but using insets to layout inside
10386 * of the screen decorations, these are the current insets for the
10387 * content of the window.
10388 */
10389 final Rect mContentInsets = new Rect();
10390
10391 /**
10392 * For windows that are full-screen but using insets to layout inside
10393 * of the screen decorations, these are the current insets for the
10394 * actual visible parts of the window.
10395 */
10396 final Rect mVisibleInsets = new Rect();
10397
10398 /**
10399 * The internal insets given by this window. This value is
10400 * supplied by the client (through
10401 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
10402 * be given to the window manager when changed to be used in laying
10403 * out windows behind it.
10404 */
10405 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
10406 = new ViewTreeObserver.InternalInsetsInfo();
10407
10408 /**
10409 * All views in the window's hierarchy that serve as scroll containers,
10410 * used to determine if the window can be resized or must be panned
10411 * to adjust for a soft input area.
10412 */
10413 final ArrayList<View> mScrollContainers = new ArrayList<View>();
10414
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070010415 final KeyEvent.DispatcherState mKeyDispatchState
10416 = new KeyEvent.DispatcherState();
10417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010418 /**
10419 * Indicates whether the view's window currently has the focus.
10420 */
10421 boolean mHasWindowFocus;
10422
10423 /**
10424 * The current visibility of the window.
10425 */
10426 int mWindowVisibility;
10427
10428 /**
10429 * Indicates the time at which drawing started to occur.
10430 */
10431 long mDrawingTime;
10432
10433 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070010434 * Indicates whether or not ignoring the DIRTY_MASK flags.
10435 */
10436 boolean mIgnoreDirtyState;
10437
10438 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010439 * Indicates whether the view's window is currently in touch mode.
10440 */
10441 boolean mInTouchMode;
10442
10443 /**
10444 * Indicates that ViewRoot should trigger a global layout change
10445 * the next time it performs a traversal
10446 */
10447 boolean mRecomputeGlobalAttributes;
10448
10449 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010450 * Set during a traveral if any views want to keep the screen on.
10451 */
10452 boolean mKeepScreenOn;
10453
10454 /**
10455 * Set if the visibility of any views has changed.
10456 */
10457 boolean mViewVisibilityChanged;
10458
10459 /**
10460 * Set to true if a view has been scrolled.
10461 */
10462 boolean mViewScrollChanged;
10463
10464 /**
10465 * Global to the view hierarchy used as a temporary for dealing with
10466 * x/y points in the transparent region computations.
10467 */
10468 final int[] mTransparentLocation = new int[2];
10469
10470 /**
10471 * Global to the view hierarchy used as a temporary for dealing with
10472 * x/y points in the ViewGroup.invalidateChild implementation.
10473 */
10474 final int[] mInvalidateChildLocation = new int[2];
10475
Chet Haasec3aa3612010-06-17 08:50:37 -070010476
10477 /**
10478 * Global to the view hierarchy used as a temporary for dealing with
10479 * x/y location when view is transformed.
10480 */
10481 final float[] mTmpTransformLocation = new float[2];
10482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010483 /**
10484 * The view tree observer used to dispatch global events like
10485 * layout, pre-draw, touch mode change, etc.
10486 */
10487 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
10488
10489 /**
10490 * A Canvas used by the view hierarchy to perform bitmap caching.
10491 */
10492 Canvas mCanvas;
10493
10494 /**
10495 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
10496 * handler can be used to pump events in the UI events queue.
10497 */
10498 final Handler mHandler;
10499
10500 /**
10501 * Identifier for messages requesting the view to be invalidated.
10502 * Such messages should be sent to {@link #mHandler}.
10503 */
10504 static final int INVALIDATE_MSG = 0x1;
10505
10506 /**
10507 * Identifier for messages requesting the view to invalidate a region.
10508 * Such messages should be sent to {@link #mHandler}.
10509 */
10510 static final int INVALIDATE_RECT_MSG = 0x2;
10511
10512 /**
10513 * Temporary for use in computing invalidate rectangles while
10514 * calling up the hierarchy.
10515 */
10516 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070010517
10518 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070010519 * Temporary for use in computing hit areas with transformed views
10520 */
10521 final RectF mTmpTransformRect = new RectF();
10522
10523 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070010524 * Temporary list for use in collecting focusable descendents of a view.
10525 */
10526 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
10527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010528 /**
10529 * Creates a new set of attachment information with the specified
10530 * events handler and thread.
10531 *
10532 * @param handler the events handler the view must use
10533 */
10534 AttachInfo(IWindowSession session, IWindow window,
10535 Handler handler, Callbacks effectPlayer) {
10536 mSession = session;
10537 mWindow = window;
10538 mWindowToken = window.asBinder();
10539 mHandler = handler;
10540 mRootCallbacks = effectPlayer;
10541 }
10542 }
10543
10544 /**
10545 * <p>ScrollabilityCache holds various fields used by a View when scrolling
10546 * is supported. This avoids keeping too many unused fields in most
10547 * instances of View.</p>
10548 */
Mike Cleronf116bf82009-09-27 19:14:12 -070010549 private static class ScrollabilityCache implements Runnable {
10550
10551 /**
10552 * Scrollbars are not visible
10553 */
10554 public static final int OFF = 0;
10555
10556 /**
10557 * Scrollbars are visible
10558 */
10559 public static final int ON = 1;
10560
10561 /**
10562 * Scrollbars are fading away
10563 */
10564 public static final int FADING = 2;
10565
10566 public boolean fadeScrollBars;
10567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010568 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070010569 public int scrollBarDefaultDelayBeforeFade;
10570 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010571
10572 public int scrollBarSize;
10573 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070010574 public float[] interpolatorValues;
10575 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010576
10577 public final Paint paint;
10578 public final Matrix matrix;
10579 public Shader shader;
10580
Mike Cleronf116bf82009-09-27 19:14:12 -070010581 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
10582
Romain Guy8fb95422010-08-17 18:38:51 -070010583 private final float[] mOpaque = { 255.0f };
10584 private final float[] mTransparent = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070010585
10586 /**
10587 * When fading should start. This time moves into the future every time
10588 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
10589 */
10590 public long fadeStartTime;
10591
10592
10593 /**
10594 * The current state of the scrollbars: ON, OFF, or FADING
10595 */
10596 public int state = OFF;
10597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010598 private int mLastColor;
10599
Mike Cleronf116bf82009-09-27 19:14:12 -070010600 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010601 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
10602 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070010603 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
10604 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605
10606 paint = new Paint();
10607 matrix = new Matrix();
10608 // use use a height of 1, and then wack the matrix each time we
10609 // actually use it.
10610 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010612 paint.setShader(shader);
10613 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070010614 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010615 }
Romain Guy8506ab42009-06-11 17:35:47 -070010616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010617 public void setFadeColor(int color) {
10618 if (color != 0 && color != mLastColor) {
10619 mLastColor = color;
10620 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070010621
Romain Guye55e1a72009-08-27 10:42:26 -070010622 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
10623 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010625 paint.setShader(shader);
10626 // Restore the default transfer mode (src_over)
10627 paint.setXfermode(null);
10628 }
10629 }
Mike Cleronf116bf82009-09-27 19:14:12 -070010630
10631 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070010632 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070010633 if (now >= fadeStartTime) {
10634
10635 // the animation fades the scrollbars out by changing
10636 // the opacity (alpha) from fully opaque to fully
10637 // transparent
10638 int nextFrame = (int) now;
10639 int framesCount = 0;
10640
10641 Interpolator interpolator = scrollBarInterpolator;
10642
10643 // Start opaque
10644 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
10645
10646 // End transparent
10647 nextFrame += scrollBarFadeDuration;
10648 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
10649
10650 state = FADING;
10651
10652 // Kick off the fade animation
10653 host.invalidate();
10654 }
10655 }
10656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010657 }
10658}