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