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