blob: 51c3879afc32f1eff279f9789a033fca498c4857 [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
19import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080020import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.content.res.Resources;
22import android.content.res.TypedArray;
23import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070024import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070026import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.graphics.LinearGradient;
28import android.graphics.Matrix;
29import android.graphics.Paint;
30import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070031import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.graphics.PorterDuff;
33import android.graphics.PorterDuffXfermode;
34import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070035import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.graphics.Region;
37import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.graphics.drawable.ColorDrawable;
39import android.graphics.drawable.Drawable;
40import android.os.Handler;
41import android.os.IBinder;
42import android.os.Message;
43import android.os.Parcel;
44import android.os.Parcelable;
45import android.os.RemoteException;
46import android.os.SystemClock;
47import android.os.SystemProperties;
48import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070050import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070051import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070052import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070053import android.util.Pools;
54import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.view.ContextMenu.ContextMenuInfo;
svetoslavganov75986cf2009-05-14 22:28:01 -070056import android.view.accessibility.AccessibilityEvent;
57import android.view.accessibility.AccessibilityEventSource;
58import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070060import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070061import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.view.inputmethod.InputConnection;
63import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.widget.ScrollBarDrawable;
Romain Guyf607bdc2010-09-10 19:20:06 -070065import com.android.internal.R;
66import com.android.internal.view.menu.MenuBuilder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
svetoslavganov75986cf2009-05-14 22:28:01 -070068import java.lang.reflect.InvocationTargetException;
69import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import java.util.ArrayList;
71import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070072import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070073import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074
75/**
76 * <p>
77 * This class represents the basic building block for user interface components. A View
78 * occupies a rectangular area on the screen and is responsible for drawing and
79 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070080 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
82 * are invisible containers that hold other Views (or other ViewGroups) and define
83 * their layout properties.
84 * </p>
85 *
86 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070087 * <p>For an introduction to using this class to develop your
88 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070090 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
92 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
93 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
94 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
95 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
99 * </p>
100 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700101 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 * <a name="Using"></a>
103 * <h3>Using Views</h3>
104 * <p>
105 * All of the views in a window are arranged in a single tree. You can add views
106 * either from code or by specifying a tree of views in one or more XML layout
107 * files. There are many specialized subclasses of views that act as controls or
108 * are capable of displaying text, images, or other content.
109 * </p>
110 * <p>
111 * Once you have created a tree of views, there are typically a few types of
112 * common operations you may wish to perform:
113 * <ul>
114 * <li><strong>Set properties:</strong> for example setting the text of a
115 * {@link android.widget.TextView}. The available properties and the methods
116 * that set them will vary among the different subclasses of views. Note that
117 * properties that are known at build time can be set in the XML layout
118 * files.</li>
119 * <li><strong>Set focus:</strong> The framework will handled moving focus in
120 * response to user input. To force focus to a specific view, call
121 * {@link #requestFocus}.</li>
122 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
123 * that will be notified when something interesting happens to the view. For
124 * example, all views will let you set a listener to be notified when the view
125 * gains or loses focus. You can register such a listener using
126 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
127 * specialized listeners. For example, a Button exposes a listener to notify
128 * clients when the button is clicked.</li>
129 * <li><strong>Set visibility:</strong> You can hide or show views using
130 * {@link #setVisibility}.</li>
131 * </ul>
132 * </p>
133 * <p><em>
134 * Note: The Android framework is responsible for measuring, laying out and
135 * drawing views. You should not call methods that perform these actions on
136 * views yourself unless you are actually implementing a
137 * {@link android.view.ViewGroup}.
138 * </em></p>
139 *
140 * <a name="Lifecycle"></a>
141 * <h3>Implementing a Custom View</h3>
142 *
143 * <p>
144 * To implement a custom view, you will usually begin by providing overrides for
145 * some of the standard methods that the framework calls on all views. You do
146 * not need to override all of these methods. In fact, you can start by just
147 * overriding {@link #onDraw(android.graphics.Canvas)}.
148 * <table border="2" width="85%" align="center" cellpadding="5">
149 * <thead>
150 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
151 * </thead>
152 *
153 * <tbody>
154 * <tr>
155 * <td rowspan="2">Creation</td>
156 * <td>Constructors</td>
157 * <td>There is a form of the constructor that are called when the view
158 * is created from code and a form that is called when the view is
159 * inflated from a layout file. The second form should parse and apply
160 * any attributes defined in the layout file.
161 * </td>
162 * </tr>
163 * <tr>
164 * <td><code>{@link #onFinishInflate()}</code></td>
165 * <td>Called after a view and all of its children has been inflated
166 * from XML.</td>
167 * </tr>
168 *
169 * <tr>
170 * <td rowspan="3">Layout</td>
171 * <td><code>{@link #onMeasure}</code></td>
172 * <td>Called to determine the size requirements for this view and all
173 * of its children.
174 * </td>
175 * </tr>
176 * <tr>
177 * <td><code>{@link #onLayout}</code></td>
178 * <td>Called when this view should assign a size and position to all
179 * of its children.
180 * </td>
181 * </tr>
182 * <tr>
183 * <td><code>{@link #onSizeChanged}</code></td>
184 * <td>Called when the size of this view has changed.
185 * </td>
186 * </tr>
187 *
188 * <tr>
189 * <td>Drawing</td>
190 * <td><code>{@link #onDraw}</code></td>
191 * <td>Called when the view should render its content.
192 * </td>
193 * </tr>
194 *
195 * <tr>
196 * <td rowspan="4">Event processing</td>
197 * <td><code>{@link #onKeyDown}</code></td>
198 * <td>Called when a new key event occurs.
199 * </td>
200 * </tr>
201 * <tr>
202 * <td><code>{@link #onKeyUp}</code></td>
203 * <td>Called when a key up event occurs.
204 * </td>
205 * </tr>
206 * <tr>
207 * <td><code>{@link #onTrackballEvent}</code></td>
208 * <td>Called when a trackball motion event occurs.
209 * </td>
210 * </tr>
211 * <tr>
212 * <td><code>{@link #onTouchEvent}</code></td>
213 * <td>Called when a touch screen motion event occurs.
214 * </td>
215 * </tr>
216 *
217 * <tr>
218 * <td rowspan="2">Focus</td>
219 * <td><code>{@link #onFocusChanged}</code></td>
220 * <td>Called when the view gains or loses focus.
221 * </td>
222 * </tr>
223 *
224 * <tr>
225 * <td><code>{@link #onWindowFocusChanged}</code></td>
226 * <td>Called when the window containing the view gains or loses focus.
227 * </td>
228 * </tr>
229 *
230 * <tr>
231 * <td rowspan="3">Attaching</td>
232 * <td><code>{@link #onAttachedToWindow()}</code></td>
233 * <td>Called when the view is attached to a window.
234 * </td>
235 * </tr>
236 *
237 * <tr>
238 * <td><code>{@link #onDetachedFromWindow}</code></td>
239 * <td>Called when the view is detached from its window.
240 * </td>
241 * </tr>
242 *
243 * <tr>
244 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
245 * <td>Called when the visibility of the window containing the view
246 * has changed.
247 * </td>
248 * </tr>
249 * </tbody>
250 *
251 * </table>
252 * </p>
253 *
254 * <a name="IDs"></a>
255 * <h3>IDs</h3>
256 * Views may have an integer id associated with them. These ids are typically
257 * assigned in the layout XML files, and are used to find specific views within
258 * the view tree. A common pattern is to:
259 * <ul>
260 * <li>Define a Button in the layout file and assign it a unique ID.
261 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700262 * &lt;Button
263 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 * android:layout_width="wrap_content"
265 * android:layout_height="wrap_content"
266 * android:text="@string/my_button_text"/&gt;
267 * </pre></li>
268 * <li>From the onCreate method of an Activity, find the Button
269 * <pre class="prettyprint">
270 * Button myButton = (Button) findViewById(R.id.my_button);
271 * </pre></li>
272 * </ul>
273 * <p>
274 * View IDs need not be unique throughout the tree, but it is good practice to
275 * ensure that they are at least unique within the part of the tree you are
276 * searching.
277 * </p>
278 *
279 * <a name="Position"></a>
280 * <h3>Position</h3>
281 * <p>
282 * The geometry of a view is that of a rectangle. A view has a location,
283 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
284 * two dimensions, expressed as a width and a height. The unit for location
285 * and dimensions is the pixel.
286 * </p>
287 *
288 * <p>
289 * It is possible to retrieve the location of a view by invoking the methods
290 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
291 * coordinate of the rectangle representing the view. The latter returns the
292 * top, or Y, coordinate of the rectangle representing the view. These methods
293 * both return the location of the view relative to its parent. For instance,
294 * when getLeft() returns 20, that means the view is located 20 pixels to the
295 * right of the left edge of its direct parent.
296 * </p>
297 *
298 * <p>
299 * In addition, several convenience methods are offered to avoid unnecessary
300 * computations, namely {@link #getRight()} and {@link #getBottom()}.
301 * These methods return the coordinates of the right and bottom edges of the
302 * rectangle representing the view. For instance, calling {@link #getRight()}
303 * is similar to the following computation: <code>getLeft() + getWidth()</code>
304 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
305 * </p>
306 *
307 * <a name="SizePaddingMargins"></a>
308 * <h3>Size, padding and margins</h3>
309 * <p>
310 * The size of a view is expressed with a width and a height. A view actually
311 * possess two pairs of width and height values.
312 * </p>
313 *
314 * <p>
315 * The first pair is known as <em>measured width</em> and
316 * <em>measured height</em>. These dimensions define how big a view wants to be
317 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
318 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
319 * and {@link #getMeasuredHeight()}.
320 * </p>
321 *
322 * <p>
323 * The second pair is simply known as <em>width</em> and <em>height</em>, or
324 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
325 * dimensions define the actual size of the view on screen, at drawing time and
326 * after layout. These values may, but do not have to, be different from the
327 * measured width and height. The width and height can be obtained by calling
328 * {@link #getWidth()} and {@link #getHeight()}.
329 * </p>
330 *
331 * <p>
332 * To measure its dimensions, a view takes into account its padding. The padding
333 * is expressed in pixels for the left, top, right and bottom parts of the view.
334 * Padding can be used to offset the content of the view by a specific amount of
335 * pixels. For instance, a left padding of 2 will push the view's content by
336 * 2 pixels to the right of the left edge. Padding can be set using the
337 * {@link #setPadding(int, int, int, int)} method and queried by calling
338 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
339 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
340 * </p>
341 *
342 * <p>
343 * Even though a view can define a padding, it does not provide any support for
344 * margins. However, view groups provide such a support. Refer to
345 * {@link android.view.ViewGroup} and
346 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
347 * </p>
348 *
349 * <a name="Layout"></a>
350 * <h3>Layout</h3>
351 * <p>
352 * Layout is a two pass process: a measure pass and a layout pass. The measuring
353 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
354 * of the view tree. Each view pushes dimension specifications down the tree
355 * during the recursion. At the end of the measure pass, every view has stored
356 * its measurements. The second pass happens in
357 * {@link #layout(int,int,int,int)} and is also top-down. During
358 * this pass each parent is responsible for positioning all of its children
359 * using the sizes computed in the measure pass.
360 * </p>
361 *
362 * <p>
363 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
364 * {@link #getMeasuredHeight()} values must be set, along with those for all of
365 * that view's descendants. A view's measured width and measured height values
366 * must respect the constraints imposed by the view's parents. This guarantees
367 * that at the end of the measure pass, all parents accept all of their
368 * children's measurements. A parent view may call measure() more than once on
369 * its children. For example, the parent may measure each child once with
370 * unspecified dimensions to find out how big they want to be, then call
371 * measure() on them again with actual numbers if the sum of all the children's
372 * unconstrained sizes is too big or too small.
373 * </p>
374 *
375 * <p>
376 * The measure pass uses two classes to communicate dimensions. The
377 * {@link MeasureSpec} class is used by views to tell their parents how they
378 * want to be measured and positioned. The base LayoutParams class just
379 * describes how big the view wants to be for both width and height. For each
380 * dimension, it can specify one of:
381 * <ul>
382 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800383 * <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 -0800384 * (minus padding)
385 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
386 * enclose its content (plus padding).
387 * </ul>
388 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
389 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
390 * an X and Y value.
391 * </p>
392 *
393 * <p>
394 * MeasureSpecs are used to push requirements down the tree from parent to
395 * child. A MeasureSpec can be in one of three modes:
396 * <ul>
397 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
398 * of a child view. For example, a LinearLayout may call measure() on its child
399 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
400 * tall the child view wants to be given a width of 240 pixels.
401 * <li>EXACTLY: This is used by the parent to impose an exact size on the
402 * child. The child must use this size, and guarantee that all of its
403 * descendants will fit within this size.
404 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
405 * child. The child must gurantee that it and all of its descendants will fit
406 * within this size.
407 * </ul>
408 * </p>
409 *
410 * <p>
411 * To intiate a layout, call {@link #requestLayout}. This method is typically
412 * called by a view on itself when it believes that is can no longer fit within
413 * its current bounds.
414 * </p>
415 *
416 * <a name="Drawing"></a>
417 * <h3>Drawing</h3>
418 * <p>
419 * Drawing is handled by walking the tree and rendering each view that
420 * intersects the the invalid region. Because the tree is traversed in-order,
421 * this means that parents will draw before (i.e., behind) their children, with
422 * siblings drawn in the order they appear in the tree.
423 * If you set a background drawable for a View, then the View will draw it for you
424 * before calling back to its <code>onDraw()</code> method.
425 * </p>
426 *
427 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700428 * 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 -0800429 * </p>
430 *
431 * <p>
432 * To force a view to draw, call {@link #invalidate()}.
433 * </p>
434 *
435 * <a name="EventHandlingThreading"></a>
436 * <h3>Event Handling and Threading</h3>
437 * <p>
438 * The basic cycle of a view is as follows:
439 * <ol>
440 * <li>An event comes in and is dispatched to the appropriate view. The view
441 * handles the event and notifies any listeners.</li>
442 * <li>If in the course of processing the event, the view's bounds may need
443 * to be changed, the view will call {@link #requestLayout()}.</li>
444 * <li>Similarly, if in the course of processing the event the view's appearance
445 * may need to be changed, the view will call {@link #invalidate()}.</li>
446 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
447 * the framework will take care of measuring, laying out, and drawing the tree
448 * as appropriate.</li>
449 * </ol>
450 * </p>
451 *
452 * <p><em>Note: The entire view tree is single threaded. You must always be on
453 * the UI thread when calling any method on any view.</em>
454 * If you are doing work on other threads and want to update the state of a view
455 * from that thread, you should use a {@link Handler}.
456 * </p>
457 *
458 * <a name="FocusHandling"></a>
459 * <h3>Focus Handling</h3>
460 * <p>
461 * The framework will handle routine focus movement in response to user input.
462 * This includes changing the focus as views are removed or hidden, or as new
463 * views become available. Views indicate their willingness to take focus
464 * through the {@link #isFocusable} method. To change whether a view can take
465 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
466 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
467 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
468 * </p>
469 * <p>
470 * Focus movement is based on an algorithm which finds the nearest neighbor in a
471 * given direction. In rare cases, the default algorithm may not match the
472 * intended behavior of the developer. In these situations, you can provide
473 * explicit overrides by using these XML attributes in the layout file:
474 * <pre>
475 * nextFocusDown
476 * nextFocusLeft
477 * nextFocusRight
478 * nextFocusUp
479 * </pre>
480 * </p>
481 *
482 *
483 * <p>
484 * To get a particular view to take focus, call {@link #requestFocus()}.
485 * </p>
486 *
487 * <a name="TouchMode"></a>
488 * <h3>Touch Mode</h3>
489 * <p>
490 * When a user is navigating a user interface via directional keys such as a D-pad, it is
491 * necessary to give focus to actionable items such as buttons so the user can see
492 * what will take input. If the device has touch capabilities, however, and the user
493 * begins interacting with the interface by touching it, it is no longer necessary to
494 * always highlight, or give focus to, a particular view. This motivates a mode
495 * for interaction named 'touch mode'.
496 * </p>
497 * <p>
498 * For a touch capable device, once the user touches the screen, the device
499 * will enter touch mode. From this point onward, only views for which
500 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
501 * Other views that are touchable, like buttons, will not take focus when touched; they will
502 * only fire the on click listeners.
503 * </p>
504 * <p>
505 * Any time a user hits a directional key, such as a D-pad direction, the view device will
506 * exit touch mode, and find a view to take focus, so that the user may resume interacting
507 * with the user interface without touching the screen again.
508 * </p>
509 * <p>
510 * The touch mode state is maintained across {@link android.app.Activity}s. Call
511 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
512 * </p>
513 *
514 * <a name="Scrolling"></a>
515 * <h3>Scrolling</h3>
516 * <p>
517 * The framework provides basic support for views that wish to internally
518 * scroll their content. This includes keeping track of the X and Y scroll
519 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700520 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
521 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 * </p>
523 *
524 * <a name="Tags"></a>
525 * <h3>Tags</h3>
526 * <p>
527 * Unlike IDs, tags are not used to identify views. Tags are essentially an
528 * extra piece of information that can be associated with a view. They are most
529 * often used as a convenience to store data related to views in the views
530 * themselves rather than by putting them in a separate structure.
531 * </p>
532 *
533 * <a name="Animation"></a>
534 * <h3>Animation</h3>
535 * <p>
536 * You can attach an {@link Animation} object to a view using
537 * {@link #setAnimation(Animation)} or
538 * {@link #startAnimation(Animation)}. The animation can alter the scale,
539 * rotation, translation and alpha of a view over time. If the animation is
540 * attached to a view that has children, the animation will affect the entire
541 * subtree rooted by that node. When an animation is started, the framework will
542 * take care of redrawing the appropriate views until the animation completes.
543 * </p>
544 *
Jeff Brown85a31762010-09-01 17:01:00 -0700545 * <a name="Security"></a>
546 * <h3>Security</h3>
547 * <p>
548 * Sometimes it is essential that an application be able to verify that an action
549 * is being performed with the full knowledge and consent of the user, such as
550 * granting a permission request, making a purchase or clicking on an advertisement.
551 * Unfortunately, a malicious application could try to spoof the user into
552 * performing these actions, unaware, by concealing the intended purpose of the view.
553 * As a remedy, the framework offers a touch filtering mechanism that can be used to
554 * improve the security of views that provide access to sensitive functionality.
555 * </p><p>
556 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
557 * andoird:filterTouchesWhenObscured attribute to true. When enabled, the framework
558 * will discard touches that are received whenever the view's window is obscured by
559 * another visible window. As a result, the view will not receive touches whenever a
560 * toast, dialog or other window appears above the view's window.
561 * </p><p>
562 * For more fine-grained control over security, consider overriding the
563 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
564 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
565 * </p>
566 *
Romain Guyd6a463a2009-05-21 23:10:10 -0700567 * @attr ref android.R.styleable#View_background
568 * @attr ref android.R.styleable#View_clickable
569 * @attr ref android.R.styleable#View_contentDescription
570 * @attr ref android.R.styleable#View_drawingCacheQuality
571 * @attr ref android.R.styleable#View_duplicateParentState
572 * @attr ref android.R.styleable#View_id
573 * @attr ref android.R.styleable#View_fadingEdge
574 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700575 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700577 * @attr ref android.R.styleable#View_isScrollContainer
578 * @attr ref android.R.styleable#View_focusable
579 * @attr ref android.R.styleable#View_focusableInTouchMode
580 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
581 * @attr ref android.R.styleable#View_keepScreenOn
582 * @attr ref android.R.styleable#View_longClickable
583 * @attr ref android.R.styleable#View_minHeight
584 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 * @attr ref android.R.styleable#View_nextFocusDown
586 * @attr ref android.R.styleable#View_nextFocusLeft
587 * @attr ref android.R.styleable#View_nextFocusRight
588 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700589 * @attr ref android.R.styleable#View_onClick
590 * @attr ref android.R.styleable#View_padding
591 * @attr ref android.R.styleable#View_paddingBottom
592 * @attr ref android.R.styleable#View_paddingLeft
593 * @attr ref android.R.styleable#View_paddingRight
594 * @attr ref android.R.styleable#View_paddingTop
595 * @attr ref android.R.styleable#View_saveEnabled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 * @attr ref android.R.styleable#View_scrollX
597 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700598 * @attr ref android.R.styleable#View_scrollbarSize
599 * @attr ref android.R.styleable#View_scrollbarStyle
600 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700601 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
602 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
604 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 * @attr ref android.R.styleable#View_scrollbarThumbVertical
606 * @attr ref android.R.styleable#View_scrollbarTrackVertical
607 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
608 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700609 * @attr ref android.R.styleable#View_soundEffectsEnabled
610 * @attr ref android.R.styleable#View_tag
611 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 *
613 * @see android.view.ViewGroup
614 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700615public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 private static final boolean DBG = false;
617
618 /**
619 * The logging tag used by this class with android.util.Log.
620 */
621 protected static final String VIEW_LOG_TAG = "View";
622
623 /**
624 * Used to mark a View that has no ID.
625 */
626 public static final int NO_ID = -1;
627
628 /**
629 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
630 * calling setFlags.
631 */
632 private static final int NOT_FOCUSABLE = 0x00000000;
633
634 /**
635 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
636 * setFlags.
637 */
638 private static final int FOCUSABLE = 0x00000001;
639
640 /**
641 * Mask for use with setFlags indicating bits used for focus.
642 */
643 private static final int FOCUSABLE_MASK = 0x00000001;
644
645 /**
646 * This view will adjust its padding to fit sytem windows (e.g. status bar)
647 */
648 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
649
650 /**
651 * This view is visible. Use with {@link #setVisibility}.
652 */
653 public static final int VISIBLE = 0x00000000;
654
655 /**
656 * This view is invisible, but it still takes up space for layout purposes.
657 * Use with {@link #setVisibility}.
658 */
659 public static final int INVISIBLE = 0x00000004;
660
661 /**
662 * This view is invisible, and it doesn't take any space for layout
663 * purposes. Use with {@link #setVisibility}.
664 */
665 public static final int GONE = 0x00000008;
666
667 /**
668 * Mask for use with setFlags indicating bits used for visibility.
669 * {@hide}
670 */
671 static final int VISIBILITY_MASK = 0x0000000C;
672
673 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
674
675 /**
676 * This view is enabled. Intrepretation varies by subclass.
677 * Use with ENABLED_MASK when calling setFlags.
678 * {@hide}
679 */
680 static final int ENABLED = 0x00000000;
681
682 /**
683 * This view is disabled. Intrepretation varies by subclass.
684 * Use with ENABLED_MASK when calling setFlags.
685 * {@hide}
686 */
687 static final int DISABLED = 0x00000020;
688
689 /**
690 * Mask for use with setFlags indicating bits used for indicating whether
691 * this view is enabled
692 * {@hide}
693 */
694 static final int ENABLED_MASK = 0x00000020;
695
696 /**
697 * This view won't draw. {@link #onDraw} won't be called and further
698 * optimizations
699 * will be performed. It is okay to have this flag set and a background.
700 * Use with DRAW_MASK when calling setFlags.
701 * {@hide}
702 */
703 static final int WILL_NOT_DRAW = 0x00000080;
704
705 /**
706 * Mask for use with setFlags indicating bits used for indicating whether
707 * this view is will draw
708 * {@hide}
709 */
710 static final int DRAW_MASK = 0x00000080;
711
712 /**
713 * <p>This view doesn't show scrollbars.</p>
714 * {@hide}
715 */
716 static final int SCROLLBARS_NONE = 0x00000000;
717
718 /**
719 * <p>This view shows horizontal scrollbars.</p>
720 * {@hide}
721 */
722 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
723
724 /**
725 * <p>This view shows vertical scrollbars.</p>
726 * {@hide}
727 */
728 static final int SCROLLBARS_VERTICAL = 0x00000200;
729
730 /**
731 * <p>Mask for use with setFlags indicating bits used for indicating which
732 * scrollbars are enabled.</p>
733 * {@hide}
734 */
735 static final int SCROLLBARS_MASK = 0x00000300;
736
Jeff Brown85a31762010-09-01 17:01:00 -0700737 /**
738 * Indicates that the view should filter touches when its window is obscured.
739 * Refer to the class comments for more information about this security feature.
740 * {@hide}
741 */
742 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
743
744 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745
746 /**
747 * <p>This view doesn't show fading edges.</p>
748 * {@hide}
749 */
750 static final int FADING_EDGE_NONE = 0x00000000;
751
752 /**
753 * <p>This view shows horizontal fading edges.</p>
754 * {@hide}
755 */
756 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
757
758 /**
759 * <p>This view shows vertical fading edges.</p>
760 * {@hide}
761 */
762 static final int FADING_EDGE_VERTICAL = 0x00002000;
763
764 /**
765 * <p>Mask for use with setFlags indicating bits used for indicating which
766 * fading edges are enabled.</p>
767 * {@hide}
768 */
769 static final int FADING_EDGE_MASK = 0x00003000;
770
771 /**
772 * <p>Indicates this view can be clicked. When clickable, a View reacts
773 * to clicks by notifying the OnClickListener.<p>
774 * {@hide}
775 */
776 static final int CLICKABLE = 0x00004000;
777
778 /**
779 * <p>Indicates this view is caching its drawing into a bitmap.</p>
780 * {@hide}
781 */
782 static final int DRAWING_CACHE_ENABLED = 0x00008000;
783
784 /**
785 * <p>Indicates that no icicle should be saved for this view.<p>
786 * {@hide}
787 */
788 static final int SAVE_DISABLED = 0x000010000;
789
790 /**
791 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
792 * property.</p>
793 * {@hide}
794 */
795 static final int SAVE_DISABLED_MASK = 0x000010000;
796
797 /**
798 * <p>Indicates that no drawing cache should ever be created for this view.<p>
799 * {@hide}
800 */
801 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
802
803 /**
804 * <p>Indicates this view can take / keep focus when int touch mode.</p>
805 * {@hide}
806 */
807 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
808
809 /**
810 * <p>Enables low quality mode for the drawing cache.</p>
811 */
812 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
813
814 /**
815 * <p>Enables high quality mode for the drawing cache.</p>
816 */
817 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
818
819 /**
820 * <p>Enables automatic quality mode for the drawing cache.</p>
821 */
822 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
823
824 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
825 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
826 };
827
828 /**
829 * <p>Mask for use with setFlags indicating bits used for the cache
830 * quality property.</p>
831 * {@hide}
832 */
833 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
834
835 /**
836 * <p>
837 * Indicates this view can be long clicked. When long clickable, a View
838 * reacts to long clicks by notifying the OnLongClickListener or showing a
839 * context menu.
840 * </p>
841 * {@hide}
842 */
843 static final int LONG_CLICKABLE = 0x00200000;
844
845 /**
846 * <p>Indicates that this view gets its drawable states from its direct parent
847 * and ignores its original internal states.</p>
848 *
849 * @hide
850 */
851 static final int DUPLICATE_PARENT_STATE = 0x00400000;
852
853 /**
854 * The scrollbar style to display the scrollbars inside the content area,
855 * without increasing the padding. The scrollbars will be overlaid with
856 * translucency on the view's content.
857 */
858 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
859
860 /**
861 * The scrollbar style to display the scrollbars inside the padded area,
862 * increasing the padding of the view. The scrollbars will not overlap the
863 * content area of the view.
864 */
865 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
866
867 /**
868 * The scrollbar style to display the scrollbars at the edge of the view,
869 * without increasing the padding. The scrollbars will be overlaid with
870 * translucency.
871 */
872 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
873
874 /**
875 * The scrollbar style to display the scrollbars at the edge of the view,
876 * increasing the padding of the view. The scrollbars will only overlap the
877 * background, if any.
878 */
879 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
880
881 /**
882 * Mask to check if the scrollbar style is overlay or inset.
883 * {@hide}
884 */
885 static final int SCROLLBARS_INSET_MASK = 0x01000000;
886
887 /**
888 * Mask to check if the scrollbar style is inside or outside.
889 * {@hide}
890 */
891 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
892
893 /**
894 * Mask for scrollbar style.
895 * {@hide}
896 */
897 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
898
899 /**
900 * View flag indicating that the screen should remain on while the
901 * window containing this view is visible to the user. This effectively
902 * takes care of automatically setting the WindowManager's
903 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
904 */
905 public static final int KEEP_SCREEN_ON = 0x04000000;
906
907 /**
908 * View flag indicating whether this view should have sound effects enabled
909 * for events such as clicking and touching.
910 */
911 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
912
913 /**
914 * View flag indicating whether this view should have haptic feedback
915 * enabled for events such as long presses.
916 */
917 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
918
919 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700920 * <p>Indicates that the view hierarchy should stop saving state when
921 * it reaches this view. If state saving is initiated immediately at
922 * the view, it will be allowed.
923 * {@hide}
924 */
925 static final int PARENT_SAVE_DISABLED = 0x20000000;
926
927 /**
928 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
929 * {@hide}
930 */
931 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
932
933 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700934 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
935 * should add all focusable Views regardless if they are focusable in touch mode.
936 */
937 public static final int FOCUSABLES_ALL = 0x00000000;
938
939 /**
940 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
941 * should add only Views focusable in touch mode.
942 */
943 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
944
945 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 * Use with {@link #focusSearch}. Move focus to the previous selectable
947 * item.
948 */
949 public static final int FOCUS_BACKWARD = 0x00000001;
950
951 /**
952 * Use with {@link #focusSearch}. Move focus to the next selectable
953 * item.
954 */
955 public static final int FOCUS_FORWARD = 0x00000002;
956
957 /**
958 * Use with {@link #focusSearch}. Move focus to the left.
959 */
960 public static final int FOCUS_LEFT = 0x00000011;
961
962 /**
963 * Use with {@link #focusSearch}. Move focus up.
964 */
965 public static final int FOCUS_UP = 0x00000021;
966
967 /**
968 * Use with {@link #focusSearch}. Move focus to the right.
969 */
970 public static final int FOCUS_RIGHT = 0x00000042;
971
972 /**
973 * Use with {@link #focusSearch}. Move focus down.
974 */
975 public static final int FOCUS_DOWN = 0x00000082;
976
977 /**
978 * Base View state sets
979 */
980 // Singles
981 /**
982 * Indicates the view has no states set. States are used with
983 * {@link android.graphics.drawable.Drawable} to change the drawing of the
984 * view depending on its state.
985 *
986 * @see android.graphics.drawable.Drawable
987 * @see #getDrawableState()
988 */
989 protected static final int[] EMPTY_STATE_SET = {};
990 /**
991 * Indicates the view is enabled. States are used with
992 * {@link android.graphics.drawable.Drawable} to change the drawing of the
993 * view depending on its state.
994 *
995 * @see android.graphics.drawable.Drawable
996 * @see #getDrawableState()
997 */
998 protected static final int[] ENABLED_STATE_SET = {R.attr.state_enabled};
999 /**
1000 * Indicates the view is focused. States are used with
1001 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1002 * view depending on its state.
1003 *
1004 * @see android.graphics.drawable.Drawable
1005 * @see #getDrawableState()
1006 */
1007 protected static final int[] FOCUSED_STATE_SET = {R.attr.state_focused};
1008 /**
1009 * Indicates the view is selected. States are used with
1010 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1011 * view depending on its state.
1012 *
1013 * @see android.graphics.drawable.Drawable
1014 * @see #getDrawableState()
1015 */
1016 protected static final int[] SELECTED_STATE_SET = {R.attr.state_selected};
1017 /**
1018 * Indicates the view is pressed. States are used with
1019 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1020 * view depending on its state.
1021 *
1022 * @see android.graphics.drawable.Drawable
1023 * @see #getDrawableState()
1024 * @hide
1025 */
1026 protected static final int[] PRESSED_STATE_SET = {R.attr.state_pressed};
1027 /**
1028 * Indicates the view's window has focus. States are used with
1029 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1030 * view depending on its state.
1031 *
1032 * @see android.graphics.drawable.Drawable
1033 * @see #getDrawableState()
1034 */
1035 protected static final int[] WINDOW_FOCUSED_STATE_SET =
1036 {R.attr.state_window_focused};
1037 // Doubles
1038 /**
1039 * Indicates the view is enabled and has the focus.
1040 *
1041 * @see #ENABLED_STATE_SET
1042 * @see #FOCUSED_STATE_SET
1043 */
1044 protected static final int[] ENABLED_FOCUSED_STATE_SET =
1045 stateSetUnion(ENABLED_STATE_SET, FOCUSED_STATE_SET);
1046 /**
1047 * Indicates the view is enabled and selected.
1048 *
1049 * @see #ENABLED_STATE_SET
1050 * @see #SELECTED_STATE_SET
1051 */
1052 protected static final int[] ENABLED_SELECTED_STATE_SET =
1053 stateSetUnion(ENABLED_STATE_SET, SELECTED_STATE_SET);
1054 /**
1055 * Indicates the view is enabled and that its window has focus.
1056 *
1057 * @see #ENABLED_STATE_SET
1058 * @see #WINDOW_FOCUSED_STATE_SET
1059 */
1060 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET =
1061 stateSetUnion(ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1062 /**
1063 * Indicates the view is focused and selected.
1064 *
1065 * @see #FOCUSED_STATE_SET
1066 * @see #SELECTED_STATE_SET
1067 */
1068 protected static final int[] FOCUSED_SELECTED_STATE_SET =
1069 stateSetUnion(FOCUSED_STATE_SET, SELECTED_STATE_SET);
1070 /**
1071 * Indicates the view has the focus and that its window has the focus.
1072 *
1073 * @see #FOCUSED_STATE_SET
1074 * @see #WINDOW_FOCUSED_STATE_SET
1075 */
1076 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET =
1077 stateSetUnion(FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1078 /**
1079 * Indicates the view is selected and that its window has the focus.
1080 *
1081 * @see #SELECTED_STATE_SET
1082 * @see #WINDOW_FOCUSED_STATE_SET
1083 */
1084 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET =
1085 stateSetUnion(SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1086 // Triples
1087 /**
1088 * Indicates the view is enabled, focused and selected.
1089 *
1090 * @see #ENABLED_STATE_SET
1091 * @see #FOCUSED_STATE_SET
1092 * @see #SELECTED_STATE_SET
1093 */
1094 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET =
1095 stateSetUnion(ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1096 /**
1097 * Indicates the view is enabled, focused and its window has the focus.
1098 *
1099 * @see #ENABLED_STATE_SET
1100 * @see #FOCUSED_STATE_SET
1101 * @see #WINDOW_FOCUSED_STATE_SET
1102 */
1103 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1104 stateSetUnion(ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1105 /**
1106 * Indicates the view is enabled, selected and its window has the focus.
1107 *
1108 * @see #ENABLED_STATE_SET
1109 * @see #SELECTED_STATE_SET
1110 * @see #WINDOW_FOCUSED_STATE_SET
1111 */
1112 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1113 stateSetUnion(ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1114 /**
1115 * Indicates the view is focused, selected and its window has the focus.
1116 *
1117 * @see #FOCUSED_STATE_SET
1118 * @see #SELECTED_STATE_SET
1119 * @see #WINDOW_FOCUSED_STATE_SET
1120 */
1121 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1122 stateSetUnion(FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1123 /**
1124 * Indicates the view is enabled, focused, selected and its window
1125 * has the focus.
1126 *
1127 * @see #ENABLED_STATE_SET
1128 * @see #FOCUSED_STATE_SET
1129 * @see #SELECTED_STATE_SET
1130 * @see #WINDOW_FOCUSED_STATE_SET
1131 */
1132 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1133 stateSetUnion(ENABLED_FOCUSED_SELECTED_STATE_SET,
1134 WINDOW_FOCUSED_STATE_SET);
1135
1136 /**
1137 * Indicates the view is pressed and its window has the focus.
1138 *
1139 * @see #PRESSED_STATE_SET
1140 * @see #WINDOW_FOCUSED_STATE_SET
1141 */
1142 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET =
1143 stateSetUnion(PRESSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1144
1145 /**
1146 * Indicates the view is pressed and selected.
1147 *
1148 * @see #PRESSED_STATE_SET
1149 * @see #SELECTED_STATE_SET
1150 */
1151 protected static final int[] PRESSED_SELECTED_STATE_SET =
1152 stateSetUnion(PRESSED_STATE_SET, SELECTED_STATE_SET);
1153
1154 /**
1155 * Indicates the view is pressed, selected and its window has the focus.
1156 *
1157 * @see #PRESSED_STATE_SET
1158 * @see #SELECTED_STATE_SET
1159 * @see #WINDOW_FOCUSED_STATE_SET
1160 */
1161 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1162 stateSetUnion(PRESSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1163
1164 /**
1165 * Indicates the view is pressed and focused.
1166 *
1167 * @see #PRESSED_STATE_SET
1168 * @see #FOCUSED_STATE_SET
1169 */
1170 protected static final int[] PRESSED_FOCUSED_STATE_SET =
1171 stateSetUnion(PRESSED_STATE_SET, FOCUSED_STATE_SET);
1172
1173 /**
1174 * Indicates the view is pressed, focused and its window has the focus.
1175 *
1176 * @see #PRESSED_STATE_SET
1177 * @see #FOCUSED_STATE_SET
1178 * @see #WINDOW_FOCUSED_STATE_SET
1179 */
1180 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1181 stateSetUnion(PRESSED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1182
1183 /**
1184 * Indicates the view is pressed, focused and selected.
1185 *
1186 * @see #PRESSED_STATE_SET
1187 * @see #SELECTED_STATE_SET
1188 * @see #FOCUSED_STATE_SET
1189 */
1190 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET =
1191 stateSetUnion(PRESSED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1192
1193 /**
1194 * Indicates the view is pressed, focused, selected and its window has the focus.
1195 *
1196 * @see #PRESSED_STATE_SET
1197 * @see #FOCUSED_STATE_SET
1198 * @see #SELECTED_STATE_SET
1199 * @see #WINDOW_FOCUSED_STATE_SET
1200 */
1201 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1202 stateSetUnion(PRESSED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1203
1204 /**
1205 * Indicates the view is pressed and enabled.
1206 *
1207 * @see #PRESSED_STATE_SET
1208 * @see #ENABLED_STATE_SET
1209 */
1210 protected static final int[] PRESSED_ENABLED_STATE_SET =
1211 stateSetUnion(PRESSED_STATE_SET, ENABLED_STATE_SET);
1212
1213 /**
1214 * Indicates the view is pressed, enabled and its window has the focus.
1215 *
1216 * @see #PRESSED_STATE_SET
1217 * @see #ENABLED_STATE_SET
1218 * @see #WINDOW_FOCUSED_STATE_SET
1219 */
1220 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET =
1221 stateSetUnion(PRESSED_ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1222
1223 /**
1224 * Indicates the view is pressed, enabled and selected.
1225 *
1226 * @see #PRESSED_STATE_SET
1227 * @see #ENABLED_STATE_SET
1228 * @see #SELECTED_STATE_SET
1229 */
1230 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET =
1231 stateSetUnion(PRESSED_ENABLED_STATE_SET, SELECTED_STATE_SET);
1232
1233 /**
1234 * Indicates the view is pressed, enabled, selected and its window has the
1235 * focus.
1236 *
1237 * @see #PRESSED_STATE_SET
1238 * @see #ENABLED_STATE_SET
1239 * @see #SELECTED_STATE_SET
1240 * @see #WINDOW_FOCUSED_STATE_SET
1241 */
1242 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1243 stateSetUnion(PRESSED_ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1244
1245 /**
1246 * Indicates the view is pressed, enabled and focused.
1247 *
1248 * @see #PRESSED_STATE_SET
1249 * @see #ENABLED_STATE_SET
1250 * @see #FOCUSED_STATE_SET
1251 */
1252 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET =
1253 stateSetUnion(PRESSED_ENABLED_STATE_SET, FOCUSED_STATE_SET);
1254
1255 /**
1256 * Indicates the view is pressed, enabled, focused and its window has the
1257 * focus.
1258 *
1259 * @see #PRESSED_STATE_SET
1260 * @see #ENABLED_STATE_SET
1261 * @see #FOCUSED_STATE_SET
1262 * @see #WINDOW_FOCUSED_STATE_SET
1263 */
1264 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1265 stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1266
1267 /**
1268 * Indicates the view is pressed, enabled, focused and selected.
1269 *
1270 * @see #PRESSED_STATE_SET
1271 * @see #ENABLED_STATE_SET
1272 * @see #SELECTED_STATE_SET
1273 * @see #FOCUSED_STATE_SET
1274 */
1275 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET =
1276 stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1277
1278 /**
1279 * Indicates the view is pressed, enabled, focused, selected and its window
1280 * has the focus.
1281 *
1282 * @see #PRESSED_STATE_SET
1283 * @see #ENABLED_STATE_SET
1284 * @see #SELECTED_STATE_SET
1285 * @see #FOCUSED_STATE_SET
1286 * @see #WINDOW_FOCUSED_STATE_SET
1287 */
1288 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1289 stateSetUnion(PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1290
1291 /**
1292 * The order here is very important to {@link #getDrawableState()}
1293 */
1294 private static final int[][] VIEW_STATE_SETS = {
1295 EMPTY_STATE_SET, // 0 0 0 0 0
1296 WINDOW_FOCUSED_STATE_SET, // 0 0 0 0 1
1297 SELECTED_STATE_SET, // 0 0 0 1 0
1298 SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 0 1 1
1299 FOCUSED_STATE_SET, // 0 0 1 0 0
1300 FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 0 1
1301 FOCUSED_SELECTED_STATE_SET, // 0 0 1 1 0
1302 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 1 1
1303 ENABLED_STATE_SET, // 0 1 0 0 0
1304 ENABLED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 0 1
1305 ENABLED_SELECTED_STATE_SET, // 0 1 0 1 0
1306 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 1 1
1307 ENABLED_FOCUSED_STATE_SET, // 0 1 1 0 0
1308 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 0 1
1309 ENABLED_FOCUSED_SELECTED_STATE_SET, // 0 1 1 1 0
1310 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 1 1
1311 PRESSED_STATE_SET, // 1 0 0 0 0
1312 PRESSED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 0 1
1313 PRESSED_SELECTED_STATE_SET, // 1 0 0 1 0
1314 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 1 1
1315 PRESSED_FOCUSED_STATE_SET, // 1 0 1 0 0
1316 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 0 1
1317 PRESSED_FOCUSED_SELECTED_STATE_SET, // 1 0 1 1 0
1318 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 1 1
1319 PRESSED_ENABLED_STATE_SET, // 1 1 0 0 0
1320 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 0 1
1321 PRESSED_ENABLED_SELECTED_STATE_SET, // 1 1 0 1 0
1322 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 1 1
1323 PRESSED_ENABLED_FOCUSED_STATE_SET, // 1 1 1 0 0
1324 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 0 1
1325 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, // 1 1 1 1 0
1326 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 1 1
1327 };
1328
1329 /**
1330 * Used by views that contain lists of items. This state indicates that
1331 * the view is showing the last item.
1332 * @hide
1333 */
1334 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1335 /**
1336 * Used by views that contain lists of items. This state indicates that
1337 * the view is showing the first item.
1338 * @hide
1339 */
1340 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1341 /**
1342 * Used by views that contain lists of items. This state indicates that
1343 * the view is showing the middle item.
1344 * @hide
1345 */
1346 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1347 /**
1348 * Used by views that contain lists of items. This state indicates that
1349 * the view is showing only one item.
1350 * @hide
1351 */
1352 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1353 /**
1354 * Used by views that contain lists of items. This state indicates that
1355 * the view is pressed and showing the last item.
1356 * @hide
1357 */
1358 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1359 /**
1360 * Used by views that contain lists of items. This state indicates that
1361 * the view is pressed and showing the first item.
1362 * @hide
1363 */
1364 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1365 /**
1366 * Used by views that contain lists of items. This state indicates that
1367 * the view is pressed and showing the middle item.
1368 * @hide
1369 */
1370 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1371 /**
1372 * Used by views that contain lists of items. This state indicates that
1373 * the view is pressed and showing only one item.
1374 * @hide
1375 */
1376 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1377
1378 /**
1379 * Temporary Rect currently for use in setBackground(). This will probably
1380 * be extended in the future to hold our own class with more than just
1381 * a Rect. :)
1382 */
1383 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001384
1385 /**
1386 * Map used to store views' tags.
1387 */
1388 private static WeakHashMap<View, SparseArray<Object>> sTags;
1389
1390 /**
1391 * Lock used to access sTags.
1392 */
1393 private static final Object sTagsLock = new Object();
1394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 /**
1396 * The animation currently associated with this view.
1397 * @hide
1398 */
1399 protected Animation mCurrentAnimation = null;
1400
1401 /**
1402 * Width as measured during measure pass.
1403 * {@hide}
1404 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001405 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 protected int mMeasuredWidth;
1407
1408 /**
1409 * Height as measured during measure pass.
1410 * {@hide}
1411 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001412 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 protected int mMeasuredHeight;
1414
1415 /**
1416 * The view's identifier.
1417 * {@hide}
1418 *
1419 * @see #setId(int)
1420 * @see #getId()
1421 */
1422 @ViewDebug.ExportedProperty(resolveId = true)
1423 int mID = NO_ID;
1424
1425 /**
1426 * The view's tag.
1427 * {@hide}
1428 *
1429 * @see #setTag(Object)
1430 * @see #getTag()
1431 */
1432 protected Object mTag;
1433
1434 // for mPrivateFlags:
1435 /** {@hide} */
1436 static final int WANTS_FOCUS = 0x00000001;
1437 /** {@hide} */
1438 static final int FOCUSED = 0x00000002;
1439 /** {@hide} */
1440 static final int SELECTED = 0x00000004;
1441 /** {@hide} */
1442 static final int IS_ROOT_NAMESPACE = 0x00000008;
1443 /** {@hide} */
1444 static final int HAS_BOUNDS = 0x00000010;
1445 /** {@hide} */
1446 static final int DRAWN = 0x00000020;
1447 /**
1448 * When this flag is set, this view is running an animation on behalf of its
1449 * children and should therefore not cancel invalidate requests, even if they
1450 * lie outside of this view's bounds.
1451 *
1452 * {@hide}
1453 */
1454 static final int DRAW_ANIMATION = 0x00000040;
1455 /** {@hide} */
1456 static final int SKIP_DRAW = 0x00000080;
1457 /** {@hide} */
1458 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1459 /** {@hide} */
1460 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1461 /** {@hide} */
1462 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1463 /** {@hide} */
1464 static final int MEASURED_DIMENSION_SET = 0x00000800;
1465 /** {@hide} */
1466 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001467 /** {@hide} */
1468 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469
1470 private static final int PRESSED = 0x00004000;
1471
1472 /** {@hide} */
1473 static final int DRAWING_CACHE_VALID = 0x00008000;
1474 /**
1475 * Flag used to indicate that this view should be drawn once more (and only once
1476 * more) after its animation has completed.
1477 * {@hide}
1478 */
1479 static final int ANIMATION_STARTED = 0x00010000;
1480
1481 private static final int SAVE_STATE_CALLED = 0x00020000;
1482
1483 /**
1484 * Indicates that the View returned true when onSetAlpha() was called and that
1485 * the alpha must be restored.
1486 * {@hide}
1487 */
1488 static final int ALPHA_SET = 0x00040000;
1489
1490 /**
1491 * Set by {@link #setScrollContainer(boolean)}.
1492 */
1493 static final int SCROLL_CONTAINER = 0x00080000;
1494
1495 /**
1496 * Set by {@link #setScrollContainer(boolean)}.
1497 */
1498 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1499
1500 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001501 * View flag indicating whether this view was invalidated (fully or partially.)
1502 *
1503 * @hide
1504 */
1505 static final int DIRTY = 0x00200000;
1506
1507 /**
1508 * View flag indicating whether this view was invalidated by an opaque
1509 * invalidate request.
1510 *
1511 * @hide
1512 */
1513 static final int DIRTY_OPAQUE = 0x00400000;
1514
1515 /**
1516 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1517 *
1518 * @hide
1519 */
1520 static final int DIRTY_MASK = 0x00600000;
1521
1522 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001523 * Indicates whether the background is opaque.
1524 *
1525 * @hide
1526 */
1527 static final int OPAQUE_BACKGROUND = 0x00800000;
1528
1529 /**
1530 * Indicates whether the scrollbars are opaque.
1531 *
1532 * @hide
1533 */
1534 static final int OPAQUE_SCROLLBARS = 0x01000000;
1535
1536 /**
1537 * Indicates whether the view is opaque.
1538 *
1539 * @hide
1540 */
1541 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001542
1543 /**
1544 * Indicates a prepressed state;
1545 * the short time between ACTION_DOWN and recognizing
1546 * a 'real' press. Prepressed is used to recognize quick taps
1547 * even when they are shorter than ViewConfiguration.getTapTimeout().
1548 *
1549 * @hide
1550 */
1551 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001552
1553 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001554 * Indicates whether the view is temporarily detached.
1555 *
1556 * @hide
1557 */
1558 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001559
1560 /**
1561 * Indicates that we should awaken scroll bars once attached
1562 *
1563 * @hide
1564 */
1565 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001566
1567 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001568 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1569 * for transform operations
1570 *
1571 * @hide
1572 */
1573 private static final int PIVOT_EXPLICITLY_SET = 0x10000000;
1574
1575 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 * The parent this view is attached to.
1577 * {@hide}
1578 *
1579 * @see #getParent()
1580 */
1581 protected ViewParent mParent;
1582
1583 /**
1584 * {@hide}
1585 */
1586 AttachInfo mAttachInfo;
1587
1588 /**
1589 * {@hide}
1590 */
Romain Guy809a7f62009-05-14 15:44:42 -07001591 @ViewDebug.ExportedProperty(flagMapping = {
1592 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1593 name = "FORCE_LAYOUT"),
1594 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1595 name = "LAYOUT_REQUIRED"),
1596 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001597 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001598 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1599 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1600 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1601 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1602 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 int mPrivateFlags;
1604
1605 /**
1606 * Count of how many windows this view has been attached to.
1607 */
1608 int mWindowAttachCount;
1609
1610 /**
1611 * The layout parameters associated with this view and used by the parent
1612 * {@link android.view.ViewGroup} to determine how this view should be
1613 * laid out.
1614 * {@hide}
1615 */
1616 protected ViewGroup.LayoutParams mLayoutParams;
1617
1618 /**
1619 * The view flags hold various views states.
1620 * {@hide}
1621 */
1622 @ViewDebug.ExportedProperty
1623 int mViewFlags;
1624
1625 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001626 * The transform matrix for the View. This transform is calculated internally
1627 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1628 * is used by default. Do *not* use this variable directly; instead call
1629 * getMatrix(), which will automatically recalculate the matrix if necessary
1630 * to get the correct matrix based on the latest rotation and scale properties.
1631 */
1632 private final Matrix mMatrix = new Matrix();
1633
1634 /**
1635 * The transform matrix for the View. This transform is calculated internally
1636 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1637 * is used by default. Do *not* use this variable directly; instead call
1638 * getMatrix(), which will automatically recalculate the matrix if necessary
1639 * to get the correct matrix based on the latest rotation and scale properties.
1640 */
1641 private Matrix mInverseMatrix;
1642
1643 /**
1644 * An internal variable that tracks whether we need to recalculate the
1645 * transform matrix, based on whether the rotation or scaleX/Y properties
1646 * have changed since the matrix was last calculated.
1647 */
1648 private boolean mMatrixDirty = false;
1649
1650 /**
1651 * An internal variable that tracks whether we need to recalculate the
1652 * transform matrix, based on whether the rotation or scaleX/Y properties
1653 * have changed since the matrix was last calculated.
1654 */
1655 private boolean mInverseMatrixDirty = true;
1656
1657 /**
1658 * A variable that tracks whether we need to recalculate the
1659 * transform matrix, based on whether the rotation or scaleX/Y properties
1660 * have changed since the matrix was last calculated. This variable
1661 * is only valid after a call to getMatrix().
1662 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001663 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001664
1665 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001666 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1667 */
1668 private Camera mCamera = null;
1669
1670 /**
1671 * This matrix is used when computing the matrix for 3D rotations.
1672 */
1673 private Matrix matrix3D = null;
1674
1675 /**
1676 * These prev values are used to recalculate a centered pivot point when necessary. The
1677 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1678 * set), so thes values are only used then as well.
1679 */
1680 private int mPrevWidth = -1;
1681 private int mPrevHeight = -1;
1682
1683 /**
1684 * Convenience value to check for float values that are close enough to zero to be considered
1685 * zero.
1686 */
Romain Guy2542d192010-08-18 11:47:12 -07001687 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001688
1689 /**
1690 * The degrees rotation around the vertical axis through the pivot point.
1691 */
1692 @ViewDebug.ExportedProperty
1693 private float mRotationY = 0f;
1694
1695 /**
1696 * The degrees rotation around the horizontal axis through the pivot point.
1697 */
1698 @ViewDebug.ExportedProperty
1699 private float mRotationX = 0f;
1700
1701 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001702 * The degrees rotation around the pivot point.
1703 */
1704 @ViewDebug.ExportedProperty
1705 private float mRotation = 0f;
1706
1707 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001708 * The amount of translation of the object away from its left property (post-layout).
1709 */
1710 @ViewDebug.ExportedProperty
1711 private float mTranslationX = 0f;
1712
1713 /**
1714 * The amount of translation of the object away from its top property (post-layout).
1715 */
1716 @ViewDebug.ExportedProperty
1717 private float mTranslationY = 0f;
1718
1719 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001720 * The amount of scale in the x direction around the pivot point. A
1721 * value of 1 means no scaling is applied.
1722 */
1723 @ViewDebug.ExportedProperty
1724 private float mScaleX = 1f;
1725
1726 /**
1727 * The amount of scale in the y direction around the pivot point. A
1728 * value of 1 means no scaling is applied.
1729 */
1730 @ViewDebug.ExportedProperty
1731 private float mScaleY = 1f;
1732
1733 /**
1734 * The amount of scale in the x direction around the pivot point. A
1735 * value of 1 means no scaling is applied.
1736 */
1737 @ViewDebug.ExportedProperty
1738 private float mPivotX = 0f;
1739
1740 /**
1741 * The amount of scale in the y direction around the pivot point. A
1742 * value of 1 means no scaling is applied.
1743 */
1744 @ViewDebug.ExportedProperty
1745 private float mPivotY = 0f;
1746
1747 /**
1748 * The opacity of the View. This is a value from 0 to 1, where 0 means
1749 * completely transparent and 1 means completely opaque.
1750 */
1751 @ViewDebug.ExportedProperty
1752 private float mAlpha = 1f;
1753
1754 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 * The distance in pixels from the left edge of this view's parent
1756 * to the left edge of this view.
1757 * {@hide}
1758 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001759 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 protected int mLeft;
1761 /**
1762 * The distance in pixels from the left edge of this view's parent
1763 * to the right edge of this view.
1764 * {@hide}
1765 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001766 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 protected int mRight;
1768 /**
1769 * The distance in pixels from the top edge of this view's parent
1770 * to the top edge of this view.
1771 * {@hide}
1772 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001773 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 protected int mTop;
1775 /**
1776 * The distance in pixels from the top edge of this view's parent
1777 * to the bottom edge of this view.
1778 * {@hide}
1779 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001780 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 protected int mBottom;
1782
1783 /**
1784 * The offset, in pixels, by which the content of this view is scrolled
1785 * horizontally.
1786 * {@hide}
1787 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001788 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 protected int mScrollX;
1790 /**
1791 * The offset, in pixels, by which the content of this view is scrolled
1792 * vertically.
1793 * {@hide}
1794 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001795 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 protected int mScrollY;
1797
1798 /**
1799 * The left padding in pixels, that is the distance in pixels between the
1800 * left edge of this view and the left edge of its content.
1801 * {@hide}
1802 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001803 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 protected int mPaddingLeft;
1805 /**
1806 * The right padding in pixels, that is the distance in pixels between the
1807 * right edge of this view and the right edge of its content.
1808 * {@hide}
1809 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001810 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 protected int mPaddingRight;
1812 /**
1813 * The top padding in pixels, that is the distance in pixels between the
1814 * top edge of this view and the top edge of its content.
1815 * {@hide}
1816 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001817 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 protected int mPaddingTop;
1819 /**
1820 * The bottom padding in pixels, that is the distance in pixels between the
1821 * bottom edge of this view and the bottom edge of its content.
1822 * {@hide}
1823 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001824 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 protected int mPaddingBottom;
1826
1827 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001828 * Briefly describes the view and is primarily used for accessibility support.
1829 */
1830 private CharSequence mContentDescription;
1831
1832 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 * Cache the paddingRight set by the user to append to the scrollbar's size.
1834 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001835 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 int mUserPaddingRight;
1837
1838 /**
1839 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1840 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001841 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 int mUserPaddingBottom;
1843
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001844 /**
1845 * @hide
1846 */
1847 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1848 /**
1849 * @hide
1850 */
1851 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852
1853 private Resources mResources = null;
1854
1855 private Drawable mBGDrawable;
1856
1857 private int mBackgroundResource;
1858 private boolean mBackgroundSizeChanged;
1859
1860 /**
1861 * Listener used to dispatch focus change events.
1862 * This field should be made private, so it is hidden from the SDK.
1863 * {@hide}
1864 */
1865 protected OnFocusChangeListener mOnFocusChangeListener;
1866
1867 /**
Chet Haase21cd1382010-09-01 17:42:29 -07001868 * Listeners for layout change events.
1869 */
1870 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
1871
1872 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 * Listener used to dispatch click events.
1874 * This field should be made private, so it is hidden from the SDK.
1875 * {@hide}
1876 */
1877 protected OnClickListener mOnClickListener;
1878
1879 /**
1880 * Listener used to dispatch long click events.
1881 * This field should be made private, so it is hidden from the SDK.
1882 * {@hide}
1883 */
1884 protected OnLongClickListener mOnLongClickListener;
1885
1886 /**
1887 * Listener used to build the context menu.
1888 * This field should be made private, so it is hidden from the SDK.
1889 * {@hide}
1890 */
1891 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
1892
1893 private OnKeyListener mOnKeyListener;
1894
1895 private OnTouchListener mOnTouchListener;
1896
1897 /**
1898 * The application environment this view lives in.
1899 * This field should be made private, so it is hidden from the SDK.
1900 * {@hide}
1901 */
1902 protected Context mContext;
1903
1904 private ScrollabilityCache mScrollCache;
1905
1906 private int[] mDrawableState = null;
1907
Romain Guy02890fd2010-08-06 17:58:44 -07001908 private Bitmap mDrawingCache;
1909 private Bitmap mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910
1911 /**
1912 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
1913 * the user may specify which view to go to next.
1914 */
1915 private int mNextFocusLeftId = View.NO_ID;
1916
1917 /**
1918 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
1919 * the user may specify which view to go to next.
1920 */
1921 private int mNextFocusRightId = View.NO_ID;
1922
1923 /**
1924 * When this view has focus and the next focus is {@link #FOCUS_UP},
1925 * the user may specify which view to go to next.
1926 */
1927 private int mNextFocusUpId = View.NO_ID;
1928
1929 /**
1930 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
1931 * the user may specify which view to go to next.
1932 */
1933 private int mNextFocusDownId = View.NO_ID;
1934
1935 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08001936 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08001937 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08001938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 private UnsetPressedState mUnsetPressedState;
1940
1941 /**
1942 * Whether the long press's action has been invoked. The tap's action is invoked on the
1943 * up event while a long press is invoked as soon as the long press duration is reached, so
1944 * a long press could be performed before the tap is checked, in which case the tap's action
1945 * should not be invoked.
1946 */
1947 private boolean mHasPerformedLongPress;
1948
1949 /**
1950 * The minimum height of the view. We'll try our best to have the height
1951 * of this view to at least this amount.
1952 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001953 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 private int mMinHeight;
1955
1956 /**
1957 * The minimum width of the view. We'll try our best to have the width
1958 * of this view to at least this amount.
1959 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001960 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 private int mMinWidth;
1962
1963 /**
1964 * The delegate to handle touch events that are physically in this view
1965 * but should be handled by another view.
1966 */
1967 private TouchDelegate mTouchDelegate = null;
1968
1969 /**
1970 * Solid color to use as a background when creating the drawing cache. Enables
1971 * the cache to use 16 bit bitmaps instead of 32 bit.
1972 */
1973 private int mDrawingCacheBackgroundColor = 0;
1974
1975 /**
1976 * Special tree observer used when mAttachInfo is null.
1977 */
1978 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08001979
1980 /**
1981 * Cache the touch slop from the context that created the view.
1982 */
1983 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 /**
1986 * Simple constructor to use when creating a view from code.
1987 *
1988 * @param context The Context the view is running in, through which it can
1989 * access the current theme, resources, etc.
1990 */
1991 public View(Context context) {
1992 mContext = context;
1993 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07001994 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08001995 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
1997
1998 /**
1999 * Constructor that is called when inflating a view from XML. This is called
2000 * when a view is being constructed from an XML file, supplying attributes
2001 * that were specified in the XML file. This version uses a default style of
2002 * 0, so the only attribute values applied are those in the Context's Theme
2003 * and the given AttributeSet.
2004 *
2005 * <p>
2006 * The method onFinishInflate() will be called after all children have been
2007 * added.
2008 *
2009 * @param context The Context the view is running in, through which it can
2010 * access the current theme, resources, etc.
2011 * @param attrs The attributes of the XML tag that is inflating the view.
2012 * @see #View(Context, AttributeSet, int)
2013 */
2014 public View(Context context, AttributeSet attrs) {
2015 this(context, attrs, 0);
2016 }
2017
2018 /**
2019 * Perform inflation from XML and apply a class-specific base style. This
2020 * constructor of View allows subclasses to use their own base style when
2021 * they are inflating. For example, a Button class's constructor would call
2022 * this version of the super class constructor and supply
2023 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2024 * the theme's button style to modify all of the base view attributes (in
2025 * particular its background) as well as the Button class's attributes.
2026 *
2027 * @param context The Context the view is running in, through which it can
2028 * access the current theme, resources, etc.
2029 * @param attrs The attributes of the XML tag that is inflating the view.
2030 * @param defStyle The default style to apply to this view. If 0, no style
2031 * will be applied (beyond what is included in the theme). This may
2032 * either be an attribute resource, whose value will be retrieved
2033 * from the current theme, or an explicit style resource.
2034 * @see #View(Context, AttributeSet)
2035 */
2036 public View(Context context, AttributeSet attrs, int defStyle) {
2037 this(context);
2038
2039 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2040 defStyle, 0);
2041
2042 Drawable background = null;
2043
2044 int leftPadding = -1;
2045 int topPadding = -1;
2046 int rightPadding = -1;
2047 int bottomPadding = -1;
2048
2049 int padding = -1;
2050
2051 int viewFlagValues = 0;
2052 int viewFlagMasks = 0;
2053
2054 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 int x = 0;
2057 int y = 0;
2058
2059 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2060
2061 final int N = a.getIndexCount();
2062 for (int i = 0; i < N; i++) {
2063 int attr = a.getIndex(i);
2064 switch (attr) {
2065 case com.android.internal.R.styleable.View_background:
2066 background = a.getDrawable(attr);
2067 break;
2068 case com.android.internal.R.styleable.View_padding:
2069 padding = a.getDimensionPixelSize(attr, -1);
2070 break;
2071 case com.android.internal.R.styleable.View_paddingLeft:
2072 leftPadding = a.getDimensionPixelSize(attr, -1);
2073 break;
2074 case com.android.internal.R.styleable.View_paddingTop:
2075 topPadding = a.getDimensionPixelSize(attr, -1);
2076 break;
2077 case com.android.internal.R.styleable.View_paddingRight:
2078 rightPadding = a.getDimensionPixelSize(attr, -1);
2079 break;
2080 case com.android.internal.R.styleable.View_paddingBottom:
2081 bottomPadding = a.getDimensionPixelSize(attr, -1);
2082 break;
2083 case com.android.internal.R.styleable.View_scrollX:
2084 x = a.getDimensionPixelOffset(attr, 0);
2085 break;
2086 case com.android.internal.R.styleable.View_scrollY:
2087 y = a.getDimensionPixelOffset(attr, 0);
2088 break;
2089 case com.android.internal.R.styleable.View_id:
2090 mID = a.getResourceId(attr, NO_ID);
2091 break;
2092 case com.android.internal.R.styleable.View_tag:
2093 mTag = a.getText(attr);
2094 break;
2095 case com.android.internal.R.styleable.View_fitsSystemWindows:
2096 if (a.getBoolean(attr, false)) {
2097 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2098 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2099 }
2100 break;
2101 case com.android.internal.R.styleable.View_focusable:
2102 if (a.getBoolean(attr, false)) {
2103 viewFlagValues |= FOCUSABLE;
2104 viewFlagMasks |= FOCUSABLE_MASK;
2105 }
2106 break;
2107 case com.android.internal.R.styleable.View_focusableInTouchMode:
2108 if (a.getBoolean(attr, false)) {
2109 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2110 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2111 }
2112 break;
2113 case com.android.internal.R.styleable.View_clickable:
2114 if (a.getBoolean(attr, false)) {
2115 viewFlagValues |= CLICKABLE;
2116 viewFlagMasks |= CLICKABLE;
2117 }
2118 break;
2119 case com.android.internal.R.styleable.View_longClickable:
2120 if (a.getBoolean(attr, false)) {
2121 viewFlagValues |= LONG_CLICKABLE;
2122 viewFlagMasks |= LONG_CLICKABLE;
2123 }
2124 break;
2125 case com.android.internal.R.styleable.View_saveEnabled:
2126 if (!a.getBoolean(attr, true)) {
2127 viewFlagValues |= SAVE_DISABLED;
2128 viewFlagMasks |= SAVE_DISABLED_MASK;
2129 }
2130 break;
2131 case com.android.internal.R.styleable.View_duplicateParentState:
2132 if (a.getBoolean(attr, false)) {
2133 viewFlagValues |= DUPLICATE_PARENT_STATE;
2134 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2135 }
2136 break;
2137 case com.android.internal.R.styleable.View_visibility:
2138 final int visibility = a.getInt(attr, 0);
2139 if (visibility != 0) {
2140 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2141 viewFlagMasks |= VISIBILITY_MASK;
2142 }
2143 break;
2144 case com.android.internal.R.styleable.View_drawingCacheQuality:
2145 final int cacheQuality = a.getInt(attr, 0);
2146 if (cacheQuality != 0) {
2147 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2148 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2149 }
2150 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002151 case com.android.internal.R.styleable.View_contentDescription:
2152 mContentDescription = a.getString(attr);
2153 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2155 if (!a.getBoolean(attr, true)) {
2156 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2157 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2158 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002159 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2161 if (!a.getBoolean(attr, true)) {
2162 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2163 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2164 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002165 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 case R.styleable.View_scrollbars:
2167 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2168 if (scrollbars != SCROLLBARS_NONE) {
2169 viewFlagValues |= scrollbars;
2170 viewFlagMasks |= SCROLLBARS_MASK;
2171 initializeScrollbars(a);
2172 }
2173 break;
2174 case R.styleable.View_fadingEdge:
2175 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2176 if (fadingEdge != FADING_EDGE_NONE) {
2177 viewFlagValues |= fadingEdge;
2178 viewFlagMasks |= FADING_EDGE_MASK;
2179 initializeFadingEdge(a);
2180 }
2181 break;
2182 case R.styleable.View_scrollbarStyle:
2183 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2184 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2185 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2186 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2187 }
2188 break;
2189 case R.styleable.View_isScrollContainer:
2190 setScrollContainer = true;
2191 if (a.getBoolean(attr, false)) {
2192 setScrollContainer(true);
2193 }
2194 break;
2195 case com.android.internal.R.styleable.View_keepScreenOn:
2196 if (a.getBoolean(attr, false)) {
2197 viewFlagValues |= KEEP_SCREEN_ON;
2198 viewFlagMasks |= KEEP_SCREEN_ON;
2199 }
2200 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002201 case R.styleable.View_filterTouchesWhenObscured:
2202 if (a.getBoolean(attr, false)) {
2203 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2204 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2205 }
2206 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 case R.styleable.View_nextFocusLeft:
2208 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2209 break;
2210 case R.styleable.View_nextFocusRight:
2211 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2212 break;
2213 case R.styleable.View_nextFocusUp:
2214 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2215 break;
2216 case R.styleable.View_nextFocusDown:
2217 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2218 break;
2219 case R.styleable.View_minWidth:
2220 mMinWidth = a.getDimensionPixelSize(attr, 0);
2221 break;
2222 case R.styleable.View_minHeight:
2223 mMinHeight = a.getDimensionPixelSize(attr, 0);
2224 break;
Romain Guy9a817362009-05-01 10:57:14 -07002225 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002226 if (context.isRestricted()) {
2227 throw new IllegalStateException("The android:onClick attribute cannot "
2228 + "be used within a restricted context");
2229 }
2230
Romain Guy9a817362009-05-01 10:57:14 -07002231 final String handlerName = a.getString(attr);
2232 if (handlerName != null) {
2233 setOnClickListener(new OnClickListener() {
2234 private Method mHandler;
2235
2236 public void onClick(View v) {
2237 if (mHandler == null) {
2238 try {
2239 mHandler = getContext().getClass().getMethod(handlerName,
2240 View.class);
2241 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002242 int id = getId();
2243 String idText = id == NO_ID ? "" : " with id '"
2244 + getContext().getResources().getResourceEntryName(
2245 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002246 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002247 handlerName + "(View) in the activity "
2248 + getContext().getClass() + " for onClick handler"
2249 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002250 }
2251 }
2252
2253 try {
2254 mHandler.invoke(getContext(), View.this);
2255 } catch (IllegalAccessException e) {
2256 throw new IllegalStateException("Could not execute non "
2257 + "public method of the activity", e);
2258 } catch (InvocationTargetException e) {
2259 throw new IllegalStateException("Could not execute "
2260 + "method of the activity", e);
2261 }
2262 }
2263 });
2264 }
2265 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 }
2267 }
2268
2269 if (background != null) {
2270 setBackgroundDrawable(background);
2271 }
2272
2273 if (padding >= 0) {
2274 leftPadding = padding;
2275 topPadding = padding;
2276 rightPadding = padding;
2277 bottomPadding = padding;
2278 }
2279
2280 // If the user specified the padding (either with android:padding or
2281 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2282 // use the default padding or the padding from the background drawable
2283 // (stored at this point in mPadding*)
2284 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2285 topPadding >= 0 ? topPadding : mPaddingTop,
2286 rightPadding >= 0 ? rightPadding : mPaddingRight,
2287 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2288
2289 if (viewFlagMasks != 0) {
2290 setFlags(viewFlagValues, viewFlagMasks);
2291 }
2292
2293 // Needs to be called after mViewFlags is set
2294 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2295 recomputePadding();
2296 }
2297
2298 if (x != 0 || y != 0) {
2299 scrollTo(x, y);
2300 }
2301
2302 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2303 setScrollContainer(true);
2304 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002305
2306 computeOpaqueFlags();
2307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 a.recycle();
2309 }
2310
2311 /**
2312 * Non-public constructor for use in testing
2313 */
2314 View() {
2315 }
2316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 /**
2318 * <p>
2319 * Initializes the fading edges from a given set of styled attributes. This
2320 * method should be called by subclasses that need fading edges and when an
2321 * instance of these subclasses is created programmatically rather than
2322 * being inflated from XML. This method is automatically called when the XML
2323 * is inflated.
2324 * </p>
2325 *
2326 * @param a the styled attributes set to initialize the fading edges from
2327 */
2328 protected void initializeFadingEdge(TypedArray a) {
2329 initScrollCache();
2330
2331 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2332 R.styleable.View_fadingEdgeLength,
2333 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2334 }
2335
2336 /**
2337 * Returns the size of the vertical faded edges used to indicate that more
2338 * content in this view is visible.
2339 *
2340 * @return The size in pixels of the vertical faded edge or 0 if vertical
2341 * faded edges are not enabled for this view.
2342 * @attr ref android.R.styleable#View_fadingEdgeLength
2343 */
2344 public int getVerticalFadingEdgeLength() {
2345 if (isVerticalFadingEdgeEnabled()) {
2346 ScrollabilityCache cache = mScrollCache;
2347 if (cache != null) {
2348 return cache.fadingEdgeLength;
2349 }
2350 }
2351 return 0;
2352 }
2353
2354 /**
2355 * Set the size of the faded edge used to indicate that more content in this
2356 * view is available. Will not change whether the fading edge is enabled; use
2357 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2358 * to enable the fading edge for the vertical or horizontal fading edges.
2359 *
2360 * @param length The size in pixels of the faded edge used to indicate that more
2361 * content in this view is visible.
2362 */
2363 public void setFadingEdgeLength(int length) {
2364 initScrollCache();
2365 mScrollCache.fadingEdgeLength = length;
2366 }
2367
2368 /**
2369 * Returns the size of the horizontal faded edges used to indicate that more
2370 * content in this view is visible.
2371 *
2372 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2373 * faded edges are not enabled for this view.
2374 * @attr ref android.R.styleable#View_fadingEdgeLength
2375 */
2376 public int getHorizontalFadingEdgeLength() {
2377 if (isHorizontalFadingEdgeEnabled()) {
2378 ScrollabilityCache cache = mScrollCache;
2379 if (cache != null) {
2380 return cache.fadingEdgeLength;
2381 }
2382 }
2383 return 0;
2384 }
2385
2386 /**
2387 * Returns the width of the vertical scrollbar.
2388 *
2389 * @return The width in pixels of the vertical scrollbar or 0 if there
2390 * is no vertical scrollbar.
2391 */
2392 public int getVerticalScrollbarWidth() {
2393 ScrollabilityCache cache = mScrollCache;
2394 if (cache != null) {
2395 ScrollBarDrawable scrollBar = cache.scrollBar;
2396 if (scrollBar != null) {
2397 int size = scrollBar.getSize(true);
2398 if (size <= 0) {
2399 size = cache.scrollBarSize;
2400 }
2401 return size;
2402 }
2403 return 0;
2404 }
2405 return 0;
2406 }
2407
2408 /**
2409 * Returns the height of the horizontal scrollbar.
2410 *
2411 * @return The height in pixels of the horizontal scrollbar or 0 if
2412 * there is no horizontal scrollbar.
2413 */
2414 protected int getHorizontalScrollbarHeight() {
2415 ScrollabilityCache cache = mScrollCache;
2416 if (cache != null) {
2417 ScrollBarDrawable scrollBar = cache.scrollBar;
2418 if (scrollBar != null) {
2419 int size = scrollBar.getSize(false);
2420 if (size <= 0) {
2421 size = cache.scrollBarSize;
2422 }
2423 return size;
2424 }
2425 return 0;
2426 }
2427 return 0;
2428 }
2429
2430 /**
2431 * <p>
2432 * Initializes the scrollbars from a given set of styled attributes. This
2433 * method should be called by subclasses that need scrollbars and when an
2434 * instance of these subclasses is created programmatically rather than
2435 * being inflated from XML. This method is automatically called when the XML
2436 * is inflated.
2437 * </p>
2438 *
2439 * @param a the styled attributes set to initialize the scrollbars from
2440 */
2441 protected void initializeScrollbars(TypedArray a) {
2442 initScrollCache();
2443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002445
2446 if (scrollabilityCache.scrollBar == null) {
2447 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2448 }
2449
Romain Guy8bda2482010-03-02 11:42:11 -08002450 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451
Mike Cleronf116bf82009-09-27 19:14:12 -07002452 if (!fadeScrollbars) {
2453 scrollabilityCache.state = ScrollabilityCache.ON;
2454 }
2455 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2456
2457
2458 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2459 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2460 .getScrollBarFadeDuration());
2461 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2462 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2463 ViewConfiguration.getScrollDefaultDelay());
2464
2465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2467 com.android.internal.R.styleable.View_scrollbarSize,
2468 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2469
2470 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2471 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2472
2473 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2474 if (thumb != null) {
2475 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2476 }
2477
2478 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2479 false);
2480 if (alwaysDraw) {
2481 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2482 }
2483
2484 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2485 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2486
2487 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2488 if (thumb != null) {
2489 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2490 }
2491
2492 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2493 false);
2494 if (alwaysDraw) {
2495 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2496 }
2497
2498 // Re-apply user/background padding so that scrollbar(s) get added
2499 recomputePadding();
2500 }
2501
2502 /**
2503 * <p>
2504 * Initalizes the scrollability cache if necessary.
2505 * </p>
2506 */
2507 private void initScrollCache() {
2508 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002509 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 }
2511 }
2512
2513 /**
2514 * Register a callback to be invoked when focus of this view changed.
2515 *
2516 * @param l The callback that will run.
2517 */
2518 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2519 mOnFocusChangeListener = l;
2520 }
2521
2522 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002523 * Add a listener that will be called when the bounds of the view change due to
2524 * layout processing.
2525 *
2526 * @param listener The listener that will be called when layout bounds change.
2527 */
2528 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2529 if (mOnLayoutChangeListeners == null) {
2530 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2531 }
2532 mOnLayoutChangeListeners.add(listener);
2533 }
2534
2535 /**
2536 * Remove a listener for layout changes.
2537 *
2538 * @param listener The listener for layout bounds change.
2539 */
2540 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2541 if (mOnLayoutChangeListeners == null) {
2542 return;
2543 }
2544 mOnLayoutChangeListeners.remove(listener);
2545 }
2546
2547 /**
2548 * Gets the current list of listeners for layout changes.
2549 * @return
2550 */
2551 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2552 return mOnLayoutChangeListeners;
2553 }
2554
2555 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 * Returns the focus-change callback registered for this view.
2557 *
2558 * @return The callback, or null if one is not registered.
2559 */
2560 public OnFocusChangeListener getOnFocusChangeListener() {
2561 return mOnFocusChangeListener;
2562 }
2563
2564 /**
2565 * Register a callback to be invoked when this view is clicked. If this view is not
2566 * clickable, it becomes clickable.
2567 *
2568 * @param l The callback that will run
2569 *
2570 * @see #setClickable(boolean)
2571 */
2572 public void setOnClickListener(OnClickListener l) {
2573 if (!isClickable()) {
2574 setClickable(true);
2575 }
2576 mOnClickListener = l;
2577 }
2578
2579 /**
2580 * Register a callback to be invoked when this view is clicked and held. If this view is not
2581 * long clickable, it becomes long clickable.
2582 *
2583 * @param l The callback that will run
2584 *
2585 * @see #setLongClickable(boolean)
2586 */
2587 public void setOnLongClickListener(OnLongClickListener l) {
2588 if (!isLongClickable()) {
2589 setLongClickable(true);
2590 }
2591 mOnLongClickListener = l;
2592 }
2593
2594 /**
2595 * Register a callback to be invoked when the context menu for this view is
2596 * being built. If this view is not long clickable, it becomes long clickable.
2597 *
2598 * @param l The callback that will run
2599 *
2600 */
2601 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2602 if (!isLongClickable()) {
2603 setLongClickable(true);
2604 }
2605 mOnCreateContextMenuListener = l;
2606 }
2607
2608 /**
2609 * Call this view's OnClickListener, if it is defined.
2610 *
2611 * @return True there was an assigned OnClickListener that was called, false
2612 * otherwise is returned.
2613 */
2614 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002615 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 if (mOnClickListener != null) {
2618 playSoundEffect(SoundEffectConstants.CLICK);
2619 mOnClickListener.onClick(this);
2620 return true;
2621 }
2622
2623 return false;
2624 }
2625
2626 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002627 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2628 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002630 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 */
2632 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002633 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 boolean handled = false;
2636 if (mOnLongClickListener != null) {
2637 handled = mOnLongClickListener.onLongClick(View.this);
2638 }
2639 if (!handled) {
2640 handled = showContextMenu();
2641 }
2642 if (handled) {
2643 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2644 }
2645 return handled;
2646 }
2647
2648 /**
2649 * Bring up the context menu for this view.
2650 *
2651 * @return Whether a context menu was displayed.
2652 */
2653 public boolean showContextMenu() {
2654 return getParent().showContextMenuForChild(this);
2655 }
2656
2657 /**
Adam Powell6e346362010-07-23 10:18:23 -07002658 * Start an action mode.
2659 *
2660 * @param callback Callback that will control the lifecycle of the action mode
2661 * @return The new action mode if it is started, null otherwise
2662 *
2663 * @see ActionMode
2664 */
2665 public ActionMode startActionMode(ActionMode.Callback callback) {
2666 return getParent().startActionModeForChild(this, callback);
2667 }
2668
2669 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 * Register a callback to be invoked when a key is pressed in this view.
2671 * @param l the key listener to attach to this view
2672 */
2673 public void setOnKeyListener(OnKeyListener l) {
2674 mOnKeyListener = l;
2675 }
2676
2677 /**
2678 * Register a callback to be invoked when a touch event is sent to this view.
2679 * @param l the touch listener to attach to this view
2680 */
2681 public void setOnTouchListener(OnTouchListener l) {
2682 mOnTouchListener = l;
2683 }
2684
2685 /**
2686 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2687 *
2688 * Note: this does not check whether this {@link View} should get focus, it just
2689 * gives it focus no matter what. It should only be called internally by framework
2690 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2691 *
2692 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2693 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2694 * focus moved when requestFocus() is called. It may not always
2695 * apply, in which case use the default View.FOCUS_DOWN.
2696 * @param previouslyFocusedRect The rectangle of the view that had focus
2697 * prior in this View's coordinate system.
2698 */
2699 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2700 if (DBG) {
2701 System.out.println(this + " requestFocus()");
2702 }
2703
2704 if ((mPrivateFlags & FOCUSED) == 0) {
2705 mPrivateFlags |= FOCUSED;
2706
2707 if (mParent != null) {
2708 mParent.requestChildFocus(this, this);
2709 }
2710
2711 onFocusChanged(true, direction, previouslyFocusedRect);
2712 refreshDrawableState();
2713 }
2714 }
2715
2716 /**
2717 * Request that a rectangle of this view be visible on the screen,
2718 * scrolling if necessary just enough.
2719 *
2720 * <p>A View should call this if it maintains some notion of which part
2721 * of its content is interesting. For example, a text editing view
2722 * should call this when its cursor moves.
2723 *
2724 * @param rectangle The rectangle.
2725 * @return Whether any parent scrolled.
2726 */
2727 public boolean requestRectangleOnScreen(Rect rectangle) {
2728 return requestRectangleOnScreen(rectangle, false);
2729 }
2730
2731 /**
2732 * Request that a rectangle of this view be visible on the screen,
2733 * scrolling if necessary just enough.
2734 *
2735 * <p>A View should call this if it maintains some notion of which part
2736 * of its content is interesting. For example, a text editing view
2737 * should call this when its cursor moves.
2738 *
2739 * <p>When <code>immediate</code> is set to true, scrolling will not be
2740 * animated.
2741 *
2742 * @param rectangle The rectangle.
2743 * @param immediate True to forbid animated scrolling, false otherwise
2744 * @return Whether any parent scrolled.
2745 */
2746 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
2747 View child = this;
2748 ViewParent parent = mParent;
2749 boolean scrolled = false;
2750 while (parent != null) {
2751 scrolled |= parent.requestChildRectangleOnScreen(child,
2752 rectangle, immediate);
2753
2754 // offset rect so next call has the rectangle in the
2755 // coordinate system of its direct child.
2756 rectangle.offset(child.getLeft(), child.getTop());
2757 rectangle.offset(-child.getScrollX(), -child.getScrollY());
2758
2759 if (!(parent instanceof View)) {
2760 break;
2761 }
Romain Guy8506ab42009-06-11 17:35:47 -07002762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 child = (View) parent;
2764 parent = child.getParent();
2765 }
2766 return scrolled;
2767 }
2768
2769 /**
2770 * Called when this view wants to give up focus. This will cause
2771 * {@link #onFocusChanged} to be called.
2772 */
2773 public void clearFocus() {
2774 if (DBG) {
2775 System.out.println(this + " clearFocus()");
2776 }
2777
2778 if ((mPrivateFlags & FOCUSED) != 0) {
2779 mPrivateFlags &= ~FOCUSED;
2780
2781 if (mParent != null) {
2782 mParent.clearChildFocus(this);
2783 }
2784
2785 onFocusChanged(false, 0, null);
2786 refreshDrawableState();
2787 }
2788 }
2789
2790 /**
2791 * Called to clear the focus of a view that is about to be removed.
2792 * Doesn't call clearChildFocus, which prevents this view from taking
2793 * focus again before it has been removed from the parent
2794 */
2795 void clearFocusForRemoval() {
2796 if ((mPrivateFlags & FOCUSED) != 0) {
2797 mPrivateFlags &= ~FOCUSED;
2798
2799 onFocusChanged(false, 0, null);
2800 refreshDrawableState();
2801 }
2802 }
2803
2804 /**
2805 * Called internally by the view system when a new view is getting focus.
2806 * This is what clears the old focus.
2807 */
2808 void unFocus() {
2809 if (DBG) {
2810 System.out.println(this + " unFocus()");
2811 }
2812
2813 if ((mPrivateFlags & FOCUSED) != 0) {
2814 mPrivateFlags &= ~FOCUSED;
2815
2816 onFocusChanged(false, 0, null);
2817 refreshDrawableState();
2818 }
2819 }
2820
2821 /**
2822 * Returns true if this view has focus iteself, or is the ancestor of the
2823 * view that has focus.
2824 *
2825 * @return True if this view has or contains focus, false otherwise.
2826 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002827 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 public boolean hasFocus() {
2829 return (mPrivateFlags & FOCUSED) != 0;
2830 }
2831
2832 /**
2833 * Returns true if this view is focusable or if it contains a reachable View
2834 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
2835 * is a View whose parents do not block descendants focus.
2836 *
2837 * Only {@link #VISIBLE} views are considered focusable.
2838 *
2839 * @return True if the view is focusable or if the view contains a focusable
2840 * View, false otherwise.
2841 *
2842 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
2843 */
2844 public boolean hasFocusable() {
2845 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
2846 }
2847
2848 /**
2849 * Called by the view system when the focus state of this view changes.
2850 * When the focus change event is caused by directional navigation, direction
2851 * and previouslyFocusedRect provide insight into where the focus is coming from.
2852 * When overriding, be sure to call up through to the super class so that
2853 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07002854 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 * @param gainFocus True if the View has focus; false otherwise.
2856 * @param direction The direction focus has moved when requestFocus()
2857 * is called to give this view focus. Values are
Romain Guyea4823c2009-12-08 15:03:39 -08002858 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT} or
2859 * {@link #FOCUS_RIGHT}. It may not always apply, in which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 * case use the default.
2861 * @param previouslyFocusedRect The rectangle, in this view's coordinate
2862 * system, of the previously focused view. If applicable, this will be
2863 * passed in as finer grained information about where the focus is coming
2864 * from (in addition to direction). Will be <code>null</code> otherwise.
2865 */
2866 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07002867 if (gainFocus) {
2868 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2869 }
2870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 InputMethodManager imm = InputMethodManager.peekInstance();
2872 if (!gainFocus) {
2873 if (isPressed()) {
2874 setPressed(false);
2875 }
2876 if (imm != null && mAttachInfo != null
2877 && mAttachInfo.mHasWindowFocus) {
2878 imm.focusOut(this);
2879 }
Romain Guya2431d02009-04-30 16:30:00 -07002880 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 } else if (imm != null && mAttachInfo != null
2882 && mAttachInfo.mHasWindowFocus) {
2883 imm.focusIn(this);
2884 }
Romain Guy8506ab42009-06-11 17:35:47 -07002885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 invalidate();
2887 if (mOnFocusChangeListener != null) {
2888 mOnFocusChangeListener.onFocusChange(this, gainFocus);
2889 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002890
2891 if (mAttachInfo != null) {
2892 mAttachInfo.mKeyDispatchState.reset(this);
2893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 }
2895
2896 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002897 * {@inheritDoc}
2898 */
2899 public void sendAccessibilityEvent(int eventType) {
2900 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2901 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
2902 }
2903 }
2904
2905 /**
2906 * {@inheritDoc}
2907 */
2908 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
2909 event.setClassName(getClass().getName());
2910 event.setPackageName(getContext().getPackageName());
2911 event.setEnabled(isEnabled());
2912 event.setContentDescription(mContentDescription);
2913
2914 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
2915 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
2916 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
2917 event.setItemCount(focusablesTempList.size());
2918 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
2919 focusablesTempList.clear();
2920 }
2921
2922 dispatchPopulateAccessibilityEvent(event);
2923
2924 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
2925 }
2926
2927 /**
2928 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
2929 * to be populated.
2930 *
2931 * @param event The event.
2932 *
2933 * @return True if the event population was completed.
2934 */
2935 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2936 return false;
2937 }
2938
2939 /**
2940 * Gets the {@link View} description. It briefly describes the view and is
2941 * primarily used for accessibility support. Set this property to enable
2942 * better accessibility support for your application. This is especially
2943 * true for views that do not have textual representation (For example,
2944 * ImageButton).
2945 *
2946 * @return The content descriptiopn.
2947 *
2948 * @attr ref android.R.styleable#View_contentDescription
2949 */
2950 public CharSequence getContentDescription() {
2951 return mContentDescription;
2952 }
2953
2954 /**
2955 * Sets the {@link View} description. It briefly describes the view and is
2956 * primarily used for accessibility support. Set this property to enable
2957 * better accessibility support for your application. This is especially
2958 * true for views that do not have textual representation (For example,
2959 * ImageButton).
2960 *
2961 * @param contentDescription The content description.
2962 *
2963 * @attr ref android.R.styleable#View_contentDescription
2964 */
2965 public void setContentDescription(CharSequence contentDescription) {
2966 mContentDescription = contentDescription;
2967 }
2968
2969 /**
Romain Guya2431d02009-04-30 16:30:00 -07002970 * Invoked whenever this view loses focus, either by losing window focus or by losing
2971 * focus within its window. This method can be used to clear any state tied to the
2972 * focus. For instance, if a button is held pressed with the trackball and the window
2973 * loses focus, this method can be used to cancel the press.
2974 *
2975 * Subclasses of View overriding this method should always call super.onFocusLost().
2976 *
2977 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07002978 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07002979 *
2980 * @hide pending API council approval
2981 */
2982 protected void onFocusLost() {
2983 resetPressedState();
2984 }
2985
2986 private void resetPressedState() {
2987 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
2988 return;
2989 }
2990
2991 if (isPressed()) {
2992 setPressed(false);
2993
2994 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05002995 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07002996 }
2997 }
2998 }
2999
3000 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 * Returns true if this view has focus
3002 *
3003 * @return True if this view has focus, false otherwise.
3004 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003005 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 public boolean isFocused() {
3007 return (mPrivateFlags & FOCUSED) != 0;
3008 }
3009
3010 /**
3011 * Find the view in the hierarchy rooted at this view that currently has
3012 * focus.
3013 *
3014 * @return The view that currently has focus, or null if no focused view can
3015 * be found.
3016 */
3017 public View findFocus() {
3018 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3019 }
3020
3021 /**
3022 * Change whether this view is one of the set of scrollable containers in
3023 * its window. This will be used to determine whether the window can
3024 * resize or must pan when a soft input area is open -- scrollable
3025 * containers allow the window to use resize mode since the container
3026 * will appropriately shrink.
3027 */
3028 public void setScrollContainer(boolean isScrollContainer) {
3029 if (isScrollContainer) {
3030 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3031 mAttachInfo.mScrollContainers.add(this);
3032 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3033 }
3034 mPrivateFlags |= SCROLL_CONTAINER;
3035 } else {
3036 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3037 mAttachInfo.mScrollContainers.remove(this);
3038 }
3039 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3040 }
3041 }
3042
3043 /**
3044 * Returns the quality of the drawing cache.
3045 *
3046 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3047 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3048 *
3049 * @see #setDrawingCacheQuality(int)
3050 * @see #setDrawingCacheEnabled(boolean)
3051 * @see #isDrawingCacheEnabled()
3052 *
3053 * @attr ref android.R.styleable#View_drawingCacheQuality
3054 */
3055 public int getDrawingCacheQuality() {
3056 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3057 }
3058
3059 /**
3060 * Set the drawing cache quality of this view. This value is used only when the
3061 * drawing cache is enabled
3062 *
3063 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3064 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3065 *
3066 * @see #getDrawingCacheQuality()
3067 * @see #setDrawingCacheEnabled(boolean)
3068 * @see #isDrawingCacheEnabled()
3069 *
3070 * @attr ref android.R.styleable#View_drawingCacheQuality
3071 */
3072 public void setDrawingCacheQuality(int quality) {
3073 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3074 }
3075
3076 /**
3077 * Returns whether the screen should remain on, corresponding to the current
3078 * value of {@link #KEEP_SCREEN_ON}.
3079 *
3080 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3081 *
3082 * @see #setKeepScreenOn(boolean)
3083 *
3084 * @attr ref android.R.styleable#View_keepScreenOn
3085 */
3086 public boolean getKeepScreenOn() {
3087 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3088 }
3089
3090 /**
3091 * Controls whether the screen should remain on, modifying the
3092 * value of {@link #KEEP_SCREEN_ON}.
3093 *
3094 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3095 *
3096 * @see #getKeepScreenOn()
3097 *
3098 * @attr ref android.R.styleable#View_keepScreenOn
3099 */
3100 public void setKeepScreenOn(boolean keepScreenOn) {
3101 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3102 }
3103
3104 /**
3105 * @return The user specified next focus ID.
3106 *
3107 * @attr ref android.R.styleable#View_nextFocusLeft
3108 */
3109 public int getNextFocusLeftId() {
3110 return mNextFocusLeftId;
3111 }
3112
3113 /**
3114 * Set the id of the view to use for the next focus
3115 *
3116 * @param nextFocusLeftId
3117 *
3118 * @attr ref android.R.styleable#View_nextFocusLeft
3119 */
3120 public void setNextFocusLeftId(int nextFocusLeftId) {
3121 mNextFocusLeftId = nextFocusLeftId;
3122 }
3123
3124 /**
3125 * @return The user specified next focus ID.
3126 *
3127 * @attr ref android.R.styleable#View_nextFocusRight
3128 */
3129 public int getNextFocusRightId() {
3130 return mNextFocusRightId;
3131 }
3132
3133 /**
3134 * Set the id of the view to use for the next focus
3135 *
3136 * @param nextFocusRightId
3137 *
3138 * @attr ref android.R.styleable#View_nextFocusRight
3139 */
3140 public void setNextFocusRightId(int nextFocusRightId) {
3141 mNextFocusRightId = nextFocusRightId;
3142 }
3143
3144 /**
3145 * @return The user specified next focus ID.
3146 *
3147 * @attr ref android.R.styleable#View_nextFocusUp
3148 */
3149 public int getNextFocusUpId() {
3150 return mNextFocusUpId;
3151 }
3152
3153 /**
3154 * Set the id of the view to use for the next focus
3155 *
3156 * @param nextFocusUpId
3157 *
3158 * @attr ref android.R.styleable#View_nextFocusUp
3159 */
3160 public void setNextFocusUpId(int nextFocusUpId) {
3161 mNextFocusUpId = nextFocusUpId;
3162 }
3163
3164 /**
3165 * @return The user specified next focus ID.
3166 *
3167 * @attr ref android.R.styleable#View_nextFocusDown
3168 */
3169 public int getNextFocusDownId() {
3170 return mNextFocusDownId;
3171 }
3172
3173 /**
3174 * Set the id of the view to use for the next focus
3175 *
3176 * @param nextFocusDownId
3177 *
3178 * @attr ref android.R.styleable#View_nextFocusDown
3179 */
3180 public void setNextFocusDownId(int nextFocusDownId) {
3181 mNextFocusDownId = nextFocusDownId;
3182 }
3183
3184 /**
3185 * Returns the visibility of this view and all of its ancestors
3186 *
3187 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3188 */
3189 public boolean isShown() {
3190 View current = this;
3191 //noinspection ConstantConditions
3192 do {
3193 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3194 return false;
3195 }
3196 ViewParent parent = current.mParent;
3197 if (parent == null) {
3198 return false; // We are not attached to the view root
3199 }
3200 if (!(parent instanceof View)) {
3201 return true;
3202 }
3203 current = (View) parent;
3204 } while (current != null);
3205
3206 return false;
3207 }
3208
3209 /**
3210 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3211 * is set
3212 *
3213 * @param insets Insets for system windows
3214 *
3215 * @return True if this view applied the insets, false otherwise
3216 */
3217 protected boolean fitSystemWindows(Rect insets) {
3218 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3219 mPaddingLeft = insets.left;
3220 mPaddingTop = insets.top;
3221 mPaddingRight = insets.right;
3222 mPaddingBottom = insets.bottom;
3223 requestLayout();
3224 return true;
3225 }
3226 return false;
3227 }
3228
3229 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003230 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3231 * @return True if window has FITS_SYSTEM_WINDOWS set
3232 *
3233 * @hide
3234 */
3235 public boolean isFitsSystemWindowsFlagSet() {
3236 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3237 }
3238
3239 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 * Returns the visibility status for this view.
3241 *
3242 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3243 * @attr ref android.R.styleable#View_visibility
3244 */
3245 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003246 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3247 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3248 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 })
3250 public int getVisibility() {
3251 return mViewFlags & VISIBILITY_MASK;
3252 }
3253
3254 /**
3255 * Set the enabled state of this view.
3256 *
3257 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3258 * @attr ref android.R.styleable#View_visibility
3259 */
3260 @RemotableViewMethod
3261 public void setVisibility(int visibility) {
3262 setFlags(visibility, VISIBILITY_MASK);
3263 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3264 }
3265
3266 /**
3267 * Returns the enabled status for this view. The interpretation of the
3268 * enabled state varies by subclass.
3269 *
3270 * @return True if this view is enabled, false otherwise.
3271 */
3272 @ViewDebug.ExportedProperty
3273 public boolean isEnabled() {
3274 return (mViewFlags & ENABLED_MASK) == ENABLED;
3275 }
3276
3277 /**
3278 * Set the enabled state of this view. The interpretation of the enabled
3279 * state varies by subclass.
3280 *
3281 * @param enabled True if this view is enabled, false otherwise.
3282 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003283 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003285 if (enabled == isEnabled()) return;
3286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3288
3289 /*
3290 * The View most likely has to change its appearance, so refresh
3291 * the drawable state.
3292 */
3293 refreshDrawableState();
3294
3295 // Invalidate too, since the default behavior for views is to be
3296 // be drawn at 50% alpha rather than to change the drawable.
3297 invalidate();
3298 }
3299
3300 /**
3301 * Set whether this view can receive the focus.
3302 *
3303 * Setting this to false will also ensure that this view is not focusable
3304 * in touch mode.
3305 *
3306 * @param focusable If true, this view can receive the focus.
3307 *
3308 * @see #setFocusableInTouchMode(boolean)
3309 * @attr ref android.R.styleable#View_focusable
3310 */
3311 public void setFocusable(boolean focusable) {
3312 if (!focusable) {
3313 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3314 }
3315 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3316 }
3317
3318 /**
3319 * Set whether this view can receive focus while in touch mode.
3320 *
3321 * Setting this to true will also ensure that this view is focusable.
3322 *
3323 * @param focusableInTouchMode If true, this view can receive the focus while
3324 * in touch mode.
3325 *
3326 * @see #setFocusable(boolean)
3327 * @attr ref android.R.styleable#View_focusableInTouchMode
3328 */
3329 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3330 // Focusable in touch mode should always be set before the focusable flag
3331 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3332 // which, in touch mode, will not successfully request focus on this view
3333 // because the focusable in touch mode flag is not set
3334 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3335 if (focusableInTouchMode) {
3336 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3337 }
3338 }
3339
3340 /**
3341 * Set whether this view should have sound effects enabled for events such as
3342 * clicking and touching.
3343 *
3344 * <p>You may wish to disable sound effects for a view if you already play sounds,
3345 * for instance, a dial key that plays dtmf tones.
3346 *
3347 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3348 * @see #isSoundEffectsEnabled()
3349 * @see #playSoundEffect(int)
3350 * @attr ref android.R.styleable#View_soundEffectsEnabled
3351 */
3352 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3353 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3354 }
3355
3356 /**
3357 * @return whether this view should have sound effects enabled for events such as
3358 * clicking and touching.
3359 *
3360 * @see #setSoundEffectsEnabled(boolean)
3361 * @see #playSoundEffect(int)
3362 * @attr ref android.R.styleable#View_soundEffectsEnabled
3363 */
3364 @ViewDebug.ExportedProperty
3365 public boolean isSoundEffectsEnabled() {
3366 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3367 }
3368
3369 /**
3370 * Set whether this view should have haptic feedback for events such as
3371 * long presses.
3372 *
3373 * <p>You may wish to disable haptic feedback if your view already controls
3374 * its own haptic feedback.
3375 *
3376 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3377 * @see #isHapticFeedbackEnabled()
3378 * @see #performHapticFeedback(int)
3379 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3380 */
3381 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3382 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3383 }
3384
3385 /**
3386 * @return whether this view should have haptic feedback enabled for events
3387 * long presses.
3388 *
3389 * @see #setHapticFeedbackEnabled(boolean)
3390 * @see #performHapticFeedback(int)
3391 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3392 */
3393 @ViewDebug.ExportedProperty
3394 public boolean isHapticFeedbackEnabled() {
3395 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3396 }
3397
3398 /**
3399 * If this view doesn't do any drawing on its own, set this flag to
3400 * allow further optimizations. By default, this flag is not set on
3401 * View, but could be set on some View subclasses such as ViewGroup.
3402 *
3403 * Typically, if you override {@link #onDraw} you should clear this flag.
3404 *
3405 * @param willNotDraw whether or not this View draw on its own
3406 */
3407 public void setWillNotDraw(boolean willNotDraw) {
3408 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3409 }
3410
3411 /**
3412 * Returns whether or not this View draws on its own.
3413 *
3414 * @return true if this view has nothing to draw, false otherwise
3415 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003416 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 public boolean willNotDraw() {
3418 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3419 }
3420
3421 /**
3422 * When a View's drawing cache is enabled, drawing is redirected to an
3423 * offscreen bitmap. Some views, like an ImageView, must be able to
3424 * bypass this mechanism if they already draw a single bitmap, to avoid
3425 * unnecessary usage of the memory.
3426 *
3427 * @param willNotCacheDrawing true if this view does not cache its
3428 * drawing, false otherwise
3429 */
3430 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3431 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3432 }
3433
3434 /**
3435 * Returns whether or not this View can cache its drawing or not.
3436 *
3437 * @return true if this view does not cache its drawing, false otherwise
3438 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003439 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 public boolean willNotCacheDrawing() {
3441 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3442 }
3443
3444 /**
3445 * Indicates whether this view reacts to click events or not.
3446 *
3447 * @return true if the view is clickable, false otherwise
3448 *
3449 * @see #setClickable(boolean)
3450 * @attr ref android.R.styleable#View_clickable
3451 */
3452 @ViewDebug.ExportedProperty
3453 public boolean isClickable() {
3454 return (mViewFlags & CLICKABLE) == CLICKABLE;
3455 }
3456
3457 /**
3458 * Enables or disables click events for this view. When a view
3459 * is clickable it will change its state to "pressed" on every click.
3460 * Subclasses should set the view clickable to visually react to
3461 * user's clicks.
3462 *
3463 * @param clickable true to make the view clickable, false otherwise
3464 *
3465 * @see #isClickable()
3466 * @attr ref android.R.styleable#View_clickable
3467 */
3468 public void setClickable(boolean clickable) {
3469 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3470 }
3471
3472 /**
3473 * Indicates whether this view reacts to long click events or not.
3474 *
3475 * @return true if the view is long clickable, false otherwise
3476 *
3477 * @see #setLongClickable(boolean)
3478 * @attr ref android.R.styleable#View_longClickable
3479 */
3480 public boolean isLongClickable() {
3481 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3482 }
3483
3484 /**
3485 * Enables or disables long click events for this view. When a view is long
3486 * clickable it reacts to the user holding down the button for a longer
3487 * duration than a tap. This event can either launch the listener or a
3488 * context menu.
3489 *
3490 * @param longClickable true to make the view long clickable, false otherwise
3491 * @see #isLongClickable()
3492 * @attr ref android.R.styleable#View_longClickable
3493 */
3494 public void setLongClickable(boolean longClickable) {
3495 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3496 }
3497
3498 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003499 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 *
3501 * @see #isClickable()
3502 * @see #setClickable(boolean)
3503 *
3504 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3505 * the View's internal state from a previously set "pressed" state.
3506 */
3507 public void setPressed(boolean pressed) {
3508 if (pressed) {
3509 mPrivateFlags |= PRESSED;
3510 } else {
3511 mPrivateFlags &= ~PRESSED;
3512 }
3513 refreshDrawableState();
3514 dispatchSetPressed(pressed);
3515 }
3516
3517 /**
3518 * Dispatch setPressed to all of this View's children.
3519 *
3520 * @see #setPressed(boolean)
3521 *
3522 * @param pressed The new pressed state
3523 */
3524 protected void dispatchSetPressed(boolean pressed) {
3525 }
3526
3527 /**
3528 * Indicates whether the view is currently in pressed state. Unless
3529 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3530 * the pressed state.
3531 *
3532 * @see #setPressed
3533 * @see #isClickable()
3534 * @see #setClickable(boolean)
3535 *
3536 * @return true if the view is currently pressed, false otherwise
3537 */
3538 public boolean isPressed() {
3539 return (mPrivateFlags & PRESSED) == PRESSED;
3540 }
3541
3542 /**
3543 * Indicates whether this view will save its state (that is,
3544 * whether its {@link #onSaveInstanceState} method will be called).
3545 *
3546 * @return Returns true if the view state saving is enabled, else false.
3547 *
3548 * @see #setSaveEnabled(boolean)
3549 * @attr ref android.R.styleable#View_saveEnabled
3550 */
3551 public boolean isSaveEnabled() {
3552 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3553 }
3554
3555 /**
3556 * Controls whether the saving of this view's state is
3557 * enabled (that is, whether its {@link #onSaveInstanceState} method
3558 * will be called). Note that even if freezing is enabled, the
3559 * view still must have an id assigned to it (via {@link #setId setId()})
3560 * for its state to be saved. This flag can only disable the
3561 * saving of this view; any child views may still have their state saved.
3562 *
3563 * @param enabled Set to false to <em>disable</em> state saving, or true
3564 * (the default) to allow it.
3565 *
3566 * @see #isSaveEnabled()
3567 * @see #setId(int)
3568 * @see #onSaveInstanceState()
3569 * @attr ref android.R.styleable#View_saveEnabled
3570 */
3571 public void setSaveEnabled(boolean enabled) {
3572 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3573 }
3574
Jeff Brown85a31762010-09-01 17:01:00 -07003575 /**
3576 * Gets whether the framework should discard touches when the view's
3577 * window is obscured by another visible window.
3578 * Refer to the {@link View} security documentation for more details.
3579 *
3580 * @return True if touch filtering is enabled.
3581 *
3582 * @see #setFilterTouchesWhenObscured(boolean)
3583 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3584 */
3585 @ViewDebug.ExportedProperty
3586 public boolean getFilterTouchesWhenObscured() {
3587 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3588 }
3589
3590 /**
3591 * Sets whether the framework should discard touches when the view's
3592 * window is obscured by another visible window.
3593 * Refer to the {@link View} security documentation for more details.
3594 *
3595 * @param enabled True if touch filtering should be enabled.
3596 *
3597 * @see #getFilterTouchesWhenObscured
3598 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3599 */
3600 public void setFilterTouchesWhenObscured(boolean enabled) {
3601 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3602 FILTER_TOUCHES_WHEN_OBSCURED);
3603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604
3605 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003606 * Indicates whether the entire hierarchy under this view will save its
3607 * state when a state saving traversal occurs from its parent. The default
3608 * is true; if false, these views will not be saved unless
3609 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3610 *
3611 * @return Returns true if the view state saving from parent is enabled, else false.
3612 *
3613 * @see #setSaveFromParentEnabled(boolean)
3614 */
3615 public boolean isSaveFromParentEnabled() {
3616 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3617 }
3618
3619 /**
3620 * Controls whether the entire hierarchy under this view will save its
3621 * state when a state saving traversal occurs from its parent. The default
3622 * is true; if false, these views will not be saved unless
3623 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3624 *
3625 * @param enabled Set to false to <em>disable</em> state saving, or true
3626 * (the default) to allow it.
3627 *
3628 * @see #isSaveFromParentEnabled()
3629 * @see #setId(int)
3630 * @see #onSaveInstanceState()
3631 */
3632 public void setSaveFromParentEnabled(boolean enabled) {
3633 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
3634 }
3635
3636
3637 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003638 * Returns whether this View is able to take focus.
3639 *
3640 * @return True if this view can take focus, or false otherwise.
3641 * @attr ref android.R.styleable#View_focusable
3642 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003643 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003644 public final boolean isFocusable() {
3645 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3646 }
3647
3648 /**
3649 * When a view is focusable, it may not want to take focus when in touch mode.
3650 * For example, a button would like focus when the user is navigating via a D-pad
3651 * so that the user can click on it, but once the user starts touching the screen,
3652 * the button shouldn't take focus
3653 * @return Whether the view is focusable in touch mode.
3654 * @attr ref android.R.styleable#View_focusableInTouchMode
3655 */
3656 @ViewDebug.ExportedProperty
3657 public final boolean isFocusableInTouchMode() {
3658 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3659 }
3660
3661 /**
3662 * Find the nearest view in the specified direction that can take focus.
3663 * This does not actually give focus to that view.
3664 *
3665 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3666 *
3667 * @return The nearest focusable in the specified direction, or null if none
3668 * can be found.
3669 */
3670 public View focusSearch(int direction) {
3671 if (mParent != null) {
3672 return mParent.focusSearch(this, direction);
3673 } else {
3674 return null;
3675 }
3676 }
3677
3678 /**
3679 * This method is the last chance for the focused view and its ancestors to
3680 * respond to an arrow key. This is called when the focused view did not
3681 * consume the key internally, nor could the view system find a new view in
3682 * the requested direction to give focus to.
3683 *
3684 * @param focused The currently focused view.
3685 * @param direction The direction focus wants to move. One of FOCUS_UP,
3686 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3687 * @return True if the this view consumed this unhandled move.
3688 */
3689 public boolean dispatchUnhandledMove(View focused, int direction) {
3690 return false;
3691 }
3692
3693 /**
3694 * If a user manually specified the next view id for a particular direction,
3695 * use the root to look up the view. Once a view is found, it is cached
3696 * for future lookups.
3697 * @param root The root view of the hierarchy containing this view.
3698 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3699 * @return The user specified next view, or null if there is none.
3700 */
3701 View findUserSetNextFocus(View root, int direction) {
3702 switch (direction) {
3703 case FOCUS_LEFT:
3704 if (mNextFocusLeftId == View.NO_ID) return null;
3705 return findViewShouldExist(root, mNextFocusLeftId);
3706 case FOCUS_RIGHT:
3707 if (mNextFocusRightId == View.NO_ID) return null;
3708 return findViewShouldExist(root, mNextFocusRightId);
3709 case FOCUS_UP:
3710 if (mNextFocusUpId == View.NO_ID) return null;
3711 return findViewShouldExist(root, mNextFocusUpId);
3712 case FOCUS_DOWN:
3713 if (mNextFocusDownId == View.NO_ID) return null;
3714 return findViewShouldExist(root, mNextFocusDownId);
3715 }
3716 return null;
3717 }
3718
3719 private static View findViewShouldExist(View root, int childViewId) {
3720 View result = root.findViewById(childViewId);
3721 if (result == null) {
3722 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3723 + "by user for id " + childViewId);
3724 }
3725 return result;
3726 }
3727
3728 /**
3729 * Find and return all focusable views that are descendants of this view,
3730 * possibly including this view if it is focusable itself.
3731 *
3732 * @param direction The direction of the focus
3733 * @return A list of focusable views
3734 */
3735 public ArrayList<View> getFocusables(int direction) {
3736 ArrayList<View> result = new ArrayList<View>(24);
3737 addFocusables(result, direction);
3738 return result;
3739 }
3740
3741 /**
3742 * Add any focusable views that are descendants of this view (possibly
3743 * including this view if it is focusable itself) to views. If we are in touch mode,
3744 * only add views that are also focusable in touch mode.
3745 *
3746 * @param views Focusable views found so far
3747 * @param direction The direction of the focus
3748 */
3749 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003750 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752
svetoslavganov75986cf2009-05-14 22:28:01 -07003753 /**
3754 * Adds any focusable views that are descendants of this view (possibly
3755 * including this view if it is focusable itself) to views. This method
3756 * adds all focusable views regardless if we are in touch mode or
3757 * only views focusable in touch mode if we are in touch mode depending on
3758 * the focusable mode paramater.
3759 *
3760 * @param views Focusable views found so far or null if all we are interested is
3761 * the number of focusables.
3762 * @param direction The direction of the focus.
3763 * @param focusableMode The type of focusables to be added.
3764 *
3765 * @see #FOCUSABLES_ALL
3766 * @see #FOCUSABLES_TOUCH_MODE
3767 */
3768 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3769 if (!isFocusable()) {
3770 return;
3771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772
svetoslavganov75986cf2009-05-14 22:28:01 -07003773 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3774 isInTouchMode() && !isFocusableInTouchMode()) {
3775 return;
3776 }
3777
3778 if (views != null) {
3779 views.add(this);
3780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 }
3782
3783 /**
3784 * Find and return all touchable views that are descendants of this view,
3785 * possibly including this view if it is touchable itself.
3786 *
3787 * @return A list of touchable views
3788 */
3789 public ArrayList<View> getTouchables() {
3790 ArrayList<View> result = new ArrayList<View>();
3791 addTouchables(result);
3792 return result;
3793 }
3794
3795 /**
3796 * Add any touchable views that are descendants of this view (possibly
3797 * including this view if it is touchable itself) to views.
3798 *
3799 * @param views Touchable views found so far
3800 */
3801 public void addTouchables(ArrayList<View> views) {
3802 final int viewFlags = mViewFlags;
3803
3804 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
3805 && (viewFlags & ENABLED_MASK) == ENABLED) {
3806 views.add(this);
3807 }
3808 }
3809
3810 /**
3811 * Call this to try to give focus to a specific view or to one of its
3812 * descendants.
3813 *
3814 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3815 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3816 * while the device is in touch mode.
3817 *
3818 * See also {@link #focusSearch}, which is what you call to say that you
3819 * have focus, and you want your parent to look for the next one.
3820 *
3821 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
3822 * {@link #FOCUS_DOWN} and <code>null</code>.
3823 *
3824 * @return Whether this view or one of its descendants actually took focus.
3825 */
3826 public final boolean requestFocus() {
3827 return requestFocus(View.FOCUS_DOWN);
3828 }
3829
3830
3831 /**
3832 * Call this to try to give focus to a specific view or to one of its
3833 * descendants and give it a hint about what direction focus is heading.
3834 *
3835 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3836 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3837 * while the device is in touch mode.
3838 *
3839 * See also {@link #focusSearch}, which is what you call to say that you
3840 * have focus, and you want your parent to look for the next one.
3841 *
3842 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
3843 * <code>null</code> set for the previously focused rectangle.
3844 *
3845 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3846 * @return Whether this view or one of its descendants actually took focus.
3847 */
3848 public final boolean requestFocus(int direction) {
3849 return requestFocus(direction, null);
3850 }
3851
3852 /**
3853 * Call this to try to give focus to a specific view or to one of its descendants
3854 * and give it hints about the direction and a specific rectangle that the focus
3855 * is coming from. The rectangle can help give larger views a finer grained hint
3856 * about where focus is coming from, and therefore, where to show selection, or
3857 * forward focus change internally.
3858 *
3859 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3860 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3861 * while the device is in touch mode.
3862 *
3863 * A View will not take focus if it is not visible.
3864 *
3865 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
3866 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
3867 *
3868 * See also {@link #focusSearch}, which is what you call to say that you
3869 * have focus, and you want your parent to look for the next one.
3870 *
3871 * You may wish to override this method if your custom {@link View} has an internal
3872 * {@link View} that it wishes to forward the request to.
3873 *
3874 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3875 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
3876 * to give a finer grained hint about where focus is coming from. May be null
3877 * if there is no hint.
3878 * @return Whether this view or one of its descendants actually took focus.
3879 */
3880 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
3881 // need to be focusable
3882 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
3883 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3884 return false;
3885 }
3886
3887 // need to be focusable in touch mode if in touch mode
3888 if (isInTouchMode() &&
3889 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
3890 return false;
3891 }
3892
3893 // need to not have any parents blocking us
3894 if (hasAncestorThatBlocksDescendantFocus()) {
3895 return false;
3896 }
3897
3898 handleFocusGainInternal(direction, previouslyFocusedRect);
3899 return true;
3900 }
3901
3902 /**
3903 * Call this to try to give focus to a specific view or to one of its descendants. This is a
3904 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
3905 * touch mode to request focus when they are touched.
3906 *
3907 * @return Whether this view or one of its descendants actually took focus.
3908 *
3909 * @see #isInTouchMode()
3910 *
3911 */
3912 public final boolean requestFocusFromTouch() {
3913 // Leave touch mode if we need to
3914 if (isInTouchMode()) {
3915 View root = getRootView();
3916 if (root != null) {
3917 ViewRoot viewRoot = (ViewRoot)root.getParent();
3918 if (viewRoot != null) {
3919 viewRoot.ensureTouchMode(false);
3920 }
3921 }
3922 }
3923 return requestFocus(View.FOCUS_DOWN);
3924 }
3925
3926 /**
3927 * @return Whether any ancestor of this view blocks descendant focus.
3928 */
3929 private boolean hasAncestorThatBlocksDescendantFocus() {
3930 ViewParent ancestor = mParent;
3931 while (ancestor instanceof ViewGroup) {
3932 final ViewGroup vgAncestor = (ViewGroup) ancestor;
3933 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
3934 return true;
3935 } else {
3936 ancestor = vgAncestor.getParent();
3937 }
3938 }
3939 return false;
3940 }
3941
3942 /**
Romain Guya440b002010-02-24 15:57:54 -08003943 * @hide
3944 */
3945 public void dispatchStartTemporaryDetach() {
3946 onStartTemporaryDetach();
3947 }
3948
3949 /**
3950 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
3952 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08003953 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 */
3955 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08003956 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08003957 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08003958 }
3959
3960 /**
3961 * @hide
3962 */
3963 public void dispatchFinishTemporaryDetach() {
3964 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965 }
Romain Guy8506ab42009-06-11 17:35:47 -07003966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 /**
3968 * Called after {@link #onStartTemporaryDetach} when the container is done
3969 * changing the view.
3970 */
3971 public void onFinishTemporaryDetach() {
3972 }
Romain Guy8506ab42009-06-11 17:35:47 -07003973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 /**
3975 * capture information of this view for later analysis: developement only
3976 * check dynamic switch to make sure we only dump view
3977 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
3978 */
3979 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003980 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 return;
3982 }
3983 ViewDebug.dumpCapturedView(subTag, v);
3984 }
3985
3986 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003987 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
3988 * for this view's window. Returns null if the view is not currently attached
3989 * to the window. Normally you will not need to use this directly, but
3990 * just use the standard high-level event callbacks like {@link #onKeyDown}.
3991 */
3992 public KeyEvent.DispatcherState getKeyDispatcherState() {
3993 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
3994 }
3995
3996 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 * Dispatch a key event before it is processed by any input method
3998 * associated with the view hierarchy. This can be used to intercept
3999 * key events in special situations before the IME consumes them; a
4000 * typical example would be handling the BACK key to update the application's
4001 * UI instead of allowing the IME to see it and close itself.
4002 *
4003 * @param event The key event to be dispatched.
4004 * @return True if the event was handled, false otherwise.
4005 */
4006 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4007 return onKeyPreIme(event.getKeyCode(), event);
4008 }
4009
4010 /**
4011 * Dispatch a key event to the next view on the focus path. This path runs
4012 * from the top of the view tree down to the currently focused view. If this
4013 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4014 * the next node down the focus path. This method also fires any key
4015 * listeners.
4016 *
4017 * @param event The key event to be dispatched.
4018 * @return True if the event was handled, false otherwise.
4019 */
4020 public boolean dispatchKeyEvent(KeyEvent event) {
4021 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022
Romain Guyf607bdc2010-09-10 19:20:06 -07004023 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 if (android.util.Config.LOGV) {
4025 captureViewInfo("captureViewKeyEvent", this);
4026 }
4027
Romain Guyf607bdc2010-09-10 19:20:06 -07004028 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4030 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4031 return true;
4032 }
4033
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004034 return event.dispatch(this, mAttachInfo != null
4035 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 }
4037
4038 /**
4039 * Dispatches a key shortcut event.
4040 *
4041 * @param event The key event to be dispatched.
4042 * @return True if the event was handled by the view, false otherwise.
4043 */
4044 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4045 return onKeyShortcut(event.getKeyCode(), event);
4046 }
4047
4048 /**
4049 * Pass the touch screen motion event down to the target view, or this
4050 * view if it is the target.
4051 *
4052 * @param event The motion event to be dispatched.
4053 * @return True if the event was handled by the view, false otherwise.
4054 */
4055 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004056 if (!onFilterTouchEventForSecurity(event)) {
4057 return false;
4058 }
4059
Romain Guyf607bdc2010-09-10 19:20:06 -07004060 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4062 mOnTouchListener.onTouch(this, event)) {
4063 return true;
4064 }
4065 return onTouchEvent(event);
4066 }
4067
4068 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004069 * Filter the touch event to apply security policies.
4070 *
4071 * @param event The motion event to be filtered.
4072 * @return True if the event should be dispatched, false if the event should be dropped.
4073 *
4074 * @see #getFilterTouchesWhenObscured
4075 */
4076 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004077 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004078 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4079 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4080 // Window is obscured, drop this touch.
4081 return false;
4082 }
4083 return true;
4084 }
4085
4086 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 * Pass a trackball motion event down to the focused view.
4088 *
4089 * @param event The motion event to be dispatched.
4090 * @return True if the event was handled by the view, false otherwise.
4091 */
4092 public boolean dispatchTrackballEvent(MotionEvent event) {
4093 //Log.i("view", "view=" + this + ", " + event.toString());
4094 return onTrackballEvent(event);
4095 }
4096
4097 /**
4098 * Called when the window containing this view gains or loses window focus.
4099 * ViewGroups should override to route to their children.
4100 *
4101 * @param hasFocus True if the window containing this view now has focus,
4102 * false otherwise.
4103 */
4104 public void dispatchWindowFocusChanged(boolean hasFocus) {
4105 onWindowFocusChanged(hasFocus);
4106 }
4107
4108 /**
4109 * Called when the window containing this view gains or loses focus. Note
4110 * that this is separate from view focus: to receive key events, both
4111 * your view and its window must have focus. If a window is displayed
4112 * on top of yours that takes input focus, then your own window will lose
4113 * focus but the view focus will remain unchanged.
4114 *
4115 * @param hasWindowFocus True if the window containing this view now has
4116 * focus, false otherwise.
4117 */
4118 public void onWindowFocusChanged(boolean hasWindowFocus) {
4119 InputMethodManager imm = InputMethodManager.peekInstance();
4120 if (!hasWindowFocus) {
4121 if (isPressed()) {
4122 setPressed(false);
4123 }
4124 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4125 imm.focusOut(this);
4126 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004127 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004128 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4130 imm.focusIn(this);
4131 }
4132 refreshDrawableState();
4133 }
4134
4135 /**
4136 * Returns true if this view is in a window that currently has window focus.
4137 * Note that this is not the same as the view itself having focus.
4138 *
4139 * @return True if this view is in a window that currently has window focus.
4140 */
4141 public boolean hasWindowFocus() {
4142 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4143 }
4144
4145 /**
Adam Powell326d8082009-12-09 15:10:07 -08004146 * Dispatch a view visibility change down the view hierarchy.
4147 * ViewGroups should override to route to their children.
4148 * @param changedView The view whose visibility changed. Could be 'this' or
4149 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004150 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4151 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004152 */
4153 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4154 onVisibilityChanged(changedView, visibility);
4155 }
4156
4157 /**
4158 * Called when the visibility of the view or an ancestor of the view is changed.
4159 * @param changedView The view whose visibility changed. Could be 'this' or
4160 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004161 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4162 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004163 */
4164 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004165 if (visibility == VISIBLE) {
4166 if (mAttachInfo != null) {
4167 initialAwakenScrollBars();
4168 } else {
4169 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4170 }
4171 }
Adam Powell326d8082009-12-09 15:10:07 -08004172 }
4173
4174 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004175 * Dispatch a hint about whether this view is displayed. For instance, when
4176 * a View moves out of the screen, it might receives a display hint indicating
4177 * the view is not displayed. Applications should not <em>rely</em> on this hint
4178 * as there is no guarantee that they will receive one.
4179 *
4180 * @param hint A hint about whether or not this view is displayed:
4181 * {@link #VISIBLE} or {@link #INVISIBLE}.
4182 */
4183 public void dispatchDisplayHint(int hint) {
4184 onDisplayHint(hint);
4185 }
4186
4187 /**
4188 * Gives this view a hint about whether is displayed or not. For instance, when
4189 * a View moves out of the screen, it might receives a display hint indicating
4190 * the view is not displayed. Applications should not <em>rely</em> on this hint
4191 * as there is no guarantee that they will receive one.
4192 *
4193 * @param hint A hint about whether or not this view is displayed:
4194 * {@link #VISIBLE} or {@link #INVISIBLE}.
4195 */
4196 protected void onDisplayHint(int hint) {
4197 }
4198
4199 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 * Dispatch a window visibility change down the view hierarchy.
4201 * ViewGroups should override to route to their children.
4202 *
4203 * @param visibility The new visibility of the window.
4204 *
4205 * @see #onWindowVisibilityChanged
4206 */
4207 public void dispatchWindowVisibilityChanged(int visibility) {
4208 onWindowVisibilityChanged(visibility);
4209 }
4210
4211 /**
4212 * Called when the window containing has change its visibility
4213 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4214 * that this tells you whether or not your window is being made visible
4215 * to the window manager; this does <em>not</em> tell you whether or not
4216 * your window is obscured by other windows on the screen, even if it
4217 * is itself visible.
4218 *
4219 * @param visibility The new visibility of the window.
4220 */
4221 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004222 if (visibility == VISIBLE) {
4223 initialAwakenScrollBars();
4224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 }
4226
4227 /**
4228 * Returns the current visibility of the window this view is attached to
4229 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4230 *
4231 * @return Returns the current visibility of the view's window.
4232 */
4233 public int getWindowVisibility() {
4234 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4235 }
4236
4237 /**
4238 * Retrieve the overall visible display size in which the window this view is
4239 * attached to has been positioned in. This takes into account screen
4240 * decorations above the window, for both cases where the window itself
4241 * is being position inside of them or the window is being placed under
4242 * then and covered insets are used for the window to position its content
4243 * inside. In effect, this tells you the available area where content can
4244 * be placed and remain visible to users.
4245 *
4246 * <p>This function requires an IPC back to the window manager to retrieve
4247 * the requested information, so should not be used in performance critical
4248 * code like drawing.
4249 *
4250 * @param outRect Filled in with the visible display frame. If the view
4251 * is not attached to a window, this is simply the raw display size.
4252 */
4253 public void getWindowVisibleDisplayFrame(Rect outRect) {
4254 if (mAttachInfo != null) {
4255 try {
4256 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4257 } catch (RemoteException e) {
4258 return;
4259 }
4260 // XXX This is really broken, and probably all needs to be done
4261 // in the window manager, and we need to know more about whether
4262 // we want the area behind or in front of the IME.
4263 final Rect insets = mAttachInfo.mVisibleInsets;
4264 outRect.left += insets.left;
4265 outRect.top += insets.top;
4266 outRect.right -= insets.right;
4267 outRect.bottom -= insets.bottom;
4268 return;
4269 }
4270 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4271 outRect.set(0, 0, d.getWidth(), d.getHeight());
4272 }
4273
4274 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004275 * Dispatch a notification about a resource configuration change down
4276 * the view hierarchy.
4277 * ViewGroups should override to route to their children.
4278 *
4279 * @param newConfig The new resource configuration.
4280 *
4281 * @see #onConfigurationChanged
4282 */
4283 public void dispatchConfigurationChanged(Configuration newConfig) {
4284 onConfigurationChanged(newConfig);
4285 }
4286
4287 /**
4288 * Called when the current configuration of the resources being used
4289 * by the application have changed. You can use this to decide when
4290 * to reload resources that can changed based on orientation and other
4291 * configuration characterstics. You only need to use this if you are
4292 * not relying on the normal {@link android.app.Activity} mechanism of
4293 * recreating the activity instance upon a configuration change.
4294 *
4295 * @param newConfig The new resource configuration.
4296 */
4297 protected void onConfigurationChanged(Configuration newConfig) {
4298 }
4299
4300 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 * Private function to aggregate all per-view attributes in to the view
4302 * root.
4303 */
4304 void dispatchCollectViewAttributes(int visibility) {
4305 performCollectViewAttributes(visibility);
4306 }
4307
4308 void performCollectViewAttributes(int visibility) {
4309 //noinspection PointlessBitwiseExpression
4310 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4311 == (VISIBLE | KEEP_SCREEN_ON)) {
4312 mAttachInfo.mKeepScreenOn = true;
4313 }
4314 }
4315
4316 void needGlobalAttributesUpdate(boolean force) {
4317 AttachInfo ai = mAttachInfo;
4318 if (ai != null) {
4319 if (ai.mKeepScreenOn || force) {
4320 ai.mRecomputeGlobalAttributes = true;
4321 }
4322 }
4323 }
4324
4325 /**
4326 * Returns whether the device is currently in touch mode. Touch mode is entered
4327 * once the user begins interacting with the device by touch, and affects various
4328 * things like whether focus is always visible to the user.
4329 *
4330 * @return Whether the device is in touch mode.
4331 */
4332 @ViewDebug.ExportedProperty
4333 public boolean isInTouchMode() {
4334 if (mAttachInfo != null) {
4335 return mAttachInfo.mInTouchMode;
4336 } else {
4337 return ViewRoot.isInTouchMode();
4338 }
4339 }
4340
4341 /**
4342 * Returns the context the view is running in, through which it can
4343 * access the current theme, resources, etc.
4344 *
4345 * @return The view's Context.
4346 */
4347 @ViewDebug.CapturedViewProperty
4348 public final Context getContext() {
4349 return mContext;
4350 }
4351
4352 /**
4353 * Handle a key event before it is processed by any input method
4354 * associated with the view hierarchy. This can be used to intercept
4355 * key events in special situations before the IME consumes them; a
4356 * typical example would be handling the BACK key to update the application's
4357 * UI instead of allowing the IME to see it and close itself.
4358 *
4359 * @param keyCode The value in event.getKeyCode().
4360 * @param event Description of the key event.
4361 * @return If you handled the event, return true. If you want to allow the
4362 * event to be handled by the next receiver, return false.
4363 */
4364 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4365 return false;
4366 }
4367
4368 /**
4369 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4370 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4371 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4372 * is released, if the view is enabled and clickable.
4373 *
4374 * @param keyCode A key code that represents the button pressed, from
4375 * {@link android.view.KeyEvent}.
4376 * @param event The KeyEvent object that defines the button action.
4377 */
4378 public boolean onKeyDown(int keyCode, KeyEvent event) {
4379 boolean result = false;
4380
4381 switch (keyCode) {
4382 case KeyEvent.KEYCODE_DPAD_CENTER:
4383 case KeyEvent.KEYCODE_ENTER: {
4384 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4385 return true;
4386 }
4387 // Long clickable items don't necessarily have to be clickable
4388 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4389 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4390 (event.getRepeatCount() == 0)) {
4391 setPressed(true);
4392 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004393 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 }
4395 return true;
4396 }
4397 break;
4398 }
4399 }
4400 return result;
4401 }
4402
4403 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004404 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4405 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4406 * the event).
4407 */
4408 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4409 return false;
4410 }
4411
4412 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004413 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4414 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4415 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4416 * {@link KeyEvent#KEYCODE_ENTER} is released.
4417 *
4418 * @param keyCode A key code that represents the button pressed, from
4419 * {@link android.view.KeyEvent}.
4420 * @param event The KeyEvent object that defines the button action.
4421 */
4422 public boolean onKeyUp(int keyCode, KeyEvent event) {
4423 boolean result = false;
4424
4425 switch (keyCode) {
4426 case KeyEvent.KEYCODE_DPAD_CENTER:
4427 case KeyEvent.KEYCODE_ENTER: {
4428 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4429 return true;
4430 }
4431 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4432 setPressed(false);
4433
4434 if (!mHasPerformedLongPress) {
4435 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004436 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004437
4438 result = performClick();
4439 }
4440 }
4441 break;
4442 }
4443 }
4444 return result;
4445 }
4446
4447 /**
4448 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4449 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4450 * the event).
4451 *
4452 * @param keyCode A key code that represents the button pressed, from
4453 * {@link android.view.KeyEvent}.
4454 * @param repeatCount The number of times the action was made.
4455 * @param event The KeyEvent object that defines the button action.
4456 */
4457 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4458 return false;
4459 }
4460
4461 /**
4462 * Called when an unhandled key shortcut event occurs.
4463 *
4464 * @param keyCode The value in event.getKeyCode().
4465 * @param event Description of the key event.
4466 * @return If you handled the event, return true. If you want to allow the
4467 * event to be handled by the next receiver, return false.
4468 */
4469 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4470 return false;
4471 }
4472
4473 /**
4474 * Check whether the called view is a text editor, in which case it
4475 * would make sense to automatically display a soft input window for
4476 * it. Subclasses should override this if they implement
4477 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004478 * a call on that method would return a non-null InputConnection, and
4479 * they are really a first-class editor that the user would normally
4480 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004481 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004482 * <p>The default implementation always returns false. This does
4483 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4484 * will not be called or the user can not otherwise perform edits on your
4485 * view; it is just a hint to the system that this is not the primary
4486 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004487 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 * @return Returns true if this view is a text editor, else false.
4489 */
4490 public boolean onCheckIsTextEditor() {
4491 return false;
4492 }
Romain Guy8506ab42009-06-11 17:35:47 -07004493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 /**
4495 * Create a new InputConnection for an InputMethod to interact
4496 * with the view. The default implementation returns null, since it doesn't
4497 * support input methods. You can override this to implement such support.
4498 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004499 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 * <p>When implementing this, you probably also want to implement
4501 * {@link #onCheckIsTextEditor()} to indicate you will return a
4502 * non-null InputConnection.
4503 *
4504 * @param outAttrs Fill in with attribute information about the connection.
4505 */
4506 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4507 return null;
4508 }
4509
4510 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004511 * Called by the {@link android.view.inputmethod.InputMethodManager}
4512 * when a view who is not the current
4513 * input connection target is trying to make a call on the manager. The
4514 * default implementation returns false; you can override this to return
4515 * true for certain views if you are performing InputConnection proxying
4516 * to them.
4517 * @param view The View that is making the InputMethodManager call.
4518 * @return Return true to allow the call, false to reject.
4519 */
4520 public boolean checkInputConnectionProxy(View view) {
4521 return false;
4522 }
Romain Guy8506ab42009-06-11 17:35:47 -07004523
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004524 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 * Show the context menu for this view. It is not safe to hold on to the
4526 * menu after returning from this method.
4527 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004528 * You should normally not overload this method. Overload
4529 * {@link #onCreateContextMenu(ContextMenu)} or define an
4530 * {@link OnCreateContextMenuListener} to add items to the context menu.
4531 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 * @param menu The context menu to populate
4533 */
4534 public void createContextMenu(ContextMenu menu) {
4535 ContextMenuInfo menuInfo = getContextMenuInfo();
4536
4537 // Sets the current menu info so all items added to menu will have
4538 // my extra info set.
4539 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4540
4541 onCreateContextMenu(menu);
4542 if (mOnCreateContextMenuListener != null) {
4543 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4544 }
4545
4546 // Clear the extra information so subsequent items that aren't mine don't
4547 // have my extra info.
4548 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4549
4550 if (mParent != null) {
4551 mParent.createContextMenu(menu);
4552 }
4553 }
4554
4555 /**
4556 * Views should implement this if they have extra information to associate
4557 * with the context menu. The return result is supplied as a parameter to
4558 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4559 * callback.
4560 *
4561 * @return Extra information about the item for which the context menu
4562 * should be shown. This information will vary across different
4563 * subclasses of View.
4564 */
4565 protected ContextMenuInfo getContextMenuInfo() {
4566 return null;
4567 }
4568
4569 /**
4570 * Views should implement this if the view itself is going to add items to
4571 * the context menu.
4572 *
4573 * @param menu the context menu to populate
4574 */
4575 protected void onCreateContextMenu(ContextMenu menu) {
4576 }
4577
4578 /**
4579 * Implement this method to handle trackball motion events. The
4580 * <em>relative</em> movement of the trackball since the last event
4581 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4582 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4583 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4584 * they will often be fractional values, representing the more fine-grained
4585 * movement information available from a trackball).
4586 *
4587 * @param event The motion event.
4588 * @return True if the event was handled, false otherwise.
4589 */
4590 public boolean onTrackballEvent(MotionEvent event) {
4591 return false;
4592 }
4593
4594 /**
4595 * Implement this method to handle touch screen motion events.
4596 *
4597 * @param event The motion event.
4598 * @return True if the event was handled, false otherwise.
4599 */
4600 public boolean onTouchEvent(MotionEvent event) {
4601 final int viewFlags = mViewFlags;
4602
4603 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4604 // A disabled view that is clickable still consumes the touch
4605 // events, it just doesn't respond to them.
4606 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4607 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4608 }
4609
4610 if (mTouchDelegate != null) {
4611 if (mTouchDelegate.onTouchEvent(event)) {
4612 return true;
4613 }
4614 }
4615
4616 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4617 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4618 switch (event.getAction()) {
4619 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004620 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4621 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 // take focus if we don't have it already and we should in
4623 // touch mode.
4624 boolean focusTaken = false;
4625 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4626 focusTaken = requestFocus();
4627 }
4628
4629 if (!mHasPerformedLongPress) {
4630 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004631 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632
4633 // Only perform take click actions if we were in the pressed state
4634 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004635 // Use a Runnable and post this rather than calling
4636 // performClick directly. This lets other visual state
4637 // of the view update before click actions start.
4638 if (mPerformClick == null) {
4639 mPerformClick = new PerformClick();
4640 }
4641 if (!post(mPerformClick)) {
4642 performClick();
4643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 }
4645 }
4646
4647 if (mUnsetPressedState == null) {
4648 mUnsetPressedState = new UnsetPressedState();
4649 }
4650
Adam Powelle14579b2009-12-16 18:39:52 -08004651 if (prepressed) {
4652 mPrivateFlags |= PRESSED;
4653 refreshDrawableState();
4654 postDelayed(mUnsetPressedState,
4655 ViewConfiguration.getPressedStateDuration());
4656 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 // If the post failed, unpress right now
4658 mUnsetPressedState.run();
4659 }
Adam Powelle14579b2009-12-16 18:39:52 -08004660 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004661 }
4662 break;
4663
4664 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004665 if (mPendingCheckForTap == null) {
4666 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004667 }
Adam Powelle14579b2009-12-16 18:39:52 -08004668 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004669 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004670 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004671 break;
4672
4673 case MotionEvent.ACTION_CANCEL:
4674 mPrivateFlags &= ~PRESSED;
4675 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004676 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 break;
4678
4679 case MotionEvent.ACTION_MOVE:
4680 final int x = (int) event.getX();
4681 final int y = (int) event.getY();
4682
4683 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004684 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004685 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004686 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004688 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004689 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004690
4691 // Need to switch from pressed to not pressed
4692 mPrivateFlags &= ~PRESSED;
4693 refreshDrawableState();
4694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004695 }
4696 break;
4697 }
4698 return true;
4699 }
4700
4701 return false;
4702 }
4703
4704 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004705 * Remove the longpress detection timer.
4706 */
4707 private void removeLongPressCallback() {
4708 if (mPendingCheckForLongPress != null) {
4709 removeCallbacks(mPendingCheckForLongPress);
4710 }
4711 }
Adam Powelle14579b2009-12-16 18:39:52 -08004712
4713 /**
Romain Guya440b002010-02-24 15:57:54 -08004714 * Remove the prepress detection timer.
4715 */
4716 private void removeUnsetPressCallback() {
4717 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4718 setPressed(false);
4719 removeCallbacks(mUnsetPressedState);
4720 }
4721 }
4722
4723 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004724 * Remove the tap detection timer.
4725 */
4726 private void removeTapCallback() {
4727 if (mPendingCheckForTap != null) {
4728 mPrivateFlags &= ~PREPRESSED;
4729 removeCallbacks(mPendingCheckForTap);
4730 }
4731 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004732
4733 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004734 * Cancels a pending long press. Your subclass can use this if you
4735 * want the context menu to come up if the user presses and holds
4736 * at the same place, but you don't want it to come up if they press
4737 * and then move around enough to cause scrolling.
4738 */
4739 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004740 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004741
4742 /*
4743 * The prepressed state handled by the tap callback is a display
4744 * construct, but the tap callback will post a long press callback
4745 * less its own timeout. Remove it here.
4746 */
4747 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 }
4749
4750 /**
4751 * Sets the TouchDelegate for this View.
4752 */
4753 public void setTouchDelegate(TouchDelegate delegate) {
4754 mTouchDelegate = delegate;
4755 }
4756
4757 /**
4758 * Gets the TouchDelegate for this View.
4759 */
4760 public TouchDelegate getTouchDelegate() {
4761 return mTouchDelegate;
4762 }
4763
4764 /**
4765 * Set flags controlling behavior of this view.
4766 *
4767 * @param flags Constant indicating the value which should be set
4768 * @param mask Constant indicating the bit range that should be changed
4769 */
4770 void setFlags(int flags, int mask) {
4771 int old = mViewFlags;
4772 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4773
4774 int changed = mViewFlags ^ old;
4775 if (changed == 0) {
4776 return;
4777 }
4778 int privateFlags = mPrivateFlags;
4779
4780 /* Check if the FOCUSABLE bit has changed */
4781 if (((changed & FOCUSABLE_MASK) != 0) &&
4782 ((privateFlags & HAS_BOUNDS) !=0)) {
4783 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4784 && ((privateFlags & FOCUSED) != 0)) {
4785 /* Give up focus if we are no longer focusable */
4786 clearFocus();
4787 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4788 && ((privateFlags & FOCUSED) == 0)) {
4789 /*
4790 * Tell the view system that we are now available to take focus
4791 * if no one else already has it.
4792 */
4793 if (mParent != null) mParent.focusableViewAvailable(this);
4794 }
4795 }
4796
4797 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4798 if ((changed & VISIBILITY_MASK) != 0) {
4799 /*
4800 * If this view is becoming visible, set the DRAWN flag so that
4801 * the next invalidate() will not be skipped.
4802 */
4803 mPrivateFlags |= DRAWN;
4804
4805 needGlobalAttributesUpdate(true);
4806
4807 // a view becoming visible is worth notifying the parent
4808 // about in case nothing has focus. even if this specific view
4809 // isn't focusable, it may contain something that is, so let
4810 // the root view try to give this focus if nothing else does.
4811 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4812 mParent.focusableViewAvailable(this);
4813 }
4814 }
4815 }
4816
4817 /* Check if the GONE bit has changed */
4818 if ((changed & GONE) != 0) {
4819 needGlobalAttributesUpdate(false);
4820 requestLayout();
4821 invalidate();
4822
Romain Guyecd80ee2009-12-03 17:13:02 -08004823 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
4824 if (hasFocus()) clearFocus();
4825 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826 }
4827 if (mAttachInfo != null) {
4828 mAttachInfo.mViewVisibilityChanged = true;
4829 }
4830 }
4831
4832 /* Check if the VISIBLE bit has changed */
4833 if ((changed & INVISIBLE) != 0) {
4834 needGlobalAttributesUpdate(false);
4835 invalidate();
4836
4837 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4838 // root view becoming invisible shouldn't clear focus
4839 if (getRootView() != this) {
4840 clearFocus();
4841 }
4842 }
4843 if (mAttachInfo != null) {
4844 mAttachInfo.mViewVisibilityChanged = true;
4845 }
4846 }
4847
Adam Powell326d8082009-12-09 15:10:07 -08004848 if ((changed & VISIBILITY_MASK) != 0) {
4849 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
4850 }
4851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004852 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4853 destroyDrawingCache();
4854 }
4855
4856 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4857 destroyDrawingCache();
4858 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4859 }
4860
4861 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4862 destroyDrawingCache();
4863 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4864 }
4865
4866 if ((changed & DRAW_MASK) != 0) {
4867 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4868 if (mBGDrawable != null) {
4869 mPrivateFlags &= ~SKIP_DRAW;
4870 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4871 } else {
4872 mPrivateFlags |= SKIP_DRAW;
4873 }
4874 } else {
4875 mPrivateFlags &= ~SKIP_DRAW;
4876 }
4877 requestLayout();
4878 invalidate();
4879 }
4880
4881 if ((changed & KEEP_SCREEN_ON) != 0) {
4882 if (mParent != null) {
4883 mParent.recomputeViewAttributes(this);
4884 }
4885 }
4886 }
4887
4888 /**
4889 * Change the view's z order in the tree, so it's on top of other sibling
4890 * views
4891 */
4892 public void bringToFront() {
4893 if (mParent != null) {
4894 mParent.bringChildToFront(this);
4895 }
4896 }
4897
4898 /**
4899 * This is called in response to an internal scroll in this view (i.e., the
4900 * view scrolled its own contents). This is typically as a result of
4901 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4902 * called.
4903 *
4904 * @param l Current horizontal scroll origin.
4905 * @param t Current vertical scroll origin.
4906 * @param oldl Previous horizontal scroll origin.
4907 * @param oldt Previous vertical scroll origin.
4908 */
4909 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4910 mBackgroundSizeChanged = true;
4911
4912 final AttachInfo ai = mAttachInfo;
4913 if (ai != null) {
4914 ai.mViewScrollChanged = true;
4915 }
4916 }
4917
4918 /**
Chet Haase21cd1382010-09-01 17:42:29 -07004919 * Interface definition for a callback to be invoked when the layout bounds of a view
4920 * changes due to layout processing.
4921 */
4922 public interface OnLayoutChangeListener {
4923 /**
4924 * Called when the focus state of a view has changed.
4925 *
4926 * @param v The view whose state has changed.
4927 * @param left The new value of the view's left property.
4928 * @param top The new value of the view's top property.
4929 * @param right The new value of the view's right property.
4930 * @param bottom The new value of the view's bottom property.
4931 * @param oldLeft The previous value of the view's left property.
4932 * @param oldTop The previous value of the view's top property.
4933 * @param oldRight The previous value of the view's right property.
4934 * @param oldBottom The previous value of the view's bottom property.
4935 */
4936 void onLayoutChange(View v, int left, int top, int right, int bottom,
4937 int oldLeft, int oldTop, int oldRight, int oldBottom);
4938 }
4939
4940 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941 * This is called during layout when the size of this view has changed. If
4942 * you were just added to the view hierarchy, you're called with the old
4943 * values of 0.
4944 *
4945 * @param w Current width of this view.
4946 * @param h Current height of this view.
4947 * @param oldw Old width of this view.
4948 * @param oldh Old height of this view.
4949 */
4950 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
4951 }
4952
4953 /**
4954 * Called by draw to draw the child views. This may be overridden
4955 * by derived classes to gain control just before its children are drawn
4956 * (but after its own view has been drawn).
4957 * @param canvas the canvas on which to draw the view
4958 */
4959 protected void dispatchDraw(Canvas canvas) {
4960 }
4961
4962 /**
4963 * Gets the parent of this view. Note that the parent is a
4964 * ViewParent and not necessarily a View.
4965 *
4966 * @return Parent of this view.
4967 */
4968 public final ViewParent getParent() {
4969 return mParent;
4970 }
4971
4972 /**
4973 * Return the scrolled left position of this view. This is the left edge of
4974 * the displayed part of your view. You do not need to draw any pixels
4975 * farther left, since those are outside of the frame of your view on
4976 * screen.
4977 *
4978 * @return The left edge of the displayed part of your view, in pixels.
4979 */
4980 public final int getScrollX() {
4981 return mScrollX;
4982 }
4983
4984 /**
4985 * Return the scrolled top position of this view. This is the top edge of
4986 * the displayed part of your view. You do not need to draw any pixels above
4987 * it, since those are outside of the frame of your view on screen.
4988 *
4989 * @return The top edge of the displayed part of your view, in pixels.
4990 */
4991 public final int getScrollY() {
4992 return mScrollY;
4993 }
4994
4995 /**
4996 * Return the width of the your view.
4997 *
4998 * @return The width of your view, in pixels.
4999 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005000 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 public final int getWidth() {
5002 return mRight - mLeft;
5003 }
5004
5005 /**
5006 * Return the height of your view.
5007 *
5008 * @return The height of your view, in pixels.
5009 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005010 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005011 public final int getHeight() {
5012 return mBottom - mTop;
5013 }
5014
5015 /**
5016 * Return the visible drawing bounds of your view. Fills in the output
5017 * rectangle with the values from getScrollX(), getScrollY(),
5018 * getWidth(), and getHeight().
5019 *
5020 * @param outRect The (scrolled) drawing bounds of the view.
5021 */
5022 public void getDrawingRect(Rect outRect) {
5023 outRect.left = mScrollX;
5024 outRect.top = mScrollY;
5025 outRect.right = mScrollX + (mRight - mLeft);
5026 outRect.bottom = mScrollY + (mBottom - mTop);
5027 }
5028
5029 /**
5030 * The width of this view as measured in the most recent call to measure().
5031 * This should be used during measurement and layout calculations only. Use
5032 * {@link #getWidth()} to see how wide a view is after layout.
5033 *
5034 * @return The measured width of this view.
5035 */
5036 public final int getMeasuredWidth() {
5037 return mMeasuredWidth;
5038 }
5039
5040 /**
5041 * The height of this view as measured in the most recent call to measure().
5042 * This should be used during measurement and layout calculations only. Use
5043 * {@link #getHeight()} to see how tall a view is after layout.
5044 *
5045 * @return The measured height of this view.
5046 */
5047 public final int getMeasuredHeight() {
5048 return mMeasuredHeight;
5049 }
5050
5051 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005052 * The transform matrix of this view, which is calculated based on the current
5053 * roation, scale, and pivot properties.
5054 *
5055 * @see #getRotation()
5056 * @see #getScaleX()
5057 * @see #getScaleY()
5058 * @see #getPivotX()
5059 * @see #getPivotY()
5060 * @return The current transform matrix for the view
5061 */
5062 public Matrix getMatrix() {
Romain Guy33e72ae2010-07-17 12:40:29 -07005063 hasIdentityMatrix();
5064 return mMatrix;
5065 }
5066
5067 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005068 * Utility function to determine if the value is far enough away from zero to be
5069 * considered non-zero.
5070 * @param value A floating point value to check for zero-ness
5071 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5072 */
5073 private static boolean nonzero(float value) {
5074 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5075 }
5076
5077 /**
Romain Guy33e72ae2010-07-17 12:40:29 -07005078 * Recomputes the transform matrix if necessary.
5079 *
5080 * @return True if the transform matrix is the identity matrix, false otherwise.
5081 */
5082 boolean hasIdentityMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005083 if (mMatrixDirty) {
5084 // transform-related properties have changed since the last time someone
5085 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005086
5087 // Figure out if we need to update the pivot point
5088 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5089 if ((mRight - mLeft) != mPrevWidth && (mBottom - mTop) != mPrevHeight) {
5090 mPrevWidth = mRight - mLeft;
5091 mPrevHeight = mBottom - mTop;
5092 mPivotX = (float) mPrevWidth / 2f;
5093 mPivotY = (float) mPrevHeight / 2f;
5094 }
5095 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005096 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005097 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5098 mMatrix.setTranslate(mTranslationX, mTranslationY);
5099 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5100 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5101 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005102 if (mCamera == null) {
5103 mCamera = new Camera();
5104 matrix3D = new Matrix();
5105 }
5106 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005107 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005108 mCamera.rotateX(mRotationX);
5109 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005110 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005111 mCamera.getMatrix(matrix3D);
5112 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005113 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005114 mMatrix.postConcat(matrix3D);
5115 mCamera.restore();
5116 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005117 mMatrixDirty = false;
5118 mMatrixIsIdentity = mMatrix.isIdentity();
5119 mInverseMatrixDirty = true;
5120 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005121 return mMatrixIsIdentity;
Chet Haasec3aa3612010-06-17 08:50:37 -07005122 }
5123
5124 /**
5125 * Utility method to retrieve the inverse of the current mMatrix property.
5126 * We cache the matrix to avoid recalculating it when transform properties
5127 * have not changed.
5128 *
5129 * @return The inverse of the current matrix of this view.
5130 */
5131 Matrix getInverseMatrix() {
5132 if (mInverseMatrixDirty) {
5133 if (mInverseMatrix == null) {
5134 mInverseMatrix = new Matrix();
5135 }
5136 mMatrix.invert(mInverseMatrix);
5137 mInverseMatrixDirty = false;
5138 }
5139 return mInverseMatrix;
5140 }
5141
5142 /**
5143 * The degrees that the view is rotated around the pivot point.
5144 *
5145 * @see #getPivotX()
5146 * @see #getPivotY()
5147 * @return The degrees of rotation.
5148 */
5149 public float getRotation() {
5150 return mRotation;
5151 }
5152
5153 /**
Chet Haase897247b2010-09-09 14:54:47 -07005154 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5155 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005156 *
5157 * @param rotation The degrees of rotation.
5158 * @see #getPivotX()
5159 * @see #getPivotY()
5160 */
5161 public void setRotation(float rotation) {
5162 if (mRotation != rotation) {
5163 // Double-invalidation is necessary to capture view's old and new areas
5164 invalidate();
5165 mRotation = rotation;
5166 mMatrixDirty = true;
5167 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5168 invalidate();
5169 }
5170 }
5171
5172 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005173 * The degrees that the view is rotated around the vertical axis through the pivot point.
5174 *
5175 * @see #getPivotX()
5176 * @see #getPivotY()
5177 * @return The degrees of Y rotation.
5178 */
5179 public float getRotationY() {
5180 return mRotationY;
5181 }
5182
5183 /**
Chet Haase897247b2010-09-09 14:54:47 -07005184 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5185 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5186 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005187 *
5188 * @param rotationY The degrees of Y rotation.
5189 * @see #getPivotX()
5190 * @see #getPivotY()
5191 */
5192 public void setRotationY(float rotationY) {
5193 if (mRotationY != rotationY) {
5194 // Double-invalidation is necessary to capture view's old and new areas
5195 invalidate();
5196 mRotationY = rotationY;
5197 mMatrixDirty = true;
5198 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5199 invalidate();
5200 }
5201 }
5202
5203 /**
5204 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5205 *
5206 * @see #getPivotX()
5207 * @see #getPivotY()
5208 * @return The degrees of X rotation.
5209 */
5210 public float getRotationX() {
5211 return mRotationX;
5212 }
5213
5214 /**
Chet Haase897247b2010-09-09 14:54:47 -07005215 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5216 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5217 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005218 *
5219 * @param rotationX The degrees of X rotation.
5220 * @see #getPivotX()
5221 * @see #getPivotY()
5222 */
5223 public void setRotationX(float rotationX) {
5224 if (mRotationX != rotationX) {
5225 // Double-invalidation is necessary to capture view's old and new areas
5226 invalidate();
5227 mRotationX = rotationX;
5228 mMatrixDirty = true;
5229 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5230 invalidate();
5231 }
5232 }
5233
5234 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005235 * The amount that the view is scaled in x around the pivot point, as a proportion of
5236 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5237 *
5238 * @default 1.0f
5239 * @see #getPivotX()
5240 * @see #getPivotY()
5241 * @return The scaling factor.
5242 */
5243 public float getScaleX() {
5244 return mScaleX;
5245 }
5246
5247 /**
5248 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5249 * the view's unscaled width. A value of 1 means that no scaling is applied.
5250 *
5251 * @param scaleX The scaling factor.
5252 * @see #getPivotX()
5253 * @see #getPivotY()
5254 */
5255 public void setScaleX(float scaleX) {
5256 if (mScaleX != scaleX) {
5257 // Double-invalidation is necessary to capture view's old and new areas
5258 invalidate();
5259 mScaleX = scaleX;
5260 mMatrixDirty = true;
5261 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5262 invalidate();
5263 }
5264 }
5265
5266 /**
5267 * The amount that the view is scaled in y around the pivot point, as a proportion of
5268 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5269 *
5270 * @default 1.0f
5271 * @see #getPivotX()
5272 * @see #getPivotY()
5273 * @return The scaling factor.
5274 */
5275 public float getScaleY() {
5276 return mScaleY;
5277 }
5278
5279 /**
5280 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5281 * the view's unscaled width. A value of 1 means that no scaling is applied.
5282 *
5283 * @param scaleY The scaling factor.
5284 * @see #getPivotX()
5285 * @see #getPivotY()
5286 */
5287 public void setScaleY(float scaleY) {
5288 if (mScaleY != scaleY) {
5289 // Double-invalidation is necessary to capture view's old and new areas
5290 invalidate();
5291 mScaleY = scaleY;
5292 mMatrixDirty = true;
5293 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5294 invalidate();
5295 }
5296 }
5297
5298 /**
5299 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5300 * and {@link #setScaleX(float) scaled}.
5301 *
5302 * @see #getRotation()
5303 * @see #getScaleX()
5304 * @see #getScaleY()
5305 * @see #getPivotY()
5306 * @return The x location of the pivot point.
5307 */
5308 public float getPivotX() {
5309 return mPivotX;
5310 }
5311
5312 /**
5313 * Sets the x location of the point around which the view is
5314 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005315 * By default, the pivot point is centered on the object.
5316 * Setting this property disables this behavior and causes the view to use only the
5317 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005318 *
5319 * @param pivotX The x location of the pivot point.
5320 * @see #getRotation()
5321 * @see #getScaleX()
5322 * @see #getScaleY()
5323 * @see #getPivotY()
5324 */
5325 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005326 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005327 if (mPivotX != pivotX) {
5328 // Double-invalidation is necessary to capture view's old and new areas
5329 invalidate();
5330 mPivotX = pivotX;
5331 mMatrixDirty = true;
5332 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5333 invalidate();
5334 }
5335 }
5336
5337 /**
5338 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5339 * and {@link #setScaleY(float) scaled}.
5340 *
5341 * @see #getRotation()
5342 * @see #getScaleX()
5343 * @see #getScaleY()
5344 * @see #getPivotY()
5345 * @return The y location of the pivot point.
5346 */
5347 public float getPivotY() {
5348 return mPivotY;
5349 }
5350
5351 /**
5352 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005353 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5354 * Setting this property disables this behavior and causes the view to use only the
5355 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005356 *
5357 * @param pivotY The y location of the pivot point.
5358 * @see #getRotation()
5359 * @see #getScaleX()
5360 * @see #getScaleY()
5361 * @see #getPivotY()
5362 */
5363 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005364 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005365 if (mPivotY != pivotY) {
5366 // Double-invalidation is necessary to capture view's old and new areas
5367 invalidate();
5368 mPivotY = pivotY;
5369 mMatrixDirty = true;
5370 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5371 invalidate();
5372 }
5373 }
5374
5375 /**
5376 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5377 * completely transparent and 1 means the view is completely opaque.
5378 *
5379 * @default 1.0f
5380 * @return The opacity of the view.
5381 */
5382 public float getAlpha() {
5383 return mAlpha;
5384 }
5385
5386 /**
5387 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5388 * completely transparent and 1 means the view is completely opaque.
5389 *
5390 * @param alpha The opacity of the view.
5391 */
5392 public void setAlpha(float alpha) {
5393 mAlpha = alpha;
Romain Guy9b34d452010-09-02 11:45:04 -07005394 onSetAlpha((int) (alpha * 255));
Chet Haasec3aa3612010-06-17 08:50:37 -07005395 invalidate();
5396 }
5397
5398 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399 * Top position of this view relative to its parent.
5400 *
5401 * @return The top of this view, in pixels.
5402 */
5403 @ViewDebug.CapturedViewProperty
5404 public final int getTop() {
5405 return mTop;
5406 }
5407
5408 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005409 * Sets the top position of this view relative to its parent. This method is meant to be called
5410 * by the layout system and should not generally be called otherwise, because the property
5411 * may be changed at any time by the layout.
5412 *
5413 * @param top The top of this view, in pixels.
5414 */
5415 public final void setTop(int top) {
5416 if (top != mTop) {
5417 if (hasIdentityMatrix()) {
5418 final ViewParent p = mParent;
5419 if (p != null && mAttachInfo != null) {
5420 final Rect r = mAttachInfo.mTmpInvalRect;
5421 int minTop;
5422 int yLoc;
5423 if (top < mTop) {
5424 minTop = top;
5425 yLoc = top - mTop;
5426 } else {
5427 minTop = mTop;
5428 yLoc = 0;
5429 }
5430 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5431 p.invalidateChild(this, r);
5432 }
5433 } else {
5434 // Double-invalidation is necessary to capture view's old and new areas
5435 invalidate();
5436 }
5437
5438 mTop = top;
5439
5440 if (!mMatrixIsIdentity) {
5441 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5442 invalidate();
5443 }
5444 }
5445 }
5446
5447 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 * Bottom position of this view relative to its parent.
5449 *
5450 * @return The bottom of this view, in pixels.
5451 */
5452 @ViewDebug.CapturedViewProperty
5453 public final int getBottom() {
5454 return mBottom;
5455 }
5456
5457 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005458 * Sets the bottom position of this view relative to its parent. This method is meant to be
5459 * called by the layout system and should not generally be called otherwise, because the
5460 * property may be changed at any time by the layout.
5461 *
5462 * @param bottom The bottom of this view, in pixels.
5463 */
5464 public final void setBottom(int bottom) {
5465 if (bottom != mBottom) {
5466 if (hasIdentityMatrix()) {
5467 final ViewParent p = mParent;
5468 if (p != null && mAttachInfo != null) {
5469 final Rect r = mAttachInfo.mTmpInvalRect;
5470 int maxBottom;
5471 if (bottom < mBottom) {
5472 maxBottom = mBottom;
5473 } else {
5474 maxBottom = bottom;
5475 }
5476 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5477 p.invalidateChild(this, r);
5478 }
5479 } else {
5480 // Double-invalidation is necessary to capture view's old and new areas
5481 invalidate();
5482 }
5483
5484 mBottom = bottom;
5485
5486 if (!mMatrixIsIdentity) {
5487 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5488 invalidate();
5489 }
5490 }
5491 }
5492
5493 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005494 * Left position of this view relative to its parent.
5495 *
5496 * @return The left edge of this view, in pixels.
5497 */
5498 @ViewDebug.CapturedViewProperty
5499 public final int getLeft() {
5500 return mLeft;
5501 }
5502
5503 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005504 * Sets the left position of this view relative to its parent. This method is meant to be called
5505 * by the layout system and should not generally be called otherwise, because the property
5506 * may be changed at any time by the layout.
5507 *
5508 * @param left The bottom of this view, in pixels.
5509 */
5510 public final void setLeft(int left) {
5511 if (left != mLeft) {
5512 System.out.println("view " + this + " left = " + left);
5513 if (hasIdentityMatrix()) {
5514 final ViewParent p = mParent;
5515 if (p != null && mAttachInfo != null) {
5516 final Rect r = mAttachInfo.mTmpInvalRect;
5517 int minLeft;
5518 int xLoc;
5519 if (left < mLeft) {
5520 minLeft = left;
5521 xLoc = left - mLeft;
5522 } else {
5523 minLeft = mLeft;
5524 xLoc = 0;
5525 }
5526 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
5527 p.invalidateChild(this, r);
5528 }
5529 } else {
5530 // Double-invalidation is necessary to capture view's old and new areas
5531 invalidate();
5532 }
5533
5534 mLeft = left;
5535
5536 if (!mMatrixIsIdentity) {
5537 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5538 invalidate();
5539 }
5540 }
5541 }
5542
5543 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 * Right position of this view relative to its parent.
5545 *
5546 * @return The right edge of this view, in pixels.
5547 */
5548 @ViewDebug.CapturedViewProperty
5549 public final int getRight() {
5550 return mRight;
5551 }
5552
5553 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005554 * Sets the right position of this view relative to its parent. This method is meant to be called
5555 * by the layout system and should not generally be called otherwise, because the property
5556 * may be changed at any time by the layout.
5557 *
5558 * @param right The bottom of this view, in pixels.
5559 */
5560 public final void setRight(int right) {
5561 if (right != mRight) {
5562 if (hasIdentityMatrix()) {
5563 final ViewParent p = mParent;
5564 if (p != null && mAttachInfo != null) {
5565 final Rect r = mAttachInfo.mTmpInvalRect;
5566 int maxRight;
5567 if (right < mRight) {
5568 maxRight = mRight;
5569 } else {
5570 maxRight = right;
5571 }
5572 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
5573 p.invalidateChild(this, r);
5574 }
5575 } else {
5576 // Double-invalidation is necessary to capture view's old and new areas
5577 invalidate();
5578 }
5579
5580 mRight = right;
5581
5582 if (!mMatrixIsIdentity) {
5583 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5584 invalidate();
5585 }
5586 }
5587 }
5588
5589 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005590 * The visual x position of this view, in pixels. This is equivalent to the
5591 * {@link #setTranslationX(float) translationX} property plus the current
5592 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07005593 *
Chet Haasedf030d22010-07-30 17:22:38 -07005594 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005595 */
Chet Haasedf030d22010-07-30 17:22:38 -07005596 public float getX() {
5597 return mLeft + mTranslationX;
5598 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005599
Chet Haasedf030d22010-07-30 17:22:38 -07005600 /**
5601 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
5602 * {@link #setTranslationX(float) translationX} property to be the difference between
5603 * the x value passed in and the current {@link #getLeft() left} property.
5604 *
5605 * @param x The visual x position of this view, in pixels.
5606 */
5607 public void setX(float x) {
5608 setTranslationX(x - mLeft);
5609 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005610
Chet Haasedf030d22010-07-30 17:22:38 -07005611 /**
5612 * The visual y position of this view, in pixels. This is equivalent to the
5613 * {@link #setTranslationY(float) translationY} property plus the current
5614 * {@link #getTop() top} property.
5615 *
5616 * @return The visual y position of this view, in pixels.
5617 */
5618 public float getY() {
5619 return mTop + mTranslationY;
5620 }
5621
5622 /**
5623 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
5624 * {@link #setTranslationY(float) translationY} property to be the difference between
5625 * the y value passed in and the current {@link #getTop() top} property.
5626 *
5627 * @param y The visual y position of this view, in pixels.
5628 */
5629 public void setY(float y) {
5630 setTranslationY(y - mTop);
5631 }
5632
5633
5634 /**
5635 * The horizontal location of this view relative to its {@link #getLeft() left} position.
5636 * This position is post-layout, in addition to wherever the object's
5637 * layout placed it.
5638 *
5639 * @return The horizontal position of this view relative to its left position, in pixels.
5640 */
5641 public float getTranslationX() {
5642 return mTranslationX;
5643 }
5644
5645 /**
5646 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
5647 * This effectively positions the object post-layout, in addition to wherever the object's
5648 * layout placed it.
5649 *
5650 * @param translationX The horizontal position of this view relative to its left position,
5651 * in pixels.
5652 */
5653 public void setTranslationX(float translationX) {
5654 if (mTranslationX != translationX) {
5655 // Double-invalidation is necessary to capture view's old and new areas
5656 invalidate();
5657 mTranslationX = translationX;
5658 mMatrixDirty = true;
5659 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5660 invalidate();
Chet Haasec3aa3612010-06-17 08:50:37 -07005661 }
5662 }
5663
5664 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005665 * The horizontal location of this view relative to its {@link #getTop() top} position.
5666 * This position is post-layout, in addition to wherever the object's
5667 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005668 *
Chet Haasedf030d22010-07-30 17:22:38 -07005669 * @return The vertical position of this view relative to its top position,
5670 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005671 */
Chet Haasedf030d22010-07-30 17:22:38 -07005672 public float getTranslationY() {
5673 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07005674 }
5675
5676 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005677 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
5678 * This effectively positions the object post-layout, in addition to wherever the object's
5679 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005680 *
Chet Haasedf030d22010-07-30 17:22:38 -07005681 * @param translationY The vertical position of this view relative to its top position,
5682 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005683 */
Chet Haasedf030d22010-07-30 17:22:38 -07005684 public void setTranslationY(float translationY) {
5685 if (mTranslationY != translationY) {
5686 // Double-invalidation is necessary to capture view's old and new areas
5687 invalidate();
5688 mTranslationY = translationY;
5689 mMatrixDirty = true;
5690 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5691 invalidate();
5692 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005693 }
5694
5695 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 * Hit rectangle in parent's coordinates
5697 *
5698 * @param outRect The hit rectangle of the view.
5699 */
5700 public void getHitRect(Rect outRect) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005701 if (hasIdentityMatrix() || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005702 outRect.set(mLeft, mTop, mRight, mBottom);
5703 } else {
Adam Powellb5de9f32010-07-17 01:00:53 -07005704 Matrix m = getMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005705 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07005706 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Chet Haasec3aa3612010-06-17 08:50:37 -07005707 m.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07005708 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
5709 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07005710 }
5711 }
5712
5713 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005714 * Utility method to determine whether the given point, in local coordinates,
5715 * is inside the view, where the area of the view is expanded by the slop factor.
5716 * This method is called while processing touch-move events to determine if the event
5717 * is still within the view.
5718 */
5719 private boolean pointInView(float localX, float localY, float slop) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005720 return localX > -slop && localY > -slop && localX < ((mRight - mLeft) + slop) &&
5721 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 }
5723
5724 /**
5725 * When a view has focus and the user navigates away from it, the next view is searched for
5726 * starting from the rectangle filled in by this method.
5727 *
5728 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
5729 * view maintains some idea of internal selection, such as a cursor, or a selected row
5730 * or column, you should override this method and fill in a more specific rectangle.
5731 *
5732 * @param r The rectangle to fill in, in this view's coordinates.
5733 */
5734 public void getFocusedRect(Rect r) {
5735 getDrawingRect(r);
5736 }
5737
5738 /**
5739 * If some part of this view is not clipped by any of its parents, then
5740 * return that area in r in global (root) coordinates. To convert r to local
5741 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
5742 * -globalOffset.y)) If the view is completely clipped or translated out,
5743 * return false.
5744 *
5745 * @param r If true is returned, r holds the global coordinates of the
5746 * visible portion of this view.
5747 * @param globalOffset If true is returned, globalOffset holds the dx,dy
5748 * between this view and its root. globalOffet may be null.
5749 * @return true if r is non-empty (i.e. part of the view is visible at the
5750 * root level.
5751 */
5752 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
5753 int width = mRight - mLeft;
5754 int height = mBottom - mTop;
5755 if (width > 0 && height > 0) {
5756 r.set(0, 0, width, height);
5757 if (globalOffset != null) {
5758 globalOffset.set(-mScrollX, -mScrollY);
5759 }
5760 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
5761 }
5762 return false;
5763 }
5764
5765 public final boolean getGlobalVisibleRect(Rect r) {
5766 return getGlobalVisibleRect(r, null);
5767 }
5768
5769 public final boolean getLocalVisibleRect(Rect r) {
5770 Point offset = new Point();
5771 if (getGlobalVisibleRect(r, offset)) {
5772 r.offset(-offset.x, -offset.y); // make r local
5773 return true;
5774 }
5775 return false;
5776 }
5777
5778 /**
5779 * Offset this view's vertical location by the specified number of pixels.
5780 *
5781 * @param offset the number of pixels to offset the view by
5782 */
5783 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005784 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005785 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005786 final ViewParent p = mParent;
5787 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005788 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005789 int minTop;
5790 int maxBottom;
5791 int yLoc;
5792 if (offset < 0) {
5793 minTop = mTop + offset;
5794 maxBottom = mBottom;
5795 yLoc = offset;
5796 } else {
5797 minTop = mTop;
5798 maxBottom = mBottom + offset;
5799 yLoc = 0;
5800 }
5801 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
5802 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005803 }
5804 } else {
5805 invalidate();
5806 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005807
Chet Haasec3aa3612010-06-17 08:50:37 -07005808 mTop += offset;
5809 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005810
Chet Haasec3aa3612010-06-17 08:50:37 -07005811 if (!mMatrixIsIdentity) {
5812 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5813 invalidate();
5814 }
5815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 }
5817
5818 /**
5819 * Offset this view's horizontal location by the specified amount of pixels.
5820 *
5821 * @param offset the numer of pixels to offset the view by
5822 */
5823 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005824 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005825 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005826 final ViewParent p = mParent;
5827 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005828 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005829 int minLeft;
5830 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005831 if (offset < 0) {
5832 minLeft = mLeft + offset;
5833 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005834 } else {
5835 minLeft = mLeft;
5836 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005837 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005838 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07005839 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005840 }
5841 } else {
5842 invalidate();
5843 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005844
Chet Haasec3aa3612010-06-17 08:50:37 -07005845 mLeft += offset;
5846 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005847
Chet Haasec3aa3612010-06-17 08:50:37 -07005848 if (!mMatrixIsIdentity) {
5849 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5850 invalidate();
5851 }
5852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 }
5854
5855 /**
5856 * Get the LayoutParams associated with this view. All views should have
5857 * layout parameters. These supply parameters to the <i>parent</i> of this
5858 * view specifying how it should be arranged. There are many subclasses of
5859 * ViewGroup.LayoutParams, and these correspond to the different subclasses
5860 * of ViewGroup that are responsible for arranging their children.
5861 * @return The LayoutParams associated with this view
5862 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07005863 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 public ViewGroup.LayoutParams getLayoutParams() {
5865 return mLayoutParams;
5866 }
5867
5868 /**
5869 * Set the layout parameters associated with this view. These supply
5870 * parameters to the <i>parent</i> of this view specifying how it should be
5871 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
5872 * correspond to the different subclasses of ViewGroup that are responsible
5873 * for arranging their children.
5874 *
5875 * @param params the layout parameters for this view
5876 */
5877 public void setLayoutParams(ViewGroup.LayoutParams params) {
5878 if (params == null) {
5879 throw new NullPointerException("params == null");
5880 }
5881 mLayoutParams = params;
5882 requestLayout();
5883 }
5884
5885 /**
5886 * Set the scrolled position of your view. This will cause a call to
5887 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5888 * invalidated.
5889 * @param x the x position to scroll to
5890 * @param y the y position to scroll to
5891 */
5892 public void scrollTo(int x, int y) {
5893 if (mScrollX != x || mScrollY != y) {
5894 int oldX = mScrollX;
5895 int oldY = mScrollY;
5896 mScrollX = x;
5897 mScrollY = y;
5898 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07005899 if (!awakenScrollBars()) {
5900 invalidate();
5901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 }
5903 }
5904
5905 /**
5906 * Move the scrolled position of your view. This will cause a call to
5907 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5908 * invalidated.
5909 * @param x the amount of pixels to scroll by horizontally
5910 * @param y the amount of pixels to scroll by vertically
5911 */
5912 public void scrollBy(int x, int y) {
5913 scrollTo(mScrollX + x, mScrollY + y);
5914 }
5915
5916 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07005917 * <p>Trigger the scrollbars to draw. When invoked this method starts an
5918 * animation to fade the scrollbars out after a default delay. If a subclass
5919 * provides animated scrolling, the start delay should equal the duration
5920 * of the scrolling animation.</p>
5921 *
5922 * <p>The animation starts only if at least one of the scrollbars is
5923 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
5924 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5925 * this method returns true, and false otherwise. If the animation is
5926 * started, this method calls {@link #invalidate()}; in that case the
5927 * caller should not call {@link #invalidate()}.</p>
5928 *
5929 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07005930 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07005931 *
5932 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
5933 * and {@link #scrollTo(int, int)}.</p>
5934 *
5935 * @return true if the animation is played, false otherwise
5936 *
5937 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07005938 * @see #scrollBy(int, int)
5939 * @see #scrollTo(int, int)
5940 * @see #isHorizontalScrollBarEnabled()
5941 * @see #isVerticalScrollBarEnabled()
5942 * @see #setHorizontalScrollBarEnabled(boolean)
5943 * @see #setVerticalScrollBarEnabled(boolean)
5944 */
5945 protected boolean awakenScrollBars() {
5946 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07005947 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07005948 }
5949
5950 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07005951 * Trigger the scrollbars to draw.
5952 * This method differs from awakenScrollBars() only in its default duration.
5953 * initialAwakenScrollBars() will show the scroll bars for longer than
5954 * usual to give the user more of a chance to notice them.
5955 *
5956 * @return true if the animation is played, false otherwise.
5957 */
5958 private boolean initialAwakenScrollBars() {
5959 return mScrollCache != null &&
5960 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
5961 }
5962
5963 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07005964 * <p>
5965 * Trigger the scrollbars to draw. When invoked this method starts an
5966 * animation to fade the scrollbars out after a fixed delay. If a subclass
5967 * provides animated scrolling, the start delay should equal the duration of
5968 * the scrolling animation.
5969 * </p>
5970 *
5971 * <p>
5972 * The animation starts only if at least one of the scrollbars is enabled,
5973 * as specified by {@link #isHorizontalScrollBarEnabled()} and
5974 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5975 * this method returns true, and false otherwise. If the animation is
5976 * started, this method calls {@link #invalidate()}; in that case the caller
5977 * should not call {@link #invalidate()}.
5978 * </p>
5979 *
5980 * <p>
5981 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07005982 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07005983 * </p>
5984 *
5985 * @param startDelay the delay, in milliseconds, after which the animation
5986 * should start; when the delay is 0, the animation starts
5987 * immediately
5988 * @return true if the animation is played, false otherwise
5989 *
Mike Cleronf116bf82009-09-27 19:14:12 -07005990 * @see #scrollBy(int, int)
5991 * @see #scrollTo(int, int)
5992 * @see #isHorizontalScrollBarEnabled()
5993 * @see #isVerticalScrollBarEnabled()
5994 * @see #setHorizontalScrollBarEnabled(boolean)
5995 * @see #setVerticalScrollBarEnabled(boolean)
5996 */
5997 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07005998 return awakenScrollBars(startDelay, true);
5999 }
6000
6001 /**
6002 * <p>
6003 * Trigger the scrollbars to draw. When invoked this method starts an
6004 * animation to fade the scrollbars out after a fixed delay. If a subclass
6005 * provides animated scrolling, the start delay should equal the duration of
6006 * the scrolling animation.
6007 * </p>
6008 *
6009 * <p>
6010 * The animation starts only if at least one of the scrollbars is enabled,
6011 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6012 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6013 * this method returns true, and false otherwise. If the animation is
6014 * started, this method calls {@link #invalidate()} if the invalidate parameter
6015 * is set to true; in that case the caller
6016 * should not call {@link #invalidate()}.
6017 * </p>
6018 *
6019 * <p>
6020 * This method should be invoked everytime a subclass directly updates the
6021 * scroll parameters.
6022 * </p>
6023 *
6024 * @param startDelay the delay, in milliseconds, after which the animation
6025 * should start; when the delay is 0, the animation starts
6026 * immediately
6027 *
6028 * @param invalidate Wheter this method should call invalidate
6029 *
6030 * @return true if the animation is played, false otherwise
6031 *
6032 * @see #scrollBy(int, int)
6033 * @see #scrollTo(int, int)
6034 * @see #isHorizontalScrollBarEnabled()
6035 * @see #isVerticalScrollBarEnabled()
6036 * @see #setHorizontalScrollBarEnabled(boolean)
6037 * @see #setVerticalScrollBarEnabled(boolean)
6038 */
6039 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006040 final ScrollabilityCache scrollCache = mScrollCache;
6041
6042 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6043 return false;
6044 }
6045
6046 if (scrollCache.scrollBar == null) {
6047 scrollCache.scrollBar = new ScrollBarDrawable();
6048 }
6049
6050 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6051
Mike Cleron290947b2009-09-29 18:34:32 -07006052 if (invalidate) {
6053 // Invalidate to show the scrollbars
6054 invalidate();
6055 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006056
6057 if (scrollCache.state == ScrollabilityCache.OFF) {
6058 // FIXME: this is copied from WindowManagerService.
6059 // We should get this value from the system when it
6060 // is possible to do so.
6061 final int KEY_REPEAT_FIRST_DELAY = 750;
6062 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6063 }
6064
6065 // Tell mScrollCache when we should start fading. This may
6066 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006067 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006068 scrollCache.fadeStartTime = fadeStartTime;
6069 scrollCache.state = ScrollabilityCache.ON;
6070
6071 // Schedule our fader to run, unscheduling any old ones first
6072 if (mAttachInfo != null) {
6073 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6074 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6075 }
6076
6077 return true;
6078 }
6079
6080 return false;
6081 }
6082
6083 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006084 * Mark the the area defined by dirty as needing to be drawn. If the view is
6085 * visible, {@link #onDraw} will be called at some point in the future.
6086 * This must be called from a UI thread. To call from a non-UI thread, call
6087 * {@link #postInvalidate()}.
6088 *
6089 * WARNING: This method is destructive to dirty.
6090 * @param dirty the rectangle representing the bounds of the dirty region
6091 */
6092 public void invalidate(Rect dirty) {
6093 if (ViewDebug.TRACE_HIERARCHY) {
6094 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6095 }
6096
6097 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6098 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6099 final ViewParent p = mParent;
6100 final AttachInfo ai = mAttachInfo;
6101 if (p != null && ai != null) {
6102 final int scrollX = mScrollX;
6103 final int scrollY = mScrollY;
6104 final Rect r = ai.mTmpInvalRect;
6105 r.set(dirty.left - scrollX, dirty.top - scrollY,
6106 dirty.right - scrollX, dirty.bottom - scrollY);
6107 mParent.invalidateChild(this, r);
6108 }
6109 }
6110 }
6111
6112 /**
6113 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6114 * The coordinates of the dirty rect are relative to the view.
6115 * If the view is visible, {@link #onDraw} will be called at some point
6116 * in the future. This must be called from a UI thread. To call
6117 * from a non-UI thread, call {@link #postInvalidate()}.
6118 * @param l the left position of the dirty region
6119 * @param t the top position of the dirty region
6120 * @param r the right position of the dirty region
6121 * @param b the bottom position of the dirty region
6122 */
6123 public void invalidate(int l, int t, int r, int b) {
6124 if (ViewDebug.TRACE_HIERARCHY) {
6125 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6126 }
6127
6128 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6129 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6130 final ViewParent p = mParent;
6131 final AttachInfo ai = mAttachInfo;
6132 if (p != null && ai != null && l < r && t < b) {
6133 final int scrollX = mScrollX;
6134 final int scrollY = mScrollY;
6135 final Rect tmpr = ai.mTmpInvalRect;
6136 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6137 p.invalidateChild(this, tmpr);
6138 }
6139 }
6140 }
6141
6142 /**
6143 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6144 * be called at some point in the future. This must be called from a
6145 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6146 */
6147 public void invalidate() {
6148 if (ViewDebug.TRACE_HIERARCHY) {
6149 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6150 }
6151
6152 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6153 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
6154 final ViewParent p = mParent;
6155 final AttachInfo ai = mAttachInfo;
6156 if (p != null && ai != null) {
6157 final Rect r = ai.mTmpInvalRect;
6158 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6159 // Don't call invalidate -- we don't want to internally scroll
6160 // our own bounds
6161 p.invalidateChild(this, r);
6162 }
6163 }
6164 }
6165
6166 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006167 * Indicates whether this View is opaque. An opaque View guarantees that it will
6168 * draw all the pixels overlapping its bounds using a fully opaque color.
6169 *
6170 * Subclasses of View should override this method whenever possible to indicate
6171 * whether an instance is opaque. Opaque Views are treated in a special way by
6172 * the View hierarchy, possibly allowing it to perform optimizations during
6173 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006174 *
Romain Guy24443ea2009-05-11 11:56:30 -07006175 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006176 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006177 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006178 public boolean isOpaque() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006179 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
6180 }
6181
6182 private void computeOpaqueFlags() {
6183 // Opaque if:
6184 // - Has a background
6185 // - Background is opaque
6186 // - Doesn't have scrollbars or scrollbars are inside overlay
6187
6188 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6189 mPrivateFlags |= OPAQUE_BACKGROUND;
6190 } else {
6191 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6192 }
6193
6194 final int flags = mViewFlags;
6195 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6196 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6197 mPrivateFlags |= OPAQUE_SCROLLBARS;
6198 } else {
6199 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6200 }
6201 }
6202
6203 /**
6204 * @hide
6205 */
6206 protected boolean hasOpaqueScrollbars() {
6207 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006208 }
6209
6210 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 * @return A handler associated with the thread running the View. This
6212 * handler can be used to pump events in the UI events queue.
6213 */
6214 public Handler getHandler() {
6215 if (mAttachInfo != null) {
6216 return mAttachInfo.mHandler;
6217 }
6218 return null;
6219 }
6220
6221 /**
6222 * Causes the Runnable to be added to the message queue.
6223 * The runnable will be run on the user interface thread.
6224 *
6225 * @param action The Runnable that will be executed.
6226 *
6227 * @return Returns true if the Runnable was successfully placed in to the
6228 * message queue. Returns false on failure, usually because the
6229 * looper processing the message queue is exiting.
6230 */
6231 public boolean post(Runnable action) {
6232 Handler handler;
6233 if (mAttachInfo != null) {
6234 handler = mAttachInfo.mHandler;
6235 } else {
6236 // Assume that post will succeed later
6237 ViewRoot.getRunQueue().post(action);
6238 return true;
6239 }
6240
6241 return handler.post(action);
6242 }
6243
6244 /**
6245 * Causes the Runnable to be added to the message queue, to be run
6246 * after the specified amount of time elapses.
6247 * The runnable will be run on the user interface thread.
6248 *
6249 * @param action The Runnable that will be executed.
6250 * @param delayMillis The delay (in milliseconds) until the Runnable
6251 * will be executed.
6252 *
6253 * @return true if the Runnable was successfully placed in to the
6254 * message queue. Returns false on failure, usually because the
6255 * looper processing the message queue is exiting. Note that a
6256 * result of true does not mean the Runnable will be processed --
6257 * if the looper is quit before the delivery time of the message
6258 * occurs then the message will be dropped.
6259 */
6260 public boolean postDelayed(Runnable action, long delayMillis) {
6261 Handler handler;
6262 if (mAttachInfo != null) {
6263 handler = mAttachInfo.mHandler;
6264 } else {
6265 // Assume that post will succeed later
6266 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6267 return true;
6268 }
6269
6270 return handler.postDelayed(action, delayMillis);
6271 }
6272
6273 /**
6274 * Removes the specified Runnable from the message queue.
6275 *
6276 * @param action The Runnable to remove from the message handling queue
6277 *
6278 * @return true if this view could ask the Handler to remove the Runnable,
6279 * false otherwise. When the returned value is true, the Runnable
6280 * may or may not have been actually removed from the message queue
6281 * (for instance, if the Runnable was not in the queue already.)
6282 */
6283 public boolean removeCallbacks(Runnable action) {
6284 Handler handler;
6285 if (mAttachInfo != null) {
6286 handler = mAttachInfo.mHandler;
6287 } else {
6288 // Assume that post will succeed later
6289 ViewRoot.getRunQueue().removeCallbacks(action);
6290 return true;
6291 }
6292
6293 handler.removeCallbacks(action);
6294 return true;
6295 }
6296
6297 /**
6298 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6299 * Use this to invalidate the View from a non-UI thread.
6300 *
6301 * @see #invalidate()
6302 */
6303 public void postInvalidate() {
6304 postInvalidateDelayed(0);
6305 }
6306
6307 /**
6308 * Cause an invalidate of the specified area to happen on a subsequent cycle
6309 * through the event loop. Use this to invalidate the View from a non-UI thread.
6310 *
6311 * @param left The left coordinate of the rectangle to invalidate.
6312 * @param top The top coordinate of the rectangle to invalidate.
6313 * @param right The right coordinate of the rectangle to invalidate.
6314 * @param bottom The bottom coordinate of the rectangle to invalidate.
6315 *
6316 * @see #invalidate(int, int, int, int)
6317 * @see #invalidate(Rect)
6318 */
6319 public void postInvalidate(int left, int top, int right, int bottom) {
6320 postInvalidateDelayed(0, left, top, right, bottom);
6321 }
6322
6323 /**
6324 * Cause an invalidate to happen on a subsequent cycle through the event
6325 * loop. Waits for the specified amount of time.
6326 *
6327 * @param delayMilliseconds the duration in milliseconds to delay the
6328 * invalidation by
6329 */
6330 public void postInvalidateDelayed(long delayMilliseconds) {
6331 // We try only with the AttachInfo because there's no point in invalidating
6332 // if we are not attached to our window
6333 if (mAttachInfo != null) {
6334 Message msg = Message.obtain();
6335 msg.what = AttachInfo.INVALIDATE_MSG;
6336 msg.obj = this;
6337 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6338 }
6339 }
6340
6341 /**
6342 * Cause an invalidate of the specified area to happen on a subsequent cycle
6343 * through the event loop. Waits for the specified amount of time.
6344 *
6345 * @param delayMilliseconds the duration in milliseconds to delay the
6346 * invalidation by
6347 * @param left The left coordinate of the rectangle to invalidate.
6348 * @param top The top coordinate of the rectangle to invalidate.
6349 * @param right The right coordinate of the rectangle to invalidate.
6350 * @param bottom The bottom coordinate of the rectangle to invalidate.
6351 */
6352 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6353 int right, int bottom) {
6354
6355 // We try only with the AttachInfo because there's no point in invalidating
6356 // if we are not attached to our window
6357 if (mAttachInfo != null) {
6358 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6359 info.target = this;
6360 info.left = left;
6361 info.top = top;
6362 info.right = right;
6363 info.bottom = bottom;
6364
6365 final Message msg = Message.obtain();
6366 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6367 msg.obj = info;
6368 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6369 }
6370 }
6371
6372 /**
6373 * Called by a parent to request that a child update its values for mScrollX
6374 * and mScrollY if necessary. This will typically be done if the child is
6375 * animating a scroll using a {@link android.widget.Scroller Scroller}
6376 * object.
6377 */
6378 public void computeScroll() {
6379 }
6380
6381 /**
6382 * <p>Indicate whether the horizontal edges are faded when the view is
6383 * scrolled horizontally.</p>
6384 *
6385 * @return true if the horizontal edges should are faded on scroll, false
6386 * otherwise
6387 *
6388 * @see #setHorizontalFadingEdgeEnabled(boolean)
6389 * @attr ref android.R.styleable#View_fadingEdge
6390 */
6391 public boolean isHorizontalFadingEdgeEnabled() {
6392 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6393 }
6394
6395 /**
6396 * <p>Define whether the horizontal edges should be faded when this view
6397 * is scrolled horizontally.</p>
6398 *
6399 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6400 * be faded when the view is scrolled
6401 * horizontally
6402 *
6403 * @see #isHorizontalFadingEdgeEnabled()
6404 * @attr ref android.R.styleable#View_fadingEdge
6405 */
6406 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6407 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6408 if (horizontalFadingEdgeEnabled) {
6409 initScrollCache();
6410 }
6411
6412 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6413 }
6414 }
6415
6416 /**
6417 * <p>Indicate whether the vertical edges are faded when the view is
6418 * scrolled horizontally.</p>
6419 *
6420 * @return true if the vertical edges should are faded on scroll, false
6421 * otherwise
6422 *
6423 * @see #setVerticalFadingEdgeEnabled(boolean)
6424 * @attr ref android.R.styleable#View_fadingEdge
6425 */
6426 public boolean isVerticalFadingEdgeEnabled() {
6427 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6428 }
6429
6430 /**
6431 * <p>Define whether the vertical edges should be faded when this view
6432 * is scrolled vertically.</p>
6433 *
6434 * @param verticalFadingEdgeEnabled true if the vertical edges should
6435 * be faded when the view is scrolled
6436 * vertically
6437 *
6438 * @see #isVerticalFadingEdgeEnabled()
6439 * @attr ref android.R.styleable#View_fadingEdge
6440 */
6441 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6442 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6443 if (verticalFadingEdgeEnabled) {
6444 initScrollCache();
6445 }
6446
6447 mViewFlags ^= FADING_EDGE_VERTICAL;
6448 }
6449 }
6450
6451 /**
6452 * Returns the strength, or intensity, of the top faded edge. The strength is
6453 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6454 * returns 0.0 or 1.0 but no value in between.
6455 *
6456 * Subclasses should override this method to provide a smoother fade transition
6457 * when scrolling occurs.
6458 *
6459 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6460 */
6461 protected float getTopFadingEdgeStrength() {
6462 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6463 }
6464
6465 /**
6466 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6467 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6468 * returns 0.0 or 1.0 but no value in between.
6469 *
6470 * Subclasses should override this method to provide a smoother fade transition
6471 * when scrolling occurs.
6472 *
6473 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6474 */
6475 protected float getBottomFadingEdgeStrength() {
6476 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6477 computeVerticalScrollRange() ? 1.0f : 0.0f;
6478 }
6479
6480 /**
6481 * Returns the strength, or intensity, of the left faded edge. The strength is
6482 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6483 * returns 0.0 or 1.0 but no value in between.
6484 *
6485 * Subclasses should override this method to provide a smoother fade transition
6486 * when scrolling occurs.
6487 *
6488 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6489 */
6490 protected float getLeftFadingEdgeStrength() {
6491 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6492 }
6493
6494 /**
6495 * Returns the strength, or intensity, of the right faded edge. The strength is
6496 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6497 * returns 0.0 or 1.0 but no value in between.
6498 *
6499 * Subclasses should override this method to provide a smoother fade transition
6500 * when scrolling occurs.
6501 *
6502 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6503 */
6504 protected float getRightFadingEdgeStrength() {
6505 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6506 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6507 }
6508
6509 /**
6510 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6511 * scrollbar is not drawn by default.</p>
6512 *
6513 * @return true if the horizontal scrollbar should be painted, false
6514 * otherwise
6515 *
6516 * @see #setHorizontalScrollBarEnabled(boolean)
6517 */
6518 public boolean isHorizontalScrollBarEnabled() {
6519 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6520 }
6521
6522 /**
6523 * <p>Define whether the horizontal scrollbar should be drawn or not. The
6524 * scrollbar is not drawn by default.</p>
6525 *
6526 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
6527 * be painted
6528 *
6529 * @see #isHorizontalScrollBarEnabled()
6530 */
6531 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
6532 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
6533 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006534 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 recomputePadding();
6536 }
6537 }
6538
6539 /**
6540 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
6541 * scrollbar is not drawn by default.</p>
6542 *
6543 * @return true if the vertical scrollbar should be painted, false
6544 * otherwise
6545 *
6546 * @see #setVerticalScrollBarEnabled(boolean)
6547 */
6548 public boolean isVerticalScrollBarEnabled() {
6549 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
6550 }
6551
6552 /**
6553 * <p>Define whether the vertical scrollbar should be drawn or not. The
6554 * scrollbar is not drawn by default.</p>
6555 *
6556 * @param verticalScrollBarEnabled true if the vertical scrollbar should
6557 * be painted
6558 *
6559 * @see #isVerticalScrollBarEnabled()
6560 */
6561 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
6562 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
6563 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006564 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006565 recomputePadding();
6566 }
6567 }
6568
6569 private void recomputePadding() {
6570 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
6571 }
Mike Cleronfe81d382009-09-28 14:22:16 -07006572
6573 /**
6574 * Define whether scrollbars will fade when the view is not scrolling.
6575 *
6576 * @param fadeScrollbars wheter to enable fading
6577 *
6578 */
6579 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
6580 initScrollCache();
6581 final ScrollabilityCache scrollabilityCache = mScrollCache;
6582 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07006583 if (fadeScrollbars) {
6584 scrollabilityCache.state = ScrollabilityCache.OFF;
6585 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07006586 scrollabilityCache.state = ScrollabilityCache.ON;
6587 }
6588 }
6589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07006591 *
6592 * Returns true if scrollbars will fade when this view is not scrolling
6593 *
6594 * @return true if scrollbar fading is enabled
6595 */
6596 public boolean isScrollbarFadingEnabled() {
6597 return mScrollCache != null && mScrollCache.fadeScrollBars;
6598 }
6599
6600 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
6602 * inset. When inset, they add to the padding of the view. And the scrollbars
6603 * can be drawn inside the padding area or on the edge of the view. For example,
6604 * if a view has a background drawable and you want to draw the scrollbars
6605 * inside the padding specified by the drawable, you can use
6606 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
6607 * appear at the edge of the view, ignoring the padding, then you can use
6608 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
6609 * @param style the style of the scrollbars. Should be one of
6610 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
6611 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
6612 * @see #SCROLLBARS_INSIDE_OVERLAY
6613 * @see #SCROLLBARS_INSIDE_INSET
6614 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6615 * @see #SCROLLBARS_OUTSIDE_INSET
6616 */
6617 public void setScrollBarStyle(int style) {
6618 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
6619 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07006620 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 recomputePadding();
6622 }
6623 }
6624
6625 /**
6626 * <p>Returns the current scrollbar style.</p>
6627 * @return the current scrollbar style
6628 * @see #SCROLLBARS_INSIDE_OVERLAY
6629 * @see #SCROLLBARS_INSIDE_INSET
6630 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6631 * @see #SCROLLBARS_OUTSIDE_INSET
6632 */
6633 public int getScrollBarStyle() {
6634 return mViewFlags & SCROLLBARS_STYLE_MASK;
6635 }
6636
6637 /**
6638 * <p>Compute the horizontal range that the horizontal scrollbar
6639 * represents.</p>
6640 *
6641 * <p>The range is expressed in arbitrary units that must be the same as the
6642 * units used by {@link #computeHorizontalScrollExtent()} and
6643 * {@link #computeHorizontalScrollOffset()}.</p>
6644 *
6645 * <p>The default range is the drawing width of this view.</p>
6646 *
6647 * @return the total horizontal range represented by the horizontal
6648 * scrollbar
6649 *
6650 * @see #computeHorizontalScrollExtent()
6651 * @see #computeHorizontalScrollOffset()
6652 * @see android.widget.ScrollBarDrawable
6653 */
6654 protected int computeHorizontalScrollRange() {
6655 return getWidth();
6656 }
6657
6658 /**
6659 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
6660 * within the horizontal range. This value is used to compute the position
6661 * of the thumb within the scrollbar's track.</p>
6662 *
6663 * <p>The range is expressed in arbitrary units that must be the same as the
6664 * units used by {@link #computeHorizontalScrollRange()} and
6665 * {@link #computeHorizontalScrollExtent()}.</p>
6666 *
6667 * <p>The default offset is the scroll offset of this view.</p>
6668 *
6669 * @return the horizontal offset of the scrollbar's thumb
6670 *
6671 * @see #computeHorizontalScrollRange()
6672 * @see #computeHorizontalScrollExtent()
6673 * @see android.widget.ScrollBarDrawable
6674 */
6675 protected int computeHorizontalScrollOffset() {
6676 return mScrollX;
6677 }
6678
6679 /**
6680 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
6681 * within the horizontal range. This value is used to compute the length
6682 * of the thumb within the scrollbar's track.</p>
6683 *
6684 * <p>The range is expressed in arbitrary units that must be the same as the
6685 * units used by {@link #computeHorizontalScrollRange()} and
6686 * {@link #computeHorizontalScrollOffset()}.</p>
6687 *
6688 * <p>The default extent is the drawing width of this view.</p>
6689 *
6690 * @return the horizontal extent of the scrollbar's thumb
6691 *
6692 * @see #computeHorizontalScrollRange()
6693 * @see #computeHorizontalScrollOffset()
6694 * @see android.widget.ScrollBarDrawable
6695 */
6696 protected int computeHorizontalScrollExtent() {
6697 return getWidth();
6698 }
6699
6700 /**
6701 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
6702 *
6703 * <p>The range is expressed in arbitrary units that must be the same as the
6704 * units used by {@link #computeVerticalScrollExtent()} and
6705 * {@link #computeVerticalScrollOffset()}.</p>
6706 *
6707 * @return the total vertical range represented by the vertical scrollbar
6708 *
6709 * <p>The default range is the drawing height of this view.</p>
6710 *
6711 * @see #computeVerticalScrollExtent()
6712 * @see #computeVerticalScrollOffset()
6713 * @see android.widget.ScrollBarDrawable
6714 */
6715 protected int computeVerticalScrollRange() {
6716 return getHeight();
6717 }
6718
6719 /**
6720 * <p>Compute the vertical offset of the vertical scrollbar's thumb
6721 * within the horizontal range. This value is used to compute the position
6722 * of the thumb within the scrollbar's track.</p>
6723 *
6724 * <p>The range is expressed in arbitrary units that must be the same as the
6725 * units used by {@link #computeVerticalScrollRange()} and
6726 * {@link #computeVerticalScrollExtent()}.</p>
6727 *
6728 * <p>The default offset is the scroll offset of this view.</p>
6729 *
6730 * @return the vertical offset of the scrollbar's thumb
6731 *
6732 * @see #computeVerticalScrollRange()
6733 * @see #computeVerticalScrollExtent()
6734 * @see android.widget.ScrollBarDrawable
6735 */
6736 protected int computeVerticalScrollOffset() {
6737 return mScrollY;
6738 }
6739
6740 /**
6741 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
6742 * within the vertical range. This value is used to compute the length
6743 * of the thumb within the scrollbar's track.</p>
6744 *
6745 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08006746 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 * {@link #computeVerticalScrollOffset()}.</p>
6748 *
6749 * <p>The default extent is the drawing height of this view.</p>
6750 *
6751 * @return the vertical extent of the scrollbar's thumb
6752 *
6753 * @see #computeVerticalScrollRange()
6754 * @see #computeVerticalScrollOffset()
6755 * @see android.widget.ScrollBarDrawable
6756 */
6757 protected int computeVerticalScrollExtent() {
6758 return getHeight();
6759 }
6760
6761 /**
6762 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
6763 * scrollbars are painted only if they have been awakened first.</p>
6764 *
6765 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07006766 *
6767 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08006769 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 // scrollbars are drawn only when the animation is running
6771 final ScrollabilityCache cache = mScrollCache;
6772 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006773
6774 int state = cache.state;
6775
6776 if (state == ScrollabilityCache.OFF) {
6777 return;
6778 }
6779
6780 boolean invalidate = false;
6781
6782 if (state == ScrollabilityCache.FADING) {
6783 // We're fading -- get our fade interpolation
6784 if (cache.interpolatorValues == null) {
6785 cache.interpolatorValues = new float[1];
6786 }
6787
6788 float[] values = cache.interpolatorValues;
6789
6790 // Stops the animation if we're done
6791 if (cache.scrollBarInterpolator.timeToValues(values) ==
6792 Interpolator.Result.FREEZE_END) {
6793 cache.state = ScrollabilityCache.OFF;
6794 } else {
6795 cache.scrollBar.setAlpha(Math.round(values[0]));
6796 }
6797
6798 // This will make the scroll bars inval themselves after
6799 // drawing. We only want this when we're fading so that
6800 // we prevent excessive redraws
6801 invalidate = true;
6802 } else {
6803 // We're just on -- but we may have been fading before so
6804 // reset alpha
6805 cache.scrollBar.setAlpha(255);
6806 }
6807
6808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 final int viewFlags = mViewFlags;
6810
6811 final boolean drawHorizontalScrollBar =
6812 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6813 final boolean drawVerticalScrollBar =
6814 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
6815 && !isVerticalScrollBarHidden();
6816
6817 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
6818 final int width = mRight - mLeft;
6819 final int height = mBottom - mTop;
6820
6821 final ScrollBarDrawable scrollBar = cache.scrollBar;
6822 int size = scrollBar.getSize(false);
6823 if (size <= 0) {
6824 size = cache.scrollBarSize;
6825 }
6826
Mike Reede8853fc2009-09-04 14:01:48 -04006827 final int scrollX = mScrollX;
6828 final int scrollY = mScrollY;
6829 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
6830
Mike Cleronf116bf82009-09-27 19:14:12 -07006831 int left, top, right, bottom;
6832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006833 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006834 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04006835 computeHorizontalScrollOffset(),
6836 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04006837 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07006838 getVerticalScrollbarWidth() : 0;
6839 top = scrollY + height - size - (mUserPaddingBottom & inside);
6840 left = scrollX + (mPaddingLeft & inside);
6841 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
6842 bottom = top + size;
6843 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
6844 if (invalidate) {
6845 invalidate(left, top, right, bottom);
6846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 }
6848
6849 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04006850 scrollBar.setParameters(computeVerticalScrollRange(),
6851 computeVerticalScrollOffset(),
6852 computeVerticalScrollExtent(), true);
6853 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07006854 left = scrollX + width - size - (mUserPaddingRight & inside);
6855 top = scrollY + (mPaddingTop & inside);
6856 right = left + size;
6857 bottom = scrollY + height - (mUserPaddingBottom & inside);
6858 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
6859 if (invalidate) {
6860 invalidate(left, top, right, bottom);
6861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 }
6863 }
6864 }
6865 }
Romain Guy8506ab42009-06-11 17:35:47 -07006866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006867 /**
Romain Guy8506ab42009-06-11 17:35:47 -07006868 * 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 -08006869 * FastScroller is visible.
6870 * @return whether to temporarily hide the vertical scrollbar
6871 * @hide
6872 */
6873 protected boolean isVerticalScrollBarHidden() {
6874 return false;
6875 }
6876
6877 /**
6878 * <p>Draw the horizontal scrollbar if
6879 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
6880 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006881 * @param canvas the canvas on which to draw the scrollbar
6882 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006883 *
6884 * @see #isHorizontalScrollBarEnabled()
6885 * @see #computeHorizontalScrollRange()
6886 * @see #computeHorizontalScrollExtent()
6887 * @see #computeHorizontalScrollOffset()
6888 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07006889 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006890 */
Romain Guy8fb95422010-08-17 18:38:51 -07006891 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
6892 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006893 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006894 scrollBar.draw(canvas);
6895 }
Mike Reede8853fc2009-09-04 14:01:48 -04006896
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006897 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006898 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
6899 * returns true.</p>
6900 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006901 * @param canvas the canvas on which to draw the scrollbar
6902 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 *
6904 * @see #isVerticalScrollBarEnabled()
6905 * @see #computeVerticalScrollRange()
6906 * @see #computeVerticalScrollExtent()
6907 * @see #computeVerticalScrollOffset()
6908 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04006909 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006910 */
Romain Guy8fb95422010-08-17 18:38:51 -07006911 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
6912 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04006913 scrollBar.setBounds(l, t, r, b);
6914 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006915 }
6916
6917 /**
6918 * Implement this to do your drawing.
6919 *
6920 * @param canvas the canvas on which the background will be drawn
6921 */
6922 protected void onDraw(Canvas canvas) {
6923 }
6924
6925 /*
6926 * Caller is responsible for calling requestLayout if necessary.
6927 * (This allows addViewInLayout to not request a new layout.)
6928 */
6929 void assignParent(ViewParent parent) {
6930 if (mParent == null) {
6931 mParent = parent;
6932 } else if (parent == null) {
6933 mParent = null;
6934 } else {
6935 throw new RuntimeException("view " + this + " being added, but"
6936 + " it already has a parent");
6937 }
6938 }
6939
6940 /**
6941 * This is called when the view is attached to a window. At this point it
6942 * has a Surface and will start drawing. Note that this function is
6943 * guaranteed to be called before {@link #onDraw}, however it may be called
6944 * any time before the first onDraw -- including before or after
6945 * {@link #onMeasure}.
6946 *
6947 * @see #onDetachedFromWindow()
6948 */
6949 protected void onAttachedToWindow() {
6950 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
6951 mParent.requestTransparentRegion(this);
6952 }
Adam Powell8568c3a2010-04-19 14:26:11 -07006953 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
6954 initialAwakenScrollBars();
6955 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
6956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006957 }
6958
6959 /**
6960 * This is called when the view is detached from a window. At this point it
6961 * no longer has a surface for drawing.
6962 *
6963 * @see #onAttachedToWindow()
6964 */
6965 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08006966 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08006967 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05006968 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 destroyDrawingCache();
6970 }
6971
6972 /**
6973 * @return The number of times this view has been attached to a window
6974 */
6975 protected int getWindowAttachCount() {
6976 return mWindowAttachCount;
6977 }
6978
6979 /**
6980 * Retrieve a unique token identifying the window this view is attached to.
6981 * @return Return the window's token for use in
6982 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
6983 */
6984 public IBinder getWindowToken() {
6985 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
6986 }
6987
6988 /**
6989 * Retrieve a unique token identifying the top-level "real" window of
6990 * the window that this view is attached to. That is, this is like
6991 * {@link #getWindowToken}, except if the window this view in is a panel
6992 * window (attached to another containing window), then the token of
6993 * the containing window is returned instead.
6994 *
6995 * @return Returns the associated window token, either
6996 * {@link #getWindowToken()} or the containing window's token.
6997 */
6998 public IBinder getApplicationWindowToken() {
6999 AttachInfo ai = mAttachInfo;
7000 if (ai != null) {
7001 IBinder appWindowToken = ai.mPanelParentWindowToken;
7002 if (appWindowToken == null) {
7003 appWindowToken = ai.mWindowToken;
7004 }
7005 return appWindowToken;
7006 }
7007 return null;
7008 }
7009
7010 /**
7011 * Retrieve private session object this view hierarchy is using to
7012 * communicate with the window manager.
7013 * @return the session object to communicate with the window manager
7014 */
7015 /*package*/ IWindowSession getWindowSession() {
7016 return mAttachInfo != null ? mAttachInfo.mSession : null;
7017 }
7018
7019 /**
7020 * @param info the {@link android.view.View.AttachInfo} to associated with
7021 * this view
7022 */
7023 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7024 //System.out.println("Attached! " + this);
7025 mAttachInfo = info;
7026 mWindowAttachCount++;
7027 if (mFloatingTreeObserver != null) {
7028 info.mTreeObserver.merge(mFloatingTreeObserver);
7029 mFloatingTreeObserver = null;
7030 }
7031 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7032 mAttachInfo.mScrollContainers.add(this);
7033 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7034 }
7035 performCollectViewAttributes(visibility);
7036 onAttachedToWindow();
7037 int vis = info.mWindowVisibility;
7038 if (vis != GONE) {
7039 onWindowVisibilityChanged(vis);
7040 }
7041 }
7042
7043 void dispatchDetachedFromWindow() {
7044 //System.out.println("Detached! " + this);
7045 AttachInfo info = mAttachInfo;
7046 if (info != null) {
7047 int vis = info.mWindowVisibility;
7048 if (vis != GONE) {
7049 onWindowVisibilityChanged(GONE);
7050 }
7051 }
7052
7053 onDetachedFromWindow();
7054 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7055 mAttachInfo.mScrollContainers.remove(this);
7056 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7057 }
7058 mAttachInfo = null;
7059 }
7060
7061 /**
7062 * Store this view hierarchy's frozen state into the given container.
7063 *
7064 * @param container The SparseArray in which to save the view's state.
7065 *
7066 * @see #restoreHierarchyState
7067 * @see #dispatchSaveInstanceState
7068 * @see #onSaveInstanceState
7069 */
7070 public void saveHierarchyState(SparseArray<Parcelable> container) {
7071 dispatchSaveInstanceState(container);
7072 }
7073
7074 /**
7075 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7076 * May be overridden to modify how freezing happens to a view's children; for example, some
7077 * views may want to not store state for their children.
7078 *
7079 * @param container The SparseArray in which to save the view's state.
7080 *
7081 * @see #dispatchRestoreInstanceState
7082 * @see #saveHierarchyState
7083 * @see #onSaveInstanceState
7084 */
7085 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7086 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7087 mPrivateFlags &= ~SAVE_STATE_CALLED;
7088 Parcelable state = onSaveInstanceState();
7089 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7090 throw new IllegalStateException(
7091 "Derived class did not call super.onSaveInstanceState()");
7092 }
7093 if (state != null) {
7094 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7095 // + ": " + state);
7096 container.put(mID, state);
7097 }
7098 }
7099 }
7100
7101 /**
7102 * Hook allowing a view to generate a representation of its internal state
7103 * that can later be used to create a new instance with that same state.
7104 * This state should only contain information that is not persistent or can
7105 * not be reconstructed later. For example, you will never store your
7106 * current position on screen because that will be computed again when a
7107 * new instance of the view is placed in its view hierarchy.
7108 * <p>
7109 * Some examples of things you may store here: the current cursor position
7110 * in a text view (but usually not the text itself since that is stored in a
7111 * content provider or other persistent storage), the currently selected
7112 * item in a list view.
7113 *
7114 * @return Returns a Parcelable object containing the view's current dynamic
7115 * state, or null if there is nothing interesting to save. The
7116 * default implementation returns null.
7117 * @see #onRestoreInstanceState
7118 * @see #saveHierarchyState
7119 * @see #dispatchSaveInstanceState
7120 * @see #setSaveEnabled(boolean)
7121 */
7122 protected Parcelable onSaveInstanceState() {
7123 mPrivateFlags |= SAVE_STATE_CALLED;
7124 return BaseSavedState.EMPTY_STATE;
7125 }
7126
7127 /**
7128 * Restore this view hierarchy's frozen state from the given container.
7129 *
7130 * @param container The SparseArray which holds previously frozen states.
7131 *
7132 * @see #saveHierarchyState
7133 * @see #dispatchRestoreInstanceState
7134 * @see #onRestoreInstanceState
7135 */
7136 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7137 dispatchRestoreInstanceState(container);
7138 }
7139
7140 /**
7141 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7142 * children. May be overridden to modify how restoreing happens to a view's children; for
7143 * example, some views may want to not store state for their children.
7144 *
7145 * @param container The SparseArray which holds previously saved state.
7146 *
7147 * @see #dispatchSaveInstanceState
7148 * @see #restoreHierarchyState
7149 * @see #onRestoreInstanceState
7150 */
7151 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7152 if (mID != NO_ID) {
7153 Parcelable state = container.get(mID);
7154 if (state != null) {
7155 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7156 // + ": " + state);
7157 mPrivateFlags &= ~SAVE_STATE_CALLED;
7158 onRestoreInstanceState(state);
7159 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7160 throw new IllegalStateException(
7161 "Derived class did not call super.onRestoreInstanceState()");
7162 }
7163 }
7164 }
7165 }
7166
7167 /**
7168 * Hook allowing a view to re-apply a representation of its internal state that had previously
7169 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7170 * null state.
7171 *
7172 * @param state The frozen state that had previously been returned by
7173 * {@link #onSaveInstanceState}.
7174 *
7175 * @see #onSaveInstanceState
7176 * @see #restoreHierarchyState
7177 * @see #dispatchRestoreInstanceState
7178 */
7179 protected void onRestoreInstanceState(Parcelable state) {
7180 mPrivateFlags |= SAVE_STATE_CALLED;
7181 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007182 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7183 + "received " + state.getClass().toString() + " instead. This usually happens "
7184 + "when two views of different type have the same id in the same hierarchy. "
7185 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7186 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 }
7188 }
7189
7190 /**
7191 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7192 *
7193 * @return the drawing start time in milliseconds
7194 */
7195 public long getDrawingTime() {
7196 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7197 }
7198
7199 /**
7200 * <p>Enables or disables the duplication of the parent's state into this view. When
7201 * duplication is enabled, this view gets its drawable state from its parent rather
7202 * than from its own internal properties.</p>
7203 *
7204 * <p>Note: in the current implementation, setting this property to true after the
7205 * view was added to a ViewGroup might have no effect at all. This property should
7206 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7207 *
7208 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7209 * property is enabled, an exception will be thrown.</p>
7210 *
7211 * @param enabled True to enable duplication of the parent's drawable state, false
7212 * to disable it.
7213 *
7214 * @see #getDrawableState()
7215 * @see #isDuplicateParentStateEnabled()
7216 */
7217 public void setDuplicateParentStateEnabled(boolean enabled) {
7218 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7219 }
7220
7221 /**
7222 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7223 *
7224 * @return True if this view's drawable state is duplicated from the parent,
7225 * false otherwise
7226 *
7227 * @see #getDrawableState()
7228 * @see #setDuplicateParentStateEnabled(boolean)
7229 */
7230 public boolean isDuplicateParentStateEnabled() {
7231 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7232 }
7233
7234 /**
7235 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
7236 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
7237 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
7238 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
7239 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
7240 * null.</p>
7241 *
7242 * @param enabled true to enable the drawing cache, false otherwise
7243 *
7244 * @see #isDrawingCacheEnabled()
7245 * @see #getDrawingCache()
7246 * @see #buildDrawingCache()
7247 */
7248 public void setDrawingCacheEnabled(boolean enabled) {
7249 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
7250 }
7251
7252 /**
7253 * <p>Indicates whether the drawing cache is enabled for this view.</p>
7254 *
7255 * @return true if the drawing cache is enabled
7256 *
7257 * @see #setDrawingCacheEnabled(boolean)
7258 * @see #getDrawingCache()
7259 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07007260 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007261 public boolean isDrawingCacheEnabled() {
7262 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
7263 }
7264
7265 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007266 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
7267 *
7268 * @return A non-scaled bitmap representing this view or null if cache is disabled.
7269 *
7270 * @see #getDrawingCache(boolean)
7271 */
7272 public Bitmap getDrawingCache() {
7273 return getDrawingCache(false);
7274 }
7275
7276 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007277 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
7278 * is null when caching is disabled. If caching is enabled and the cache is not ready,
7279 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
7280 * draw from the cache when the cache is enabled. To benefit from the cache, you must
7281 * request the drawing cache by calling this method and draw it on screen if the
7282 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007283 *
7284 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7285 * this method will create a bitmap of the same size as this view. Because this bitmap
7286 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7287 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7288 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7289 * size than the view. This implies that your application must be able to handle this
7290 * size.</p>
7291 *
7292 * @param autoScale Indicates whether the generated bitmap should be scaled based on
7293 * the current density of the screen when the application is in compatibility
7294 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 *
Romain Guyfbd8f692009-06-26 14:51:58 -07007296 * @return A bitmap representing this view or null if cache is disabled.
7297 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007298 * @see #setDrawingCacheEnabled(boolean)
7299 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07007300 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007301 * @see #destroyDrawingCache()
7302 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007303 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007304 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7305 return null;
7306 }
7307 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007308 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 }
Romain Guy02890fd2010-08-06 17:58:44 -07007310 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007311 }
7312
7313 /**
7314 * <p>Frees the resources used by the drawing cache. If you call
7315 * {@link #buildDrawingCache()} manually without calling
7316 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7317 * should cleanup the cache with this method afterwards.</p>
7318 *
7319 * @see #setDrawingCacheEnabled(boolean)
7320 * @see #buildDrawingCache()
7321 * @see #getDrawingCache()
7322 */
7323 public void destroyDrawingCache() {
7324 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007325 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 mDrawingCache = null;
7327 }
Romain Guyfbd8f692009-06-26 14:51:58 -07007328 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007329 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07007330 mUnscaledDrawingCache = null;
7331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007332 }
7333
7334 /**
7335 * Setting a solid background color for the drawing cache's bitmaps will improve
7336 * perfromance and memory usage. Note, though that this should only be used if this
7337 * view will always be drawn on top of a solid color.
7338 *
7339 * @param color The background color to use for the drawing cache's bitmap
7340 *
7341 * @see #setDrawingCacheEnabled(boolean)
7342 * @see #buildDrawingCache()
7343 * @see #getDrawingCache()
7344 */
7345 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08007346 if (color != mDrawingCacheBackgroundColor) {
7347 mDrawingCacheBackgroundColor = color;
7348 mPrivateFlags &= ~DRAWING_CACHE_VALID;
7349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007350 }
7351
7352 /**
7353 * @see #setDrawingCacheBackgroundColor(int)
7354 *
7355 * @return The background color to used for the drawing cache's bitmap
7356 */
7357 public int getDrawingCacheBackgroundColor() {
7358 return mDrawingCacheBackgroundColor;
7359 }
7360
7361 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007362 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
7363 *
7364 * @see #buildDrawingCache(boolean)
7365 */
7366 public void buildDrawingCache() {
7367 buildDrawingCache(false);
7368 }
7369
7370 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
7372 *
7373 * <p>If you call {@link #buildDrawingCache()} manually without calling
7374 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7375 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007376 *
7377 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7378 * this method will create a bitmap of the same size as this view. Because this bitmap
7379 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7380 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7381 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7382 * size than the view. This implies that your application must be able to handle this
7383 * size.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007384 *
7385 * @see #getDrawingCache()
7386 * @see #destroyDrawingCache()
7387 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007388 public void buildDrawingCache(boolean autoScale) {
7389 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07007390 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007391
7392 if (ViewDebug.TRACE_HIERARCHY) {
7393 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395
Romain Guy8506ab42009-06-11 17:35:47 -07007396 int width = mRight - mLeft;
7397 int height = mBottom - mTop;
7398
7399 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007400 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007401
Romain Guye1123222009-06-29 14:24:56 -07007402 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007403 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7404 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406
7407 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007408 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Romain Guya62e4702009-10-08 10:48:54 -07007409 final boolean translucentWindow = attachInfo != null && attachInfo.mTranslucentWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007410
7411 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007412 // Projected bitmap size in bytes
7413 (width * height * (opaque && !translucentWindow ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007414 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7415 destroyDrawingCache();
7416 return;
7417 }
7418
7419 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07007420 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421
7422 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007423 Bitmap.Config quality;
7424 if (!opaque) {
7425 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7426 case DRAWING_CACHE_QUALITY_AUTO:
7427 quality = Bitmap.Config.ARGB_8888;
7428 break;
7429 case DRAWING_CACHE_QUALITY_LOW:
7430 quality = Bitmap.Config.ARGB_4444;
7431 break;
7432 case DRAWING_CACHE_QUALITY_HIGH:
7433 quality = Bitmap.Config.ARGB_8888;
7434 break;
7435 default:
7436 quality = Bitmap.Config.ARGB_8888;
7437 break;
7438 }
7439 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07007440 // Optimization for translucent windows
7441 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
7442 quality = translucentWindow ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007443 }
7444
7445 // Try to cleanup memory
7446 if (bitmap != null) bitmap.recycle();
7447
7448 try {
7449 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07007450 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07007451 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07007452 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007453 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07007454 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007455 }
Romain Guy35b38ce2009-10-07 13:38:55 -07007456 if (opaque && translucentWindow) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007457 } catch (OutOfMemoryError e) {
7458 // If there is not enough memory to create the bitmap cache, just
7459 // ignore the issue as bitmap caches are not required to draw the
7460 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07007461 if (autoScale) {
7462 mDrawingCache = null;
7463 } else {
7464 mUnscaledDrawingCache = null;
7465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007466 return;
7467 }
7468
7469 clear = drawingCacheBackgroundColor != 0;
7470 }
7471
7472 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007473 if (attachInfo != null) {
7474 canvas = attachInfo.mCanvas;
7475 if (canvas == null) {
7476 canvas = new Canvas();
7477 }
7478 canvas.setBitmap(bitmap);
7479 // Temporarily clobber the cached Canvas in case one of our children
7480 // is also using a drawing cache. Without this, the children would
7481 // steal the canvas by attaching their own bitmap to it and bad, bad
7482 // thing would happen (invisible views, corrupted drawings, etc.)
7483 attachInfo.mCanvas = null;
7484 } else {
7485 // This case should hopefully never or seldom happen
7486 canvas = new Canvas(bitmap);
7487 }
7488
7489 if (clear) {
7490 bitmap.eraseColor(drawingCacheBackgroundColor);
7491 }
7492
7493 computeScroll();
7494 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07007495
Romain Guye1123222009-06-29 14:24:56 -07007496 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007497 final float scale = attachInfo.mApplicationScale;
7498 canvas.scale(scale, scale);
7499 }
7500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007501 canvas.translate(-mScrollX, -mScrollY);
7502
Romain Guy5bcdff42009-05-14 21:27:18 -07007503 mPrivateFlags |= DRAWN;
Romain Guyecd80ee2009-12-03 17:13:02 -08007504 mPrivateFlags |= DRAWING_CACHE_VALID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007505
7506 // Fast path for layouts with no backgrounds
7507 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7508 if (ViewDebug.TRACE_HIERARCHY) {
7509 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7510 }
Romain Guy5bcdff42009-05-14 21:27:18 -07007511 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007512 dispatchDraw(canvas);
7513 } else {
7514 draw(canvas);
7515 }
7516
7517 canvas.restoreToCount(restoreCount);
7518
7519 if (attachInfo != null) {
7520 // Restore the cached Canvas for our siblings
7521 attachInfo.mCanvas = canvas;
7522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 }
7524 }
7525
7526 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007527 * Create a snapshot of the view into a bitmap. We should probably make
7528 * some form of this public, but should think about the API.
7529 */
Romain Guy223ff5c2010-03-02 17:07:47 -08007530 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007531 int width = mRight - mLeft;
7532 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007533
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007534 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07007535 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007536 width = (int) ((width * scale) + 0.5f);
7537 height = (int) ((height * scale) + 0.5f);
7538
Romain Guy8c11e312009-09-14 15:15:30 -07007539 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007540 if (bitmap == null) {
7541 throw new OutOfMemoryError();
7542 }
7543
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007544 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
7545
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007546 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007547 if (attachInfo != null) {
7548 canvas = attachInfo.mCanvas;
7549 if (canvas == null) {
7550 canvas = new Canvas();
7551 }
7552 canvas.setBitmap(bitmap);
7553 // Temporarily clobber the cached Canvas in case one of our children
7554 // is also using a drawing cache. Without this, the children would
7555 // steal the canvas by attaching their own bitmap to it and bad, bad
7556 // things would happen (invisible views, corrupted drawings, etc.)
7557 attachInfo.mCanvas = null;
7558 } else {
7559 // This case should hopefully never or seldom happen
7560 canvas = new Canvas(bitmap);
7561 }
7562
Romain Guy5bcdff42009-05-14 21:27:18 -07007563 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007564 bitmap.eraseColor(backgroundColor);
7565 }
7566
7567 computeScroll();
7568 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007569 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007570 canvas.translate(-mScrollX, -mScrollY);
7571
Romain Guy5bcdff42009-05-14 21:27:18 -07007572 // Temporarily remove the dirty mask
7573 int flags = mPrivateFlags;
7574 mPrivateFlags &= ~DIRTY_MASK;
7575
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007576 // Fast path for layouts with no backgrounds
7577 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7578 dispatchDraw(canvas);
7579 } else {
7580 draw(canvas);
7581 }
7582
Romain Guy5bcdff42009-05-14 21:27:18 -07007583 mPrivateFlags = flags;
7584
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007585 canvas.restoreToCount(restoreCount);
7586
7587 if (attachInfo != null) {
7588 // Restore the cached Canvas for our siblings
7589 attachInfo.mCanvas = canvas;
7590 }
Romain Guy8506ab42009-06-11 17:35:47 -07007591
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007592 return bitmap;
7593 }
7594
7595 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 * Indicates whether this View is currently in edit mode. A View is usually
7597 * in edit mode when displayed within a developer tool. For instance, if
7598 * this View is being drawn by a visual user interface builder, this method
7599 * should return true.
7600 *
7601 * Subclasses should check the return value of this method to provide
7602 * different behaviors if their normal behavior might interfere with the
7603 * host environment. For instance: the class spawns a thread in its
7604 * constructor, the drawing code relies on device-specific features, etc.
7605 *
7606 * This method is usually checked in the drawing code of custom widgets.
7607 *
7608 * @return True if this View is in edit mode, false otherwise.
7609 */
7610 public boolean isInEditMode() {
7611 return false;
7612 }
7613
7614 /**
7615 * If the View draws content inside its padding and enables fading edges,
7616 * it needs to support padding offsets. Padding offsets are added to the
7617 * fading edges to extend the length of the fade so that it covers pixels
7618 * drawn inside the padding.
7619 *
7620 * Subclasses of this class should override this method if they need
7621 * to draw content inside the padding.
7622 *
7623 * @return True if padding offset must be applied, false otherwise.
7624 *
7625 * @see #getLeftPaddingOffset()
7626 * @see #getRightPaddingOffset()
7627 * @see #getTopPaddingOffset()
7628 * @see #getBottomPaddingOffset()
7629 *
7630 * @since CURRENT
7631 */
7632 protected boolean isPaddingOffsetRequired() {
7633 return false;
7634 }
7635
7636 /**
7637 * Amount by which to extend the left fading region. Called only when
7638 * {@link #isPaddingOffsetRequired()} returns true.
7639 *
7640 * @return The left padding offset in pixels.
7641 *
7642 * @see #isPaddingOffsetRequired()
7643 *
7644 * @since CURRENT
7645 */
7646 protected int getLeftPaddingOffset() {
7647 return 0;
7648 }
7649
7650 /**
7651 * Amount by which to extend the right fading region. Called only when
7652 * {@link #isPaddingOffsetRequired()} returns true.
7653 *
7654 * @return The right padding offset in pixels.
7655 *
7656 * @see #isPaddingOffsetRequired()
7657 *
7658 * @since CURRENT
7659 */
7660 protected int getRightPaddingOffset() {
7661 return 0;
7662 }
7663
7664 /**
7665 * Amount by which to extend the top fading region. Called only when
7666 * {@link #isPaddingOffsetRequired()} returns true.
7667 *
7668 * @return The top padding offset in pixels.
7669 *
7670 * @see #isPaddingOffsetRequired()
7671 *
7672 * @since CURRENT
7673 */
7674 protected int getTopPaddingOffset() {
7675 return 0;
7676 }
7677
7678 /**
7679 * Amount by which to extend the bottom fading region. Called only when
7680 * {@link #isPaddingOffsetRequired()} returns true.
7681 *
7682 * @return The bottom padding offset in pixels.
7683 *
7684 * @see #isPaddingOffsetRequired()
7685 *
7686 * @since CURRENT
7687 */
7688 protected int getBottomPaddingOffset() {
7689 return 0;
7690 }
7691
7692 /**
Romain Guy2bffd262010-09-12 17:40:02 -07007693 * <p>Indicates whether this view is attached to an hardware accelerated
7694 * window or not.</p>
7695 *
7696 * <p>Even if this method returns true, it does not mean that every call
7697 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
7698 * accelerated {@link android.graphics.Canvas}. For instance, if this view
7699 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
7700 * window is hardware accelerated,
7701 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
7702 * return false, and this method will return true.</p>
7703 *
7704 * @return True if the view is attached to a window and the window is
7705 * hardware accelerated; false in any other case.
7706 */
7707 public boolean isHardwareAccelerated() {
7708 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
7709 }
7710
7711 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 * Manually render this view (and all of its children) to the given Canvas.
7713 * The view must have already done a full layout before this function is
7714 * called. When implementing a view, do not override this method; instead,
7715 * you should implement {@link #onDraw}.
7716 *
7717 * @param canvas The Canvas to which the View is rendered.
7718 */
7719 public void draw(Canvas canvas) {
7720 if (ViewDebug.TRACE_HIERARCHY) {
7721 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7722 }
7723
Romain Guy5bcdff42009-05-14 21:27:18 -07007724 final int privateFlags = mPrivateFlags;
7725 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
7726 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
7727 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07007728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729 /*
7730 * Draw traversal performs several drawing steps which must be executed
7731 * in the appropriate order:
7732 *
7733 * 1. Draw the background
7734 * 2. If necessary, save the canvas' layers to prepare for fading
7735 * 3. Draw view's content
7736 * 4. Draw children
7737 * 5. If necessary, draw the fading edges and restore layers
7738 * 6. Draw decorations (scrollbars for instance)
7739 */
7740
7741 // Step 1, draw the background, if needed
7742 int saveCount;
7743
Romain Guy24443ea2009-05-11 11:56:30 -07007744 if (!dirtyOpaque) {
7745 final Drawable background = mBGDrawable;
7746 if (background != null) {
7747 final int scrollX = mScrollX;
7748 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007749
Romain Guy24443ea2009-05-11 11:56:30 -07007750 if (mBackgroundSizeChanged) {
7751 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
7752 mBackgroundSizeChanged = false;
7753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007754
Romain Guy24443ea2009-05-11 11:56:30 -07007755 if ((scrollX | scrollY) == 0) {
7756 background.draw(canvas);
7757 } else {
7758 canvas.translate(scrollX, scrollY);
7759 background.draw(canvas);
7760 canvas.translate(-scrollX, -scrollY);
7761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007762 }
7763 }
7764
7765 // skip step 2 & 5 if possible (common case)
7766 final int viewFlags = mViewFlags;
7767 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
7768 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
7769 if (!verticalEdges && !horizontalEdges) {
7770 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007771 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772
7773 // Step 4, draw the children
7774 dispatchDraw(canvas);
7775
7776 // Step 6, draw decorations (scrollbars)
7777 onDrawScrollBars(canvas);
7778
7779 // we're done...
7780 return;
7781 }
7782
7783 /*
7784 * Here we do the full fledged routine...
7785 * (this is an uncommon case where speed matters less,
7786 * this is why we repeat some of the tests that have been
7787 * done above)
7788 */
7789
7790 boolean drawTop = false;
7791 boolean drawBottom = false;
7792 boolean drawLeft = false;
7793 boolean drawRight = false;
7794
7795 float topFadeStrength = 0.0f;
7796 float bottomFadeStrength = 0.0f;
7797 float leftFadeStrength = 0.0f;
7798 float rightFadeStrength = 0.0f;
7799
7800 // Step 2, save the canvas' layers
7801 int paddingLeft = mPaddingLeft;
7802 int paddingTop = mPaddingTop;
7803
7804 final boolean offsetRequired = isPaddingOffsetRequired();
7805 if (offsetRequired) {
7806 paddingLeft += getLeftPaddingOffset();
7807 paddingTop += getTopPaddingOffset();
7808 }
7809
7810 int left = mScrollX + paddingLeft;
7811 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
7812 int top = mScrollY + paddingTop;
7813 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
7814
7815 if (offsetRequired) {
7816 right += getRightPaddingOffset();
7817 bottom += getBottomPaddingOffset();
7818 }
7819
7820 final ScrollabilityCache scrollabilityCache = mScrollCache;
7821 int length = scrollabilityCache.fadingEdgeLength;
7822
7823 // clip the fade length if top and bottom fades overlap
7824 // overlapping fades produce odd-looking artifacts
7825 if (verticalEdges && (top + length > bottom - length)) {
7826 length = (bottom - top) / 2;
7827 }
7828
7829 // also clip horizontal fades if necessary
7830 if (horizontalEdges && (left + length > right - length)) {
7831 length = (right - left) / 2;
7832 }
7833
7834 if (verticalEdges) {
7835 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007836 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007837 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007838 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007839 }
7840
7841 if (horizontalEdges) {
7842 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007843 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007845 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007846 }
7847
7848 saveCount = canvas.getSaveCount();
7849
7850 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07007851 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
7853
7854 if (drawTop) {
7855 canvas.saveLayer(left, top, right, top + length, null, flags);
7856 }
7857
7858 if (drawBottom) {
7859 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
7860 }
7861
7862 if (drawLeft) {
7863 canvas.saveLayer(left, top, left + length, bottom, null, flags);
7864 }
7865
7866 if (drawRight) {
7867 canvas.saveLayer(right - length, top, right, bottom, null, flags);
7868 }
7869 } else {
7870 scrollabilityCache.setFadeColor(solidColor);
7871 }
7872
7873 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007874 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007875
7876 // Step 4, draw the children
7877 dispatchDraw(canvas);
7878
7879 // Step 5, draw the fade effect and restore layers
7880 final Paint p = scrollabilityCache.paint;
7881 final Matrix matrix = scrollabilityCache.matrix;
7882 final Shader fade = scrollabilityCache.shader;
7883 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
7884
7885 if (drawTop) {
7886 matrix.setScale(1, fadeHeight * topFadeStrength);
7887 matrix.postTranslate(left, top);
7888 fade.setLocalMatrix(matrix);
7889 canvas.drawRect(left, top, right, top + length, p);
7890 }
7891
7892 if (drawBottom) {
7893 matrix.setScale(1, fadeHeight * bottomFadeStrength);
7894 matrix.postRotate(180);
7895 matrix.postTranslate(left, bottom);
7896 fade.setLocalMatrix(matrix);
7897 canvas.drawRect(left, bottom - length, right, bottom, p);
7898 }
7899
7900 if (drawLeft) {
7901 matrix.setScale(1, fadeHeight * leftFadeStrength);
7902 matrix.postRotate(-90);
7903 matrix.postTranslate(left, top);
7904 fade.setLocalMatrix(matrix);
7905 canvas.drawRect(left, top, left + length, bottom, p);
7906 }
7907
7908 if (drawRight) {
7909 matrix.setScale(1, fadeHeight * rightFadeStrength);
7910 matrix.postRotate(90);
7911 matrix.postTranslate(right, top);
7912 fade.setLocalMatrix(matrix);
7913 canvas.drawRect(right - length, top, right, bottom, p);
7914 }
7915
7916 canvas.restoreToCount(saveCount);
7917
7918 // Step 6, draw decorations (scrollbars)
7919 onDrawScrollBars(canvas);
7920 }
7921
7922 /**
7923 * Override this if your view is known to always be drawn on top of a solid color background,
7924 * and needs to draw fading edges. Returning a non-zero color enables the view system to
7925 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
7926 * should be set to 0xFF.
7927 *
7928 * @see #setVerticalFadingEdgeEnabled
7929 * @see #setHorizontalFadingEdgeEnabled
7930 *
7931 * @return The known solid color background for this view, or 0 if the color may vary
7932 */
7933 public int getSolidColor() {
7934 return 0;
7935 }
7936
7937 /**
7938 * Build a human readable string representation of the specified view flags.
7939 *
7940 * @param flags the view flags to convert to a string
7941 * @return a String representing the supplied flags
7942 */
7943 private static String printFlags(int flags) {
7944 String output = "";
7945 int numFlags = 0;
7946 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
7947 output += "TAKES_FOCUS";
7948 numFlags++;
7949 }
7950
7951 switch (flags & VISIBILITY_MASK) {
7952 case INVISIBLE:
7953 if (numFlags > 0) {
7954 output += " ";
7955 }
7956 output += "INVISIBLE";
7957 // USELESS HERE numFlags++;
7958 break;
7959 case GONE:
7960 if (numFlags > 0) {
7961 output += " ";
7962 }
7963 output += "GONE";
7964 // USELESS HERE numFlags++;
7965 break;
7966 default:
7967 break;
7968 }
7969 return output;
7970 }
7971
7972 /**
7973 * Build a human readable string representation of the specified private
7974 * view flags.
7975 *
7976 * @param privateFlags the private view flags to convert to a string
7977 * @return a String representing the supplied flags
7978 */
7979 private static String printPrivateFlags(int privateFlags) {
7980 String output = "";
7981 int numFlags = 0;
7982
7983 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
7984 output += "WANTS_FOCUS";
7985 numFlags++;
7986 }
7987
7988 if ((privateFlags & FOCUSED) == FOCUSED) {
7989 if (numFlags > 0) {
7990 output += " ";
7991 }
7992 output += "FOCUSED";
7993 numFlags++;
7994 }
7995
7996 if ((privateFlags & SELECTED) == SELECTED) {
7997 if (numFlags > 0) {
7998 output += " ";
7999 }
8000 output += "SELECTED";
8001 numFlags++;
8002 }
8003
8004 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8005 if (numFlags > 0) {
8006 output += " ";
8007 }
8008 output += "IS_ROOT_NAMESPACE";
8009 numFlags++;
8010 }
8011
8012 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8013 if (numFlags > 0) {
8014 output += " ";
8015 }
8016 output += "HAS_BOUNDS";
8017 numFlags++;
8018 }
8019
8020 if ((privateFlags & DRAWN) == DRAWN) {
8021 if (numFlags > 0) {
8022 output += " ";
8023 }
8024 output += "DRAWN";
8025 // USELESS HERE numFlags++;
8026 }
8027 return output;
8028 }
8029
8030 /**
8031 * <p>Indicates whether or not this view's layout will be requested during
8032 * the next hierarchy layout pass.</p>
8033 *
8034 * @return true if the layout will be forced during next layout pass
8035 */
8036 public boolean isLayoutRequested() {
8037 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8038 }
8039
8040 /**
8041 * Assign a size and position to a view and all of its
8042 * descendants
8043 *
8044 * <p>This is the second phase of the layout mechanism.
8045 * (The first is measuring). In this phase, each parent calls
8046 * layout on all of its children to position them.
8047 * This is typically done using the child measurements
8048 * that were stored in the measure pass().
8049 *
8050 * Derived classes with children should override
8051 * onLayout. In that method, they should
Chet Haase21cd1382010-09-01 17:42:29 -07008052 * call layout on each of their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008053 *
8054 * @param l Left position, relative to parent
8055 * @param t Top position, relative to parent
8056 * @param r Right position, relative to parent
8057 * @param b Bottom position, relative to parent
8058 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008059 @SuppressWarnings({"unchecked"})
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 public final void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008061 int oldL = mLeft;
8062 int oldT = mTop;
8063 int oldB = mBottom;
8064 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008065 boolean changed = setFrame(l, t, r, b);
8066 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8067 if (ViewDebug.TRACE_HIERARCHY) {
8068 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8069 }
8070
8071 onLayout(changed, l, t, r, b);
8072 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008073
8074 if (mOnLayoutChangeListeners != null) {
8075 ArrayList<OnLayoutChangeListener> listenersCopy =
8076 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8077 int numListeners = listenersCopy.size();
8078 for (int i = 0; i < numListeners; ++i) {
8079 listenersCopy.get(i).onLayoutChange(this, l, r, t, b, oldL, oldT, oldR, oldB);
8080 }
8081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 }
8083 mPrivateFlags &= ~FORCE_LAYOUT;
8084 }
8085
8086 /**
8087 * Called from layout when this view should
8088 * assign a size and position to each of its children.
8089 *
8090 * Derived classes with children should override
8091 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008092 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008093 * @param changed This is a new size or position for this view
8094 * @param left Left position, relative to parent
8095 * @param top Top position, relative to parent
8096 * @param right Right position, relative to parent
8097 * @param bottom Bottom position, relative to parent
8098 */
8099 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8100 }
8101
8102 /**
8103 * Assign a size and position to this view.
8104 *
8105 * This is called from layout.
8106 *
8107 * @param left Left position, relative to parent
8108 * @param top Top position, relative to parent
8109 * @param right Right position, relative to parent
8110 * @param bottom Bottom position, relative to parent
8111 * @return true if the new size and position are different than the
8112 * previous ones
8113 * {@hide}
8114 */
8115 protected boolean setFrame(int left, int top, int right, int bottom) {
8116 boolean changed = false;
8117
8118 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008119 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008120 + right + "," + bottom + ")");
8121 }
8122
8123 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8124 changed = true;
8125
8126 // Remember our drawn bit
8127 int drawn = mPrivateFlags & DRAWN;
8128
8129 // Invalidate our old position
8130 invalidate();
8131
8132
8133 int oldWidth = mRight - mLeft;
8134 int oldHeight = mBottom - mTop;
8135
8136 mLeft = left;
8137 mTop = top;
8138 mRight = right;
8139 mBottom = bottom;
8140
8141 mPrivateFlags |= HAS_BOUNDS;
8142
8143 int newWidth = right - left;
8144 int newHeight = bottom - top;
8145
8146 if (newWidth != oldWidth || newHeight != oldHeight) {
8147 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8148 }
8149
8150 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8151 // If we are visible, force the DRAWN bit to on so that
8152 // this invalidate will go through (at least to our parent).
8153 // This is because someone may have invalidated this view
8154 // before this call to setFrame came in, therby clearing
8155 // the DRAWN bit.
8156 mPrivateFlags |= DRAWN;
8157 invalidate();
8158 }
8159
8160 // Reset drawn bit to original value (invalidate turns it off)
8161 mPrivateFlags |= drawn;
8162
8163 mBackgroundSizeChanged = true;
8164 }
8165 return changed;
8166 }
8167
8168 /**
8169 * Finalize inflating a view from XML. This is called as the last phase
8170 * of inflation, after all child views have been added.
8171 *
8172 * <p>Even if the subclass overrides onFinishInflate, they should always be
8173 * sure to call the super method, so that we get called.
8174 */
8175 protected void onFinishInflate() {
8176 }
8177
8178 /**
8179 * Returns the resources associated with this view.
8180 *
8181 * @return Resources object.
8182 */
8183 public Resources getResources() {
8184 return mResources;
8185 }
8186
8187 /**
8188 * Invalidates the specified Drawable.
8189 *
8190 * @param drawable the drawable to invalidate
8191 */
8192 public void invalidateDrawable(Drawable drawable) {
8193 if (verifyDrawable(drawable)) {
8194 final Rect dirty = drawable.getBounds();
8195 final int scrollX = mScrollX;
8196 final int scrollY = mScrollY;
8197
8198 invalidate(dirty.left + scrollX, dirty.top + scrollY,
8199 dirty.right + scrollX, dirty.bottom + scrollY);
8200 }
8201 }
8202
8203 /**
8204 * Schedules an action on a drawable to occur at a specified time.
8205 *
8206 * @param who the recipient of the action
8207 * @param what the action to run on the drawable
8208 * @param when the time at which the action must occur. Uses the
8209 * {@link SystemClock#uptimeMillis} timebase.
8210 */
8211 public void scheduleDrawable(Drawable who, Runnable what, long when) {
8212 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8213 mAttachInfo.mHandler.postAtTime(what, who, when);
8214 }
8215 }
8216
8217 /**
8218 * Cancels a scheduled action on a drawable.
8219 *
8220 * @param who the recipient of the action
8221 * @param what the action to cancel
8222 */
8223 public void unscheduleDrawable(Drawable who, Runnable what) {
8224 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8225 mAttachInfo.mHandler.removeCallbacks(what, who);
8226 }
8227 }
8228
8229 /**
8230 * Unschedule any events associated with the given Drawable. This can be
8231 * used when selecting a new Drawable into a view, so that the previous
8232 * one is completely unscheduled.
8233 *
8234 * @param who The Drawable to unschedule.
8235 *
8236 * @see #drawableStateChanged
8237 */
8238 public void unscheduleDrawable(Drawable who) {
8239 if (mAttachInfo != null) {
8240 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
8241 }
8242 }
8243
8244 /**
8245 * If your view subclass is displaying its own Drawable objects, it should
8246 * override this function and return true for any Drawable it is
8247 * displaying. This allows animations for those drawables to be
8248 * scheduled.
8249 *
8250 * <p>Be sure to call through to the super class when overriding this
8251 * function.
8252 *
8253 * @param who The Drawable to verify. Return true if it is one you are
8254 * displaying, else return the result of calling through to the
8255 * super class.
8256 *
8257 * @return boolean If true than the Drawable is being displayed in the
8258 * view; else false and it is not allowed to animate.
8259 *
8260 * @see #unscheduleDrawable
8261 * @see #drawableStateChanged
8262 */
8263 protected boolean verifyDrawable(Drawable who) {
8264 return who == mBGDrawable;
8265 }
8266
8267 /**
8268 * This function is called whenever the state of the view changes in such
8269 * a way that it impacts the state of drawables being shown.
8270 *
8271 * <p>Be sure to call through to the superclass when overriding this
8272 * function.
8273 *
8274 * @see Drawable#setState
8275 */
8276 protected void drawableStateChanged() {
8277 Drawable d = mBGDrawable;
8278 if (d != null && d.isStateful()) {
8279 d.setState(getDrawableState());
8280 }
8281 }
8282
8283 /**
8284 * Call this to force a view to update its drawable state. This will cause
8285 * drawableStateChanged to be called on this view. Views that are interested
8286 * in the new state should call getDrawableState.
8287 *
8288 * @see #drawableStateChanged
8289 * @see #getDrawableState
8290 */
8291 public void refreshDrawableState() {
8292 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
8293 drawableStateChanged();
8294
8295 ViewParent parent = mParent;
8296 if (parent != null) {
8297 parent.childDrawableStateChanged(this);
8298 }
8299 }
8300
8301 /**
8302 * Return an array of resource IDs of the drawable states representing the
8303 * current state of the view.
8304 *
8305 * @return The current drawable state
8306 *
8307 * @see Drawable#setState
8308 * @see #drawableStateChanged
8309 * @see #onCreateDrawableState
8310 */
8311 public final int[] getDrawableState() {
8312 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
8313 return mDrawableState;
8314 } else {
8315 mDrawableState = onCreateDrawableState(0);
8316 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
8317 return mDrawableState;
8318 }
8319 }
8320
8321 /**
8322 * Generate the new {@link android.graphics.drawable.Drawable} state for
8323 * this view. This is called by the view
8324 * system when the cached Drawable state is determined to be invalid. To
8325 * retrieve the current state, you should use {@link #getDrawableState}.
8326 *
8327 * @param extraSpace if non-zero, this is the number of extra entries you
8328 * would like in the returned array in which you can place your own
8329 * states.
8330 *
8331 * @return Returns an array holding the current {@link Drawable} state of
8332 * the view.
8333 *
8334 * @see #mergeDrawableStates
8335 */
8336 protected int[] onCreateDrawableState(int extraSpace) {
8337 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
8338 mParent instanceof View) {
8339 return ((View) mParent).onCreateDrawableState(extraSpace);
8340 }
8341
8342 int[] drawableState;
8343
8344 int privateFlags = mPrivateFlags;
8345
8346 int viewStateIndex = (((privateFlags & PRESSED) != 0) ? 1 : 0);
8347
8348 viewStateIndex = (viewStateIndex << 1)
8349 + (((mViewFlags & ENABLED_MASK) == ENABLED) ? 1 : 0);
8350
8351 viewStateIndex = (viewStateIndex << 1) + (isFocused() ? 1 : 0);
8352
8353 viewStateIndex = (viewStateIndex << 1)
8354 + (((privateFlags & SELECTED) != 0) ? 1 : 0);
8355
8356 final boolean hasWindowFocus = hasWindowFocus();
8357 viewStateIndex = (viewStateIndex << 1) + (hasWindowFocus ? 1 : 0);
8358
8359 drawableState = VIEW_STATE_SETS[viewStateIndex];
8360
8361 //noinspection ConstantIfStatement
8362 if (false) {
8363 Log.i("View", "drawableStateIndex=" + viewStateIndex);
8364 Log.i("View", toString()
8365 + " pressed=" + ((privateFlags & PRESSED) != 0)
8366 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
8367 + " fo=" + hasFocus()
8368 + " sl=" + ((privateFlags & SELECTED) != 0)
8369 + " wf=" + hasWindowFocus
8370 + ": " + Arrays.toString(drawableState));
8371 }
8372
8373 if (extraSpace == 0) {
8374 return drawableState;
8375 }
8376
8377 final int[] fullState;
8378 if (drawableState != null) {
8379 fullState = new int[drawableState.length + extraSpace];
8380 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
8381 } else {
8382 fullState = new int[extraSpace];
8383 }
8384
8385 return fullState;
8386 }
8387
8388 /**
8389 * Merge your own state values in <var>additionalState</var> into the base
8390 * state values <var>baseState</var> that were returned by
8391 * {@link #onCreateDrawableState}.
8392 *
8393 * @param baseState The base state values returned by
8394 * {@link #onCreateDrawableState}, which will be modified to also hold your
8395 * own additional state values.
8396 *
8397 * @param additionalState The additional state values you would like
8398 * added to <var>baseState</var>; this array is not modified.
8399 *
8400 * @return As a convenience, the <var>baseState</var> array you originally
8401 * passed into the function is returned.
8402 *
8403 * @see #onCreateDrawableState
8404 */
8405 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
8406 final int N = baseState.length;
8407 int i = N - 1;
8408 while (i >= 0 && baseState[i] == 0) {
8409 i--;
8410 }
8411 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
8412 return baseState;
8413 }
8414
8415 /**
8416 * Sets the background color for this view.
8417 * @param color the color of the background
8418 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008419 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008420 public void setBackgroundColor(int color) {
8421 setBackgroundDrawable(new ColorDrawable(color));
8422 }
8423
8424 /**
8425 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07008426 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008427 * @param resid The identifier of the resource.
8428 * @attr ref android.R.styleable#View_background
8429 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008430 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008431 public void setBackgroundResource(int resid) {
8432 if (resid != 0 && resid == mBackgroundResource) {
8433 return;
8434 }
8435
8436 Drawable d= null;
8437 if (resid != 0) {
8438 d = mResources.getDrawable(resid);
8439 }
8440 setBackgroundDrawable(d);
8441
8442 mBackgroundResource = resid;
8443 }
8444
8445 /**
8446 * Set the background to a given Drawable, or remove the background. If the
8447 * background has padding, this View's padding is set to the background's
8448 * padding. However, when a background is removed, this View's padding isn't
8449 * touched. If setting the padding is desired, please use
8450 * {@link #setPadding(int, int, int, int)}.
8451 *
8452 * @param d The Drawable to use as the background, or null to remove the
8453 * background
8454 */
8455 public void setBackgroundDrawable(Drawable d) {
8456 boolean requestLayout = false;
8457
8458 mBackgroundResource = 0;
8459
8460 /*
8461 * Regardless of whether we're setting a new background or not, we want
8462 * to clear the previous drawable.
8463 */
8464 if (mBGDrawable != null) {
8465 mBGDrawable.setCallback(null);
8466 unscheduleDrawable(mBGDrawable);
8467 }
8468
8469 if (d != null) {
8470 Rect padding = sThreadLocal.get();
8471 if (padding == null) {
8472 padding = new Rect();
8473 sThreadLocal.set(padding);
8474 }
8475 if (d.getPadding(padding)) {
8476 setPadding(padding.left, padding.top, padding.right, padding.bottom);
8477 }
8478
8479 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
8480 // if it has a different minimum size, we should layout again
8481 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
8482 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
8483 requestLayout = true;
8484 }
8485
8486 d.setCallback(this);
8487 if (d.isStateful()) {
8488 d.setState(getDrawableState());
8489 }
8490 d.setVisible(getVisibility() == VISIBLE, false);
8491 mBGDrawable = d;
8492
8493 if ((mPrivateFlags & SKIP_DRAW) != 0) {
8494 mPrivateFlags &= ~SKIP_DRAW;
8495 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8496 requestLayout = true;
8497 }
8498 } else {
8499 /* Remove the background */
8500 mBGDrawable = null;
8501
8502 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
8503 /*
8504 * This view ONLY drew the background before and we're removing
8505 * the background, so now it won't draw anything
8506 * (hence we SKIP_DRAW)
8507 */
8508 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
8509 mPrivateFlags |= SKIP_DRAW;
8510 }
8511
8512 /*
8513 * When the background is set, we try to apply its padding to this
8514 * View. When the background is removed, we don't touch this View's
8515 * padding. This is noted in the Javadocs. Hence, we don't need to
8516 * requestLayout(), the invalidate() below is sufficient.
8517 */
8518
8519 // The old background's minimum size could have affected this
8520 // View's layout, so let's requestLayout
8521 requestLayout = true;
8522 }
8523
Romain Guy8f1344f52009-05-15 16:03:59 -07008524 computeOpaqueFlags();
8525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008526 if (requestLayout) {
8527 requestLayout();
8528 }
8529
8530 mBackgroundSizeChanged = true;
8531 invalidate();
8532 }
8533
8534 /**
8535 * Gets the background drawable
8536 * @return The drawable used as the background for this view, if any.
8537 */
8538 public Drawable getBackground() {
8539 return mBGDrawable;
8540 }
8541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008542 /**
8543 * Sets the padding. The view may add on the space required to display
8544 * the scrollbars, depending on the style and visibility of the scrollbars.
8545 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
8546 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
8547 * from the values set in this call.
8548 *
8549 * @attr ref android.R.styleable#View_padding
8550 * @attr ref android.R.styleable#View_paddingBottom
8551 * @attr ref android.R.styleable#View_paddingLeft
8552 * @attr ref android.R.styleable#View_paddingRight
8553 * @attr ref android.R.styleable#View_paddingTop
8554 * @param left the left padding in pixels
8555 * @param top the top padding in pixels
8556 * @param right the right padding in pixels
8557 * @param bottom the bottom padding in pixels
8558 */
8559 public void setPadding(int left, int top, int right, int bottom) {
8560 boolean changed = false;
8561
8562 mUserPaddingRight = right;
8563 mUserPaddingBottom = bottom;
8564
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008565 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07008566
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008567 // Common case is there are no scroll bars.
8568 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
8569 // TODO: Deal with RTL languages to adjust left padding instead of right.
8570 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
8571 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8572 ? 0 : getVerticalScrollbarWidth();
8573 }
8574 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
8575 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8576 ? 0 : getHorizontalScrollbarHeight();
8577 }
8578 }
Romain Guy8506ab42009-06-11 17:35:47 -07008579
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008580 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008581 changed = true;
8582 mPaddingLeft = left;
8583 }
8584 if (mPaddingTop != top) {
8585 changed = true;
8586 mPaddingTop = top;
8587 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008588 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008589 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008590 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008592 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008594 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595 }
8596
8597 if (changed) {
8598 requestLayout();
8599 }
8600 }
8601
8602 /**
8603 * Returns the top padding of this view.
8604 *
8605 * @return the top padding in pixels
8606 */
8607 public int getPaddingTop() {
8608 return mPaddingTop;
8609 }
8610
8611 /**
8612 * Returns the bottom padding of this view. If there are inset and enabled
8613 * scrollbars, this value may include the space required to display the
8614 * scrollbars as well.
8615 *
8616 * @return the bottom padding in pixels
8617 */
8618 public int getPaddingBottom() {
8619 return mPaddingBottom;
8620 }
8621
8622 /**
8623 * Returns the left padding of this view. If there are inset and enabled
8624 * scrollbars, this value may include the space required to display the
8625 * scrollbars as well.
8626 *
8627 * @return the left padding in pixels
8628 */
8629 public int getPaddingLeft() {
8630 return mPaddingLeft;
8631 }
8632
8633 /**
8634 * Returns the right padding of this view. If there are inset and enabled
8635 * scrollbars, this value may include the space required to display the
8636 * scrollbars as well.
8637 *
8638 * @return the right padding in pixels
8639 */
8640 public int getPaddingRight() {
8641 return mPaddingRight;
8642 }
8643
8644 /**
8645 * Changes the selection state of this view. A view can be selected or not.
8646 * Note that selection is not the same as focus. Views are typically
8647 * selected in the context of an AdapterView like ListView or GridView;
8648 * the selected view is the view that is highlighted.
8649 *
8650 * @param selected true if the view must be selected, false otherwise
8651 */
8652 public void setSelected(boolean selected) {
8653 if (((mPrivateFlags & SELECTED) != 0) != selected) {
8654 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07008655 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 invalidate();
8657 refreshDrawableState();
8658 dispatchSetSelected(selected);
8659 }
8660 }
8661
8662 /**
8663 * Dispatch setSelected to all of this View's children.
8664 *
8665 * @see #setSelected(boolean)
8666 *
8667 * @param selected The new selected state
8668 */
8669 protected void dispatchSetSelected(boolean selected) {
8670 }
8671
8672 /**
8673 * Indicates the selection state of this view.
8674 *
8675 * @return true if the view is selected, false otherwise
8676 */
8677 @ViewDebug.ExportedProperty
8678 public boolean isSelected() {
8679 return (mPrivateFlags & SELECTED) != 0;
8680 }
8681
8682 /**
8683 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
8684 * observer can be used to get notifications when global events, like
8685 * layout, happen.
8686 *
8687 * The returned ViewTreeObserver observer is not guaranteed to remain
8688 * valid for the lifetime of this View. If the caller of this method keeps
8689 * a long-lived reference to ViewTreeObserver, it should always check for
8690 * the return value of {@link ViewTreeObserver#isAlive()}.
8691 *
8692 * @return The ViewTreeObserver for this view's hierarchy.
8693 */
8694 public ViewTreeObserver getViewTreeObserver() {
8695 if (mAttachInfo != null) {
8696 return mAttachInfo.mTreeObserver;
8697 }
8698 if (mFloatingTreeObserver == null) {
8699 mFloatingTreeObserver = new ViewTreeObserver();
8700 }
8701 return mFloatingTreeObserver;
8702 }
8703
8704 /**
8705 * <p>Finds the topmost view in the current view hierarchy.</p>
8706 *
8707 * @return the topmost view containing this view
8708 */
8709 public View getRootView() {
8710 if (mAttachInfo != null) {
8711 final View v = mAttachInfo.mRootView;
8712 if (v != null) {
8713 return v;
8714 }
8715 }
Romain Guy8506ab42009-06-11 17:35:47 -07008716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008717 View parent = this;
8718
8719 while (parent.mParent != null && parent.mParent instanceof View) {
8720 parent = (View) parent.mParent;
8721 }
8722
8723 return parent;
8724 }
8725
8726 /**
8727 * <p>Computes the coordinates of this view on the screen. The argument
8728 * must be an array of two integers. After the method returns, the array
8729 * contains the x and y location in that order.</p>
8730 *
8731 * @param location an array of two integers in which to hold the coordinates
8732 */
8733 public void getLocationOnScreen(int[] location) {
8734 getLocationInWindow(location);
8735
8736 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07008737 if (info != null) {
8738 location[0] += info.mWindowLeft;
8739 location[1] += info.mWindowTop;
8740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008741 }
8742
8743 /**
8744 * <p>Computes the coordinates of this view in its window. The argument
8745 * must be an array of two integers. After the method returns, the array
8746 * contains the x and y location in that order.</p>
8747 *
8748 * @param location an array of two integers in which to hold the coordinates
8749 */
8750 public void getLocationInWindow(int[] location) {
8751 if (location == null || location.length < 2) {
8752 throw new IllegalArgumentException("location must be an array of "
8753 + "two integers");
8754 }
8755
8756 location[0] = mLeft;
8757 location[1] = mTop;
8758
8759 ViewParent viewParent = mParent;
8760 while (viewParent instanceof View) {
8761 final View view = (View)viewParent;
8762 location[0] += view.mLeft - view.mScrollX;
8763 location[1] += view.mTop - view.mScrollY;
8764 viewParent = view.mParent;
8765 }
Romain Guy8506ab42009-06-11 17:35:47 -07008766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008767 if (viewParent instanceof ViewRoot) {
8768 // *cough*
8769 final ViewRoot vr = (ViewRoot)viewParent;
8770 location[1] -= vr.mCurScrollY;
8771 }
8772 }
8773
8774 /**
8775 * {@hide}
8776 * @param id the id of the view to be found
8777 * @return the view of the specified id, null if cannot be found
8778 */
8779 protected View findViewTraversal(int id) {
8780 if (id == mID) {
8781 return this;
8782 }
8783 return null;
8784 }
8785
8786 /**
8787 * {@hide}
8788 * @param tag the tag of the view to be found
8789 * @return the view of specified tag, null if cannot be found
8790 */
8791 protected View findViewWithTagTraversal(Object tag) {
8792 if (tag != null && tag.equals(mTag)) {
8793 return this;
8794 }
8795 return null;
8796 }
8797
8798 /**
8799 * Look for a child view with the given id. If this view has the given
8800 * id, return this view.
8801 *
8802 * @param id The id to search for.
8803 * @return The view that has the given id in the hierarchy or null
8804 */
8805 public final View findViewById(int id) {
8806 if (id < 0) {
8807 return null;
8808 }
8809 return findViewTraversal(id);
8810 }
8811
8812 /**
8813 * Look for a child view with the given tag. If this view has the given
8814 * tag, return this view.
8815 *
8816 * @param tag The tag to search for, using "tag.equals(getTag())".
8817 * @return The View that has the given tag in the hierarchy or null
8818 */
8819 public final View findViewWithTag(Object tag) {
8820 if (tag == null) {
8821 return null;
8822 }
8823 return findViewWithTagTraversal(tag);
8824 }
8825
8826 /**
8827 * Sets the identifier for this view. The identifier does not have to be
8828 * unique in this view's hierarchy. The identifier should be a positive
8829 * number.
8830 *
8831 * @see #NO_ID
8832 * @see #getId
8833 * @see #findViewById
8834 *
8835 * @param id a number used to identify the view
8836 *
8837 * @attr ref android.R.styleable#View_id
8838 */
8839 public void setId(int id) {
8840 mID = id;
8841 }
8842
8843 /**
8844 * {@hide}
8845 *
8846 * @param isRoot true if the view belongs to the root namespace, false
8847 * otherwise
8848 */
8849 public void setIsRootNamespace(boolean isRoot) {
8850 if (isRoot) {
8851 mPrivateFlags |= IS_ROOT_NAMESPACE;
8852 } else {
8853 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
8854 }
8855 }
8856
8857 /**
8858 * {@hide}
8859 *
8860 * @return true if the view belongs to the root namespace, false otherwise
8861 */
8862 public boolean isRootNamespace() {
8863 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
8864 }
8865
8866 /**
8867 * Returns this view's identifier.
8868 *
8869 * @return a positive integer used to identify the view or {@link #NO_ID}
8870 * if the view has no ID
8871 *
8872 * @see #setId
8873 * @see #findViewById
8874 * @attr ref android.R.styleable#View_id
8875 */
8876 @ViewDebug.CapturedViewProperty
8877 public int getId() {
8878 return mID;
8879 }
8880
8881 /**
8882 * Returns this view's tag.
8883 *
8884 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07008885 *
8886 * @see #setTag(Object)
8887 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008888 */
8889 @ViewDebug.ExportedProperty
8890 public Object getTag() {
8891 return mTag;
8892 }
8893
8894 /**
8895 * Sets the tag associated with this view. A tag can be used to mark
8896 * a view in its hierarchy and does not have to be unique within the
8897 * hierarchy. Tags can also be used to store data within a view without
8898 * resorting to another data structure.
8899 *
8900 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07008901 *
8902 * @see #getTag()
8903 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008904 */
8905 public void setTag(final Object tag) {
8906 mTag = tag;
8907 }
8908
8909 /**
Romain Guyd90a3312009-05-06 14:54:28 -07008910 * Returns the tag associated with this view and the specified key.
8911 *
8912 * @param key The key identifying the tag
8913 *
8914 * @return the Object stored in this view as a tag
8915 *
8916 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07008917 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07008918 */
8919 public Object getTag(int key) {
8920 SparseArray<Object> tags = null;
8921 synchronized (sTagsLock) {
8922 if (sTags != null) {
8923 tags = sTags.get(this);
8924 }
8925 }
8926
8927 if (tags != null) return tags.get(key);
8928 return null;
8929 }
8930
8931 /**
8932 * Sets a tag associated with this view and a key. A tag can be used
8933 * to mark a view in its hierarchy and does not have to be unique within
8934 * the hierarchy. Tags can also be used to store data within a view
8935 * without resorting to another data structure.
8936 *
8937 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07008938 * application to ensure it is unique (see the <a
8939 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
8940 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07008941 * the Android framework or not associated with any package will cause
8942 * an {@link IllegalArgumentException} to be thrown.
8943 *
8944 * @param key The key identifying the tag
8945 * @param tag An Object to tag the view with
8946 *
8947 * @throws IllegalArgumentException If they specified key is not valid
8948 *
8949 * @see #setTag(Object)
8950 * @see #getTag(int)
8951 */
8952 public void setTag(int key, final Object tag) {
8953 // If the package id is 0x00 or 0x01, it's either an undefined package
8954 // or a framework id
8955 if ((key >>> 24) < 2) {
8956 throw new IllegalArgumentException("The key must be an application-specific "
8957 + "resource id.");
8958 }
8959
8960 setTagInternal(this, key, tag);
8961 }
8962
8963 /**
8964 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
8965 * framework id.
8966 *
8967 * @hide
8968 */
8969 public void setTagInternal(int key, Object tag) {
8970 if ((key >>> 24) != 0x1) {
8971 throw new IllegalArgumentException("The key must be a framework-specific "
8972 + "resource id.");
8973 }
8974
Romain Guy8506ab42009-06-11 17:35:47 -07008975 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07008976 }
8977
8978 private static void setTagInternal(View view, int key, Object tag) {
8979 SparseArray<Object> tags = null;
8980 synchronized (sTagsLock) {
8981 if (sTags == null) {
8982 sTags = new WeakHashMap<View, SparseArray<Object>>();
8983 } else {
8984 tags = sTags.get(view);
8985 }
8986 }
8987
8988 if (tags == null) {
8989 tags = new SparseArray<Object>(2);
8990 synchronized (sTagsLock) {
8991 sTags.put(view, tags);
8992 }
8993 }
8994
8995 tags.put(key, tag);
8996 }
8997
8998 /**
Romain Guy13922e02009-05-12 17:56:14 -07008999 * @param consistency The type of consistency. See ViewDebug for more information.
9000 *
9001 * @hide
9002 */
9003 protected boolean dispatchConsistencyCheck(int consistency) {
9004 return onConsistencyCheck(consistency);
9005 }
9006
9007 /**
9008 * Method that subclasses should implement to check their consistency. The type of
9009 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009010 *
Romain Guy13922e02009-05-12 17:56:14 -07009011 * @param consistency The type of consistency. See ViewDebug for more information.
9012 *
9013 * @throws IllegalStateException if the view is in an inconsistent state.
9014 *
9015 * @hide
9016 */
9017 protected boolean onConsistencyCheck(int consistency) {
9018 boolean result = true;
9019
9020 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9021 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9022
9023 if (checkLayout) {
9024 if (getParent() == null) {
9025 result = false;
9026 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9027 "View " + this + " does not have a parent.");
9028 }
9029
9030 if (mAttachInfo == null) {
9031 result = false;
9032 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9033 "View " + this + " is not attached to a window.");
9034 }
9035 }
9036
9037 if (checkDrawing) {
9038 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9039 // from their draw() method
9040
9041 if ((mPrivateFlags & DRAWN) != DRAWN &&
9042 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9043 result = false;
9044 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9045 "View " + this + " was invalidated but its drawing cache is valid.");
9046 }
9047 }
9048
9049 return result;
9050 }
9051
9052 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009053 * Prints information about this view in the log output, with the tag
9054 * {@link #VIEW_LOG_TAG}.
9055 *
9056 * @hide
9057 */
9058 public void debug() {
9059 debug(0);
9060 }
9061
9062 /**
9063 * Prints information about this view in the log output, with the tag
9064 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
9065 * indentation defined by the <code>depth</code>.
9066 *
9067 * @param depth the indentation level
9068 *
9069 * @hide
9070 */
9071 protected void debug(int depth) {
9072 String output = debugIndent(depth - 1);
9073
9074 output += "+ " + this;
9075 int id = getId();
9076 if (id != -1) {
9077 output += " (id=" + id + ")";
9078 }
9079 Object tag = getTag();
9080 if (tag != null) {
9081 output += " (tag=" + tag + ")";
9082 }
9083 Log.d(VIEW_LOG_TAG, output);
9084
9085 if ((mPrivateFlags & FOCUSED) != 0) {
9086 output = debugIndent(depth) + " FOCUSED";
9087 Log.d(VIEW_LOG_TAG, output);
9088 }
9089
9090 output = debugIndent(depth);
9091 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
9092 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
9093 + "} ";
9094 Log.d(VIEW_LOG_TAG, output);
9095
9096 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
9097 || mPaddingBottom != 0) {
9098 output = debugIndent(depth);
9099 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
9100 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
9101 Log.d(VIEW_LOG_TAG, output);
9102 }
9103
9104 output = debugIndent(depth);
9105 output += "mMeasureWidth=" + mMeasuredWidth +
9106 " mMeasureHeight=" + mMeasuredHeight;
9107 Log.d(VIEW_LOG_TAG, output);
9108
9109 output = debugIndent(depth);
9110 if (mLayoutParams == null) {
9111 output += "BAD! no layout params";
9112 } else {
9113 output = mLayoutParams.debug(output);
9114 }
9115 Log.d(VIEW_LOG_TAG, output);
9116
9117 output = debugIndent(depth);
9118 output += "flags={";
9119 output += View.printFlags(mViewFlags);
9120 output += "}";
9121 Log.d(VIEW_LOG_TAG, output);
9122
9123 output = debugIndent(depth);
9124 output += "privateFlags={";
9125 output += View.printPrivateFlags(mPrivateFlags);
9126 output += "}";
9127 Log.d(VIEW_LOG_TAG, output);
9128 }
9129
9130 /**
9131 * Creates an string of whitespaces used for indentation.
9132 *
9133 * @param depth the indentation level
9134 * @return a String containing (depth * 2 + 3) * 2 white spaces
9135 *
9136 * @hide
9137 */
9138 protected static String debugIndent(int depth) {
9139 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
9140 for (int i = 0; i < (depth * 2) + 3; i++) {
9141 spaces.append(' ').append(' ');
9142 }
9143 return spaces.toString();
9144 }
9145
9146 /**
9147 * <p>Return the offset of the widget's text baseline from the widget's top
9148 * boundary. If this widget does not support baseline alignment, this
9149 * method returns -1. </p>
9150 *
9151 * @return the offset of the baseline within the widget's bounds or -1
9152 * if baseline alignment is not supported
9153 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07009154 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009155 public int getBaseline() {
9156 return -1;
9157 }
9158
9159 /**
9160 * Call this when something has changed which has invalidated the
9161 * layout of this view. This will schedule a layout pass of the view
9162 * tree.
9163 */
9164 public void requestLayout() {
9165 if (ViewDebug.TRACE_HIERARCHY) {
9166 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
9167 }
9168
9169 mPrivateFlags |= FORCE_LAYOUT;
9170
9171 if (mParent != null && !mParent.isLayoutRequested()) {
9172 mParent.requestLayout();
9173 }
9174 }
9175
9176 /**
9177 * Forces this view to be laid out during the next layout pass.
9178 * This method does not call requestLayout() or forceLayout()
9179 * on the parent.
9180 */
9181 public void forceLayout() {
9182 mPrivateFlags |= FORCE_LAYOUT;
9183 }
9184
9185 /**
9186 * <p>
9187 * This is called to find out how big a view should be. The parent
9188 * supplies constraint information in the width and height parameters.
9189 * </p>
9190 *
9191 * <p>
9192 * The actual mesurement work of a view is performed in
9193 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
9194 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
9195 * </p>
9196 *
9197 *
9198 * @param widthMeasureSpec Horizontal space requirements as imposed by the
9199 * parent
9200 * @param heightMeasureSpec Vertical space requirements as imposed by the
9201 * parent
9202 *
9203 * @see #onMeasure(int, int)
9204 */
9205 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
9206 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
9207 widthMeasureSpec != mOldWidthMeasureSpec ||
9208 heightMeasureSpec != mOldHeightMeasureSpec) {
9209
9210 // first clears the measured dimension flag
9211 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9212
9213 if (ViewDebug.TRACE_HIERARCHY) {
9214 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
9215 }
9216
9217 // measure ourselves, this should set the measured dimension flag back
9218 onMeasure(widthMeasureSpec, heightMeasureSpec);
9219
9220 // flag not set, setMeasuredDimension() was not invoked, we raise
9221 // an exception to warn the developer
9222 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9223 throw new IllegalStateException("onMeasure() did not set the"
9224 + " measured dimension by calling"
9225 + " setMeasuredDimension()");
9226 }
9227
9228 mPrivateFlags |= LAYOUT_REQUIRED;
9229 }
9230
9231 mOldWidthMeasureSpec = widthMeasureSpec;
9232 mOldHeightMeasureSpec = heightMeasureSpec;
9233 }
9234
9235 /**
9236 * <p>
9237 * Measure the view and its content to determine the measured width and the
9238 * measured height. This method is invoked by {@link #measure(int, int)} and
9239 * should be overriden by subclasses to provide accurate and efficient
9240 * measurement of their contents.
9241 * </p>
9242 *
9243 * <p>
9244 * <strong>CONTRACT:</strong> When overriding this method, you
9245 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
9246 * measured width and height of this view. Failure to do so will trigger an
9247 * <code>IllegalStateException</code>, thrown by
9248 * {@link #measure(int, int)}. Calling the superclass'
9249 * {@link #onMeasure(int, int)} is a valid use.
9250 * </p>
9251 *
9252 * <p>
9253 * The base class implementation of measure defaults to the background size,
9254 * unless a larger size is allowed by the MeasureSpec. Subclasses should
9255 * override {@link #onMeasure(int, int)} to provide better measurements of
9256 * their content.
9257 * </p>
9258 *
9259 * <p>
9260 * If this method is overridden, it is the subclass's responsibility to make
9261 * sure the measured height and width are at least the view's minimum height
9262 * and width ({@link #getSuggestedMinimumHeight()} and
9263 * {@link #getSuggestedMinimumWidth()}).
9264 * </p>
9265 *
9266 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
9267 * The requirements are encoded with
9268 * {@link android.view.View.MeasureSpec}.
9269 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
9270 * The requirements are encoded with
9271 * {@link android.view.View.MeasureSpec}.
9272 *
9273 * @see #getMeasuredWidth()
9274 * @see #getMeasuredHeight()
9275 * @see #setMeasuredDimension(int, int)
9276 * @see #getSuggestedMinimumHeight()
9277 * @see #getSuggestedMinimumWidth()
9278 * @see android.view.View.MeasureSpec#getMode(int)
9279 * @see android.view.View.MeasureSpec#getSize(int)
9280 */
9281 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9282 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
9283 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
9284 }
9285
9286 /**
9287 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
9288 * measured width and measured height. Failing to do so will trigger an
9289 * exception at measurement time.</p>
9290 *
9291 * @param measuredWidth the measured width of this view
9292 * @param measuredHeight the measured height of this view
9293 */
9294 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
9295 mMeasuredWidth = measuredWidth;
9296 mMeasuredHeight = measuredHeight;
9297
9298 mPrivateFlags |= MEASURED_DIMENSION_SET;
9299 }
9300
9301 /**
9302 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
9303 * Will take the desired size, unless a different size is imposed by the constraints.
9304 *
9305 * @param size How big the view wants to be
9306 * @param measureSpec Constraints imposed by the parent
9307 * @return The size this view should be.
9308 */
9309 public static int resolveSize(int size, int measureSpec) {
9310 int result = size;
9311 int specMode = MeasureSpec.getMode(measureSpec);
9312 int specSize = MeasureSpec.getSize(measureSpec);
9313 switch (specMode) {
9314 case MeasureSpec.UNSPECIFIED:
9315 result = size;
9316 break;
9317 case MeasureSpec.AT_MOST:
9318 result = Math.min(size, specSize);
9319 break;
9320 case MeasureSpec.EXACTLY:
9321 result = specSize;
9322 break;
9323 }
9324 return result;
9325 }
9326
9327 /**
9328 * Utility to return a default size. Uses the supplied size if the
9329 * MeasureSpec imposed no contraints. Will get larger if allowed
9330 * by the MeasureSpec.
9331 *
9332 * @param size Default size for this view
9333 * @param measureSpec Constraints imposed by the parent
9334 * @return The size this view should be.
9335 */
9336 public static int getDefaultSize(int size, int measureSpec) {
9337 int result = size;
9338 int specMode = MeasureSpec.getMode(measureSpec);
9339 int specSize = MeasureSpec.getSize(measureSpec);
9340
9341 switch (specMode) {
9342 case MeasureSpec.UNSPECIFIED:
9343 result = size;
9344 break;
9345 case MeasureSpec.AT_MOST:
9346 case MeasureSpec.EXACTLY:
9347 result = specSize;
9348 break;
9349 }
9350 return result;
9351 }
9352
9353 /**
9354 * Returns the suggested minimum height that the view should use. This
9355 * returns the maximum of the view's minimum height
9356 * and the background's minimum height
9357 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
9358 * <p>
9359 * When being used in {@link #onMeasure(int, int)}, the caller should still
9360 * ensure the returned height is within the requirements of the parent.
9361 *
9362 * @return The suggested minimum height of the view.
9363 */
9364 protected int getSuggestedMinimumHeight() {
9365 int suggestedMinHeight = mMinHeight;
9366
9367 if (mBGDrawable != null) {
9368 final int bgMinHeight = mBGDrawable.getMinimumHeight();
9369 if (suggestedMinHeight < bgMinHeight) {
9370 suggestedMinHeight = bgMinHeight;
9371 }
9372 }
9373
9374 return suggestedMinHeight;
9375 }
9376
9377 /**
9378 * Returns the suggested minimum width that the view should use. This
9379 * returns the maximum of the view's minimum width)
9380 * and the background's minimum width
9381 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
9382 * <p>
9383 * When being used in {@link #onMeasure(int, int)}, the caller should still
9384 * ensure the returned width is within the requirements of the parent.
9385 *
9386 * @return The suggested minimum width of the view.
9387 */
9388 protected int getSuggestedMinimumWidth() {
9389 int suggestedMinWidth = mMinWidth;
9390
9391 if (mBGDrawable != null) {
9392 final int bgMinWidth = mBGDrawable.getMinimumWidth();
9393 if (suggestedMinWidth < bgMinWidth) {
9394 suggestedMinWidth = bgMinWidth;
9395 }
9396 }
9397
9398 return suggestedMinWidth;
9399 }
9400
9401 /**
9402 * Sets the minimum height of the view. It is not guaranteed the view will
9403 * be able to achieve this minimum height (for example, if its parent layout
9404 * constrains it with less available height).
9405 *
9406 * @param minHeight The minimum height the view will try to be.
9407 */
9408 public void setMinimumHeight(int minHeight) {
9409 mMinHeight = minHeight;
9410 }
9411
9412 /**
9413 * Sets the minimum width of the view. It is not guaranteed the view will
9414 * be able to achieve this minimum width (for example, if its parent layout
9415 * constrains it with less available width).
9416 *
9417 * @param minWidth The minimum width the view will try to be.
9418 */
9419 public void setMinimumWidth(int minWidth) {
9420 mMinWidth = minWidth;
9421 }
9422
9423 /**
9424 * Get the animation currently associated with this view.
9425 *
9426 * @return The animation that is currently playing or
9427 * scheduled to play for this view.
9428 */
9429 public Animation getAnimation() {
9430 return mCurrentAnimation;
9431 }
9432
9433 /**
9434 * Start the specified animation now.
9435 *
9436 * @param animation the animation to start now
9437 */
9438 public void startAnimation(Animation animation) {
9439 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
9440 setAnimation(animation);
9441 invalidate();
9442 }
9443
9444 /**
9445 * Cancels any animations for this view.
9446 */
9447 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08009448 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08009449 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08009450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009451 mCurrentAnimation = null;
9452 }
9453
9454 /**
9455 * Sets the next animation to play for this view.
9456 * If you want the animation to play immediately, use
9457 * startAnimation. This method provides allows fine-grained
9458 * control over the start time and invalidation, but you
9459 * must make sure that 1) the animation has a start time set, and
9460 * 2) the view will be invalidated when the animation is supposed to
9461 * start.
9462 *
9463 * @param animation The next animation, or null.
9464 */
9465 public void setAnimation(Animation animation) {
9466 mCurrentAnimation = animation;
9467 if (animation != null) {
9468 animation.reset();
9469 }
9470 }
9471
9472 /**
9473 * Invoked by a parent ViewGroup to notify the start of the animation
9474 * currently associated with this view. If you override this method,
9475 * always call super.onAnimationStart();
9476 *
9477 * @see #setAnimation(android.view.animation.Animation)
9478 * @see #getAnimation()
9479 */
9480 protected void onAnimationStart() {
9481 mPrivateFlags |= ANIMATION_STARTED;
9482 }
9483
9484 /**
9485 * Invoked by a parent ViewGroup to notify the end of the animation
9486 * currently associated with this view. If you override this method,
9487 * always call super.onAnimationEnd();
9488 *
9489 * @see #setAnimation(android.view.animation.Animation)
9490 * @see #getAnimation()
9491 */
9492 protected void onAnimationEnd() {
9493 mPrivateFlags &= ~ANIMATION_STARTED;
9494 }
9495
9496 /**
9497 * Invoked if there is a Transform that involves alpha. Subclass that can
9498 * draw themselves with the specified alpha should return true, and then
9499 * respect that alpha when their onDraw() is called. If this returns false
9500 * then the view may be redirected to draw into an offscreen buffer to
9501 * fulfill the request, which will look fine, but may be slower than if the
9502 * subclass handles it internally. The default implementation returns false.
9503 *
9504 * @param alpha The alpha (0..255) to apply to the view's drawing
9505 * @return true if the view can draw with the specified alpha.
9506 */
9507 protected boolean onSetAlpha(int alpha) {
9508 return false;
9509 }
9510
9511 /**
9512 * This is used by the RootView to perform an optimization when
9513 * the view hierarchy contains one or several SurfaceView.
9514 * SurfaceView is always considered transparent, but its children are not,
9515 * therefore all View objects remove themselves from the global transparent
9516 * region (passed as a parameter to this function).
9517 *
9518 * @param region The transparent region for this ViewRoot (window).
9519 *
9520 * @return Returns true if the effective visibility of the view at this
9521 * point is opaque, regardless of the transparent region; returns false
9522 * if it is possible for underlying windows to be seen behind the view.
9523 *
9524 * {@hide}
9525 */
9526 public boolean gatherTransparentRegion(Region region) {
9527 final AttachInfo attachInfo = mAttachInfo;
9528 if (region != null && attachInfo != null) {
9529 final int pflags = mPrivateFlags;
9530 if ((pflags & SKIP_DRAW) == 0) {
9531 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
9532 // remove it from the transparent region.
9533 final int[] location = attachInfo.mTransparentLocation;
9534 getLocationInWindow(location);
9535 region.op(location[0], location[1], location[0] + mRight - mLeft,
9536 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
9537 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
9538 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
9539 // exists, so we remove the background drawable's non-transparent
9540 // parts from this transparent region.
9541 applyDrawableToTransparentRegion(mBGDrawable, region);
9542 }
9543 }
9544 return true;
9545 }
9546
9547 /**
9548 * Play a sound effect for this view.
9549 *
9550 * <p>The framework will play sound effects for some built in actions, such as
9551 * clicking, but you may wish to play these effects in your widget,
9552 * for instance, for internal navigation.
9553 *
9554 * <p>The sound effect will only be played if sound effects are enabled by the user, and
9555 * {@link #isSoundEffectsEnabled()} is true.
9556 *
9557 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
9558 */
9559 public void playSoundEffect(int soundConstant) {
9560 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
9561 return;
9562 }
9563 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
9564 }
9565
9566 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009567 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009568 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009569 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009570 *
9571 * <p>The framework will provide haptic feedback for some built in actions,
9572 * such as long presses, but you may wish to provide feedback for your
9573 * own widget.
9574 *
9575 * <p>The feedback will only be performed if
9576 * {@link #isHapticFeedbackEnabled()} is true.
9577 *
9578 * @param feedbackConstant One of the constants defined in
9579 * {@link HapticFeedbackConstants}
9580 */
9581 public boolean performHapticFeedback(int feedbackConstant) {
9582 return performHapticFeedback(feedbackConstant, 0);
9583 }
9584
9585 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009586 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009587 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009588 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009589 *
9590 * @param feedbackConstant One of the constants defined in
9591 * {@link HapticFeedbackConstants}
9592 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
9593 */
9594 public boolean performHapticFeedback(int feedbackConstant, int flags) {
9595 if (mAttachInfo == null) {
9596 return false;
9597 }
Romain Guyf607bdc2010-09-10 19:20:06 -07009598 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -07009599 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009600 && !isHapticFeedbackEnabled()) {
9601 return false;
9602 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009603 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
9604 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009605 }
9606
9607 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -07009608 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
9609 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -07009610 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -07009611 */
9612 public void onCloseSystemDialogs(String reason) {
9613 }
9614
9615 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009616 * Given a Drawable whose bounds have been set to draw into this view,
9617 * update a Region being computed for {@link #gatherTransparentRegion} so
9618 * that any non-transparent parts of the Drawable are removed from the
9619 * given transparent region.
9620 *
9621 * @param dr The Drawable whose transparency is to be applied to the region.
9622 * @param region A Region holding the current transparency information,
9623 * where any parts of the region that are set are considered to be
9624 * transparent. On return, this region will be modified to have the
9625 * transparency information reduced by the corresponding parts of the
9626 * Drawable that are not transparent.
9627 * {@hide}
9628 */
9629 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
9630 if (DBG) {
9631 Log.i("View", "Getting transparent region for: " + this);
9632 }
9633 final Region r = dr.getTransparentRegion();
9634 final Rect db = dr.getBounds();
9635 final AttachInfo attachInfo = mAttachInfo;
9636 if (r != null && attachInfo != null) {
9637 final int w = getRight()-getLeft();
9638 final int h = getBottom()-getTop();
9639 if (db.left > 0) {
9640 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
9641 r.op(0, 0, db.left, h, Region.Op.UNION);
9642 }
9643 if (db.right < w) {
9644 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
9645 r.op(db.right, 0, w, h, Region.Op.UNION);
9646 }
9647 if (db.top > 0) {
9648 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
9649 r.op(0, 0, w, db.top, Region.Op.UNION);
9650 }
9651 if (db.bottom < h) {
9652 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
9653 r.op(0, db.bottom, w, h, Region.Op.UNION);
9654 }
9655 final int[] location = attachInfo.mTransparentLocation;
9656 getLocationInWindow(location);
9657 r.translate(location[0], location[1]);
9658 region.op(r, Region.Op.INTERSECT);
9659 } else {
9660 region.op(db, Region.Op.DIFFERENCE);
9661 }
9662 }
9663
Adam Powelle14579b2009-12-16 18:39:52 -08009664 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009665 mHasPerformedLongPress = false;
9666
9667 if (mPendingCheckForLongPress == null) {
9668 mPendingCheckForLongPress = new CheckForLongPress();
9669 }
9670 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -08009671 postDelayed(mPendingCheckForLongPress,
9672 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009673 }
9674
Romain Guy812ccbe2010-06-01 14:07:24 -07009675 private static int[] stateSetUnion(final int[] stateSet1, final int[] stateSet2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009676 final int stateSet1Length = stateSet1.length;
9677 final int stateSet2Length = stateSet2.length;
9678 final int[] newSet = new int[stateSet1Length + stateSet2Length];
9679 int k = 0;
9680 int i = 0;
9681 int j = 0;
9682 // This is a merge of the two input state sets and assumes that the
9683 // input sets are sorted by the order imposed by ViewDrawableStates.
9684 for (int viewState : R.styleable.ViewDrawableStates) {
9685 if (i < stateSet1Length && stateSet1[i] == viewState) {
9686 newSet[k++] = viewState;
9687 i++;
9688 } else if (j < stateSet2Length && stateSet2[j] == viewState) {
9689 newSet[k++] = viewState;
9690 j++;
9691 }
9692 if (k > 1) {
9693 assert(newSet[k - 1] > newSet[k - 2]);
9694 }
9695 }
9696 return newSet;
9697 }
9698
9699 /**
9700 * Inflate a view from an XML resource. This convenience method wraps the {@link
9701 * LayoutInflater} class, which provides a full range of options for view inflation.
9702 *
9703 * @param context The Context object for your activity or application.
9704 * @param resource The resource ID to inflate
9705 * @param root A view group that will be the parent. Used to properly inflate the
9706 * layout_* parameters.
9707 * @see LayoutInflater
9708 */
9709 public static View inflate(Context context, int resource, ViewGroup root) {
9710 LayoutInflater factory = LayoutInflater.from(context);
9711 return factory.inflate(resource, root);
9712 }
Romain Guy33e72ae2010-07-17 12:40:29 -07009713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009714 /**
9715 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
9716 * Each MeasureSpec represents a requirement for either the width or the height.
9717 * A MeasureSpec is comprised of a size and a mode. There are three possible
9718 * modes:
9719 * <dl>
9720 * <dt>UNSPECIFIED</dt>
9721 * <dd>
9722 * The parent has not imposed any constraint on the child. It can be whatever size
9723 * it wants.
9724 * </dd>
9725 *
9726 * <dt>EXACTLY</dt>
9727 * <dd>
9728 * The parent has determined an exact size for the child. The child is going to be
9729 * given those bounds regardless of how big it wants to be.
9730 * </dd>
9731 *
9732 * <dt>AT_MOST</dt>
9733 * <dd>
9734 * The child can be as large as it wants up to the specified size.
9735 * </dd>
9736 * </dl>
9737 *
9738 * MeasureSpecs are implemented as ints to reduce object allocation. This class
9739 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
9740 */
9741 public static class MeasureSpec {
9742 private static final int MODE_SHIFT = 30;
9743 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
9744
9745 /**
9746 * Measure specification mode: The parent has not imposed any constraint
9747 * on the child. It can be whatever size it wants.
9748 */
9749 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
9750
9751 /**
9752 * Measure specification mode: The parent has determined an exact size
9753 * for the child. The child is going to be given those bounds regardless
9754 * of how big it wants to be.
9755 */
9756 public static final int EXACTLY = 1 << MODE_SHIFT;
9757
9758 /**
9759 * Measure specification mode: The child can be as large as it wants up
9760 * to the specified size.
9761 */
9762 public static final int AT_MOST = 2 << MODE_SHIFT;
9763
9764 /**
9765 * Creates a measure specification based on the supplied size and mode.
9766 *
9767 * The mode must always be one of the following:
9768 * <ul>
9769 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
9770 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
9771 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
9772 * </ul>
9773 *
9774 * @param size the size of the measure specification
9775 * @param mode the mode of the measure specification
9776 * @return the measure specification based on size and mode
9777 */
9778 public static int makeMeasureSpec(int size, int mode) {
9779 return size + mode;
9780 }
9781
9782 /**
9783 * Extracts the mode from the supplied measure specification.
9784 *
9785 * @param measureSpec the measure specification to extract the mode from
9786 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
9787 * {@link android.view.View.MeasureSpec#AT_MOST} or
9788 * {@link android.view.View.MeasureSpec#EXACTLY}
9789 */
9790 public static int getMode(int measureSpec) {
9791 return (measureSpec & MODE_MASK);
9792 }
9793
9794 /**
9795 * Extracts the size from the supplied measure specification.
9796 *
9797 * @param measureSpec the measure specification to extract the size from
9798 * @return the size in pixels defined in the supplied measure specification
9799 */
9800 public static int getSize(int measureSpec) {
9801 return (measureSpec & ~MODE_MASK);
9802 }
9803
9804 /**
9805 * Returns a String representation of the specified measure
9806 * specification.
9807 *
9808 * @param measureSpec the measure specification to convert to a String
9809 * @return a String with the following format: "MeasureSpec: MODE SIZE"
9810 */
9811 public static String toString(int measureSpec) {
9812 int mode = getMode(measureSpec);
9813 int size = getSize(measureSpec);
9814
9815 StringBuilder sb = new StringBuilder("MeasureSpec: ");
9816
9817 if (mode == UNSPECIFIED)
9818 sb.append("UNSPECIFIED ");
9819 else if (mode == EXACTLY)
9820 sb.append("EXACTLY ");
9821 else if (mode == AT_MOST)
9822 sb.append("AT_MOST ");
9823 else
9824 sb.append(mode).append(" ");
9825
9826 sb.append(size);
9827 return sb.toString();
9828 }
9829 }
9830
9831 class CheckForLongPress implements Runnable {
9832
9833 private int mOriginalWindowAttachCount;
9834
9835 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -07009836 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009837 && mOriginalWindowAttachCount == mWindowAttachCount) {
9838 if (performLongClick()) {
9839 mHasPerformedLongPress = true;
9840 }
9841 }
9842 }
9843
9844 public void rememberWindowAttachCount() {
9845 mOriginalWindowAttachCount = mWindowAttachCount;
9846 }
9847 }
Adam Powelle14579b2009-12-16 18:39:52 -08009848
9849 private final class CheckForTap implements Runnable {
9850 public void run() {
9851 mPrivateFlags &= ~PREPRESSED;
9852 mPrivateFlags |= PRESSED;
9853 refreshDrawableState();
9854 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
9855 postCheckForLongClick(ViewConfiguration.getTapTimeout());
9856 }
9857 }
9858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009859
Adam Powella35d7682010-03-12 14:48:13 -08009860 private final class PerformClick implements Runnable {
9861 public void run() {
9862 performClick();
9863 }
9864 }
9865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009866 /**
9867 * Interface definition for a callback to be invoked when a key event is
9868 * dispatched to this view. The callback will be invoked before the key
9869 * event is given to the view.
9870 */
9871 public interface OnKeyListener {
9872 /**
9873 * Called when a key is dispatched to a view. This allows listeners to
9874 * get a chance to respond before the target view.
9875 *
9876 * @param v The view the key has been dispatched to.
9877 * @param keyCode The code for the physical key that was pressed
9878 * @param event The KeyEvent object containing full information about
9879 * the event.
9880 * @return True if the listener has consumed the event, false otherwise.
9881 */
9882 boolean onKey(View v, int keyCode, KeyEvent event);
9883 }
9884
9885 /**
9886 * Interface definition for a callback to be invoked when a touch event is
9887 * dispatched to this view. The callback will be invoked before the touch
9888 * event is given to the view.
9889 */
9890 public interface OnTouchListener {
9891 /**
9892 * Called when a touch event is dispatched to a view. This allows listeners to
9893 * get a chance to respond before the target view.
9894 *
9895 * @param v The view the touch event has been dispatched to.
9896 * @param event The MotionEvent object containing full information about
9897 * the event.
9898 * @return True if the listener has consumed the event, false otherwise.
9899 */
9900 boolean onTouch(View v, MotionEvent event);
9901 }
9902
9903 /**
9904 * Interface definition for a callback to be invoked when a view has been clicked and held.
9905 */
9906 public interface OnLongClickListener {
9907 /**
9908 * Called when a view has been clicked and held.
9909 *
9910 * @param v The view that was clicked and held.
9911 *
9912 * return True if the callback consumed the long click, false otherwise
9913 */
9914 boolean onLongClick(View v);
9915 }
9916
9917 /**
9918 * Interface definition for a callback to be invoked when the focus state of
9919 * a view changed.
9920 */
9921 public interface OnFocusChangeListener {
9922 /**
9923 * Called when the focus state of a view has changed.
9924 *
9925 * @param v The view whose state has changed.
9926 * @param hasFocus The new focus state of v.
9927 */
9928 void onFocusChange(View v, boolean hasFocus);
9929 }
9930
9931 /**
9932 * Interface definition for a callback to be invoked when a view is clicked.
9933 */
9934 public interface OnClickListener {
9935 /**
9936 * Called when a view has been clicked.
9937 *
9938 * @param v The view that was clicked.
9939 */
9940 void onClick(View v);
9941 }
9942
9943 /**
9944 * Interface definition for a callback to be invoked when the context menu
9945 * for this view is being built.
9946 */
9947 public interface OnCreateContextMenuListener {
9948 /**
9949 * Called when the context menu for this view is being built. It is not
9950 * safe to hold onto the menu after this method returns.
9951 *
9952 * @param menu The context menu that is being built
9953 * @param v The view for which the context menu is being built
9954 * @param menuInfo Extra information about the item for which the
9955 * context menu should be shown. This information will vary
9956 * depending on the class of v.
9957 */
9958 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
9959 }
9960
9961 private final class UnsetPressedState implements Runnable {
9962 public void run() {
9963 setPressed(false);
9964 }
9965 }
9966
9967 /**
9968 * Base class for derived classes that want to save and restore their own
9969 * state in {@link android.view.View#onSaveInstanceState()}.
9970 */
9971 public static class BaseSavedState extends AbsSavedState {
9972 /**
9973 * Constructor used when reading from a parcel. Reads the state of the superclass.
9974 *
9975 * @param source
9976 */
9977 public BaseSavedState(Parcel source) {
9978 super(source);
9979 }
9980
9981 /**
9982 * Constructor called by derived classes when creating their SavedState objects
9983 *
9984 * @param superState The state of the superclass of this view
9985 */
9986 public BaseSavedState(Parcelable superState) {
9987 super(superState);
9988 }
9989
9990 public static final Parcelable.Creator<BaseSavedState> CREATOR =
9991 new Parcelable.Creator<BaseSavedState>() {
9992 public BaseSavedState createFromParcel(Parcel in) {
9993 return new BaseSavedState(in);
9994 }
9995
9996 public BaseSavedState[] newArray(int size) {
9997 return new BaseSavedState[size];
9998 }
9999 };
10000 }
10001
10002 /**
10003 * A set of information given to a view when it is attached to its parent
10004 * window.
10005 */
10006 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010007 interface Callbacks {
10008 void playSoundEffect(int effectId);
10009 boolean performHapticFeedback(int effectId, boolean always);
10010 }
10011
10012 /**
10013 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
10014 * to a Handler. This class contains the target (View) to invalidate and
10015 * the coordinates of the dirty rectangle.
10016 *
10017 * For performance purposes, this class also implements a pool of up to
10018 * POOL_LIMIT objects that get reused. This reduces memory allocations
10019 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010020 */
Romain Guyd928d682009-03-31 17:52:16 -070010021 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010022 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070010023 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
10024 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070010025 public InvalidateInfo newInstance() {
10026 return new InvalidateInfo();
10027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010028
Romain Guyd928d682009-03-31 17:52:16 -070010029 public void onAcquired(InvalidateInfo element) {
10030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010031
Romain Guyd928d682009-03-31 17:52:16 -070010032 public void onReleased(InvalidateInfo element) {
10033 }
10034 }, POOL_LIMIT)
10035 );
10036
10037 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010038
10039 View target;
10040
10041 int left;
10042 int top;
10043 int right;
10044 int bottom;
10045
Romain Guyd928d682009-03-31 17:52:16 -070010046 public void setNextPoolable(InvalidateInfo element) {
10047 mNext = element;
10048 }
10049
10050 public InvalidateInfo getNextPoolable() {
10051 return mNext;
10052 }
10053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010054 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070010055 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010056 }
10057
10058 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070010059 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010060 }
10061 }
10062
10063 final IWindowSession mSession;
10064
10065 final IWindow mWindow;
10066
10067 final IBinder mWindowToken;
10068
10069 final Callbacks mRootCallbacks;
10070
10071 /**
10072 * The top view of the hierarchy.
10073 */
10074 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070010075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010076 IBinder mPanelParentWindowToken;
10077 Surface mSurface;
10078
Romain Guy2bffd262010-09-12 17:40:02 -070010079 boolean mHardwareAccelerated;
10080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010081 /**
Romain Guy8506ab42009-06-11 17:35:47 -070010082 * Scale factor used by the compatibility mode
10083 */
10084 float mApplicationScale;
10085
10086 /**
10087 * Indicates whether the application is in compatibility mode
10088 */
10089 boolean mScalingRequired;
10090
10091 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010092 * Left position of this view's window
10093 */
10094 int mWindowLeft;
10095
10096 /**
10097 * Top position of this view's window
10098 */
10099 int mWindowTop;
10100
10101 /**
Romain Guy35b38ce2009-10-07 13:38:55 -070010102 * Indicates whether the window is translucent/transparent
10103 */
10104 boolean mTranslucentWindow;
10105
10106 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010107 * For windows that are full-screen but using insets to layout inside
10108 * of the screen decorations, these are the current insets for the
10109 * content of the window.
10110 */
10111 final Rect mContentInsets = new Rect();
10112
10113 /**
10114 * For windows that are full-screen but using insets to layout inside
10115 * of the screen decorations, these are the current insets for the
10116 * actual visible parts of the window.
10117 */
10118 final Rect mVisibleInsets = new Rect();
10119
10120 /**
10121 * The internal insets given by this window. This value is
10122 * supplied by the client (through
10123 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
10124 * be given to the window manager when changed to be used in laying
10125 * out windows behind it.
10126 */
10127 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
10128 = new ViewTreeObserver.InternalInsetsInfo();
10129
10130 /**
10131 * All views in the window's hierarchy that serve as scroll containers,
10132 * used to determine if the window can be resized or must be panned
10133 * to adjust for a soft input area.
10134 */
10135 final ArrayList<View> mScrollContainers = new ArrayList<View>();
10136
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070010137 final KeyEvent.DispatcherState mKeyDispatchState
10138 = new KeyEvent.DispatcherState();
10139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010140 /**
10141 * Indicates whether the view's window currently has the focus.
10142 */
10143 boolean mHasWindowFocus;
10144
10145 /**
10146 * The current visibility of the window.
10147 */
10148 int mWindowVisibility;
10149
10150 /**
10151 * Indicates the time at which drawing started to occur.
10152 */
10153 long mDrawingTime;
10154
10155 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070010156 * Indicates whether or not ignoring the DIRTY_MASK flags.
10157 */
10158 boolean mIgnoreDirtyState;
10159
10160 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010161 * Indicates whether the view's window is currently in touch mode.
10162 */
10163 boolean mInTouchMode;
10164
10165 /**
10166 * Indicates that ViewRoot should trigger a global layout change
10167 * the next time it performs a traversal
10168 */
10169 boolean mRecomputeGlobalAttributes;
10170
10171 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010172 * Set during a traveral if any views want to keep the screen on.
10173 */
10174 boolean mKeepScreenOn;
10175
10176 /**
10177 * Set if the visibility of any views has changed.
10178 */
10179 boolean mViewVisibilityChanged;
10180
10181 /**
10182 * Set to true if a view has been scrolled.
10183 */
10184 boolean mViewScrollChanged;
10185
10186 /**
10187 * Global to the view hierarchy used as a temporary for dealing with
10188 * x/y points in the transparent region computations.
10189 */
10190 final int[] mTransparentLocation = new int[2];
10191
10192 /**
10193 * Global to the view hierarchy used as a temporary for dealing with
10194 * x/y points in the ViewGroup.invalidateChild implementation.
10195 */
10196 final int[] mInvalidateChildLocation = new int[2];
10197
Chet Haasec3aa3612010-06-17 08:50:37 -070010198
10199 /**
10200 * Global to the view hierarchy used as a temporary for dealing with
10201 * x/y location when view is transformed.
10202 */
10203 final float[] mTmpTransformLocation = new float[2];
10204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010205 /**
10206 * The view tree observer used to dispatch global events like
10207 * layout, pre-draw, touch mode change, etc.
10208 */
10209 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
10210
10211 /**
10212 * A Canvas used by the view hierarchy to perform bitmap caching.
10213 */
10214 Canvas mCanvas;
10215
10216 /**
10217 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
10218 * handler can be used to pump events in the UI events queue.
10219 */
10220 final Handler mHandler;
10221
10222 /**
10223 * Identifier for messages requesting the view to be invalidated.
10224 * Such messages should be sent to {@link #mHandler}.
10225 */
10226 static final int INVALIDATE_MSG = 0x1;
10227
10228 /**
10229 * Identifier for messages requesting the view to invalidate a region.
10230 * Such messages should be sent to {@link #mHandler}.
10231 */
10232 static final int INVALIDATE_RECT_MSG = 0x2;
10233
10234 /**
10235 * Temporary for use in computing invalidate rectangles while
10236 * calling up the hierarchy.
10237 */
10238 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070010239
10240 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070010241 * Temporary for use in computing hit areas with transformed views
10242 */
10243 final RectF mTmpTransformRect = new RectF();
10244
10245 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070010246 * Temporary list for use in collecting focusable descendents of a view.
10247 */
10248 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
10249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010250 /**
10251 * Creates a new set of attachment information with the specified
10252 * events handler and thread.
10253 *
10254 * @param handler the events handler the view must use
10255 */
10256 AttachInfo(IWindowSession session, IWindow window,
10257 Handler handler, Callbacks effectPlayer) {
10258 mSession = session;
10259 mWindow = window;
10260 mWindowToken = window.asBinder();
10261 mHandler = handler;
10262 mRootCallbacks = effectPlayer;
10263 }
10264 }
10265
10266 /**
10267 * <p>ScrollabilityCache holds various fields used by a View when scrolling
10268 * is supported. This avoids keeping too many unused fields in most
10269 * instances of View.</p>
10270 */
Mike Cleronf116bf82009-09-27 19:14:12 -070010271 private static class ScrollabilityCache implements Runnable {
10272
10273 /**
10274 * Scrollbars are not visible
10275 */
10276 public static final int OFF = 0;
10277
10278 /**
10279 * Scrollbars are visible
10280 */
10281 public static final int ON = 1;
10282
10283 /**
10284 * Scrollbars are fading away
10285 */
10286 public static final int FADING = 2;
10287
10288 public boolean fadeScrollBars;
10289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010290 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070010291 public int scrollBarDefaultDelayBeforeFade;
10292 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010293
10294 public int scrollBarSize;
10295 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070010296 public float[] interpolatorValues;
10297 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010298
10299 public final Paint paint;
10300 public final Matrix matrix;
10301 public Shader shader;
10302
Mike Cleronf116bf82009-09-27 19:14:12 -070010303 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
10304
Romain Guy8fb95422010-08-17 18:38:51 -070010305 private final float[] mOpaque = { 255.0f };
10306 private final float[] mTransparent = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070010307
10308 /**
10309 * When fading should start. This time moves into the future every time
10310 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
10311 */
10312 public long fadeStartTime;
10313
10314
10315 /**
10316 * The current state of the scrollbars: ON, OFF, or FADING
10317 */
10318 public int state = OFF;
10319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010320 private int mLastColor;
10321
Mike Cleronf116bf82009-09-27 19:14:12 -070010322 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010323 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
10324 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070010325 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
10326 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010327
10328 paint = new Paint();
10329 matrix = new Matrix();
10330 // use use a height of 1, and then wack the matrix each time we
10331 // actually use it.
10332 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010334 paint.setShader(shader);
10335 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070010336 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010337 }
Romain Guy8506ab42009-06-11 17:35:47 -070010338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010339 public void setFadeColor(int color) {
10340 if (color != 0 && color != mLastColor) {
10341 mLastColor = color;
10342 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070010343
Romain Guye55e1a72009-08-27 10:42:26 -070010344 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
10345 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010347 paint.setShader(shader);
10348 // Restore the default transfer mode (src_over)
10349 paint.setXfermode(null);
10350 }
10351 }
Mike Cleronf116bf82009-09-27 19:14:12 -070010352
10353 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070010354 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070010355 if (now >= fadeStartTime) {
10356
10357 // the animation fades the scrollbars out by changing
10358 // the opacity (alpha) from fully opaque to fully
10359 // transparent
10360 int nextFrame = (int) now;
10361 int framesCount = 0;
10362
10363 Interpolator interpolator = scrollBarInterpolator;
10364
10365 // Start opaque
10366 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
10367
10368 // End transparent
10369 nextFrame += scrollBarFadeDuration;
10370 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
10371
10372 state = FADING;
10373
10374 // Kick off the fade animation
10375 host.invalidate();
10376 }
10377 }
10378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010379 }
10380}