blob: 7c644e41b946b09363640378c6032be2a7c98b58 [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
svetoslavganov75986cf2009-05-14 22:28:01 -070019import com.android.internal.R;
20import com.android.internal.view.menu.MenuBuilder;
21
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080023import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.res.Resources;
25import android.content.res.TypedArray;
26import android.graphics.Bitmap;
27import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070028import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.graphics.LinearGradient;
30import android.graphics.Matrix;
31import android.graphics.Paint;
32import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070033import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.graphics.PorterDuff;
35import android.graphics.PorterDuffXfermode;
36import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070037import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.graphics.Region;
39import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.graphics.drawable.ColorDrawable;
41import android.graphics.drawable.Drawable;
42import android.os.Handler;
43import android.os.IBinder;
44import android.os.Message;
45import android.os.Parcel;
46import android.os.Parcelable;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.os.SystemProperties;
50import android.util.AttributeSet;
svetoslavganov75986cf2009-05-14 22:28:01 -070051import android.util.Config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.util.EventLog;
53import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070054import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070055import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070056import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070057import android.util.Pools;
58import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.ContextMenu.ContextMenuInfo;
Adam Powell6e346362010-07-23 10:18:23 -070060import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070061import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070065import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070066import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.view.inputmethod.InputConnection;
68import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.widget.ScrollBarDrawable;
70
svetoslavganov75986cf2009-05-14 22:28:01 -070071import java.lang.ref.SoftReference;
72import java.lang.reflect.InvocationTargetException;
73import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import java.util.ArrayList;
75import java.util.Arrays;
Romain Guyd90a3312009-05-06 14:54:28 -070076import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077
78/**
79 * <p>
80 * This class represents the basic building block for user interface components. A View
81 * occupies a rectangular area on the screen and is responsible for drawing and
82 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070083 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
85 * are invisible containers that hold other Views (or other ViewGroups) and define
86 * their layout properties.
87 * </p>
88 *
89 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070090 * <p>For an introduction to using this class to develop your
91 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070093 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
95 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
102 * </p>
103 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700104 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 * <a name="Using"></a>
106 * <h3>Using Views</h3>
107 * <p>
108 * All of the views in a window are arranged in a single tree. You can add views
109 * either from code or by specifying a tree of views in one or more XML layout
110 * files. There are many specialized subclasses of views that act as controls or
111 * are capable of displaying text, images, or other content.
112 * </p>
113 * <p>
114 * Once you have created a tree of views, there are typically a few types of
115 * common operations you may wish to perform:
116 * <ul>
117 * <li><strong>Set properties:</strong> for example setting the text of a
118 * {@link android.widget.TextView}. The available properties and the methods
119 * that set them will vary among the different subclasses of views. Note that
120 * properties that are known at build time can be set in the XML layout
121 * files.</li>
122 * <li><strong>Set focus:</strong> The framework will handled moving focus in
123 * response to user input. To force focus to a specific view, call
124 * {@link #requestFocus}.</li>
125 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
126 * that will be notified when something interesting happens to the view. For
127 * example, all views will let you set a listener to be notified when the view
128 * gains or loses focus. You can register such a listener using
129 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
130 * specialized listeners. For example, a Button exposes a listener to notify
131 * clients when the button is clicked.</li>
132 * <li><strong>Set visibility:</strong> You can hide or show views using
133 * {@link #setVisibility}.</li>
134 * </ul>
135 * </p>
136 * <p><em>
137 * Note: The Android framework is responsible for measuring, laying out and
138 * drawing views. You should not call methods that perform these actions on
139 * views yourself unless you are actually implementing a
140 * {@link android.view.ViewGroup}.
141 * </em></p>
142 *
143 * <a name="Lifecycle"></a>
144 * <h3>Implementing a Custom View</h3>
145 *
146 * <p>
147 * To implement a custom view, you will usually begin by providing overrides for
148 * some of the standard methods that the framework calls on all views. You do
149 * not need to override all of these methods. In fact, you can start by just
150 * overriding {@link #onDraw(android.graphics.Canvas)}.
151 * <table border="2" width="85%" align="center" cellpadding="5">
152 * <thead>
153 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
154 * </thead>
155 *
156 * <tbody>
157 * <tr>
158 * <td rowspan="2">Creation</td>
159 * <td>Constructors</td>
160 * <td>There is a form of the constructor that are called when the view
161 * is created from code and a form that is called when the view is
162 * inflated from a layout file. The second form should parse and apply
163 * any attributes defined in the layout file.
164 * </td>
165 * </tr>
166 * <tr>
167 * <td><code>{@link #onFinishInflate()}</code></td>
168 * <td>Called after a view and all of its children has been inflated
169 * from XML.</td>
170 * </tr>
171 *
172 * <tr>
173 * <td rowspan="3">Layout</td>
174 * <td><code>{@link #onMeasure}</code></td>
175 * <td>Called to determine the size requirements for this view and all
176 * of its children.
177 * </td>
178 * </tr>
179 * <tr>
180 * <td><code>{@link #onLayout}</code></td>
181 * <td>Called when this view should assign a size and position to all
182 * of its children.
183 * </td>
184 * </tr>
185 * <tr>
186 * <td><code>{@link #onSizeChanged}</code></td>
187 * <td>Called when the size of this view has changed.
188 * </td>
189 * </tr>
190 *
191 * <tr>
192 * <td>Drawing</td>
193 * <td><code>{@link #onDraw}</code></td>
194 * <td>Called when the view should render its content.
195 * </td>
196 * </tr>
197 *
198 * <tr>
199 * <td rowspan="4">Event processing</td>
200 * <td><code>{@link #onKeyDown}</code></td>
201 * <td>Called when a new key event occurs.
202 * </td>
203 * </tr>
204 * <tr>
205 * <td><code>{@link #onKeyUp}</code></td>
206 * <td>Called when a key up event occurs.
207 * </td>
208 * </tr>
209 * <tr>
210 * <td><code>{@link #onTrackballEvent}</code></td>
211 * <td>Called when a trackball motion event occurs.
212 * </td>
213 * </tr>
214 * <tr>
215 * <td><code>{@link #onTouchEvent}</code></td>
216 * <td>Called when a touch screen motion event occurs.
217 * </td>
218 * </tr>
219 *
220 * <tr>
221 * <td rowspan="2">Focus</td>
222 * <td><code>{@link #onFocusChanged}</code></td>
223 * <td>Called when the view gains or loses focus.
224 * </td>
225 * </tr>
226 *
227 * <tr>
228 * <td><code>{@link #onWindowFocusChanged}</code></td>
229 * <td>Called when the window containing the view gains or loses focus.
230 * </td>
231 * </tr>
232 *
233 * <tr>
234 * <td rowspan="3">Attaching</td>
235 * <td><code>{@link #onAttachedToWindow()}</code></td>
236 * <td>Called when the view is attached to a window.
237 * </td>
238 * </tr>
239 *
240 * <tr>
241 * <td><code>{@link #onDetachedFromWindow}</code></td>
242 * <td>Called when the view is detached from its window.
243 * </td>
244 * </tr>
245 *
246 * <tr>
247 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
248 * <td>Called when the visibility of the window containing the view
249 * has changed.
250 * </td>
251 * </tr>
252 * </tbody>
253 *
254 * </table>
255 * </p>
256 *
257 * <a name="IDs"></a>
258 * <h3>IDs</h3>
259 * Views may have an integer id associated with them. These ids are typically
260 * assigned in the layout XML files, and are used to find specific views within
261 * the view tree. A common pattern is to:
262 * <ul>
263 * <li>Define a Button in the layout file and assign it a unique ID.
264 * <pre>
265 * &lt;Button id="@+id/my_button"
266 * android:layout_width="wrap_content"
267 * android:layout_height="wrap_content"
268 * android:text="@string/my_button_text"/&gt;
269 * </pre></li>
270 * <li>From the onCreate method of an Activity, find the Button
271 * <pre class="prettyprint">
272 * Button myButton = (Button) findViewById(R.id.my_button);
273 * </pre></li>
274 * </ul>
275 * <p>
276 * View IDs need not be unique throughout the tree, but it is good practice to
277 * ensure that they are at least unique within the part of the tree you are
278 * searching.
279 * </p>
280 *
281 * <a name="Position"></a>
282 * <h3>Position</h3>
283 * <p>
284 * The geometry of a view is that of a rectangle. A view has a location,
285 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
286 * two dimensions, expressed as a width and a height. The unit for location
287 * and dimensions is the pixel.
288 * </p>
289 *
290 * <p>
291 * It is possible to retrieve the location of a view by invoking the methods
292 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
293 * coordinate of the rectangle representing the view. The latter returns the
294 * top, or Y, coordinate of the rectangle representing the view. These methods
295 * both return the location of the view relative to its parent. For instance,
296 * when getLeft() returns 20, that means the view is located 20 pixels to the
297 * right of the left edge of its direct parent.
298 * </p>
299 *
300 * <p>
301 * In addition, several convenience methods are offered to avoid unnecessary
302 * computations, namely {@link #getRight()} and {@link #getBottom()}.
303 * These methods return the coordinates of the right and bottom edges of the
304 * rectangle representing the view. For instance, calling {@link #getRight()}
305 * is similar to the following computation: <code>getLeft() + getWidth()</code>
306 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
307 * </p>
308 *
309 * <a name="SizePaddingMargins"></a>
310 * <h3>Size, padding and margins</h3>
311 * <p>
312 * The size of a view is expressed with a width and a height. A view actually
313 * possess two pairs of width and height values.
314 * </p>
315 *
316 * <p>
317 * The first pair is known as <em>measured width</em> and
318 * <em>measured height</em>. These dimensions define how big a view wants to be
319 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
320 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
321 * and {@link #getMeasuredHeight()}.
322 * </p>
323 *
324 * <p>
325 * The second pair is simply known as <em>width</em> and <em>height</em>, or
326 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
327 * dimensions define the actual size of the view on screen, at drawing time and
328 * after layout. These values may, but do not have to, be different from the
329 * measured width and height. The width and height can be obtained by calling
330 * {@link #getWidth()} and {@link #getHeight()}.
331 * </p>
332 *
333 * <p>
334 * To measure its dimensions, a view takes into account its padding. The padding
335 * is expressed in pixels for the left, top, right and bottom parts of the view.
336 * Padding can be used to offset the content of the view by a specific amount of
337 * pixels. For instance, a left padding of 2 will push the view's content by
338 * 2 pixels to the right of the left edge. Padding can be set using the
339 * {@link #setPadding(int, int, int, int)} method and queried by calling
340 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
341 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
342 * </p>
343 *
344 * <p>
345 * Even though a view can define a padding, it does not provide any support for
346 * margins. However, view groups provide such a support. Refer to
347 * {@link android.view.ViewGroup} and
348 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
349 * </p>
350 *
351 * <a name="Layout"></a>
352 * <h3>Layout</h3>
353 * <p>
354 * Layout is a two pass process: a measure pass and a layout pass. The measuring
355 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
356 * of the view tree. Each view pushes dimension specifications down the tree
357 * during the recursion. At the end of the measure pass, every view has stored
358 * its measurements. The second pass happens in
359 * {@link #layout(int,int,int,int)} and is also top-down. During
360 * this pass each parent is responsible for positioning all of its children
361 * using the sizes computed in the measure pass.
362 * </p>
363 *
364 * <p>
365 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
366 * {@link #getMeasuredHeight()} values must be set, along with those for all of
367 * that view's descendants. A view's measured width and measured height values
368 * must respect the constraints imposed by the view's parents. This guarantees
369 * that at the end of the measure pass, all parents accept all of their
370 * children's measurements. A parent view may call measure() more than once on
371 * its children. For example, the parent may measure each child once with
372 * unspecified dimensions to find out how big they want to be, then call
373 * measure() on them again with actual numbers if the sum of all the children's
374 * unconstrained sizes is too big or too small.
375 * </p>
376 *
377 * <p>
378 * The measure pass uses two classes to communicate dimensions. The
379 * {@link MeasureSpec} class is used by views to tell their parents how they
380 * want to be measured and positioned. The base LayoutParams class just
381 * describes how big the view wants to be for both width and height. For each
382 * dimension, it can specify one of:
383 * <ul>
384 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800385 * <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 -0800386 * (minus padding)
387 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
388 * enclose its content (plus padding).
389 * </ul>
390 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
391 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
392 * an X and Y value.
393 * </p>
394 *
395 * <p>
396 * MeasureSpecs are used to push requirements down the tree from parent to
397 * child. A MeasureSpec can be in one of three modes:
398 * <ul>
399 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
400 * of a child view. For example, a LinearLayout may call measure() on its child
401 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
402 * tall the child view wants to be given a width of 240 pixels.
403 * <li>EXACTLY: This is used by the parent to impose an exact size on the
404 * child. The child must use this size, and guarantee that all of its
405 * descendants will fit within this size.
406 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
407 * child. The child must gurantee that it and all of its descendants will fit
408 * within this size.
409 * </ul>
410 * </p>
411 *
412 * <p>
413 * To intiate a layout, call {@link #requestLayout}. This method is typically
414 * called by a view on itself when it believes that is can no longer fit within
415 * its current bounds.
416 * </p>
417 *
418 * <a name="Drawing"></a>
419 * <h3>Drawing</h3>
420 * <p>
421 * Drawing is handled by walking the tree and rendering each view that
422 * intersects the the invalid region. Because the tree is traversed in-order,
423 * this means that parents will draw before (i.e., behind) their children, with
424 * siblings drawn in the order they appear in the tree.
425 * If you set a background drawable for a View, then the View will draw it for you
426 * before calling back to its <code>onDraw()</code> method.
427 * </p>
428 *
429 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700430 * 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 -0800431 * </p>
432 *
433 * <p>
434 * To force a view to draw, call {@link #invalidate()}.
435 * </p>
436 *
437 * <a name="EventHandlingThreading"></a>
438 * <h3>Event Handling and Threading</h3>
439 * <p>
440 * The basic cycle of a view is as follows:
441 * <ol>
442 * <li>An event comes in and is dispatched to the appropriate view. The view
443 * handles the event and notifies any listeners.</li>
444 * <li>If in the course of processing the event, the view's bounds may need
445 * to be changed, the view will call {@link #requestLayout()}.</li>
446 * <li>Similarly, if in the course of processing the event the view's appearance
447 * may need to be changed, the view will call {@link #invalidate()}.</li>
448 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
449 * the framework will take care of measuring, laying out, and drawing the tree
450 * as appropriate.</li>
451 * </ol>
452 * </p>
453 *
454 * <p><em>Note: The entire view tree is single threaded. You must always be on
455 * the UI thread when calling any method on any view.</em>
456 * If you are doing work on other threads and want to update the state of a view
457 * from that thread, you should use a {@link Handler}.
458 * </p>
459 *
460 * <a name="FocusHandling"></a>
461 * <h3>Focus Handling</h3>
462 * <p>
463 * The framework will handle routine focus movement in response to user input.
464 * This includes changing the focus as views are removed or hidden, or as new
465 * views become available. Views indicate their willingness to take focus
466 * through the {@link #isFocusable} method. To change whether a view can take
467 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
468 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
469 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
470 * </p>
471 * <p>
472 * Focus movement is based on an algorithm which finds the nearest neighbor in a
473 * given direction. In rare cases, the default algorithm may not match the
474 * intended behavior of the developer. In these situations, you can provide
475 * explicit overrides by using these XML attributes in the layout file:
476 * <pre>
477 * nextFocusDown
478 * nextFocusLeft
479 * nextFocusRight
480 * nextFocusUp
481 * </pre>
482 * </p>
483 *
484 *
485 * <p>
486 * To get a particular view to take focus, call {@link #requestFocus()}.
487 * </p>
488 *
489 * <a name="TouchMode"></a>
490 * <h3>Touch Mode</h3>
491 * <p>
492 * When a user is navigating a user interface via directional keys such as a D-pad, it is
493 * necessary to give focus to actionable items such as buttons so the user can see
494 * what will take input. If the device has touch capabilities, however, and the user
495 * begins interacting with the interface by touching it, it is no longer necessary to
496 * always highlight, or give focus to, a particular view. This motivates a mode
497 * for interaction named 'touch mode'.
498 * </p>
499 * <p>
500 * For a touch capable device, once the user touches the screen, the device
501 * will enter touch mode. From this point onward, only views for which
502 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
503 * Other views that are touchable, like buttons, will not take focus when touched; they will
504 * only fire the on click listeners.
505 * </p>
506 * <p>
507 * Any time a user hits a directional key, such as a D-pad direction, the view device will
508 * exit touch mode, and find a view to take focus, so that the user may resume interacting
509 * with the user interface without touching the screen again.
510 * </p>
511 * <p>
512 * The touch mode state is maintained across {@link android.app.Activity}s. Call
513 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
514 * </p>
515 *
516 * <a name="Scrolling"></a>
517 * <h3>Scrolling</h3>
518 * <p>
519 * The framework provides basic support for views that wish to internally
520 * scroll their content. This includes keeping track of the X and Y scroll
521 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700522 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
523 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 * </p>
525 *
526 * <a name="Tags"></a>
527 * <h3>Tags</h3>
528 * <p>
529 * Unlike IDs, tags are not used to identify views. Tags are essentially an
530 * extra piece of information that can be associated with a view. They are most
531 * often used as a convenience to store data related to views in the views
532 * themselves rather than by putting them in a separate structure.
533 * </p>
534 *
535 * <a name="Animation"></a>
536 * <h3>Animation</h3>
537 * <p>
538 * You can attach an {@link Animation} object to a view using
539 * {@link #setAnimation(Animation)} or
540 * {@link #startAnimation(Animation)}. The animation can alter the scale,
541 * rotation, translation and alpha of a view over time. If the animation is
542 * attached to a view that has children, the animation will affect the entire
543 * subtree rooted by that node. When an animation is started, the framework will
544 * take care of redrawing the appropriate views until the animation completes.
545 * </p>
546 *
Romain Guyd6a463a2009-05-21 23:10:10 -0700547 * @attr ref android.R.styleable#View_background
548 * @attr ref android.R.styleable#View_clickable
549 * @attr ref android.R.styleable#View_contentDescription
550 * @attr ref android.R.styleable#View_drawingCacheQuality
551 * @attr ref android.R.styleable#View_duplicateParentState
552 * @attr ref android.R.styleable#View_id
553 * @attr ref android.R.styleable#View_fadingEdge
554 * @attr ref android.R.styleable#View_fadingEdgeLength
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700556 * @attr ref android.R.styleable#View_isScrollContainer
557 * @attr ref android.R.styleable#View_focusable
558 * @attr ref android.R.styleable#View_focusableInTouchMode
559 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
560 * @attr ref android.R.styleable#View_keepScreenOn
561 * @attr ref android.R.styleable#View_longClickable
562 * @attr ref android.R.styleable#View_minHeight
563 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 * @attr ref android.R.styleable#View_nextFocusDown
565 * @attr ref android.R.styleable#View_nextFocusLeft
566 * @attr ref android.R.styleable#View_nextFocusRight
567 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700568 * @attr ref android.R.styleable#View_onClick
569 * @attr ref android.R.styleable#View_padding
570 * @attr ref android.R.styleable#View_paddingBottom
571 * @attr ref android.R.styleable#View_paddingLeft
572 * @attr ref android.R.styleable#View_paddingRight
573 * @attr ref android.R.styleable#View_paddingTop
574 * @attr ref android.R.styleable#View_saveEnabled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 * @attr ref android.R.styleable#View_scrollX
576 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700577 * @attr ref android.R.styleable#View_scrollbarSize
578 * @attr ref android.R.styleable#View_scrollbarStyle
579 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700580 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
581 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
583 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 * @attr ref android.R.styleable#View_scrollbarThumbVertical
585 * @attr ref android.R.styleable#View_scrollbarTrackVertical
586 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
587 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700588 * @attr ref android.R.styleable#View_soundEffectsEnabled
589 * @attr ref android.R.styleable#View_tag
590 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 *
592 * @see android.view.ViewGroup
593 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700594public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 private static final boolean DBG = false;
596
597 /**
598 * The logging tag used by this class with android.util.Log.
599 */
600 protected static final String VIEW_LOG_TAG = "View";
601
602 /**
603 * Used to mark a View that has no ID.
604 */
605 public static final int NO_ID = -1;
606
607 /**
608 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
609 * calling setFlags.
610 */
611 private static final int NOT_FOCUSABLE = 0x00000000;
612
613 /**
614 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
615 * setFlags.
616 */
617 private static final int FOCUSABLE = 0x00000001;
618
619 /**
620 * Mask for use with setFlags indicating bits used for focus.
621 */
622 private static final int FOCUSABLE_MASK = 0x00000001;
623
624 /**
625 * This view will adjust its padding to fit sytem windows (e.g. status bar)
626 */
627 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
628
629 /**
630 * This view is visible. Use with {@link #setVisibility}.
631 */
632 public static final int VISIBLE = 0x00000000;
633
634 /**
635 * This view is invisible, but it still takes up space for layout purposes.
636 * Use with {@link #setVisibility}.
637 */
638 public static final int INVISIBLE = 0x00000004;
639
640 /**
641 * This view is invisible, and it doesn't take any space for layout
642 * purposes. Use with {@link #setVisibility}.
643 */
644 public static final int GONE = 0x00000008;
645
646 /**
647 * Mask for use with setFlags indicating bits used for visibility.
648 * {@hide}
649 */
650 static final int VISIBILITY_MASK = 0x0000000C;
651
652 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
653
654 /**
655 * This view is enabled. Intrepretation varies by subclass.
656 * Use with ENABLED_MASK when calling setFlags.
657 * {@hide}
658 */
659 static final int ENABLED = 0x00000000;
660
661 /**
662 * This view is disabled. Intrepretation varies by subclass.
663 * Use with ENABLED_MASK when calling setFlags.
664 * {@hide}
665 */
666 static final int DISABLED = 0x00000020;
667
668 /**
669 * Mask for use with setFlags indicating bits used for indicating whether
670 * this view is enabled
671 * {@hide}
672 */
673 static final int ENABLED_MASK = 0x00000020;
674
675 /**
676 * This view won't draw. {@link #onDraw} won't be called and further
677 * optimizations
678 * will be performed. It is okay to have this flag set and a background.
679 * Use with DRAW_MASK when calling setFlags.
680 * {@hide}
681 */
682 static final int WILL_NOT_DRAW = 0x00000080;
683
684 /**
685 * Mask for use with setFlags indicating bits used for indicating whether
686 * this view is will draw
687 * {@hide}
688 */
689 static final int DRAW_MASK = 0x00000080;
690
691 /**
692 * <p>This view doesn't show scrollbars.</p>
693 * {@hide}
694 */
695 static final int SCROLLBARS_NONE = 0x00000000;
696
697 /**
698 * <p>This view shows horizontal scrollbars.</p>
699 * {@hide}
700 */
701 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
702
703 /**
704 * <p>This view shows vertical scrollbars.</p>
705 * {@hide}
706 */
707 static final int SCROLLBARS_VERTICAL = 0x00000200;
708
709 /**
710 * <p>Mask for use with setFlags indicating bits used for indicating which
711 * scrollbars are enabled.</p>
712 * {@hide}
713 */
714 static final int SCROLLBARS_MASK = 0x00000300;
715
716 // note 0x00000400 and 0x00000800 are now available for next flags...
717
718 /**
719 * <p>This view doesn't show fading edges.</p>
720 * {@hide}
721 */
722 static final int FADING_EDGE_NONE = 0x00000000;
723
724 /**
725 * <p>This view shows horizontal fading edges.</p>
726 * {@hide}
727 */
728 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
729
730 /**
731 * <p>This view shows vertical fading edges.</p>
732 * {@hide}
733 */
734 static final int FADING_EDGE_VERTICAL = 0x00002000;
735
736 /**
737 * <p>Mask for use with setFlags indicating bits used for indicating which
738 * fading edges are enabled.</p>
739 * {@hide}
740 */
741 static final int FADING_EDGE_MASK = 0x00003000;
742
743 /**
744 * <p>Indicates this view can be clicked. When clickable, a View reacts
745 * to clicks by notifying the OnClickListener.<p>
746 * {@hide}
747 */
748 static final int CLICKABLE = 0x00004000;
749
750 /**
751 * <p>Indicates this view is caching its drawing into a bitmap.</p>
752 * {@hide}
753 */
754 static final int DRAWING_CACHE_ENABLED = 0x00008000;
755
756 /**
757 * <p>Indicates that no icicle should be saved for this view.<p>
758 * {@hide}
759 */
760 static final int SAVE_DISABLED = 0x000010000;
761
762 /**
763 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
764 * property.</p>
765 * {@hide}
766 */
767 static final int SAVE_DISABLED_MASK = 0x000010000;
768
769 /**
770 * <p>Indicates that no drawing cache should ever be created for this view.<p>
771 * {@hide}
772 */
773 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
774
775 /**
776 * <p>Indicates this view can take / keep focus when int touch mode.</p>
777 * {@hide}
778 */
779 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
780
781 /**
782 * <p>Enables low quality mode for the drawing cache.</p>
783 */
784 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
785
786 /**
787 * <p>Enables high quality mode for the drawing cache.</p>
788 */
789 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
790
791 /**
792 * <p>Enables automatic quality mode for the drawing cache.</p>
793 */
794 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
795
796 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
797 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
798 };
799
800 /**
801 * <p>Mask for use with setFlags indicating bits used for the cache
802 * quality property.</p>
803 * {@hide}
804 */
805 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
806
807 /**
808 * <p>
809 * Indicates this view can be long clicked. When long clickable, a View
810 * reacts to long clicks by notifying the OnLongClickListener or showing a
811 * context menu.
812 * </p>
813 * {@hide}
814 */
815 static final int LONG_CLICKABLE = 0x00200000;
816
817 /**
818 * <p>Indicates that this view gets its drawable states from its direct parent
819 * and ignores its original internal states.</p>
820 *
821 * @hide
822 */
823 static final int DUPLICATE_PARENT_STATE = 0x00400000;
824
825 /**
826 * The scrollbar style to display the scrollbars inside the content area,
827 * without increasing the padding. The scrollbars will be overlaid with
828 * translucency on the view's content.
829 */
830 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
831
832 /**
833 * The scrollbar style to display the scrollbars inside the padded area,
834 * increasing the padding of the view. The scrollbars will not overlap the
835 * content area of the view.
836 */
837 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
838
839 /**
840 * The scrollbar style to display the scrollbars at the edge of the view,
841 * without increasing the padding. The scrollbars will be overlaid with
842 * translucency.
843 */
844 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
845
846 /**
847 * The scrollbar style to display the scrollbars at the edge of the view,
848 * increasing the padding of the view. The scrollbars will only overlap the
849 * background, if any.
850 */
851 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
852
853 /**
854 * Mask to check if the scrollbar style is overlay or inset.
855 * {@hide}
856 */
857 static final int SCROLLBARS_INSET_MASK = 0x01000000;
858
859 /**
860 * Mask to check if the scrollbar style is inside or outside.
861 * {@hide}
862 */
863 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
864
865 /**
866 * Mask for scrollbar style.
867 * {@hide}
868 */
869 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
870
871 /**
872 * View flag indicating that the screen should remain on while the
873 * window containing this view is visible to the user. This effectively
874 * takes care of automatically setting the WindowManager's
875 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
876 */
877 public static final int KEEP_SCREEN_ON = 0x04000000;
878
879 /**
880 * View flag indicating whether this view should have sound effects enabled
881 * for events such as clicking and touching.
882 */
883 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
884
885 /**
886 * View flag indicating whether this view should have haptic feedback
887 * enabled for events such as long presses.
888 */
889 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
890
891 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700892 * <p>Indicates that the view hierarchy should stop saving state when
893 * it reaches this view. If state saving is initiated immediately at
894 * the view, it will be allowed.
895 * {@hide}
896 */
897 static final int PARENT_SAVE_DISABLED = 0x20000000;
898
899 /**
900 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
901 * {@hide}
902 */
903 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
904
905 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700906 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
907 * should add all focusable Views regardless if they are focusable in touch mode.
908 */
909 public static final int FOCUSABLES_ALL = 0x00000000;
910
911 /**
912 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
913 * should add only Views focusable in touch mode.
914 */
915 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
916
917 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 * Use with {@link #focusSearch}. Move focus to the previous selectable
919 * item.
920 */
921 public static final int FOCUS_BACKWARD = 0x00000001;
922
923 /**
924 * Use with {@link #focusSearch}. Move focus to the next selectable
925 * item.
926 */
927 public static final int FOCUS_FORWARD = 0x00000002;
928
929 /**
930 * Use with {@link #focusSearch}. Move focus to the left.
931 */
932 public static final int FOCUS_LEFT = 0x00000011;
933
934 /**
935 * Use with {@link #focusSearch}. Move focus up.
936 */
937 public static final int FOCUS_UP = 0x00000021;
938
939 /**
940 * Use with {@link #focusSearch}. Move focus to the right.
941 */
942 public static final int FOCUS_RIGHT = 0x00000042;
943
944 /**
945 * Use with {@link #focusSearch}. Move focus down.
946 */
947 public static final int FOCUS_DOWN = 0x00000082;
948
949 /**
950 * Base View state sets
951 */
952 // Singles
953 /**
954 * Indicates the view has no states set. States are used with
955 * {@link android.graphics.drawable.Drawable} to change the drawing of the
956 * view depending on its state.
957 *
958 * @see android.graphics.drawable.Drawable
959 * @see #getDrawableState()
960 */
961 protected static final int[] EMPTY_STATE_SET = {};
962 /**
963 * Indicates the view is enabled. States are used with
964 * {@link android.graphics.drawable.Drawable} to change the drawing of the
965 * view depending on its state.
966 *
967 * @see android.graphics.drawable.Drawable
968 * @see #getDrawableState()
969 */
970 protected static final int[] ENABLED_STATE_SET = {R.attr.state_enabled};
971 /**
972 * Indicates the view is focused. States are used with
973 * {@link android.graphics.drawable.Drawable} to change the drawing of the
974 * view depending on its state.
975 *
976 * @see android.graphics.drawable.Drawable
977 * @see #getDrawableState()
978 */
979 protected static final int[] FOCUSED_STATE_SET = {R.attr.state_focused};
980 /**
981 * Indicates the view is selected. States are used with
982 * {@link android.graphics.drawable.Drawable} to change the drawing of the
983 * view depending on its state.
984 *
985 * @see android.graphics.drawable.Drawable
986 * @see #getDrawableState()
987 */
988 protected static final int[] SELECTED_STATE_SET = {R.attr.state_selected};
989 /**
990 * Indicates the view is pressed. States are used with
991 * {@link android.graphics.drawable.Drawable} to change the drawing of the
992 * view depending on its state.
993 *
994 * @see android.graphics.drawable.Drawable
995 * @see #getDrawableState()
996 * @hide
997 */
998 protected static final int[] PRESSED_STATE_SET = {R.attr.state_pressed};
999 /**
1000 * Indicates the view's window has focus. States are used with
1001 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1002 * view depending on its state.
1003 *
1004 * @see android.graphics.drawable.Drawable
1005 * @see #getDrawableState()
1006 */
1007 protected static final int[] WINDOW_FOCUSED_STATE_SET =
1008 {R.attr.state_window_focused};
1009 // Doubles
1010 /**
1011 * Indicates the view is enabled and has the focus.
1012 *
1013 * @see #ENABLED_STATE_SET
1014 * @see #FOCUSED_STATE_SET
1015 */
1016 protected static final int[] ENABLED_FOCUSED_STATE_SET =
1017 stateSetUnion(ENABLED_STATE_SET, FOCUSED_STATE_SET);
1018 /**
1019 * Indicates the view is enabled and selected.
1020 *
1021 * @see #ENABLED_STATE_SET
1022 * @see #SELECTED_STATE_SET
1023 */
1024 protected static final int[] ENABLED_SELECTED_STATE_SET =
1025 stateSetUnion(ENABLED_STATE_SET, SELECTED_STATE_SET);
1026 /**
1027 * Indicates the view is enabled and that its window has focus.
1028 *
1029 * @see #ENABLED_STATE_SET
1030 * @see #WINDOW_FOCUSED_STATE_SET
1031 */
1032 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET =
1033 stateSetUnion(ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1034 /**
1035 * Indicates the view is focused and selected.
1036 *
1037 * @see #FOCUSED_STATE_SET
1038 * @see #SELECTED_STATE_SET
1039 */
1040 protected static final int[] FOCUSED_SELECTED_STATE_SET =
1041 stateSetUnion(FOCUSED_STATE_SET, SELECTED_STATE_SET);
1042 /**
1043 * Indicates the view has the focus and that its window has the focus.
1044 *
1045 * @see #FOCUSED_STATE_SET
1046 * @see #WINDOW_FOCUSED_STATE_SET
1047 */
1048 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET =
1049 stateSetUnion(FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1050 /**
1051 * Indicates the view is selected and that its window has the focus.
1052 *
1053 * @see #SELECTED_STATE_SET
1054 * @see #WINDOW_FOCUSED_STATE_SET
1055 */
1056 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET =
1057 stateSetUnion(SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1058 // Triples
1059 /**
1060 * Indicates the view is enabled, focused and selected.
1061 *
1062 * @see #ENABLED_STATE_SET
1063 * @see #FOCUSED_STATE_SET
1064 * @see #SELECTED_STATE_SET
1065 */
1066 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET =
1067 stateSetUnion(ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1068 /**
1069 * Indicates the view is enabled, focused and its window has the focus.
1070 *
1071 * @see #ENABLED_STATE_SET
1072 * @see #FOCUSED_STATE_SET
1073 * @see #WINDOW_FOCUSED_STATE_SET
1074 */
1075 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1076 stateSetUnion(ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1077 /**
1078 * Indicates the view is enabled, selected and its window has the focus.
1079 *
1080 * @see #ENABLED_STATE_SET
1081 * @see #SELECTED_STATE_SET
1082 * @see #WINDOW_FOCUSED_STATE_SET
1083 */
1084 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1085 stateSetUnion(ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1086 /**
1087 * Indicates the view is focused, selected and its window has the focus.
1088 *
1089 * @see #FOCUSED_STATE_SET
1090 * @see #SELECTED_STATE_SET
1091 * @see #WINDOW_FOCUSED_STATE_SET
1092 */
1093 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1094 stateSetUnion(FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1095 /**
1096 * Indicates the view is enabled, focused, selected and its window
1097 * has the focus.
1098 *
1099 * @see #ENABLED_STATE_SET
1100 * @see #FOCUSED_STATE_SET
1101 * @see #SELECTED_STATE_SET
1102 * @see #WINDOW_FOCUSED_STATE_SET
1103 */
1104 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1105 stateSetUnion(ENABLED_FOCUSED_SELECTED_STATE_SET,
1106 WINDOW_FOCUSED_STATE_SET);
1107
1108 /**
1109 * Indicates the view is pressed and its window has the focus.
1110 *
1111 * @see #PRESSED_STATE_SET
1112 * @see #WINDOW_FOCUSED_STATE_SET
1113 */
1114 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET =
1115 stateSetUnion(PRESSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1116
1117 /**
1118 * Indicates the view is pressed and selected.
1119 *
1120 * @see #PRESSED_STATE_SET
1121 * @see #SELECTED_STATE_SET
1122 */
1123 protected static final int[] PRESSED_SELECTED_STATE_SET =
1124 stateSetUnion(PRESSED_STATE_SET, SELECTED_STATE_SET);
1125
1126 /**
1127 * Indicates the view is pressed, selected and its window has the focus.
1128 *
1129 * @see #PRESSED_STATE_SET
1130 * @see #SELECTED_STATE_SET
1131 * @see #WINDOW_FOCUSED_STATE_SET
1132 */
1133 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1134 stateSetUnion(PRESSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1135
1136 /**
1137 * Indicates the view is pressed and focused.
1138 *
1139 * @see #PRESSED_STATE_SET
1140 * @see #FOCUSED_STATE_SET
1141 */
1142 protected static final int[] PRESSED_FOCUSED_STATE_SET =
1143 stateSetUnion(PRESSED_STATE_SET, FOCUSED_STATE_SET);
1144
1145 /**
1146 * Indicates the view is pressed, focused and its window has the focus.
1147 *
1148 * @see #PRESSED_STATE_SET
1149 * @see #FOCUSED_STATE_SET
1150 * @see #WINDOW_FOCUSED_STATE_SET
1151 */
1152 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1153 stateSetUnion(PRESSED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1154
1155 /**
1156 * Indicates the view is pressed, focused and selected.
1157 *
1158 * @see #PRESSED_STATE_SET
1159 * @see #SELECTED_STATE_SET
1160 * @see #FOCUSED_STATE_SET
1161 */
1162 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET =
1163 stateSetUnion(PRESSED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1164
1165 /**
1166 * Indicates the view is pressed, focused, selected and its window has the focus.
1167 *
1168 * @see #PRESSED_STATE_SET
1169 * @see #FOCUSED_STATE_SET
1170 * @see #SELECTED_STATE_SET
1171 * @see #WINDOW_FOCUSED_STATE_SET
1172 */
1173 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1174 stateSetUnion(PRESSED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1175
1176 /**
1177 * Indicates the view is pressed and enabled.
1178 *
1179 * @see #PRESSED_STATE_SET
1180 * @see #ENABLED_STATE_SET
1181 */
1182 protected static final int[] PRESSED_ENABLED_STATE_SET =
1183 stateSetUnion(PRESSED_STATE_SET, ENABLED_STATE_SET);
1184
1185 /**
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 */
1192 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET =
1193 stateSetUnion(PRESSED_ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1194
1195 /**
1196 * Indicates the view is pressed, enabled and selected.
1197 *
1198 * @see #PRESSED_STATE_SET
1199 * @see #ENABLED_STATE_SET
1200 * @see #SELECTED_STATE_SET
1201 */
1202 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET =
1203 stateSetUnion(PRESSED_ENABLED_STATE_SET, SELECTED_STATE_SET);
1204
1205 /**
1206 * Indicates the view is pressed, enabled, selected and its window has the
1207 * focus.
1208 *
1209 * @see #PRESSED_STATE_SET
1210 * @see #ENABLED_STATE_SET
1211 * @see #SELECTED_STATE_SET
1212 * @see #WINDOW_FOCUSED_STATE_SET
1213 */
1214 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1215 stateSetUnion(PRESSED_ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1216
1217 /**
1218 * Indicates the view is pressed, enabled and focused.
1219 *
1220 * @see #PRESSED_STATE_SET
1221 * @see #ENABLED_STATE_SET
1222 * @see #FOCUSED_STATE_SET
1223 */
1224 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET =
1225 stateSetUnion(PRESSED_ENABLED_STATE_SET, FOCUSED_STATE_SET);
1226
1227 /**
1228 * Indicates the view is pressed, enabled, focused and its window has the
1229 * focus.
1230 *
1231 * @see #PRESSED_STATE_SET
1232 * @see #ENABLED_STATE_SET
1233 * @see #FOCUSED_STATE_SET
1234 * @see #WINDOW_FOCUSED_STATE_SET
1235 */
1236 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1237 stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1238
1239 /**
1240 * Indicates the view is pressed, enabled, focused and selected.
1241 *
1242 * @see #PRESSED_STATE_SET
1243 * @see #ENABLED_STATE_SET
1244 * @see #SELECTED_STATE_SET
1245 * @see #FOCUSED_STATE_SET
1246 */
1247 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET =
1248 stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1249
1250 /**
1251 * Indicates the view is pressed, enabled, focused, selected and its window
1252 * has the focus.
1253 *
1254 * @see #PRESSED_STATE_SET
1255 * @see #ENABLED_STATE_SET
1256 * @see #SELECTED_STATE_SET
1257 * @see #FOCUSED_STATE_SET
1258 * @see #WINDOW_FOCUSED_STATE_SET
1259 */
1260 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1261 stateSetUnion(PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1262
1263 /**
1264 * The order here is very important to {@link #getDrawableState()}
1265 */
1266 private static final int[][] VIEW_STATE_SETS = {
1267 EMPTY_STATE_SET, // 0 0 0 0 0
1268 WINDOW_FOCUSED_STATE_SET, // 0 0 0 0 1
1269 SELECTED_STATE_SET, // 0 0 0 1 0
1270 SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 0 1 1
1271 FOCUSED_STATE_SET, // 0 0 1 0 0
1272 FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 0 1
1273 FOCUSED_SELECTED_STATE_SET, // 0 0 1 1 0
1274 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 1 1
1275 ENABLED_STATE_SET, // 0 1 0 0 0
1276 ENABLED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 0 1
1277 ENABLED_SELECTED_STATE_SET, // 0 1 0 1 0
1278 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 1 1
1279 ENABLED_FOCUSED_STATE_SET, // 0 1 1 0 0
1280 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 0 1
1281 ENABLED_FOCUSED_SELECTED_STATE_SET, // 0 1 1 1 0
1282 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 1 1
1283 PRESSED_STATE_SET, // 1 0 0 0 0
1284 PRESSED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 0 1
1285 PRESSED_SELECTED_STATE_SET, // 1 0 0 1 0
1286 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 1 1
1287 PRESSED_FOCUSED_STATE_SET, // 1 0 1 0 0
1288 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 0 1
1289 PRESSED_FOCUSED_SELECTED_STATE_SET, // 1 0 1 1 0
1290 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 1 1
1291 PRESSED_ENABLED_STATE_SET, // 1 1 0 0 0
1292 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 0 1
1293 PRESSED_ENABLED_SELECTED_STATE_SET, // 1 1 0 1 0
1294 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 1 1
1295 PRESSED_ENABLED_FOCUSED_STATE_SET, // 1 1 1 0 0
1296 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 0 1
1297 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, // 1 1 1 1 0
1298 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 1 1
1299 };
1300
1301 /**
1302 * Used by views that contain lists of items. This state indicates that
1303 * the view is showing the last item.
1304 * @hide
1305 */
1306 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1307 /**
1308 * Used by views that contain lists of items. This state indicates that
1309 * the view is showing the first item.
1310 * @hide
1311 */
1312 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1313 /**
1314 * Used by views that contain lists of items. This state indicates that
1315 * the view is showing the middle item.
1316 * @hide
1317 */
1318 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1319 /**
1320 * Used by views that contain lists of items. This state indicates that
1321 * the view is showing only one item.
1322 * @hide
1323 */
1324 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1325 /**
1326 * Used by views that contain lists of items. This state indicates that
1327 * the view is pressed and showing the last item.
1328 * @hide
1329 */
1330 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1331 /**
1332 * Used by views that contain lists of items. This state indicates that
1333 * the view is pressed and showing the first item.
1334 * @hide
1335 */
1336 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1337 /**
1338 * Used by views that contain lists of items. This state indicates that
1339 * the view is pressed and showing the middle item.
1340 * @hide
1341 */
1342 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1343 /**
1344 * Used by views that contain lists of items. This state indicates that
1345 * the view is pressed and showing only one item.
1346 * @hide
1347 */
1348 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1349
1350 /**
1351 * Temporary Rect currently for use in setBackground(). This will probably
1352 * be extended in the future to hold our own class with more than just
1353 * a Rect. :)
1354 */
1355 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001356
1357 /**
1358 * Map used to store views' tags.
1359 */
1360 private static WeakHashMap<View, SparseArray<Object>> sTags;
1361
1362 /**
1363 * Lock used to access sTags.
1364 */
1365 private static final Object sTagsLock = new Object();
1366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 /**
1368 * The animation currently associated with this view.
1369 * @hide
1370 */
1371 protected Animation mCurrentAnimation = null;
1372
1373 /**
1374 * Width as measured during measure pass.
1375 * {@hide}
1376 */
1377 @ViewDebug.ExportedProperty
1378 protected int mMeasuredWidth;
1379
1380 /**
1381 * Height as measured during measure pass.
1382 * {@hide}
1383 */
1384 @ViewDebug.ExportedProperty
1385 protected int mMeasuredHeight;
1386
1387 /**
1388 * The view's identifier.
1389 * {@hide}
1390 *
1391 * @see #setId(int)
1392 * @see #getId()
1393 */
1394 @ViewDebug.ExportedProperty(resolveId = true)
1395 int mID = NO_ID;
1396
1397 /**
1398 * The view's tag.
1399 * {@hide}
1400 *
1401 * @see #setTag(Object)
1402 * @see #getTag()
1403 */
1404 protected Object mTag;
1405
1406 // for mPrivateFlags:
1407 /** {@hide} */
1408 static final int WANTS_FOCUS = 0x00000001;
1409 /** {@hide} */
1410 static final int FOCUSED = 0x00000002;
1411 /** {@hide} */
1412 static final int SELECTED = 0x00000004;
1413 /** {@hide} */
1414 static final int IS_ROOT_NAMESPACE = 0x00000008;
1415 /** {@hide} */
1416 static final int HAS_BOUNDS = 0x00000010;
1417 /** {@hide} */
1418 static final int DRAWN = 0x00000020;
1419 /**
1420 * When this flag is set, this view is running an animation on behalf of its
1421 * children and should therefore not cancel invalidate requests, even if they
1422 * lie outside of this view's bounds.
1423 *
1424 * {@hide}
1425 */
1426 static final int DRAW_ANIMATION = 0x00000040;
1427 /** {@hide} */
1428 static final int SKIP_DRAW = 0x00000080;
1429 /** {@hide} */
1430 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1431 /** {@hide} */
1432 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1433 /** {@hide} */
1434 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1435 /** {@hide} */
1436 static final int MEASURED_DIMENSION_SET = 0x00000800;
1437 /** {@hide} */
1438 static final int FORCE_LAYOUT = 0x00001000;
1439
1440 private static final int LAYOUT_REQUIRED = 0x00002000;
1441
1442 private static final int PRESSED = 0x00004000;
1443
1444 /** {@hide} */
1445 static final int DRAWING_CACHE_VALID = 0x00008000;
1446 /**
1447 * Flag used to indicate that this view should be drawn once more (and only once
1448 * more) after its animation has completed.
1449 * {@hide}
1450 */
1451 static final int ANIMATION_STARTED = 0x00010000;
1452
1453 private static final int SAVE_STATE_CALLED = 0x00020000;
1454
1455 /**
1456 * Indicates that the View returned true when onSetAlpha() was called and that
1457 * the alpha must be restored.
1458 * {@hide}
1459 */
1460 static final int ALPHA_SET = 0x00040000;
1461
1462 /**
1463 * Set by {@link #setScrollContainer(boolean)}.
1464 */
1465 static final int SCROLL_CONTAINER = 0x00080000;
1466
1467 /**
1468 * Set by {@link #setScrollContainer(boolean)}.
1469 */
1470 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1471
1472 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001473 * View flag indicating whether this view was invalidated (fully or partially.)
1474 *
1475 * @hide
1476 */
1477 static final int DIRTY = 0x00200000;
1478
1479 /**
1480 * View flag indicating whether this view was invalidated by an opaque
1481 * invalidate request.
1482 *
1483 * @hide
1484 */
1485 static final int DIRTY_OPAQUE = 0x00400000;
1486
1487 /**
1488 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1489 *
1490 * @hide
1491 */
1492 static final int DIRTY_MASK = 0x00600000;
1493
1494 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001495 * Indicates whether the background is opaque.
1496 *
1497 * @hide
1498 */
1499 static final int OPAQUE_BACKGROUND = 0x00800000;
1500
1501 /**
1502 * Indicates whether the scrollbars are opaque.
1503 *
1504 * @hide
1505 */
1506 static final int OPAQUE_SCROLLBARS = 0x01000000;
1507
1508 /**
1509 * Indicates whether the view is opaque.
1510 *
1511 * @hide
1512 */
1513 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001514
1515 /**
1516 * Indicates a prepressed state;
1517 * the short time between ACTION_DOWN and recognizing
1518 * a 'real' press. Prepressed is used to recognize quick taps
1519 * even when they are shorter than ViewConfiguration.getTapTimeout().
1520 *
1521 * @hide
1522 */
1523 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001524
1525 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001526 * Indicates whether the view is temporarily detached.
1527 *
1528 * @hide
1529 */
1530 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001531
1532 /**
1533 * Indicates that we should awaken scroll bars once attached
1534 *
1535 * @hide
1536 */
1537 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001538
1539 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 * The parent this view is attached to.
1541 * {@hide}
1542 *
1543 * @see #getParent()
1544 */
1545 protected ViewParent mParent;
1546
1547 /**
1548 * {@hide}
1549 */
1550 AttachInfo mAttachInfo;
1551
1552 /**
1553 * {@hide}
1554 */
Romain Guy809a7f62009-05-14 15:44:42 -07001555 @ViewDebug.ExportedProperty(flagMapping = {
1556 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1557 name = "FORCE_LAYOUT"),
1558 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1559 name = "LAYOUT_REQUIRED"),
1560 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001561 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001562 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1563 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1564 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1565 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1566 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 int mPrivateFlags;
1568
1569 /**
1570 * Count of how many windows this view has been attached to.
1571 */
1572 int mWindowAttachCount;
1573
1574 /**
1575 * The layout parameters associated with this view and used by the parent
1576 * {@link android.view.ViewGroup} to determine how this view should be
1577 * laid out.
1578 * {@hide}
1579 */
1580 protected ViewGroup.LayoutParams mLayoutParams;
1581
1582 /**
1583 * The view flags hold various views states.
1584 * {@hide}
1585 */
1586 @ViewDebug.ExportedProperty
1587 int mViewFlags;
1588
1589 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001590 * The transform matrix for the View. This transform is calculated internally
1591 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1592 * is used by default. Do *not* use this variable directly; instead call
1593 * getMatrix(), which will automatically recalculate the matrix if necessary
1594 * to get the correct matrix based on the latest rotation and scale properties.
1595 */
1596 private final Matrix mMatrix = new Matrix();
1597
1598 /**
1599 * The transform matrix for the View. This transform is calculated internally
1600 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1601 * is used by default. Do *not* use this variable directly; instead call
1602 * getMatrix(), which will automatically recalculate the matrix if necessary
1603 * to get the correct matrix based on the latest rotation and scale properties.
1604 */
1605 private Matrix mInverseMatrix;
1606
1607 /**
1608 * An internal variable that tracks whether we need to recalculate the
1609 * transform matrix, based on whether the rotation or scaleX/Y properties
1610 * have changed since the matrix was last calculated.
1611 */
1612 private boolean mMatrixDirty = false;
1613
1614 /**
1615 * An internal variable that tracks whether we need to recalculate the
1616 * transform matrix, based on whether the rotation or scaleX/Y properties
1617 * have changed since the matrix was last calculated.
1618 */
1619 private boolean mInverseMatrixDirty = true;
1620
1621 /**
1622 * A variable that tracks whether we need to recalculate the
1623 * transform matrix, based on whether the rotation or scaleX/Y properties
1624 * have changed since the matrix was last calculated. This variable
1625 * is only valid after a call to getMatrix().
1626 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001627 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001628
1629 /**
1630 * The degrees rotation around the pivot point.
1631 */
1632 @ViewDebug.ExportedProperty
1633 private float mRotation = 0f;
1634
1635 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001636 * The amount of translation of the object away from its left property (post-layout).
1637 */
1638 @ViewDebug.ExportedProperty
1639 private float mTranslationX = 0f;
1640
1641 /**
1642 * The amount of translation of the object away from its top property (post-layout).
1643 */
1644 @ViewDebug.ExportedProperty
1645 private float mTranslationY = 0f;
1646
1647 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001648 * The amount of scale in the x direction around the pivot point. A
1649 * value of 1 means no scaling is applied.
1650 */
1651 @ViewDebug.ExportedProperty
1652 private float mScaleX = 1f;
1653
1654 /**
1655 * The amount of scale in the y direction around the pivot point. A
1656 * value of 1 means no scaling is applied.
1657 */
1658 @ViewDebug.ExportedProperty
1659 private float mScaleY = 1f;
1660
1661 /**
1662 * The amount of scale in the x direction around the pivot point. A
1663 * value of 1 means no scaling is applied.
1664 */
1665 @ViewDebug.ExportedProperty
1666 private float mPivotX = 0f;
1667
1668 /**
1669 * The amount of scale in the y direction around the pivot point. A
1670 * value of 1 means no scaling is applied.
1671 */
1672 @ViewDebug.ExportedProperty
1673 private float mPivotY = 0f;
1674
1675 /**
1676 * The opacity of the View. This is a value from 0 to 1, where 0 means
1677 * completely transparent and 1 means completely opaque.
1678 */
1679 @ViewDebug.ExportedProperty
1680 private float mAlpha = 1f;
1681
1682 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 * The distance in pixels from the left edge of this view's parent
1684 * to the left edge of this view.
1685 * {@hide}
1686 */
1687 @ViewDebug.ExportedProperty
1688 protected int mLeft;
1689 /**
1690 * The distance in pixels from the left edge of this view's parent
1691 * to the right edge of this view.
1692 * {@hide}
1693 */
1694 @ViewDebug.ExportedProperty
1695 protected int mRight;
1696 /**
1697 * The distance in pixels from the top edge of this view's parent
1698 * to the top edge of this view.
1699 * {@hide}
1700 */
1701 @ViewDebug.ExportedProperty
1702 protected int mTop;
1703 /**
1704 * The distance in pixels from the top edge of this view's parent
1705 * to the bottom edge of this view.
1706 * {@hide}
1707 */
1708 @ViewDebug.ExportedProperty
1709 protected int mBottom;
1710
1711 /**
1712 * The offset, in pixels, by which the content of this view is scrolled
1713 * horizontally.
1714 * {@hide}
1715 */
1716 @ViewDebug.ExportedProperty
1717 protected int mScrollX;
1718 /**
1719 * The offset, in pixels, by which the content of this view is scrolled
1720 * vertically.
1721 * {@hide}
1722 */
1723 @ViewDebug.ExportedProperty
1724 protected int mScrollY;
1725
1726 /**
1727 * The left padding in pixels, that is the distance in pixels between the
1728 * left edge of this view and the left edge of its content.
1729 * {@hide}
1730 */
1731 @ViewDebug.ExportedProperty
1732 protected int mPaddingLeft;
1733 /**
1734 * The right padding in pixels, that is the distance in pixels between the
1735 * right edge of this view and the right edge of its content.
1736 * {@hide}
1737 */
1738 @ViewDebug.ExportedProperty
1739 protected int mPaddingRight;
1740 /**
1741 * The top padding in pixels, that is the distance in pixels between the
1742 * top edge of this view and the top edge of its content.
1743 * {@hide}
1744 */
1745 @ViewDebug.ExportedProperty
1746 protected int mPaddingTop;
1747 /**
1748 * The bottom padding in pixels, that is the distance in pixels between the
1749 * bottom edge of this view and the bottom edge of its content.
1750 * {@hide}
1751 */
1752 @ViewDebug.ExportedProperty
1753 protected int mPaddingBottom;
1754
1755 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001756 * Briefly describes the view and is primarily used for accessibility support.
1757 */
1758 private CharSequence mContentDescription;
1759
1760 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 * Cache the paddingRight set by the user to append to the scrollbar's size.
1762 */
1763 @ViewDebug.ExportedProperty
1764 int mUserPaddingRight;
1765
1766 /**
1767 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1768 */
1769 @ViewDebug.ExportedProperty
1770 int mUserPaddingBottom;
1771
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001772 /**
1773 * @hide
1774 */
1775 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1776 /**
1777 * @hide
1778 */
1779 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780
1781 private Resources mResources = null;
1782
1783 private Drawable mBGDrawable;
1784
1785 private int mBackgroundResource;
1786 private boolean mBackgroundSizeChanged;
1787
1788 /**
1789 * Listener used to dispatch focus change events.
1790 * This field should be made private, so it is hidden from the SDK.
1791 * {@hide}
1792 */
1793 protected OnFocusChangeListener mOnFocusChangeListener;
1794
1795 /**
1796 * Listener used to dispatch click events.
1797 * This field should be made private, so it is hidden from the SDK.
1798 * {@hide}
1799 */
1800 protected OnClickListener mOnClickListener;
1801
1802 /**
1803 * Listener used to dispatch long click events.
1804 * This field should be made private, so it is hidden from the SDK.
1805 * {@hide}
1806 */
1807 protected OnLongClickListener mOnLongClickListener;
1808
1809 /**
1810 * Listener used to build the context menu.
1811 * This field should be made private, so it is hidden from the SDK.
1812 * {@hide}
1813 */
1814 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
1815
1816 private OnKeyListener mOnKeyListener;
1817
1818 private OnTouchListener mOnTouchListener;
1819
1820 /**
1821 * The application environment this view lives in.
1822 * This field should be made private, so it is hidden from the SDK.
1823 * {@hide}
1824 */
1825 protected Context mContext;
1826
1827 private ScrollabilityCache mScrollCache;
1828
1829 private int[] mDrawableState = null;
1830
1831 private SoftReference<Bitmap> mDrawingCache;
Romain Guyfbd8f692009-06-26 14:51:58 -07001832 private SoftReference<Bitmap> mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833
1834 /**
1835 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
1836 * the user may specify which view to go to next.
1837 */
1838 private int mNextFocusLeftId = View.NO_ID;
1839
1840 /**
1841 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
1842 * the user may specify which view to go to next.
1843 */
1844 private int mNextFocusRightId = View.NO_ID;
1845
1846 /**
1847 * When this view has focus and the next focus is {@link #FOCUS_UP},
1848 * the user may specify which view to go to next.
1849 */
1850 private int mNextFocusUpId = View.NO_ID;
1851
1852 /**
1853 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
1854 * the user may specify which view to go to next.
1855 */
1856 private int mNextFocusDownId = View.NO_ID;
1857
1858 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08001859 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08001860 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08001861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 private UnsetPressedState mUnsetPressedState;
1863
1864 /**
1865 * Whether the long press's action has been invoked. The tap's action is invoked on the
1866 * up event while a long press is invoked as soon as the long press duration is reached, so
1867 * a long press could be performed before the tap is checked, in which case the tap's action
1868 * should not be invoked.
1869 */
1870 private boolean mHasPerformedLongPress;
1871
1872 /**
1873 * The minimum height of the view. We'll try our best to have the height
1874 * of this view to at least this amount.
1875 */
1876 @ViewDebug.ExportedProperty
1877 private int mMinHeight;
1878
1879 /**
1880 * The minimum width of the view. We'll try our best to have the width
1881 * of this view to at least this amount.
1882 */
1883 @ViewDebug.ExportedProperty
1884 private int mMinWidth;
1885
1886 /**
1887 * The delegate to handle touch events that are physically in this view
1888 * but should be handled by another view.
1889 */
1890 private TouchDelegate mTouchDelegate = null;
1891
1892 /**
1893 * Solid color to use as a background when creating the drawing cache. Enables
1894 * the cache to use 16 bit bitmaps instead of 32 bit.
1895 */
1896 private int mDrawingCacheBackgroundColor = 0;
1897
1898 /**
1899 * Special tree observer used when mAttachInfo is null.
1900 */
1901 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08001902
1903 /**
1904 * Cache the touch slop from the context that created the view.
1905 */
1906 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907
1908 // Used for debug only
1909 static long sInstanceCount = 0;
1910
1911 /**
1912 * Simple constructor to use when creating a view from code.
1913 *
1914 * @param context The Context the view is running in, through which it can
1915 * access the current theme, resources, etc.
1916 */
1917 public View(Context context) {
1918 mContext = context;
1919 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07001920 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Carl Shapiro82fe5642010-02-24 00:14:23 -08001921 // Used for debug only
1922 //++sInstanceCount;
Adam Powelle14579b2009-12-16 18:39:52 -08001923 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 }
1925
1926 /**
1927 * Constructor that is called when inflating a view from XML. This is called
1928 * when a view is being constructed from an XML file, supplying attributes
1929 * that were specified in the XML file. This version uses a default style of
1930 * 0, so the only attribute values applied are those in the Context's Theme
1931 * and the given AttributeSet.
1932 *
1933 * <p>
1934 * The method onFinishInflate() will be called after all children have been
1935 * added.
1936 *
1937 * @param context The Context the view is running in, through which it can
1938 * access the current theme, resources, etc.
1939 * @param attrs The attributes of the XML tag that is inflating the view.
1940 * @see #View(Context, AttributeSet, int)
1941 */
1942 public View(Context context, AttributeSet attrs) {
1943 this(context, attrs, 0);
1944 }
1945
1946 /**
1947 * Perform inflation from XML and apply a class-specific base style. This
1948 * constructor of View allows subclasses to use their own base style when
1949 * they are inflating. For example, a Button class's constructor would call
1950 * this version of the super class constructor and supply
1951 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
1952 * the theme's button style to modify all of the base view attributes (in
1953 * particular its background) as well as the Button class's attributes.
1954 *
1955 * @param context The Context the view is running in, through which it can
1956 * access the current theme, resources, etc.
1957 * @param attrs The attributes of the XML tag that is inflating the view.
1958 * @param defStyle The default style to apply to this view. If 0, no style
1959 * will be applied (beyond what is included in the theme). This may
1960 * either be an attribute resource, whose value will be retrieved
1961 * from the current theme, or an explicit style resource.
1962 * @see #View(Context, AttributeSet)
1963 */
1964 public View(Context context, AttributeSet attrs, int defStyle) {
1965 this(context);
1966
1967 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
1968 defStyle, 0);
1969
1970 Drawable background = null;
1971
1972 int leftPadding = -1;
1973 int topPadding = -1;
1974 int rightPadding = -1;
1975 int bottomPadding = -1;
1976
1977 int padding = -1;
1978
1979 int viewFlagValues = 0;
1980 int viewFlagMasks = 0;
1981
1982 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 int x = 0;
1985 int y = 0;
1986
1987 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
1988
1989 final int N = a.getIndexCount();
1990 for (int i = 0; i < N; i++) {
1991 int attr = a.getIndex(i);
1992 switch (attr) {
1993 case com.android.internal.R.styleable.View_background:
1994 background = a.getDrawable(attr);
1995 break;
1996 case com.android.internal.R.styleable.View_padding:
1997 padding = a.getDimensionPixelSize(attr, -1);
1998 break;
1999 case com.android.internal.R.styleable.View_paddingLeft:
2000 leftPadding = a.getDimensionPixelSize(attr, -1);
2001 break;
2002 case com.android.internal.R.styleable.View_paddingTop:
2003 topPadding = a.getDimensionPixelSize(attr, -1);
2004 break;
2005 case com.android.internal.R.styleable.View_paddingRight:
2006 rightPadding = a.getDimensionPixelSize(attr, -1);
2007 break;
2008 case com.android.internal.R.styleable.View_paddingBottom:
2009 bottomPadding = a.getDimensionPixelSize(attr, -1);
2010 break;
2011 case com.android.internal.R.styleable.View_scrollX:
2012 x = a.getDimensionPixelOffset(attr, 0);
2013 break;
2014 case com.android.internal.R.styleable.View_scrollY:
2015 y = a.getDimensionPixelOffset(attr, 0);
2016 break;
2017 case com.android.internal.R.styleable.View_id:
2018 mID = a.getResourceId(attr, NO_ID);
2019 break;
2020 case com.android.internal.R.styleable.View_tag:
2021 mTag = a.getText(attr);
2022 break;
2023 case com.android.internal.R.styleable.View_fitsSystemWindows:
2024 if (a.getBoolean(attr, false)) {
2025 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2026 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2027 }
2028 break;
2029 case com.android.internal.R.styleable.View_focusable:
2030 if (a.getBoolean(attr, false)) {
2031 viewFlagValues |= FOCUSABLE;
2032 viewFlagMasks |= FOCUSABLE_MASK;
2033 }
2034 break;
2035 case com.android.internal.R.styleable.View_focusableInTouchMode:
2036 if (a.getBoolean(attr, false)) {
2037 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2038 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2039 }
2040 break;
2041 case com.android.internal.R.styleable.View_clickable:
2042 if (a.getBoolean(attr, false)) {
2043 viewFlagValues |= CLICKABLE;
2044 viewFlagMasks |= CLICKABLE;
2045 }
2046 break;
2047 case com.android.internal.R.styleable.View_longClickable:
2048 if (a.getBoolean(attr, false)) {
2049 viewFlagValues |= LONG_CLICKABLE;
2050 viewFlagMasks |= LONG_CLICKABLE;
2051 }
2052 break;
2053 case com.android.internal.R.styleable.View_saveEnabled:
2054 if (!a.getBoolean(attr, true)) {
2055 viewFlagValues |= SAVE_DISABLED;
2056 viewFlagMasks |= SAVE_DISABLED_MASK;
2057 }
2058 break;
2059 case com.android.internal.R.styleable.View_duplicateParentState:
2060 if (a.getBoolean(attr, false)) {
2061 viewFlagValues |= DUPLICATE_PARENT_STATE;
2062 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2063 }
2064 break;
2065 case com.android.internal.R.styleable.View_visibility:
2066 final int visibility = a.getInt(attr, 0);
2067 if (visibility != 0) {
2068 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2069 viewFlagMasks |= VISIBILITY_MASK;
2070 }
2071 break;
2072 case com.android.internal.R.styleable.View_drawingCacheQuality:
2073 final int cacheQuality = a.getInt(attr, 0);
2074 if (cacheQuality != 0) {
2075 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2076 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2077 }
2078 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002079 case com.android.internal.R.styleable.View_contentDescription:
2080 mContentDescription = a.getString(attr);
2081 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2083 if (!a.getBoolean(attr, true)) {
2084 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2085 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2086 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002087 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2089 if (!a.getBoolean(attr, true)) {
2090 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2091 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2092 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002093 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 case R.styleable.View_scrollbars:
2095 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2096 if (scrollbars != SCROLLBARS_NONE) {
2097 viewFlagValues |= scrollbars;
2098 viewFlagMasks |= SCROLLBARS_MASK;
2099 initializeScrollbars(a);
2100 }
2101 break;
2102 case R.styleable.View_fadingEdge:
2103 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2104 if (fadingEdge != FADING_EDGE_NONE) {
2105 viewFlagValues |= fadingEdge;
2106 viewFlagMasks |= FADING_EDGE_MASK;
2107 initializeFadingEdge(a);
2108 }
2109 break;
2110 case R.styleable.View_scrollbarStyle:
2111 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2112 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2113 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2114 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2115 }
2116 break;
2117 case R.styleable.View_isScrollContainer:
2118 setScrollContainer = true;
2119 if (a.getBoolean(attr, false)) {
2120 setScrollContainer(true);
2121 }
2122 break;
2123 case com.android.internal.R.styleable.View_keepScreenOn:
2124 if (a.getBoolean(attr, false)) {
2125 viewFlagValues |= KEEP_SCREEN_ON;
2126 viewFlagMasks |= KEEP_SCREEN_ON;
2127 }
2128 break;
2129 case R.styleable.View_nextFocusLeft:
2130 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2131 break;
2132 case R.styleable.View_nextFocusRight:
2133 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2134 break;
2135 case R.styleable.View_nextFocusUp:
2136 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2137 break;
2138 case R.styleable.View_nextFocusDown:
2139 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2140 break;
2141 case R.styleable.View_minWidth:
2142 mMinWidth = a.getDimensionPixelSize(attr, 0);
2143 break;
2144 case R.styleable.View_minHeight:
2145 mMinHeight = a.getDimensionPixelSize(attr, 0);
2146 break;
Romain Guy9a817362009-05-01 10:57:14 -07002147 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002148 if (context.isRestricted()) {
2149 throw new IllegalStateException("The android:onClick attribute cannot "
2150 + "be used within a restricted context");
2151 }
2152
Romain Guy9a817362009-05-01 10:57:14 -07002153 final String handlerName = a.getString(attr);
2154 if (handlerName != null) {
2155 setOnClickListener(new OnClickListener() {
2156 private Method mHandler;
2157
2158 public void onClick(View v) {
2159 if (mHandler == null) {
2160 try {
2161 mHandler = getContext().getClass().getMethod(handlerName,
2162 View.class);
2163 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002164 int id = getId();
2165 String idText = id == NO_ID ? "" : " with id '"
2166 + getContext().getResources().getResourceEntryName(
2167 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002168 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002169 handlerName + "(View) in the activity "
2170 + getContext().getClass() + " for onClick handler"
2171 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002172 }
2173 }
2174
2175 try {
2176 mHandler.invoke(getContext(), View.this);
2177 } catch (IllegalAccessException e) {
2178 throw new IllegalStateException("Could not execute non "
2179 + "public method of the activity", e);
2180 } catch (InvocationTargetException e) {
2181 throw new IllegalStateException("Could not execute "
2182 + "method of the activity", e);
2183 }
2184 }
2185 });
2186 }
2187 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002188 }
2189 }
2190
2191 if (background != null) {
2192 setBackgroundDrawable(background);
2193 }
2194
2195 if (padding >= 0) {
2196 leftPadding = padding;
2197 topPadding = padding;
2198 rightPadding = padding;
2199 bottomPadding = padding;
2200 }
2201
2202 // If the user specified the padding (either with android:padding or
2203 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2204 // use the default padding or the padding from the background drawable
2205 // (stored at this point in mPadding*)
2206 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2207 topPadding >= 0 ? topPadding : mPaddingTop,
2208 rightPadding >= 0 ? rightPadding : mPaddingRight,
2209 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2210
2211 if (viewFlagMasks != 0) {
2212 setFlags(viewFlagValues, viewFlagMasks);
2213 }
2214
2215 // Needs to be called after mViewFlags is set
2216 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2217 recomputePadding();
2218 }
2219
2220 if (x != 0 || y != 0) {
2221 scrollTo(x, y);
2222 }
2223
2224 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2225 setScrollContainer(true);
2226 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002227
2228 computeOpaqueFlags();
2229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 a.recycle();
2231 }
2232
2233 /**
2234 * Non-public constructor for use in testing
2235 */
2236 View() {
2237 }
2238
Carl Shapiro82fe5642010-02-24 00:14:23 -08002239 // Used for debug only
2240 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 @Override
2242 protected void finalize() throws Throwable {
2243 super.finalize();
2244 --sInstanceCount;
2245 }
Carl Shapiro82fe5642010-02-24 00:14:23 -08002246 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247
2248 /**
2249 * <p>
2250 * Initializes the fading edges from a given set of styled attributes. This
2251 * method should be called by subclasses that need fading edges and when an
2252 * instance of these subclasses is created programmatically rather than
2253 * being inflated from XML. This method is automatically called when the XML
2254 * is inflated.
2255 * </p>
2256 *
2257 * @param a the styled attributes set to initialize the fading edges from
2258 */
2259 protected void initializeFadingEdge(TypedArray a) {
2260 initScrollCache();
2261
2262 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2263 R.styleable.View_fadingEdgeLength,
2264 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2265 }
2266
2267 /**
2268 * Returns the size of the vertical faded edges used to indicate that more
2269 * content in this view is visible.
2270 *
2271 * @return The size in pixels of the vertical faded edge or 0 if vertical
2272 * faded edges are not enabled for this view.
2273 * @attr ref android.R.styleable#View_fadingEdgeLength
2274 */
2275 public int getVerticalFadingEdgeLength() {
2276 if (isVerticalFadingEdgeEnabled()) {
2277 ScrollabilityCache cache = mScrollCache;
2278 if (cache != null) {
2279 return cache.fadingEdgeLength;
2280 }
2281 }
2282 return 0;
2283 }
2284
2285 /**
2286 * Set the size of the faded edge used to indicate that more content in this
2287 * view is available. Will not change whether the fading edge is enabled; use
2288 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2289 * to enable the fading edge for the vertical or horizontal fading edges.
2290 *
2291 * @param length The size in pixels of the faded edge used to indicate that more
2292 * content in this view is visible.
2293 */
2294 public void setFadingEdgeLength(int length) {
2295 initScrollCache();
2296 mScrollCache.fadingEdgeLength = length;
2297 }
2298
2299 /**
2300 * Returns the size of the horizontal faded edges used to indicate that more
2301 * content in this view is visible.
2302 *
2303 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2304 * faded edges are not enabled for this view.
2305 * @attr ref android.R.styleable#View_fadingEdgeLength
2306 */
2307 public int getHorizontalFadingEdgeLength() {
2308 if (isHorizontalFadingEdgeEnabled()) {
2309 ScrollabilityCache cache = mScrollCache;
2310 if (cache != null) {
2311 return cache.fadingEdgeLength;
2312 }
2313 }
2314 return 0;
2315 }
2316
2317 /**
2318 * Returns the width of the vertical scrollbar.
2319 *
2320 * @return The width in pixels of the vertical scrollbar or 0 if there
2321 * is no vertical scrollbar.
2322 */
2323 public int getVerticalScrollbarWidth() {
2324 ScrollabilityCache cache = mScrollCache;
2325 if (cache != null) {
2326 ScrollBarDrawable scrollBar = cache.scrollBar;
2327 if (scrollBar != null) {
2328 int size = scrollBar.getSize(true);
2329 if (size <= 0) {
2330 size = cache.scrollBarSize;
2331 }
2332 return size;
2333 }
2334 return 0;
2335 }
2336 return 0;
2337 }
2338
2339 /**
2340 * Returns the height of the horizontal scrollbar.
2341 *
2342 * @return The height in pixels of the horizontal scrollbar or 0 if
2343 * there is no horizontal scrollbar.
2344 */
2345 protected int getHorizontalScrollbarHeight() {
2346 ScrollabilityCache cache = mScrollCache;
2347 if (cache != null) {
2348 ScrollBarDrawable scrollBar = cache.scrollBar;
2349 if (scrollBar != null) {
2350 int size = scrollBar.getSize(false);
2351 if (size <= 0) {
2352 size = cache.scrollBarSize;
2353 }
2354 return size;
2355 }
2356 return 0;
2357 }
2358 return 0;
2359 }
2360
2361 /**
2362 * <p>
2363 * Initializes the scrollbars from a given set of styled attributes. This
2364 * method should be called by subclasses that need scrollbars and when an
2365 * instance of these subclasses is created programmatically rather than
2366 * being inflated from XML. This method is automatically called when the XML
2367 * is inflated.
2368 * </p>
2369 *
2370 * @param a the styled attributes set to initialize the scrollbars from
2371 */
2372 protected void initializeScrollbars(TypedArray a) {
2373 initScrollCache();
2374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002376
2377 if (scrollabilityCache.scrollBar == null) {
2378 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2379 }
2380
Romain Guy8bda2482010-03-02 11:42:11 -08002381 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382
Mike Cleronf116bf82009-09-27 19:14:12 -07002383 if (!fadeScrollbars) {
2384 scrollabilityCache.state = ScrollabilityCache.ON;
2385 }
2386 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2387
2388
2389 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2390 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2391 .getScrollBarFadeDuration());
2392 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2393 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2394 ViewConfiguration.getScrollDefaultDelay());
2395
2396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2398 com.android.internal.R.styleable.View_scrollbarSize,
2399 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2400
2401 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2402 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2403
2404 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2405 if (thumb != null) {
2406 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2407 }
2408
2409 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2410 false);
2411 if (alwaysDraw) {
2412 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2413 }
2414
2415 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2416 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2417
2418 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2419 if (thumb != null) {
2420 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2421 }
2422
2423 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2424 false);
2425 if (alwaysDraw) {
2426 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2427 }
2428
2429 // Re-apply user/background padding so that scrollbar(s) get added
2430 recomputePadding();
2431 }
2432
2433 /**
2434 * <p>
2435 * Initalizes the scrollability cache if necessary.
2436 * </p>
2437 */
2438 private void initScrollCache() {
2439 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002440 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 }
2442 }
2443
2444 /**
2445 * Register a callback to be invoked when focus of this view changed.
2446 *
2447 * @param l The callback that will run.
2448 */
2449 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2450 mOnFocusChangeListener = l;
2451 }
2452
2453 /**
2454 * Returns the focus-change callback registered for this view.
2455 *
2456 * @return The callback, or null if one is not registered.
2457 */
2458 public OnFocusChangeListener getOnFocusChangeListener() {
2459 return mOnFocusChangeListener;
2460 }
2461
2462 /**
2463 * Register a callback to be invoked when this view is clicked. If this view is not
2464 * clickable, it becomes clickable.
2465 *
2466 * @param l The callback that will run
2467 *
2468 * @see #setClickable(boolean)
2469 */
2470 public void setOnClickListener(OnClickListener l) {
2471 if (!isClickable()) {
2472 setClickable(true);
2473 }
2474 mOnClickListener = l;
2475 }
2476
2477 /**
2478 * Register a callback to be invoked when this view is clicked and held. If this view is not
2479 * long clickable, it becomes long clickable.
2480 *
2481 * @param l The callback that will run
2482 *
2483 * @see #setLongClickable(boolean)
2484 */
2485 public void setOnLongClickListener(OnLongClickListener l) {
2486 if (!isLongClickable()) {
2487 setLongClickable(true);
2488 }
2489 mOnLongClickListener = l;
2490 }
2491
2492 /**
2493 * Register a callback to be invoked when the context menu for this view is
2494 * being built. If this view is not long clickable, it becomes long clickable.
2495 *
2496 * @param l The callback that will run
2497 *
2498 */
2499 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2500 if (!isLongClickable()) {
2501 setLongClickable(true);
2502 }
2503 mOnCreateContextMenuListener = l;
2504 }
2505
2506 /**
2507 * Call this view's OnClickListener, if it is defined.
2508 *
2509 * @return True there was an assigned OnClickListener that was called, false
2510 * otherwise is returned.
2511 */
2512 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002513 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 if (mOnClickListener != null) {
2516 playSoundEffect(SoundEffectConstants.CLICK);
2517 mOnClickListener.onClick(this);
2518 return true;
2519 }
2520
2521 return false;
2522 }
2523
2524 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002525 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2526 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002528 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 */
2530 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002531 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 boolean handled = false;
2534 if (mOnLongClickListener != null) {
2535 handled = mOnLongClickListener.onLongClick(View.this);
2536 }
2537 if (!handled) {
2538 handled = showContextMenu();
2539 }
2540 if (handled) {
2541 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2542 }
2543 return handled;
2544 }
2545
2546 /**
2547 * Bring up the context menu for this view.
2548 *
2549 * @return Whether a context menu was displayed.
2550 */
2551 public boolean showContextMenu() {
2552 return getParent().showContextMenuForChild(this);
2553 }
2554
2555 /**
Adam Powell6e346362010-07-23 10:18:23 -07002556 * Start an action mode.
2557 *
2558 * @param callback Callback that will control the lifecycle of the action mode
2559 * @return The new action mode if it is started, null otherwise
2560 *
2561 * @see ActionMode
2562 */
2563 public ActionMode startActionMode(ActionMode.Callback callback) {
2564 return getParent().startActionModeForChild(this, callback);
2565 }
2566
2567 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 * Register a callback to be invoked when a key is pressed in this view.
2569 * @param l the key listener to attach to this view
2570 */
2571 public void setOnKeyListener(OnKeyListener l) {
2572 mOnKeyListener = l;
2573 }
2574
2575 /**
2576 * Register a callback to be invoked when a touch event is sent to this view.
2577 * @param l the touch listener to attach to this view
2578 */
2579 public void setOnTouchListener(OnTouchListener l) {
2580 mOnTouchListener = l;
2581 }
2582
2583 /**
2584 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2585 *
2586 * Note: this does not check whether this {@link View} should get focus, it just
2587 * gives it focus no matter what. It should only be called internally by framework
2588 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2589 *
2590 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2591 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2592 * focus moved when requestFocus() is called. It may not always
2593 * apply, in which case use the default View.FOCUS_DOWN.
2594 * @param previouslyFocusedRect The rectangle of the view that had focus
2595 * prior in this View's coordinate system.
2596 */
2597 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2598 if (DBG) {
2599 System.out.println(this + " requestFocus()");
2600 }
2601
2602 if ((mPrivateFlags & FOCUSED) == 0) {
2603 mPrivateFlags |= FOCUSED;
2604
2605 if (mParent != null) {
2606 mParent.requestChildFocus(this, this);
2607 }
2608
2609 onFocusChanged(true, direction, previouslyFocusedRect);
2610 refreshDrawableState();
2611 }
2612 }
2613
2614 /**
2615 * Request that a rectangle of this view be visible on the screen,
2616 * scrolling if necessary just enough.
2617 *
2618 * <p>A View should call this if it maintains some notion of which part
2619 * of its content is interesting. For example, a text editing view
2620 * should call this when its cursor moves.
2621 *
2622 * @param rectangle The rectangle.
2623 * @return Whether any parent scrolled.
2624 */
2625 public boolean requestRectangleOnScreen(Rect rectangle) {
2626 return requestRectangleOnScreen(rectangle, false);
2627 }
2628
2629 /**
2630 * Request that a rectangle of this view be visible on the screen,
2631 * scrolling if necessary just enough.
2632 *
2633 * <p>A View should call this if it maintains some notion of which part
2634 * of its content is interesting. For example, a text editing view
2635 * should call this when its cursor moves.
2636 *
2637 * <p>When <code>immediate</code> is set to true, scrolling will not be
2638 * animated.
2639 *
2640 * @param rectangle The rectangle.
2641 * @param immediate True to forbid animated scrolling, false otherwise
2642 * @return Whether any parent scrolled.
2643 */
2644 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
2645 View child = this;
2646 ViewParent parent = mParent;
2647 boolean scrolled = false;
2648 while (parent != null) {
2649 scrolled |= parent.requestChildRectangleOnScreen(child,
2650 rectangle, immediate);
2651
2652 // offset rect so next call has the rectangle in the
2653 // coordinate system of its direct child.
2654 rectangle.offset(child.getLeft(), child.getTop());
2655 rectangle.offset(-child.getScrollX(), -child.getScrollY());
2656
2657 if (!(parent instanceof View)) {
2658 break;
2659 }
Romain Guy8506ab42009-06-11 17:35:47 -07002660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 child = (View) parent;
2662 parent = child.getParent();
2663 }
2664 return scrolled;
2665 }
2666
2667 /**
2668 * Called when this view wants to give up focus. This will cause
2669 * {@link #onFocusChanged} to be called.
2670 */
2671 public void clearFocus() {
2672 if (DBG) {
2673 System.out.println(this + " clearFocus()");
2674 }
2675
2676 if ((mPrivateFlags & FOCUSED) != 0) {
2677 mPrivateFlags &= ~FOCUSED;
2678
2679 if (mParent != null) {
2680 mParent.clearChildFocus(this);
2681 }
2682
2683 onFocusChanged(false, 0, null);
2684 refreshDrawableState();
2685 }
2686 }
2687
2688 /**
2689 * Called to clear the focus of a view that is about to be removed.
2690 * Doesn't call clearChildFocus, which prevents this view from taking
2691 * focus again before it has been removed from the parent
2692 */
2693 void clearFocusForRemoval() {
2694 if ((mPrivateFlags & FOCUSED) != 0) {
2695 mPrivateFlags &= ~FOCUSED;
2696
2697 onFocusChanged(false, 0, null);
2698 refreshDrawableState();
2699 }
2700 }
2701
2702 /**
2703 * Called internally by the view system when a new view is getting focus.
2704 * This is what clears the old focus.
2705 */
2706 void unFocus() {
2707 if (DBG) {
2708 System.out.println(this + " unFocus()");
2709 }
2710
2711 if ((mPrivateFlags & FOCUSED) != 0) {
2712 mPrivateFlags &= ~FOCUSED;
2713
2714 onFocusChanged(false, 0, null);
2715 refreshDrawableState();
2716 }
2717 }
2718
2719 /**
2720 * Returns true if this view has focus iteself, or is the ancestor of the
2721 * view that has focus.
2722 *
2723 * @return True if this view has or contains focus, false otherwise.
2724 */
2725 @ViewDebug.ExportedProperty
2726 public boolean hasFocus() {
2727 return (mPrivateFlags & FOCUSED) != 0;
2728 }
2729
2730 /**
2731 * Returns true if this view is focusable or if it contains a reachable View
2732 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
2733 * is a View whose parents do not block descendants focus.
2734 *
2735 * Only {@link #VISIBLE} views are considered focusable.
2736 *
2737 * @return True if the view is focusable or if the view contains a focusable
2738 * View, false otherwise.
2739 *
2740 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
2741 */
2742 public boolean hasFocusable() {
2743 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
2744 }
2745
2746 /**
2747 * Called by the view system when the focus state of this view changes.
2748 * When the focus change event is caused by directional navigation, direction
2749 * and previouslyFocusedRect provide insight into where the focus is coming from.
2750 * When overriding, be sure to call up through to the super class so that
2751 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07002752 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 * @param gainFocus True if the View has focus; false otherwise.
2754 * @param direction The direction focus has moved when requestFocus()
2755 * is called to give this view focus. Values are
Romain Guyea4823c2009-12-08 15:03:39 -08002756 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT} or
2757 * {@link #FOCUS_RIGHT}. It may not always apply, in which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 * case use the default.
2759 * @param previouslyFocusedRect The rectangle, in this view's coordinate
2760 * system, of the previously focused view. If applicable, this will be
2761 * passed in as finer grained information about where the focus is coming
2762 * from (in addition to direction). Will be <code>null</code> otherwise.
2763 */
2764 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07002765 if (gainFocus) {
2766 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2767 }
2768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 InputMethodManager imm = InputMethodManager.peekInstance();
2770 if (!gainFocus) {
2771 if (isPressed()) {
2772 setPressed(false);
2773 }
2774 if (imm != null && mAttachInfo != null
2775 && mAttachInfo.mHasWindowFocus) {
2776 imm.focusOut(this);
2777 }
Romain Guya2431d02009-04-30 16:30:00 -07002778 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 } else if (imm != null && mAttachInfo != null
2780 && mAttachInfo.mHasWindowFocus) {
2781 imm.focusIn(this);
2782 }
Romain Guy8506ab42009-06-11 17:35:47 -07002783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 invalidate();
2785 if (mOnFocusChangeListener != null) {
2786 mOnFocusChangeListener.onFocusChange(this, gainFocus);
2787 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002788
2789 if (mAttachInfo != null) {
2790 mAttachInfo.mKeyDispatchState.reset(this);
2791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 }
2793
2794 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002795 * {@inheritDoc}
2796 */
2797 public void sendAccessibilityEvent(int eventType) {
2798 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2799 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
2800 }
2801 }
2802
2803 /**
2804 * {@inheritDoc}
2805 */
2806 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
2807 event.setClassName(getClass().getName());
2808 event.setPackageName(getContext().getPackageName());
2809 event.setEnabled(isEnabled());
2810 event.setContentDescription(mContentDescription);
2811
2812 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
2813 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
2814 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
2815 event.setItemCount(focusablesTempList.size());
2816 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
2817 focusablesTempList.clear();
2818 }
2819
2820 dispatchPopulateAccessibilityEvent(event);
2821
2822 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
2823 }
2824
2825 /**
2826 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
2827 * to be populated.
2828 *
2829 * @param event The event.
2830 *
2831 * @return True if the event population was completed.
2832 */
2833 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2834 return false;
2835 }
2836
2837 /**
2838 * Gets the {@link View} description. It briefly describes the view and is
2839 * primarily used for accessibility support. Set this property to enable
2840 * better accessibility support for your application. This is especially
2841 * true for views that do not have textual representation (For example,
2842 * ImageButton).
2843 *
2844 * @return The content descriptiopn.
2845 *
2846 * @attr ref android.R.styleable#View_contentDescription
2847 */
2848 public CharSequence getContentDescription() {
2849 return mContentDescription;
2850 }
2851
2852 /**
2853 * Sets the {@link View} description. It briefly describes the view and is
2854 * primarily used for accessibility support. Set this property to enable
2855 * better accessibility support for your application. This is especially
2856 * true for views that do not have textual representation (For example,
2857 * ImageButton).
2858 *
2859 * @param contentDescription The content description.
2860 *
2861 * @attr ref android.R.styleable#View_contentDescription
2862 */
2863 public void setContentDescription(CharSequence contentDescription) {
2864 mContentDescription = contentDescription;
2865 }
2866
2867 /**
Romain Guya2431d02009-04-30 16:30:00 -07002868 * Invoked whenever this view loses focus, either by losing window focus or by losing
2869 * focus within its window. This method can be used to clear any state tied to the
2870 * focus. For instance, if a button is held pressed with the trackball and the window
2871 * loses focus, this method can be used to cancel the press.
2872 *
2873 * Subclasses of View overriding this method should always call super.onFocusLost().
2874 *
2875 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07002876 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07002877 *
2878 * @hide pending API council approval
2879 */
2880 protected void onFocusLost() {
2881 resetPressedState();
2882 }
2883
2884 private void resetPressedState() {
2885 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
2886 return;
2887 }
2888
2889 if (isPressed()) {
2890 setPressed(false);
2891
2892 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05002893 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07002894 }
2895 }
2896 }
2897
2898 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 * Returns true if this view has focus
2900 *
2901 * @return True if this view has focus, false otherwise.
2902 */
2903 @ViewDebug.ExportedProperty
2904 public boolean isFocused() {
2905 return (mPrivateFlags & FOCUSED) != 0;
2906 }
2907
2908 /**
2909 * Find the view in the hierarchy rooted at this view that currently has
2910 * focus.
2911 *
2912 * @return The view that currently has focus, or null if no focused view can
2913 * be found.
2914 */
2915 public View findFocus() {
2916 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
2917 }
2918
2919 /**
2920 * Change whether this view is one of the set of scrollable containers in
2921 * its window. This will be used to determine whether the window can
2922 * resize or must pan when a soft input area is open -- scrollable
2923 * containers allow the window to use resize mode since the container
2924 * will appropriately shrink.
2925 */
2926 public void setScrollContainer(boolean isScrollContainer) {
2927 if (isScrollContainer) {
2928 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
2929 mAttachInfo.mScrollContainers.add(this);
2930 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
2931 }
2932 mPrivateFlags |= SCROLL_CONTAINER;
2933 } else {
2934 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
2935 mAttachInfo.mScrollContainers.remove(this);
2936 }
2937 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
2938 }
2939 }
2940
2941 /**
2942 * Returns the quality of the drawing cache.
2943 *
2944 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
2945 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
2946 *
2947 * @see #setDrawingCacheQuality(int)
2948 * @see #setDrawingCacheEnabled(boolean)
2949 * @see #isDrawingCacheEnabled()
2950 *
2951 * @attr ref android.R.styleable#View_drawingCacheQuality
2952 */
2953 public int getDrawingCacheQuality() {
2954 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
2955 }
2956
2957 /**
2958 * Set the drawing cache quality of this view. This value is used only when the
2959 * drawing cache is enabled
2960 *
2961 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
2962 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
2963 *
2964 * @see #getDrawingCacheQuality()
2965 * @see #setDrawingCacheEnabled(boolean)
2966 * @see #isDrawingCacheEnabled()
2967 *
2968 * @attr ref android.R.styleable#View_drawingCacheQuality
2969 */
2970 public void setDrawingCacheQuality(int quality) {
2971 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
2972 }
2973
2974 /**
2975 * Returns whether the screen should remain on, corresponding to the current
2976 * value of {@link #KEEP_SCREEN_ON}.
2977 *
2978 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
2979 *
2980 * @see #setKeepScreenOn(boolean)
2981 *
2982 * @attr ref android.R.styleable#View_keepScreenOn
2983 */
2984 public boolean getKeepScreenOn() {
2985 return (mViewFlags & KEEP_SCREEN_ON) != 0;
2986 }
2987
2988 /**
2989 * Controls whether the screen should remain on, modifying the
2990 * value of {@link #KEEP_SCREEN_ON}.
2991 *
2992 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
2993 *
2994 * @see #getKeepScreenOn()
2995 *
2996 * @attr ref android.R.styleable#View_keepScreenOn
2997 */
2998 public void setKeepScreenOn(boolean keepScreenOn) {
2999 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3000 }
3001
3002 /**
3003 * @return The user specified next focus ID.
3004 *
3005 * @attr ref android.R.styleable#View_nextFocusLeft
3006 */
3007 public int getNextFocusLeftId() {
3008 return mNextFocusLeftId;
3009 }
3010
3011 /**
3012 * Set the id of the view to use for the next focus
3013 *
3014 * @param nextFocusLeftId
3015 *
3016 * @attr ref android.R.styleable#View_nextFocusLeft
3017 */
3018 public void setNextFocusLeftId(int nextFocusLeftId) {
3019 mNextFocusLeftId = nextFocusLeftId;
3020 }
3021
3022 /**
3023 * @return The user specified next focus ID.
3024 *
3025 * @attr ref android.R.styleable#View_nextFocusRight
3026 */
3027 public int getNextFocusRightId() {
3028 return mNextFocusRightId;
3029 }
3030
3031 /**
3032 * Set the id of the view to use for the next focus
3033 *
3034 * @param nextFocusRightId
3035 *
3036 * @attr ref android.R.styleable#View_nextFocusRight
3037 */
3038 public void setNextFocusRightId(int nextFocusRightId) {
3039 mNextFocusRightId = nextFocusRightId;
3040 }
3041
3042 /**
3043 * @return The user specified next focus ID.
3044 *
3045 * @attr ref android.R.styleable#View_nextFocusUp
3046 */
3047 public int getNextFocusUpId() {
3048 return mNextFocusUpId;
3049 }
3050
3051 /**
3052 * Set the id of the view to use for the next focus
3053 *
3054 * @param nextFocusUpId
3055 *
3056 * @attr ref android.R.styleable#View_nextFocusUp
3057 */
3058 public void setNextFocusUpId(int nextFocusUpId) {
3059 mNextFocusUpId = nextFocusUpId;
3060 }
3061
3062 /**
3063 * @return The user specified next focus ID.
3064 *
3065 * @attr ref android.R.styleable#View_nextFocusDown
3066 */
3067 public int getNextFocusDownId() {
3068 return mNextFocusDownId;
3069 }
3070
3071 /**
3072 * Set the id of the view to use for the next focus
3073 *
3074 * @param nextFocusDownId
3075 *
3076 * @attr ref android.R.styleable#View_nextFocusDown
3077 */
3078 public void setNextFocusDownId(int nextFocusDownId) {
3079 mNextFocusDownId = nextFocusDownId;
3080 }
3081
3082 /**
3083 * Returns the visibility of this view and all of its ancestors
3084 *
3085 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3086 */
3087 public boolean isShown() {
3088 View current = this;
3089 //noinspection ConstantConditions
3090 do {
3091 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3092 return false;
3093 }
3094 ViewParent parent = current.mParent;
3095 if (parent == null) {
3096 return false; // We are not attached to the view root
3097 }
3098 if (!(parent instanceof View)) {
3099 return true;
3100 }
3101 current = (View) parent;
3102 } while (current != null);
3103
3104 return false;
3105 }
3106
3107 /**
3108 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3109 * is set
3110 *
3111 * @param insets Insets for system windows
3112 *
3113 * @return True if this view applied the insets, false otherwise
3114 */
3115 protected boolean fitSystemWindows(Rect insets) {
3116 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3117 mPaddingLeft = insets.left;
3118 mPaddingTop = insets.top;
3119 mPaddingRight = insets.right;
3120 mPaddingBottom = insets.bottom;
3121 requestLayout();
3122 return true;
3123 }
3124 return false;
3125 }
3126
3127 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003128 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3129 * @return True if window has FITS_SYSTEM_WINDOWS set
3130 *
3131 * @hide
3132 */
3133 public boolean isFitsSystemWindowsFlagSet() {
3134 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3135 }
3136
3137 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 * Returns the visibility status for this view.
3139 *
3140 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3141 * @attr ref android.R.styleable#View_visibility
3142 */
3143 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003144 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3145 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3146 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 })
3148 public int getVisibility() {
3149 return mViewFlags & VISIBILITY_MASK;
3150 }
3151
3152 /**
3153 * Set the enabled state of this view.
3154 *
3155 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3156 * @attr ref android.R.styleable#View_visibility
3157 */
3158 @RemotableViewMethod
3159 public void setVisibility(int visibility) {
3160 setFlags(visibility, VISIBILITY_MASK);
3161 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3162 }
3163
3164 /**
3165 * Returns the enabled status for this view. The interpretation of the
3166 * enabled state varies by subclass.
3167 *
3168 * @return True if this view is enabled, false otherwise.
3169 */
3170 @ViewDebug.ExportedProperty
3171 public boolean isEnabled() {
3172 return (mViewFlags & ENABLED_MASK) == ENABLED;
3173 }
3174
3175 /**
3176 * Set the enabled state of this view. The interpretation of the enabled
3177 * state varies by subclass.
3178 *
3179 * @param enabled True if this view is enabled, false otherwise.
3180 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003181 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003183 if (enabled == isEnabled()) return;
3184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3186
3187 /*
3188 * The View most likely has to change its appearance, so refresh
3189 * the drawable state.
3190 */
3191 refreshDrawableState();
3192
3193 // Invalidate too, since the default behavior for views is to be
3194 // be drawn at 50% alpha rather than to change the drawable.
3195 invalidate();
3196 }
3197
3198 /**
3199 * Set whether this view can receive the focus.
3200 *
3201 * Setting this to false will also ensure that this view is not focusable
3202 * in touch mode.
3203 *
3204 * @param focusable If true, this view can receive the focus.
3205 *
3206 * @see #setFocusableInTouchMode(boolean)
3207 * @attr ref android.R.styleable#View_focusable
3208 */
3209 public void setFocusable(boolean focusable) {
3210 if (!focusable) {
3211 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3212 }
3213 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3214 }
3215
3216 /**
3217 * Set whether this view can receive focus while in touch mode.
3218 *
3219 * Setting this to true will also ensure that this view is focusable.
3220 *
3221 * @param focusableInTouchMode If true, this view can receive the focus while
3222 * in touch mode.
3223 *
3224 * @see #setFocusable(boolean)
3225 * @attr ref android.R.styleable#View_focusableInTouchMode
3226 */
3227 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3228 // Focusable in touch mode should always be set before the focusable flag
3229 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3230 // which, in touch mode, will not successfully request focus on this view
3231 // because the focusable in touch mode flag is not set
3232 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3233 if (focusableInTouchMode) {
3234 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3235 }
3236 }
3237
3238 /**
3239 * Set whether this view should have sound effects enabled for events such as
3240 * clicking and touching.
3241 *
3242 * <p>You may wish to disable sound effects for a view if you already play sounds,
3243 * for instance, a dial key that plays dtmf tones.
3244 *
3245 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3246 * @see #isSoundEffectsEnabled()
3247 * @see #playSoundEffect(int)
3248 * @attr ref android.R.styleable#View_soundEffectsEnabled
3249 */
3250 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3251 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3252 }
3253
3254 /**
3255 * @return whether this view should have sound effects enabled for events such as
3256 * clicking and touching.
3257 *
3258 * @see #setSoundEffectsEnabled(boolean)
3259 * @see #playSoundEffect(int)
3260 * @attr ref android.R.styleable#View_soundEffectsEnabled
3261 */
3262 @ViewDebug.ExportedProperty
3263 public boolean isSoundEffectsEnabled() {
3264 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3265 }
3266
3267 /**
3268 * Set whether this view should have haptic feedback for events such as
3269 * long presses.
3270 *
3271 * <p>You may wish to disable haptic feedback if your view already controls
3272 * its own haptic feedback.
3273 *
3274 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3275 * @see #isHapticFeedbackEnabled()
3276 * @see #performHapticFeedback(int)
3277 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3278 */
3279 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3280 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3281 }
3282
3283 /**
3284 * @return whether this view should have haptic feedback enabled for events
3285 * long presses.
3286 *
3287 * @see #setHapticFeedbackEnabled(boolean)
3288 * @see #performHapticFeedback(int)
3289 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3290 */
3291 @ViewDebug.ExportedProperty
3292 public boolean isHapticFeedbackEnabled() {
3293 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3294 }
3295
3296 /**
3297 * If this view doesn't do any drawing on its own, set this flag to
3298 * allow further optimizations. By default, this flag is not set on
3299 * View, but could be set on some View subclasses such as ViewGroup.
3300 *
3301 * Typically, if you override {@link #onDraw} you should clear this flag.
3302 *
3303 * @param willNotDraw whether or not this View draw on its own
3304 */
3305 public void setWillNotDraw(boolean willNotDraw) {
3306 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3307 }
3308
3309 /**
3310 * Returns whether or not this View draws on its own.
3311 *
3312 * @return true if this view has nothing to draw, false otherwise
3313 */
3314 @ViewDebug.ExportedProperty
3315 public boolean willNotDraw() {
3316 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3317 }
3318
3319 /**
3320 * When a View's drawing cache is enabled, drawing is redirected to an
3321 * offscreen bitmap. Some views, like an ImageView, must be able to
3322 * bypass this mechanism if they already draw a single bitmap, to avoid
3323 * unnecessary usage of the memory.
3324 *
3325 * @param willNotCacheDrawing true if this view does not cache its
3326 * drawing, false otherwise
3327 */
3328 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3329 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3330 }
3331
3332 /**
3333 * Returns whether or not this View can cache its drawing or not.
3334 *
3335 * @return true if this view does not cache its drawing, false otherwise
3336 */
3337 @ViewDebug.ExportedProperty
3338 public boolean willNotCacheDrawing() {
3339 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3340 }
3341
3342 /**
3343 * Indicates whether this view reacts to click events or not.
3344 *
3345 * @return true if the view is clickable, false otherwise
3346 *
3347 * @see #setClickable(boolean)
3348 * @attr ref android.R.styleable#View_clickable
3349 */
3350 @ViewDebug.ExportedProperty
3351 public boolean isClickable() {
3352 return (mViewFlags & CLICKABLE) == CLICKABLE;
3353 }
3354
3355 /**
3356 * Enables or disables click events for this view. When a view
3357 * is clickable it will change its state to "pressed" on every click.
3358 * Subclasses should set the view clickable to visually react to
3359 * user's clicks.
3360 *
3361 * @param clickable true to make the view clickable, false otherwise
3362 *
3363 * @see #isClickable()
3364 * @attr ref android.R.styleable#View_clickable
3365 */
3366 public void setClickable(boolean clickable) {
3367 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3368 }
3369
3370 /**
3371 * Indicates whether this view reacts to long click events or not.
3372 *
3373 * @return true if the view is long clickable, false otherwise
3374 *
3375 * @see #setLongClickable(boolean)
3376 * @attr ref android.R.styleable#View_longClickable
3377 */
3378 public boolean isLongClickable() {
3379 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3380 }
3381
3382 /**
3383 * Enables or disables long click events for this view. When a view is long
3384 * clickable it reacts to the user holding down the button for a longer
3385 * duration than a tap. This event can either launch the listener or a
3386 * context menu.
3387 *
3388 * @param longClickable true to make the view long clickable, false otherwise
3389 * @see #isLongClickable()
3390 * @attr ref android.R.styleable#View_longClickable
3391 */
3392 public void setLongClickable(boolean longClickable) {
3393 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3394 }
3395
3396 /**
3397 * Sets the pressed that for this view.
3398 *
3399 * @see #isClickable()
3400 * @see #setClickable(boolean)
3401 *
3402 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3403 * the View's internal state from a previously set "pressed" state.
3404 */
3405 public void setPressed(boolean pressed) {
3406 if (pressed) {
3407 mPrivateFlags |= PRESSED;
3408 } else {
3409 mPrivateFlags &= ~PRESSED;
3410 }
3411 refreshDrawableState();
3412 dispatchSetPressed(pressed);
3413 }
3414
3415 /**
3416 * Dispatch setPressed to all of this View's children.
3417 *
3418 * @see #setPressed(boolean)
3419 *
3420 * @param pressed The new pressed state
3421 */
3422 protected void dispatchSetPressed(boolean pressed) {
3423 }
3424
3425 /**
3426 * Indicates whether the view is currently in pressed state. Unless
3427 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3428 * the pressed state.
3429 *
3430 * @see #setPressed
3431 * @see #isClickable()
3432 * @see #setClickable(boolean)
3433 *
3434 * @return true if the view is currently pressed, false otherwise
3435 */
3436 public boolean isPressed() {
3437 return (mPrivateFlags & PRESSED) == PRESSED;
3438 }
3439
3440 /**
3441 * Indicates whether this view will save its state (that is,
3442 * whether its {@link #onSaveInstanceState} method will be called).
3443 *
3444 * @return Returns true if the view state saving is enabled, else false.
3445 *
3446 * @see #setSaveEnabled(boolean)
3447 * @attr ref android.R.styleable#View_saveEnabled
3448 */
3449 public boolean isSaveEnabled() {
3450 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3451 }
3452
3453 /**
3454 * Controls whether the saving of this view's state is
3455 * enabled (that is, whether its {@link #onSaveInstanceState} method
3456 * will be called). Note that even if freezing is enabled, the
3457 * view still must have an id assigned to it (via {@link #setId setId()})
3458 * for its state to be saved. This flag can only disable the
3459 * saving of this view; any child views may still have their state saved.
3460 *
3461 * @param enabled Set to false to <em>disable</em> state saving, or true
3462 * (the default) to allow it.
3463 *
3464 * @see #isSaveEnabled()
3465 * @see #setId(int)
3466 * @see #onSaveInstanceState()
3467 * @attr ref android.R.styleable#View_saveEnabled
3468 */
3469 public void setSaveEnabled(boolean enabled) {
3470 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3471 }
3472
3473
3474 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003475 * Indicates whether the entire hierarchy under this view will save its
3476 * state when a state saving traversal occurs from its parent. The default
3477 * is true; if false, these views will not be saved unless
3478 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3479 *
3480 * @return Returns true if the view state saving from parent is enabled, else false.
3481 *
3482 * @see #setSaveFromParentEnabled(boolean)
3483 */
3484 public boolean isSaveFromParentEnabled() {
3485 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3486 }
3487
3488 /**
3489 * Controls whether the entire hierarchy under this view will save its
3490 * state when a state saving traversal occurs from its parent. The default
3491 * is true; if false, these views will not be saved unless
3492 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3493 *
3494 * @param enabled Set to false to <em>disable</em> state saving, or true
3495 * (the default) to allow it.
3496 *
3497 * @see #isSaveFromParentEnabled()
3498 * @see #setId(int)
3499 * @see #onSaveInstanceState()
3500 */
3501 public void setSaveFromParentEnabled(boolean enabled) {
3502 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
3503 }
3504
3505
3506 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 * Returns whether this View is able to take focus.
3508 *
3509 * @return True if this view can take focus, or false otherwise.
3510 * @attr ref android.R.styleable#View_focusable
3511 */
3512 @ViewDebug.ExportedProperty
3513 public final boolean isFocusable() {
3514 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3515 }
3516
3517 /**
3518 * When a view is focusable, it may not want to take focus when in touch mode.
3519 * For example, a button would like focus when the user is navigating via a D-pad
3520 * so that the user can click on it, but once the user starts touching the screen,
3521 * the button shouldn't take focus
3522 * @return Whether the view is focusable in touch mode.
3523 * @attr ref android.R.styleable#View_focusableInTouchMode
3524 */
3525 @ViewDebug.ExportedProperty
3526 public final boolean isFocusableInTouchMode() {
3527 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3528 }
3529
3530 /**
3531 * Find the nearest view in the specified direction that can take focus.
3532 * This does not actually give focus to that view.
3533 *
3534 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3535 *
3536 * @return The nearest focusable in the specified direction, or null if none
3537 * can be found.
3538 */
3539 public View focusSearch(int direction) {
3540 if (mParent != null) {
3541 return mParent.focusSearch(this, direction);
3542 } else {
3543 return null;
3544 }
3545 }
3546
3547 /**
3548 * This method is the last chance for the focused view and its ancestors to
3549 * respond to an arrow key. This is called when the focused view did not
3550 * consume the key internally, nor could the view system find a new view in
3551 * the requested direction to give focus to.
3552 *
3553 * @param focused The currently focused view.
3554 * @param direction The direction focus wants to move. One of FOCUS_UP,
3555 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3556 * @return True if the this view consumed this unhandled move.
3557 */
3558 public boolean dispatchUnhandledMove(View focused, int direction) {
3559 return false;
3560 }
3561
3562 /**
3563 * If a user manually specified the next view id for a particular direction,
3564 * use the root to look up the view. Once a view is found, it is cached
3565 * for future lookups.
3566 * @param root The root view of the hierarchy containing this view.
3567 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3568 * @return The user specified next view, or null if there is none.
3569 */
3570 View findUserSetNextFocus(View root, int direction) {
3571 switch (direction) {
3572 case FOCUS_LEFT:
3573 if (mNextFocusLeftId == View.NO_ID) return null;
3574 return findViewShouldExist(root, mNextFocusLeftId);
3575 case FOCUS_RIGHT:
3576 if (mNextFocusRightId == View.NO_ID) return null;
3577 return findViewShouldExist(root, mNextFocusRightId);
3578 case FOCUS_UP:
3579 if (mNextFocusUpId == View.NO_ID) return null;
3580 return findViewShouldExist(root, mNextFocusUpId);
3581 case FOCUS_DOWN:
3582 if (mNextFocusDownId == View.NO_ID) return null;
3583 return findViewShouldExist(root, mNextFocusDownId);
3584 }
3585 return null;
3586 }
3587
3588 private static View findViewShouldExist(View root, int childViewId) {
3589 View result = root.findViewById(childViewId);
3590 if (result == null) {
3591 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3592 + "by user for id " + childViewId);
3593 }
3594 return result;
3595 }
3596
3597 /**
3598 * Find and return all focusable views that are descendants of this view,
3599 * possibly including this view if it is focusable itself.
3600 *
3601 * @param direction The direction of the focus
3602 * @return A list of focusable views
3603 */
3604 public ArrayList<View> getFocusables(int direction) {
3605 ArrayList<View> result = new ArrayList<View>(24);
3606 addFocusables(result, direction);
3607 return result;
3608 }
3609
3610 /**
3611 * Add any focusable views that are descendants of this view (possibly
3612 * including this view if it is focusable itself) to views. If we are in touch mode,
3613 * only add views that are also focusable in touch mode.
3614 *
3615 * @param views Focusable views found so far
3616 * @param direction The direction of the focus
3617 */
3618 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003619 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621
svetoslavganov75986cf2009-05-14 22:28:01 -07003622 /**
3623 * Adds any focusable views that are descendants of this view (possibly
3624 * including this view if it is focusable itself) to views. This method
3625 * adds all focusable views regardless if we are in touch mode or
3626 * only views focusable in touch mode if we are in touch mode depending on
3627 * the focusable mode paramater.
3628 *
3629 * @param views Focusable views found so far or null if all we are interested is
3630 * the number of focusables.
3631 * @param direction The direction of the focus.
3632 * @param focusableMode The type of focusables to be added.
3633 *
3634 * @see #FOCUSABLES_ALL
3635 * @see #FOCUSABLES_TOUCH_MODE
3636 */
3637 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3638 if (!isFocusable()) {
3639 return;
3640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641
svetoslavganov75986cf2009-05-14 22:28:01 -07003642 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3643 isInTouchMode() && !isFocusableInTouchMode()) {
3644 return;
3645 }
3646
3647 if (views != null) {
3648 views.add(this);
3649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 }
3651
3652 /**
3653 * Find and return all touchable views that are descendants of this view,
3654 * possibly including this view if it is touchable itself.
3655 *
3656 * @return A list of touchable views
3657 */
3658 public ArrayList<View> getTouchables() {
3659 ArrayList<View> result = new ArrayList<View>();
3660 addTouchables(result);
3661 return result;
3662 }
3663
3664 /**
3665 * Add any touchable views that are descendants of this view (possibly
3666 * including this view if it is touchable itself) to views.
3667 *
3668 * @param views Touchable views found so far
3669 */
3670 public void addTouchables(ArrayList<View> views) {
3671 final int viewFlags = mViewFlags;
3672
3673 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
3674 && (viewFlags & ENABLED_MASK) == ENABLED) {
3675 views.add(this);
3676 }
3677 }
3678
3679 /**
3680 * Call this to try to give focus to a specific view or to one of its
3681 * descendants.
3682 *
3683 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3684 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3685 * while the device is in touch mode.
3686 *
3687 * See also {@link #focusSearch}, which is what you call to say that you
3688 * have focus, and you want your parent to look for the next one.
3689 *
3690 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
3691 * {@link #FOCUS_DOWN} and <code>null</code>.
3692 *
3693 * @return Whether this view or one of its descendants actually took focus.
3694 */
3695 public final boolean requestFocus() {
3696 return requestFocus(View.FOCUS_DOWN);
3697 }
3698
3699
3700 /**
3701 * Call this to try to give focus to a specific view or to one of its
3702 * descendants and give it a hint about what direction focus is heading.
3703 *
3704 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3705 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3706 * while the device is in touch mode.
3707 *
3708 * See also {@link #focusSearch}, which is what you call to say that you
3709 * have focus, and you want your parent to look for the next one.
3710 *
3711 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
3712 * <code>null</code> set for the previously focused rectangle.
3713 *
3714 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3715 * @return Whether this view or one of its descendants actually took focus.
3716 */
3717 public final boolean requestFocus(int direction) {
3718 return requestFocus(direction, null);
3719 }
3720
3721 /**
3722 * Call this to try to give focus to a specific view or to one of its descendants
3723 * and give it hints about the direction and a specific rectangle that the focus
3724 * is coming from. The rectangle can help give larger views a finer grained hint
3725 * about where focus is coming from, and therefore, where to show selection, or
3726 * forward focus change internally.
3727 *
3728 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3729 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3730 * while the device is in touch mode.
3731 *
3732 * A View will not take focus if it is not visible.
3733 *
3734 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
3735 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
3736 *
3737 * See also {@link #focusSearch}, which is what you call to say that you
3738 * have focus, and you want your parent to look for the next one.
3739 *
3740 * You may wish to override this method if your custom {@link View} has an internal
3741 * {@link View} that it wishes to forward the request to.
3742 *
3743 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3744 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
3745 * to give a finer grained hint about where focus is coming from. May be null
3746 * if there is no hint.
3747 * @return Whether this view or one of its descendants actually took focus.
3748 */
3749 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
3750 // need to be focusable
3751 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
3752 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3753 return false;
3754 }
3755
3756 // need to be focusable in touch mode if in touch mode
3757 if (isInTouchMode() &&
3758 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
3759 return false;
3760 }
3761
3762 // need to not have any parents blocking us
3763 if (hasAncestorThatBlocksDescendantFocus()) {
3764 return false;
3765 }
3766
3767 handleFocusGainInternal(direction, previouslyFocusedRect);
3768 return true;
3769 }
3770
3771 /**
3772 * Call this to try to give focus to a specific view or to one of its descendants. This is a
3773 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
3774 * touch mode to request focus when they are touched.
3775 *
3776 * @return Whether this view or one of its descendants actually took focus.
3777 *
3778 * @see #isInTouchMode()
3779 *
3780 */
3781 public final boolean requestFocusFromTouch() {
3782 // Leave touch mode if we need to
3783 if (isInTouchMode()) {
3784 View root = getRootView();
3785 if (root != null) {
3786 ViewRoot viewRoot = (ViewRoot)root.getParent();
3787 if (viewRoot != null) {
3788 viewRoot.ensureTouchMode(false);
3789 }
3790 }
3791 }
3792 return requestFocus(View.FOCUS_DOWN);
3793 }
3794
3795 /**
3796 * @return Whether any ancestor of this view blocks descendant focus.
3797 */
3798 private boolean hasAncestorThatBlocksDescendantFocus() {
3799 ViewParent ancestor = mParent;
3800 while (ancestor instanceof ViewGroup) {
3801 final ViewGroup vgAncestor = (ViewGroup) ancestor;
3802 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
3803 return true;
3804 } else {
3805 ancestor = vgAncestor.getParent();
3806 }
3807 }
3808 return false;
3809 }
3810
3811 /**
Romain Guya440b002010-02-24 15:57:54 -08003812 * @hide
3813 */
3814 public void dispatchStartTemporaryDetach() {
3815 onStartTemporaryDetach();
3816 }
3817
3818 /**
3819 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
3821 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08003822 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 */
3824 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08003825 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08003826 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08003827 }
3828
3829 /**
3830 * @hide
3831 */
3832 public void dispatchFinishTemporaryDetach() {
3833 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 }
Romain Guy8506ab42009-06-11 17:35:47 -07003835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 /**
3837 * Called after {@link #onStartTemporaryDetach} when the container is done
3838 * changing the view.
3839 */
3840 public void onFinishTemporaryDetach() {
3841 }
Romain Guy8506ab42009-06-11 17:35:47 -07003842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 /**
3844 * capture information of this view for later analysis: developement only
3845 * check dynamic switch to make sure we only dump view
3846 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
3847 */
3848 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003849 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 return;
3851 }
3852 ViewDebug.dumpCapturedView(subTag, v);
3853 }
3854
3855 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003856 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
3857 * for this view's window. Returns null if the view is not currently attached
3858 * to the window. Normally you will not need to use this directly, but
3859 * just use the standard high-level event callbacks like {@link #onKeyDown}.
3860 */
3861 public KeyEvent.DispatcherState getKeyDispatcherState() {
3862 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
3863 }
3864
3865 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 * Dispatch a key event before it is processed by any input method
3867 * associated with the view hierarchy. This can be used to intercept
3868 * key events in special situations before the IME consumes them; a
3869 * typical example would be handling the BACK key to update the application's
3870 * UI instead of allowing the IME to see it and close itself.
3871 *
3872 * @param event The key event to be dispatched.
3873 * @return True if the event was handled, false otherwise.
3874 */
3875 public boolean dispatchKeyEventPreIme(KeyEvent event) {
3876 return onKeyPreIme(event.getKeyCode(), event);
3877 }
3878
3879 /**
3880 * Dispatch a key event to the next view on the focus path. This path runs
3881 * from the top of the view tree down to the currently focused view. If this
3882 * view has focus, it will dispatch to itself. Otherwise it will dispatch
3883 * the next node down the focus path. This method also fires any key
3884 * listeners.
3885 *
3886 * @param event The key event to be dispatched.
3887 * @return True if the event was handled, false otherwise.
3888 */
3889 public boolean dispatchKeyEvent(KeyEvent event) {
3890 // If any attached key listener a first crack at the event.
3891 //noinspection SimplifiableIfStatement
3892
3893 if (android.util.Config.LOGV) {
3894 captureViewInfo("captureViewKeyEvent", this);
3895 }
3896
3897 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
3898 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
3899 return true;
3900 }
3901
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003902 return event.dispatch(this, mAttachInfo != null
3903 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 }
3905
3906 /**
3907 * Dispatches a key shortcut event.
3908 *
3909 * @param event The key event to be dispatched.
3910 * @return True if the event was handled by the view, false otherwise.
3911 */
3912 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3913 return onKeyShortcut(event.getKeyCode(), event);
3914 }
3915
3916 /**
3917 * Pass the touch screen motion event down to the target view, or this
3918 * view if it is the target.
3919 *
3920 * @param event The motion event to be dispatched.
3921 * @return True if the event was handled by the view, false otherwise.
3922 */
3923 public boolean dispatchTouchEvent(MotionEvent event) {
3924 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
3925 mOnTouchListener.onTouch(this, event)) {
3926 return true;
3927 }
3928 return onTouchEvent(event);
3929 }
3930
3931 /**
3932 * Pass a trackball motion event down to the focused view.
3933 *
3934 * @param event The motion event to be dispatched.
3935 * @return True if the event was handled by the view, false otherwise.
3936 */
3937 public boolean dispatchTrackballEvent(MotionEvent event) {
3938 //Log.i("view", "view=" + this + ", " + event.toString());
3939 return onTrackballEvent(event);
3940 }
3941
3942 /**
3943 * Called when the window containing this view gains or loses window focus.
3944 * ViewGroups should override to route to their children.
3945 *
3946 * @param hasFocus True if the window containing this view now has focus,
3947 * false otherwise.
3948 */
3949 public void dispatchWindowFocusChanged(boolean hasFocus) {
3950 onWindowFocusChanged(hasFocus);
3951 }
3952
3953 /**
3954 * Called when the window containing this view gains or loses focus. Note
3955 * that this is separate from view focus: to receive key events, both
3956 * your view and its window must have focus. If a window is displayed
3957 * on top of yours that takes input focus, then your own window will lose
3958 * focus but the view focus will remain unchanged.
3959 *
3960 * @param hasWindowFocus True if the window containing this view now has
3961 * focus, false otherwise.
3962 */
3963 public void onWindowFocusChanged(boolean hasWindowFocus) {
3964 InputMethodManager imm = InputMethodManager.peekInstance();
3965 if (!hasWindowFocus) {
3966 if (isPressed()) {
3967 setPressed(false);
3968 }
3969 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
3970 imm.focusOut(this);
3971 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05003972 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003973 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
3975 imm.focusIn(this);
3976 }
3977 refreshDrawableState();
3978 }
3979
3980 /**
3981 * Returns true if this view is in a window that currently has window focus.
3982 * Note that this is not the same as the view itself having focus.
3983 *
3984 * @return True if this view is in a window that currently has window focus.
3985 */
3986 public boolean hasWindowFocus() {
3987 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
3988 }
3989
3990 /**
Adam Powell326d8082009-12-09 15:10:07 -08003991 * Dispatch a view visibility change down the view hierarchy.
3992 * ViewGroups should override to route to their children.
3993 * @param changedView The view whose visibility changed. Could be 'this' or
3994 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08003995 * @param visibility The new visibility of changedView: {@link #VISIBLE},
3996 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08003997 */
3998 protected void dispatchVisibilityChanged(View changedView, int visibility) {
3999 onVisibilityChanged(changedView, visibility);
4000 }
4001
4002 /**
4003 * Called when the visibility of the view or an ancestor of the view is changed.
4004 * @param changedView The view whose visibility changed. Could be 'this' or
4005 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004006 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4007 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004008 */
4009 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004010 if (visibility == VISIBLE) {
4011 if (mAttachInfo != null) {
4012 initialAwakenScrollBars();
4013 } else {
4014 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4015 }
4016 }
Adam Powell326d8082009-12-09 15:10:07 -08004017 }
4018
4019 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004020 * Dispatch a hint about whether this view is displayed. For instance, when
4021 * a View moves out of the screen, it might receives a display hint indicating
4022 * the view is not displayed. Applications should not <em>rely</em> on this hint
4023 * as there is no guarantee that they will receive one.
4024 *
4025 * @param hint A hint about whether or not this view is displayed:
4026 * {@link #VISIBLE} or {@link #INVISIBLE}.
4027 */
4028 public void dispatchDisplayHint(int hint) {
4029 onDisplayHint(hint);
4030 }
4031
4032 /**
4033 * Gives this view a hint about whether is displayed or not. For instance, when
4034 * a View moves out of the screen, it might receives a display hint indicating
4035 * the view is not displayed. Applications should not <em>rely</em> on this hint
4036 * as there is no guarantee that they will receive one.
4037 *
4038 * @param hint A hint about whether or not this view is displayed:
4039 * {@link #VISIBLE} or {@link #INVISIBLE}.
4040 */
4041 protected void onDisplayHint(int hint) {
4042 }
4043
4044 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 * Dispatch a window visibility change down the view hierarchy.
4046 * ViewGroups should override to route to their children.
4047 *
4048 * @param visibility The new visibility of the window.
4049 *
4050 * @see #onWindowVisibilityChanged
4051 */
4052 public void dispatchWindowVisibilityChanged(int visibility) {
4053 onWindowVisibilityChanged(visibility);
4054 }
4055
4056 /**
4057 * Called when the window containing has change its visibility
4058 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4059 * that this tells you whether or not your window is being made visible
4060 * to the window manager; this does <em>not</em> tell you whether or not
4061 * your window is obscured by other windows on the screen, even if it
4062 * is itself visible.
4063 *
4064 * @param visibility The new visibility of the window.
4065 */
4066 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004067 if (visibility == VISIBLE) {
4068 initialAwakenScrollBars();
4069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 }
4071
4072 /**
4073 * Returns the current visibility of the window this view is attached to
4074 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4075 *
4076 * @return Returns the current visibility of the view's window.
4077 */
4078 public int getWindowVisibility() {
4079 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4080 }
4081
4082 /**
4083 * Retrieve the overall visible display size in which the window this view is
4084 * attached to has been positioned in. This takes into account screen
4085 * decorations above the window, for both cases where the window itself
4086 * is being position inside of them or the window is being placed under
4087 * then and covered insets are used for the window to position its content
4088 * inside. In effect, this tells you the available area where content can
4089 * be placed and remain visible to users.
4090 *
4091 * <p>This function requires an IPC back to the window manager to retrieve
4092 * the requested information, so should not be used in performance critical
4093 * code like drawing.
4094 *
4095 * @param outRect Filled in with the visible display frame. If the view
4096 * is not attached to a window, this is simply the raw display size.
4097 */
4098 public void getWindowVisibleDisplayFrame(Rect outRect) {
4099 if (mAttachInfo != null) {
4100 try {
4101 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4102 } catch (RemoteException e) {
4103 return;
4104 }
4105 // XXX This is really broken, and probably all needs to be done
4106 // in the window manager, and we need to know more about whether
4107 // we want the area behind or in front of the IME.
4108 final Rect insets = mAttachInfo.mVisibleInsets;
4109 outRect.left += insets.left;
4110 outRect.top += insets.top;
4111 outRect.right -= insets.right;
4112 outRect.bottom -= insets.bottom;
4113 return;
4114 }
4115 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4116 outRect.set(0, 0, d.getWidth(), d.getHeight());
4117 }
4118
4119 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004120 * Dispatch a notification about a resource configuration change down
4121 * the view hierarchy.
4122 * ViewGroups should override to route to their children.
4123 *
4124 * @param newConfig The new resource configuration.
4125 *
4126 * @see #onConfigurationChanged
4127 */
4128 public void dispatchConfigurationChanged(Configuration newConfig) {
4129 onConfigurationChanged(newConfig);
4130 }
4131
4132 /**
4133 * Called when the current configuration of the resources being used
4134 * by the application have changed. You can use this to decide when
4135 * to reload resources that can changed based on orientation and other
4136 * configuration characterstics. You only need to use this if you are
4137 * not relying on the normal {@link android.app.Activity} mechanism of
4138 * recreating the activity instance upon a configuration change.
4139 *
4140 * @param newConfig The new resource configuration.
4141 */
4142 protected void onConfigurationChanged(Configuration newConfig) {
4143 }
4144
4145 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 * Private function to aggregate all per-view attributes in to the view
4147 * root.
4148 */
4149 void dispatchCollectViewAttributes(int visibility) {
4150 performCollectViewAttributes(visibility);
4151 }
4152
4153 void performCollectViewAttributes(int visibility) {
4154 //noinspection PointlessBitwiseExpression
4155 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4156 == (VISIBLE | KEEP_SCREEN_ON)) {
4157 mAttachInfo.mKeepScreenOn = true;
4158 }
4159 }
4160
4161 void needGlobalAttributesUpdate(boolean force) {
4162 AttachInfo ai = mAttachInfo;
4163 if (ai != null) {
4164 if (ai.mKeepScreenOn || force) {
4165 ai.mRecomputeGlobalAttributes = true;
4166 }
4167 }
4168 }
4169
4170 /**
4171 * Returns whether the device is currently in touch mode. Touch mode is entered
4172 * once the user begins interacting with the device by touch, and affects various
4173 * things like whether focus is always visible to the user.
4174 *
4175 * @return Whether the device is in touch mode.
4176 */
4177 @ViewDebug.ExportedProperty
4178 public boolean isInTouchMode() {
4179 if (mAttachInfo != null) {
4180 return mAttachInfo.mInTouchMode;
4181 } else {
4182 return ViewRoot.isInTouchMode();
4183 }
4184 }
4185
4186 /**
4187 * Returns the context the view is running in, through which it can
4188 * access the current theme, resources, etc.
4189 *
4190 * @return The view's Context.
4191 */
4192 @ViewDebug.CapturedViewProperty
4193 public final Context getContext() {
4194 return mContext;
4195 }
4196
4197 /**
4198 * Handle a key event before it is processed by any input method
4199 * associated with the view hierarchy. This can be used to intercept
4200 * key events in special situations before the IME consumes them; a
4201 * typical example would be handling the BACK key to update the application's
4202 * UI instead of allowing the IME to see it and close itself.
4203 *
4204 * @param keyCode The value in event.getKeyCode().
4205 * @param event Description of the key event.
4206 * @return If you handled the event, return true. If you want to allow the
4207 * event to be handled by the next receiver, return false.
4208 */
4209 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4210 return false;
4211 }
4212
4213 /**
4214 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4215 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4216 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4217 * is released, if the view is enabled and clickable.
4218 *
4219 * @param keyCode A key code that represents the button pressed, from
4220 * {@link android.view.KeyEvent}.
4221 * @param event The KeyEvent object that defines the button action.
4222 */
4223 public boolean onKeyDown(int keyCode, KeyEvent event) {
4224 boolean result = false;
4225
4226 switch (keyCode) {
4227 case KeyEvent.KEYCODE_DPAD_CENTER:
4228 case KeyEvent.KEYCODE_ENTER: {
4229 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4230 return true;
4231 }
4232 // Long clickable items don't necessarily have to be clickable
4233 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4234 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4235 (event.getRepeatCount() == 0)) {
4236 setPressed(true);
4237 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004238 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 }
4240 return true;
4241 }
4242 break;
4243 }
4244 }
4245 return result;
4246 }
4247
4248 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004249 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4250 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4251 * the event).
4252 */
4253 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4254 return false;
4255 }
4256
4257 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4259 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4260 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4261 * {@link KeyEvent#KEYCODE_ENTER} is released.
4262 *
4263 * @param keyCode A key code that represents the button pressed, from
4264 * {@link android.view.KeyEvent}.
4265 * @param event The KeyEvent object that defines the button action.
4266 */
4267 public boolean onKeyUp(int keyCode, KeyEvent event) {
4268 boolean result = false;
4269
4270 switch (keyCode) {
4271 case KeyEvent.KEYCODE_DPAD_CENTER:
4272 case KeyEvent.KEYCODE_ENTER: {
4273 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4274 return true;
4275 }
4276 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4277 setPressed(false);
4278
4279 if (!mHasPerformedLongPress) {
4280 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004281 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282
4283 result = performClick();
4284 }
4285 }
4286 break;
4287 }
4288 }
4289 return result;
4290 }
4291
4292 /**
4293 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4294 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4295 * the event).
4296 *
4297 * @param keyCode A key code that represents the button pressed, from
4298 * {@link android.view.KeyEvent}.
4299 * @param repeatCount The number of times the action was made.
4300 * @param event The KeyEvent object that defines the button action.
4301 */
4302 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4303 return false;
4304 }
4305
4306 /**
4307 * Called when an unhandled key shortcut event occurs.
4308 *
4309 * @param keyCode The value in event.getKeyCode().
4310 * @param event Description of the key event.
4311 * @return If you handled the event, return true. If you want to allow the
4312 * event to be handled by the next receiver, return false.
4313 */
4314 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4315 return false;
4316 }
4317
4318 /**
4319 * Check whether the called view is a text editor, in which case it
4320 * would make sense to automatically display a soft input window for
4321 * it. Subclasses should override this if they implement
4322 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004323 * a call on that method would return a non-null InputConnection, and
4324 * they are really a first-class editor that the user would normally
4325 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004326 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004327 * <p>The default implementation always returns false. This does
4328 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4329 * will not be called or the user can not otherwise perform edits on your
4330 * view; it is just a hint to the system that this is not the primary
4331 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004332 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 * @return Returns true if this view is a text editor, else false.
4334 */
4335 public boolean onCheckIsTextEditor() {
4336 return false;
4337 }
Romain Guy8506ab42009-06-11 17:35:47 -07004338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 /**
4340 * Create a new InputConnection for an InputMethod to interact
4341 * with the view. The default implementation returns null, since it doesn't
4342 * support input methods. You can override this to implement such support.
4343 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004344 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 * <p>When implementing this, you probably also want to implement
4346 * {@link #onCheckIsTextEditor()} to indicate you will return a
4347 * non-null InputConnection.
4348 *
4349 * @param outAttrs Fill in with attribute information about the connection.
4350 */
4351 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4352 return null;
4353 }
4354
4355 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004356 * Called by the {@link android.view.inputmethod.InputMethodManager}
4357 * when a view who is not the current
4358 * input connection target is trying to make a call on the manager. The
4359 * default implementation returns false; you can override this to return
4360 * true for certain views if you are performing InputConnection proxying
4361 * to them.
4362 * @param view The View that is making the InputMethodManager call.
4363 * @return Return true to allow the call, false to reject.
4364 */
4365 public boolean checkInputConnectionProxy(View view) {
4366 return false;
4367 }
Romain Guy8506ab42009-06-11 17:35:47 -07004368
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004369 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004370 * Show the context menu for this view. It is not safe to hold on to the
4371 * menu after returning from this method.
4372 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004373 * You should normally not overload this method. Overload
4374 * {@link #onCreateContextMenu(ContextMenu)} or define an
4375 * {@link OnCreateContextMenuListener} to add items to the context menu.
4376 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004377 * @param menu The context menu to populate
4378 */
4379 public void createContextMenu(ContextMenu menu) {
4380 ContextMenuInfo menuInfo = getContextMenuInfo();
4381
4382 // Sets the current menu info so all items added to menu will have
4383 // my extra info set.
4384 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4385
4386 onCreateContextMenu(menu);
4387 if (mOnCreateContextMenuListener != null) {
4388 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4389 }
4390
4391 // Clear the extra information so subsequent items that aren't mine don't
4392 // have my extra info.
4393 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4394
4395 if (mParent != null) {
4396 mParent.createContextMenu(menu);
4397 }
4398 }
4399
4400 /**
4401 * Views should implement this if they have extra information to associate
4402 * with the context menu. The return result is supplied as a parameter to
4403 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4404 * callback.
4405 *
4406 * @return Extra information about the item for which the context menu
4407 * should be shown. This information will vary across different
4408 * subclasses of View.
4409 */
4410 protected ContextMenuInfo getContextMenuInfo() {
4411 return null;
4412 }
4413
4414 /**
4415 * Views should implement this if the view itself is going to add items to
4416 * the context menu.
4417 *
4418 * @param menu the context menu to populate
4419 */
4420 protected void onCreateContextMenu(ContextMenu menu) {
4421 }
4422
4423 /**
4424 * Implement this method to handle trackball motion events. The
4425 * <em>relative</em> movement of the trackball since the last event
4426 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4427 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4428 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4429 * they will often be fractional values, representing the more fine-grained
4430 * movement information available from a trackball).
4431 *
4432 * @param event The motion event.
4433 * @return True if the event was handled, false otherwise.
4434 */
4435 public boolean onTrackballEvent(MotionEvent event) {
4436 return false;
4437 }
4438
4439 /**
4440 * Implement this method to handle touch screen motion events.
4441 *
4442 * @param event The motion event.
4443 * @return True if the event was handled, false otherwise.
4444 */
4445 public boolean onTouchEvent(MotionEvent event) {
4446 final int viewFlags = mViewFlags;
4447
4448 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4449 // A disabled view that is clickable still consumes the touch
4450 // events, it just doesn't respond to them.
4451 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4452 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4453 }
4454
4455 if (mTouchDelegate != null) {
4456 if (mTouchDelegate.onTouchEvent(event)) {
4457 return true;
4458 }
4459 }
4460
4461 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4462 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4463 switch (event.getAction()) {
4464 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004465 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4466 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004467 // take focus if we don't have it already and we should in
4468 // touch mode.
4469 boolean focusTaken = false;
4470 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4471 focusTaken = requestFocus();
4472 }
4473
4474 if (!mHasPerformedLongPress) {
4475 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004476 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477
4478 // Only perform take click actions if we were in the pressed state
4479 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004480 // Use a Runnable and post this rather than calling
4481 // performClick directly. This lets other visual state
4482 // of the view update before click actions start.
4483 if (mPerformClick == null) {
4484 mPerformClick = new PerformClick();
4485 }
4486 if (!post(mPerformClick)) {
4487 performClick();
4488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 }
4490 }
4491
4492 if (mUnsetPressedState == null) {
4493 mUnsetPressedState = new UnsetPressedState();
4494 }
4495
Adam Powelle14579b2009-12-16 18:39:52 -08004496 if (prepressed) {
4497 mPrivateFlags |= PRESSED;
4498 refreshDrawableState();
4499 postDelayed(mUnsetPressedState,
4500 ViewConfiguration.getPressedStateDuration());
4501 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 // If the post failed, unpress right now
4503 mUnsetPressedState.run();
4504 }
Adam Powelle14579b2009-12-16 18:39:52 -08004505 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 }
4507 break;
4508
4509 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004510 if (mPendingCheckForTap == null) {
4511 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004512 }
Adam Powelle14579b2009-12-16 18:39:52 -08004513 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004514 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004515 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 break;
4517
4518 case MotionEvent.ACTION_CANCEL:
4519 mPrivateFlags &= ~PRESSED;
4520 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004521 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004522 break;
4523
4524 case MotionEvent.ACTION_MOVE:
4525 final int x = (int) event.getX();
4526 final int y = (int) event.getY();
4527
4528 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004529 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004531 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004533 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004534 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535
4536 // Need to switch from pressed to not pressed
4537 mPrivateFlags &= ~PRESSED;
4538 refreshDrawableState();
4539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004540 }
4541 break;
4542 }
4543 return true;
4544 }
4545
4546 return false;
4547 }
4548
4549 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004550 * Remove the longpress detection timer.
4551 */
4552 private void removeLongPressCallback() {
4553 if (mPendingCheckForLongPress != null) {
4554 removeCallbacks(mPendingCheckForLongPress);
4555 }
4556 }
Adam Powelle14579b2009-12-16 18:39:52 -08004557
4558 /**
Romain Guya440b002010-02-24 15:57:54 -08004559 * Remove the prepress detection timer.
4560 */
4561 private void removeUnsetPressCallback() {
4562 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4563 setPressed(false);
4564 removeCallbacks(mUnsetPressedState);
4565 }
4566 }
4567
4568 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004569 * Remove the tap detection timer.
4570 */
4571 private void removeTapCallback() {
4572 if (mPendingCheckForTap != null) {
4573 mPrivateFlags &= ~PREPRESSED;
4574 removeCallbacks(mPendingCheckForTap);
4575 }
4576 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004577
4578 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004579 * Cancels a pending long press. Your subclass can use this if you
4580 * want the context menu to come up if the user presses and holds
4581 * at the same place, but you don't want it to come up if they press
4582 * and then move around enough to cause scrolling.
4583 */
4584 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004585 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004586
4587 /*
4588 * The prepressed state handled by the tap callback is a display
4589 * construct, but the tap callback will post a long press callback
4590 * less its own timeout. Remove it here.
4591 */
4592 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 }
4594
4595 /**
4596 * Sets the TouchDelegate for this View.
4597 */
4598 public void setTouchDelegate(TouchDelegate delegate) {
4599 mTouchDelegate = delegate;
4600 }
4601
4602 /**
4603 * Gets the TouchDelegate for this View.
4604 */
4605 public TouchDelegate getTouchDelegate() {
4606 return mTouchDelegate;
4607 }
4608
4609 /**
4610 * Set flags controlling behavior of this view.
4611 *
4612 * @param flags Constant indicating the value which should be set
4613 * @param mask Constant indicating the bit range that should be changed
4614 */
4615 void setFlags(int flags, int mask) {
4616 int old = mViewFlags;
4617 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4618
4619 int changed = mViewFlags ^ old;
4620 if (changed == 0) {
4621 return;
4622 }
4623 int privateFlags = mPrivateFlags;
4624
4625 /* Check if the FOCUSABLE bit has changed */
4626 if (((changed & FOCUSABLE_MASK) != 0) &&
4627 ((privateFlags & HAS_BOUNDS) !=0)) {
4628 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4629 && ((privateFlags & FOCUSED) != 0)) {
4630 /* Give up focus if we are no longer focusable */
4631 clearFocus();
4632 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4633 && ((privateFlags & FOCUSED) == 0)) {
4634 /*
4635 * Tell the view system that we are now available to take focus
4636 * if no one else already has it.
4637 */
4638 if (mParent != null) mParent.focusableViewAvailable(this);
4639 }
4640 }
4641
4642 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4643 if ((changed & VISIBILITY_MASK) != 0) {
4644 /*
4645 * If this view is becoming visible, set the DRAWN flag so that
4646 * the next invalidate() will not be skipped.
4647 */
4648 mPrivateFlags |= DRAWN;
4649
4650 needGlobalAttributesUpdate(true);
4651
4652 // a view becoming visible is worth notifying the parent
4653 // about in case nothing has focus. even if this specific view
4654 // isn't focusable, it may contain something that is, so let
4655 // the root view try to give this focus if nothing else does.
4656 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4657 mParent.focusableViewAvailable(this);
4658 }
4659 }
4660 }
4661
4662 /* Check if the GONE bit has changed */
4663 if ((changed & GONE) != 0) {
4664 needGlobalAttributesUpdate(false);
4665 requestLayout();
4666 invalidate();
4667
Romain Guyecd80ee2009-12-03 17:13:02 -08004668 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
4669 if (hasFocus()) clearFocus();
4670 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004671 }
4672 if (mAttachInfo != null) {
4673 mAttachInfo.mViewVisibilityChanged = true;
4674 }
4675 }
4676
4677 /* Check if the VISIBLE bit has changed */
4678 if ((changed & INVISIBLE) != 0) {
4679 needGlobalAttributesUpdate(false);
4680 invalidate();
4681
4682 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4683 // root view becoming invisible shouldn't clear focus
4684 if (getRootView() != this) {
4685 clearFocus();
4686 }
4687 }
4688 if (mAttachInfo != null) {
4689 mAttachInfo.mViewVisibilityChanged = true;
4690 }
4691 }
4692
Adam Powell326d8082009-12-09 15:10:07 -08004693 if ((changed & VISIBILITY_MASK) != 0) {
4694 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
4695 }
4696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004697 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4698 destroyDrawingCache();
4699 }
4700
4701 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4702 destroyDrawingCache();
4703 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4704 }
4705
4706 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4707 destroyDrawingCache();
4708 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4709 }
4710
4711 if ((changed & DRAW_MASK) != 0) {
4712 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4713 if (mBGDrawable != null) {
4714 mPrivateFlags &= ~SKIP_DRAW;
4715 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4716 } else {
4717 mPrivateFlags |= SKIP_DRAW;
4718 }
4719 } else {
4720 mPrivateFlags &= ~SKIP_DRAW;
4721 }
4722 requestLayout();
4723 invalidate();
4724 }
4725
4726 if ((changed & KEEP_SCREEN_ON) != 0) {
4727 if (mParent != null) {
4728 mParent.recomputeViewAttributes(this);
4729 }
4730 }
4731 }
4732
4733 /**
4734 * Change the view's z order in the tree, so it's on top of other sibling
4735 * views
4736 */
4737 public void bringToFront() {
4738 if (mParent != null) {
4739 mParent.bringChildToFront(this);
4740 }
4741 }
4742
4743 /**
4744 * This is called in response to an internal scroll in this view (i.e., the
4745 * view scrolled its own contents). This is typically as a result of
4746 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4747 * called.
4748 *
4749 * @param l Current horizontal scroll origin.
4750 * @param t Current vertical scroll origin.
4751 * @param oldl Previous horizontal scroll origin.
4752 * @param oldt Previous vertical scroll origin.
4753 */
4754 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4755 mBackgroundSizeChanged = true;
4756
4757 final AttachInfo ai = mAttachInfo;
4758 if (ai != null) {
4759 ai.mViewScrollChanged = true;
4760 }
4761 }
4762
4763 /**
4764 * This is called during layout when the size of this view has changed. If
4765 * you were just added to the view hierarchy, you're called with the old
4766 * values of 0.
4767 *
4768 * @param w Current width of this view.
4769 * @param h Current height of this view.
4770 * @param oldw Old width of this view.
4771 * @param oldh Old height of this view.
4772 */
4773 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
4774 }
4775
4776 /**
4777 * Called by draw to draw the child views. This may be overridden
4778 * by derived classes to gain control just before its children are drawn
4779 * (but after its own view has been drawn).
4780 * @param canvas the canvas on which to draw the view
4781 */
4782 protected void dispatchDraw(Canvas canvas) {
4783 }
4784
4785 /**
4786 * Gets the parent of this view. Note that the parent is a
4787 * ViewParent and not necessarily a View.
4788 *
4789 * @return Parent of this view.
4790 */
4791 public final ViewParent getParent() {
4792 return mParent;
4793 }
4794
4795 /**
4796 * Return the scrolled left position of this view. This is the left edge of
4797 * the displayed part of your view. You do not need to draw any pixels
4798 * farther left, since those are outside of the frame of your view on
4799 * screen.
4800 *
4801 * @return The left edge of the displayed part of your view, in pixels.
4802 */
4803 public final int getScrollX() {
4804 return mScrollX;
4805 }
4806
4807 /**
4808 * Return the scrolled top position of this view. This is the top edge of
4809 * the displayed part of your view. You do not need to draw any pixels above
4810 * it, since those are outside of the frame of your view on screen.
4811 *
4812 * @return The top edge of the displayed part of your view, in pixels.
4813 */
4814 public final int getScrollY() {
4815 return mScrollY;
4816 }
4817
4818 /**
4819 * Return the width of the your view.
4820 *
4821 * @return The width of your view, in pixels.
4822 */
4823 @ViewDebug.ExportedProperty
4824 public final int getWidth() {
4825 return mRight - mLeft;
4826 }
4827
4828 /**
4829 * Return the height of your view.
4830 *
4831 * @return The height of your view, in pixels.
4832 */
4833 @ViewDebug.ExportedProperty
4834 public final int getHeight() {
4835 return mBottom - mTop;
4836 }
4837
4838 /**
4839 * Return the visible drawing bounds of your view. Fills in the output
4840 * rectangle with the values from getScrollX(), getScrollY(),
4841 * getWidth(), and getHeight().
4842 *
4843 * @param outRect The (scrolled) drawing bounds of the view.
4844 */
4845 public void getDrawingRect(Rect outRect) {
4846 outRect.left = mScrollX;
4847 outRect.top = mScrollY;
4848 outRect.right = mScrollX + (mRight - mLeft);
4849 outRect.bottom = mScrollY + (mBottom - mTop);
4850 }
4851
4852 /**
4853 * The width of this view as measured in the most recent call to measure().
4854 * This should be used during measurement and layout calculations only. Use
4855 * {@link #getWidth()} to see how wide a view is after layout.
4856 *
4857 * @return The measured width of this view.
4858 */
4859 public final int getMeasuredWidth() {
4860 return mMeasuredWidth;
4861 }
4862
4863 /**
4864 * The height of this view as measured in the most recent call to measure().
4865 * This should be used during measurement and layout calculations only. Use
4866 * {@link #getHeight()} to see how tall a view is after layout.
4867 *
4868 * @return The measured height of this view.
4869 */
4870 public final int getMeasuredHeight() {
4871 return mMeasuredHeight;
4872 }
4873
4874 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07004875 * The transform matrix of this view, which is calculated based on the current
4876 * roation, scale, and pivot properties.
4877 *
4878 * @see #getRotation()
4879 * @see #getScaleX()
4880 * @see #getScaleY()
4881 * @see #getPivotX()
4882 * @see #getPivotY()
4883 * @return The current transform matrix for the view
4884 */
4885 public Matrix getMatrix() {
Romain Guy33e72ae2010-07-17 12:40:29 -07004886 hasIdentityMatrix();
4887 return mMatrix;
4888 }
4889
4890 /**
4891 * Recomputes the transform matrix if necessary.
4892 *
4893 * @return True if the transform matrix is the identity matrix, false otherwise.
4894 */
4895 boolean hasIdentityMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07004896 if (mMatrixDirty) {
4897 // transform-related properties have changed since the last time someone
4898 // asked for the matrix; recalculate it with the current values
4899 mMatrix.reset();
Chet Haasedf030d22010-07-30 17:22:38 -07004900 mMatrix.setTranslate(mTranslationX, mTranslationY);
4901 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
Chet Haasec3aa3612010-06-17 08:50:37 -07004902 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
4903 mMatrixDirty = false;
4904 mMatrixIsIdentity = mMatrix.isIdentity();
4905 mInverseMatrixDirty = true;
4906 }
Romain Guy33e72ae2010-07-17 12:40:29 -07004907 return mMatrixIsIdentity;
Chet Haasec3aa3612010-06-17 08:50:37 -07004908 }
4909
4910 /**
4911 * Utility method to retrieve the inverse of the current mMatrix property.
4912 * We cache the matrix to avoid recalculating it when transform properties
4913 * have not changed.
4914 *
4915 * @return The inverse of the current matrix of this view.
4916 */
4917 Matrix getInverseMatrix() {
4918 if (mInverseMatrixDirty) {
4919 if (mInverseMatrix == null) {
4920 mInverseMatrix = new Matrix();
4921 }
4922 mMatrix.invert(mInverseMatrix);
4923 mInverseMatrixDirty = false;
4924 }
4925 return mInverseMatrix;
4926 }
4927
4928 /**
4929 * The degrees that the view is rotated around the pivot point.
4930 *
4931 * @see #getPivotX()
4932 * @see #getPivotY()
4933 * @return The degrees of rotation.
4934 */
4935 public float getRotation() {
4936 return mRotation;
4937 }
4938
4939 /**
4940 * Sets the degrees that the view is rotated around the pivot point.
4941 *
4942 * @param rotation The degrees of rotation.
4943 * @see #getPivotX()
4944 * @see #getPivotY()
4945 */
4946 public void setRotation(float rotation) {
4947 if (mRotation != rotation) {
4948 // Double-invalidation is necessary to capture view's old and new areas
4949 invalidate();
4950 mRotation = rotation;
4951 mMatrixDirty = true;
4952 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
4953 invalidate();
4954 }
4955 }
4956
4957 /**
4958 * The amount that the view is scaled in x around the pivot point, as a proportion of
4959 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
4960 *
4961 * @default 1.0f
4962 * @see #getPivotX()
4963 * @see #getPivotY()
4964 * @return The scaling factor.
4965 */
4966 public float getScaleX() {
4967 return mScaleX;
4968 }
4969
4970 /**
4971 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
4972 * the view's unscaled width. A value of 1 means that no scaling is applied.
4973 *
4974 * @param scaleX The scaling factor.
4975 * @see #getPivotX()
4976 * @see #getPivotY()
4977 */
4978 public void setScaleX(float scaleX) {
4979 if (mScaleX != scaleX) {
4980 // Double-invalidation is necessary to capture view's old and new areas
4981 invalidate();
4982 mScaleX = scaleX;
4983 mMatrixDirty = true;
4984 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
4985 invalidate();
4986 }
4987 }
4988
4989 /**
4990 * The amount that the view is scaled in y around the pivot point, as a proportion of
4991 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
4992 *
4993 * @default 1.0f
4994 * @see #getPivotX()
4995 * @see #getPivotY()
4996 * @return The scaling factor.
4997 */
4998 public float getScaleY() {
4999 return mScaleY;
5000 }
5001
5002 /**
5003 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5004 * the view's unscaled width. A value of 1 means that no scaling is applied.
5005 *
5006 * @param scaleY The scaling factor.
5007 * @see #getPivotX()
5008 * @see #getPivotY()
5009 */
5010 public void setScaleY(float scaleY) {
5011 if (mScaleY != scaleY) {
5012 // Double-invalidation is necessary to capture view's old and new areas
5013 invalidate();
5014 mScaleY = scaleY;
5015 mMatrixDirty = true;
5016 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5017 invalidate();
5018 }
5019 }
5020
5021 /**
5022 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5023 * and {@link #setScaleX(float) scaled}.
5024 *
5025 * @see #getRotation()
5026 * @see #getScaleX()
5027 * @see #getScaleY()
5028 * @see #getPivotY()
5029 * @return The x location of the pivot point.
5030 */
5031 public float getPivotX() {
5032 return mPivotX;
5033 }
5034
5035 /**
5036 * Sets the x location of the point around which the view is
5037 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
5038 *
5039 * @param pivotX The x location of the pivot point.
5040 * @see #getRotation()
5041 * @see #getScaleX()
5042 * @see #getScaleY()
5043 * @see #getPivotY()
5044 */
5045 public void setPivotX(float pivotX) {
5046 if (mPivotX != pivotX) {
5047 // Double-invalidation is necessary to capture view's old and new areas
5048 invalidate();
5049 mPivotX = pivotX;
5050 mMatrixDirty = true;
5051 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5052 invalidate();
5053 }
5054 }
5055
5056 /**
5057 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5058 * and {@link #setScaleY(float) scaled}.
5059 *
5060 * @see #getRotation()
5061 * @see #getScaleX()
5062 * @see #getScaleY()
5063 * @see #getPivotY()
5064 * @return The y location of the pivot point.
5065 */
5066 public float getPivotY() {
5067 return mPivotY;
5068 }
5069
5070 /**
5071 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
5072 * and {@link #setScaleY(float) scaled}.
5073 *
5074 * @param pivotY The y location of the pivot point.
5075 * @see #getRotation()
5076 * @see #getScaleX()
5077 * @see #getScaleY()
5078 * @see #getPivotY()
5079 */
5080 public void setPivotY(float pivotY) {
5081 if (mPivotY != pivotY) {
5082 // Double-invalidation is necessary to capture view's old and new areas
5083 invalidate();
5084 mPivotY = pivotY;
5085 mMatrixDirty = true;
5086 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5087 invalidate();
5088 }
5089 }
5090
5091 /**
5092 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5093 * completely transparent and 1 means the view is completely opaque.
5094 *
5095 * @default 1.0f
5096 * @return The opacity of the view.
5097 */
5098 public float getAlpha() {
5099 return mAlpha;
5100 }
5101
5102 /**
5103 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5104 * completely transparent and 1 means the view is completely opaque.
5105 *
5106 * @param alpha The opacity of the view.
5107 */
5108 public void setAlpha(float alpha) {
5109 mAlpha = alpha;
5110 invalidate();
5111 }
5112
5113 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005114 * Top position of this view relative to its parent.
5115 *
5116 * @return The top of this view, in pixels.
5117 */
5118 @ViewDebug.CapturedViewProperty
5119 public final int getTop() {
5120 return mTop;
5121 }
5122
5123 /**
5124 * Bottom position of this view relative to its parent.
5125 *
5126 * @return The bottom of this view, in pixels.
5127 */
5128 @ViewDebug.CapturedViewProperty
5129 public final int getBottom() {
5130 return mBottom;
5131 }
5132
5133 /**
5134 * Left position of this view relative to its parent.
5135 *
5136 * @return The left edge of this view, in pixels.
5137 */
5138 @ViewDebug.CapturedViewProperty
5139 public final int getLeft() {
5140 return mLeft;
5141 }
5142
5143 /**
5144 * Right position of this view relative to its parent.
5145 *
5146 * @return The right edge of this view, in pixels.
5147 */
5148 @ViewDebug.CapturedViewProperty
5149 public final int getRight() {
5150 return mRight;
5151 }
5152
5153 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005154 * The visual x position of this view, in pixels. This is equivalent to the
5155 * {@link #setTranslationX(float) translationX} property plus the current
5156 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07005157 *
Chet Haasedf030d22010-07-30 17:22:38 -07005158 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005159 */
Chet Haasedf030d22010-07-30 17:22:38 -07005160 public float getX() {
5161 return mLeft + mTranslationX;
5162 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005163
Chet Haasedf030d22010-07-30 17:22:38 -07005164 /**
5165 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
5166 * {@link #setTranslationX(float) translationX} property to be the difference between
5167 * the x value passed in and the current {@link #getLeft() left} property.
5168 *
5169 * @param x The visual x position of this view, in pixels.
5170 */
5171 public void setX(float x) {
5172 setTranslationX(x - mLeft);
5173 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005174
Chet Haasedf030d22010-07-30 17:22:38 -07005175 /**
5176 * The visual y position of this view, in pixels. This is equivalent to the
5177 * {@link #setTranslationY(float) translationY} property plus the current
5178 * {@link #getTop() top} property.
5179 *
5180 * @return The visual y position of this view, in pixels.
5181 */
5182 public float getY() {
5183 return mTop + mTranslationY;
5184 }
5185
5186 /**
5187 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
5188 * {@link #setTranslationY(float) translationY} property to be the difference between
5189 * the y value passed in and the current {@link #getTop() top} property.
5190 *
5191 * @param y The visual y position of this view, in pixels.
5192 */
5193 public void setY(float y) {
5194 setTranslationY(y - mTop);
5195 }
5196
5197
5198 /**
5199 * The horizontal location of this view relative to its {@link #getLeft() left} position.
5200 * This position is post-layout, in addition to wherever the object's
5201 * layout placed it.
5202 *
5203 * @return The horizontal position of this view relative to its left position, in pixels.
5204 */
5205 public float getTranslationX() {
5206 return mTranslationX;
5207 }
5208
5209 /**
5210 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
5211 * This effectively positions the object post-layout, in addition to wherever the object's
5212 * layout placed it.
5213 *
5214 * @param translationX The horizontal position of this view relative to its left position,
5215 * in pixels.
5216 */
5217 public void setTranslationX(float translationX) {
5218 if (mTranslationX != translationX) {
5219 // Double-invalidation is necessary to capture view's old and new areas
5220 invalidate();
5221 mTranslationX = translationX;
5222 mMatrixDirty = true;
5223 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5224 invalidate();
Chet Haasec3aa3612010-06-17 08:50:37 -07005225 }
5226 }
5227
5228 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005229 * The horizontal location of this view relative to its {@link #getTop() top} position.
5230 * This position is post-layout, in addition to wherever the object's
5231 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005232 *
Chet Haasedf030d22010-07-30 17:22:38 -07005233 * @return The vertical position of this view relative to its top position,
5234 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005235 */
Chet Haasedf030d22010-07-30 17:22:38 -07005236 public float getTranslationY() {
5237 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07005238 }
5239
5240 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005241 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
5242 * This effectively positions the object post-layout, in addition to wherever the object's
5243 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005244 *
Chet Haasedf030d22010-07-30 17:22:38 -07005245 * @param translationY The vertical position of this view relative to its top position,
5246 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005247 */
Chet Haasedf030d22010-07-30 17:22:38 -07005248 public void setTranslationY(float translationY) {
5249 if (mTranslationY != translationY) {
5250 // Double-invalidation is necessary to capture view's old and new areas
5251 invalidate();
5252 mTranslationY = translationY;
5253 mMatrixDirty = true;
5254 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5255 invalidate();
5256 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005257 }
5258
5259 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 * Hit rectangle in parent's coordinates
5261 *
5262 * @param outRect The hit rectangle of the view.
5263 */
5264 public void getHitRect(Rect outRect) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005265 if (hasIdentityMatrix() || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005266 outRect.set(mLeft, mTop, mRight, mBottom);
5267 } else {
Adam Powellb5de9f32010-07-17 01:00:53 -07005268 Matrix m = getMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005269 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07005270 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Chet Haasec3aa3612010-06-17 08:50:37 -07005271 m.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07005272 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
5273 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07005274 }
5275 }
5276
5277 /**
5278 * This method detects whether the given event is inside the view and, if so,
5279 * handles it via the dispatchEvent(MotionEvent) method.
5280 *
5281 * @param ev The event that is being dispatched.
5282 * @param parentX The x location of the event in the parent's coordinates.
5283 * @param parentY The y location of the event in the parent's coordinates.
5284 * @return true if the event was inside this view, false otherwise.
5285 */
5286 boolean dispatchTouchEvent(MotionEvent ev, float parentX, float parentY) {
5287 float localX = parentX - mLeft;
5288 float localY = parentY - mTop;
Romain Guy33e72ae2010-07-17 12:40:29 -07005289 if (!hasIdentityMatrix() && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005290 // non-identity matrix: transform the point into the view's coordinates
5291 final float[] localXY = mAttachInfo.mTmpTransformLocation;
5292 localXY[0] = localX;
5293 localXY[1] = localY;
5294 getInverseMatrix().mapPoints(localXY);
5295 localX = localXY[0];
5296 localY = localXY[1];
5297 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005298 if (localX >= 0 && localY >= 0 && localX < (mRight - mLeft) && localY < (mBottom - mTop)) {
Adam Powellb5de9f32010-07-17 01:00:53 -07005299 // It would be safer to clone the event here but we don't for performance.
5300 // There are many subtle interactions in touch event dispatch; change at your own risk.
5301 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Chet Haasec3aa3612010-06-17 08:50:37 -07005302 ev.setLocation(localX, localY);
5303 return dispatchTouchEvent(ev);
5304 }
5305 return false;
5306 }
5307
5308 /**
5309 * Utility method to determine whether the given point, in local coordinates,
5310 * is inside the view, where the area of the view is expanded by the slop factor.
5311 * This method is called while processing touch-move events to determine if the event
5312 * is still within the view.
5313 */
5314 private boolean pointInView(float localX, float localY, float slop) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005315 if (!hasIdentityMatrix() && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005316 // non-identity matrix: transform the point into the view's coordinates
5317 final float[] localXY = mAttachInfo.mTmpTransformLocation;
5318 localXY[0] = localX;
5319 localXY[1] = localY;
5320 getInverseMatrix().mapPoints(localXY);
5321 localX = localXY[0];
5322 localY = localXY[1];
5323 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005324 return localX > -slop && localY > -slop && localX < ((mRight - mLeft) + slop) &&
5325 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005326 }
5327
5328 /**
5329 * When a view has focus and the user navigates away from it, the next view is searched for
5330 * starting from the rectangle filled in by this method.
5331 *
5332 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
5333 * view maintains some idea of internal selection, such as a cursor, or a selected row
5334 * or column, you should override this method and fill in a more specific rectangle.
5335 *
5336 * @param r The rectangle to fill in, in this view's coordinates.
5337 */
5338 public void getFocusedRect(Rect r) {
5339 getDrawingRect(r);
5340 }
5341
5342 /**
5343 * If some part of this view is not clipped by any of its parents, then
5344 * return that area in r in global (root) coordinates. To convert r to local
5345 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
5346 * -globalOffset.y)) If the view is completely clipped or translated out,
5347 * return false.
5348 *
5349 * @param r If true is returned, r holds the global coordinates of the
5350 * visible portion of this view.
5351 * @param globalOffset If true is returned, globalOffset holds the dx,dy
5352 * between this view and its root. globalOffet may be null.
5353 * @return true if r is non-empty (i.e. part of the view is visible at the
5354 * root level.
5355 */
5356 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
5357 int width = mRight - mLeft;
5358 int height = mBottom - mTop;
5359 if (width > 0 && height > 0) {
5360 r.set(0, 0, width, height);
5361 if (globalOffset != null) {
5362 globalOffset.set(-mScrollX, -mScrollY);
5363 }
5364 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
5365 }
5366 return false;
5367 }
5368
5369 public final boolean getGlobalVisibleRect(Rect r) {
5370 return getGlobalVisibleRect(r, null);
5371 }
5372
5373 public final boolean getLocalVisibleRect(Rect r) {
5374 Point offset = new Point();
5375 if (getGlobalVisibleRect(r, offset)) {
5376 r.offset(-offset.x, -offset.y); // make r local
5377 return true;
5378 }
5379 return false;
5380 }
5381
5382 /**
5383 * Offset this view's vertical location by the specified number of pixels.
5384 *
5385 * @param offset the number of pixels to offset the view by
5386 */
5387 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005388 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005389 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005390 final ViewParent p = mParent;
5391 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005392 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005393 int minTop;
5394 int maxBottom;
5395 int yLoc;
5396 if (offset < 0) {
5397 minTop = mTop + offset;
5398 maxBottom = mBottom;
5399 yLoc = offset;
5400 } else {
5401 minTop = mTop;
5402 maxBottom = mBottom + offset;
5403 yLoc = 0;
5404 }
5405 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
5406 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005407 }
5408 } else {
5409 invalidate();
5410 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005411
Chet Haasec3aa3612010-06-17 08:50:37 -07005412 mTop += offset;
5413 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005414
Chet Haasec3aa3612010-06-17 08:50:37 -07005415 if (!mMatrixIsIdentity) {
5416 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5417 invalidate();
5418 }
5419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 }
5421
5422 /**
5423 * Offset this view's horizontal location by the specified amount of pixels.
5424 *
5425 * @param offset the numer of pixels to offset the view by
5426 */
5427 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005428 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005429 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005430 final ViewParent p = mParent;
5431 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005432 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005433 int minLeft;
5434 int maxRight;
5435 int xLoc;
5436 if (offset < 0) {
5437 minLeft = mLeft + offset;
5438 maxRight = mRight;
5439 xLoc = offset;
5440 } else {
5441 minLeft = mLeft;
5442 maxRight = mRight + offset;
5443 xLoc = 0;
5444 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005445 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07005446 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005447 }
5448 } else {
5449 invalidate();
5450 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005451
Chet Haasec3aa3612010-06-17 08:50:37 -07005452 mLeft += offset;
5453 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005454
Chet Haasec3aa3612010-06-17 08:50:37 -07005455 if (!mMatrixIsIdentity) {
5456 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5457 invalidate();
5458 }
5459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460 }
5461
5462 /**
5463 * Get the LayoutParams associated with this view. All views should have
5464 * layout parameters. These supply parameters to the <i>parent</i> of this
5465 * view specifying how it should be arranged. There are many subclasses of
5466 * ViewGroup.LayoutParams, and these correspond to the different subclasses
5467 * of ViewGroup that are responsible for arranging their children.
5468 * @return The LayoutParams associated with this view
5469 */
5470 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
5471 public ViewGroup.LayoutParams getLayoutParams() {
5472 return mLayoutParams;
5473 }
5474
5475 /**
5476 * Set the layout parameters associated with this view. These supply
5477 * parameters to the <i>parent</i> of this view specifying how it should be
5478 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
5479 * correspond to the different subclasses of ViewGroup that are responsible
5480 * for arranging their children.
5481 *
5482 * @param params the layout parameters for this view
5483 */
5484 public void setLayoutParams(ViewGroup.LayoutParams params) {
5485 if (params == null) {
5486 throw new NullPointerException("params == null");
5487 }
5488 mLayoutParams = params;
5489 requestLayout();
5490 }
5491
5492 /**
5493 * Set the scrolled position of your view. This will cause a call to
5494 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5495 * invalidated.
5496 * @param x the x position to scroll to
5497 * @param y the y position to scroll to
5498 */
5499 public void scrollTo(int x, int y) {
5500 if (mScrollX != x || mScrollY != y) {
5501 int oldX = mScrollX;
5502 int oldY = mScrollY;
5503 mScrollX = x;
5504 mScrollY = y;
5505 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07005506 if (!awakenScrollBars()) {
5507 invalidate();
5508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 }
5510 }
5511
5512 /**
5513 * Move the scrolled position of your view. This will cause a call to
5514 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5515 * invalidated.
5516 * @param x the amount of pixels to scroll by horizontally
5517 * @param y the amount of pixels to scroll by vertically
5518 */
5519 public void scrollBy(int x, int y) {
5520 scrollTo(mScrollX + x, mScrollY + y);
5521 }
5522
5523 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07005524 * <p>Trigger the scrollbars to draw. When invoked this method starts an
5525 * animation to fade the scrollbars out after a default delay. If a subclass
5526 * provides animated scrolling, the start delay should equal the duration
5527 * of the scrolling animation.</p>
5528 *
5529 * <p>The animation starts only if at least one of the scrollbars is
5530 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
5531 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5532 * this method returns true, and false otherwise. If the animation is
5533 * started, this method calls {@link #invalidate()}; in that case the
5534 * caller should not call {@link #invalidate()}.</p>
5535 *
5536 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07005537 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07005538 *
5539 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
5540 * and {@link #scrollTo(int, int)}.</p>
5541 *
5542 * @return true if the animation is played, false otherwise
5543 *
5544 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07005545 * @see #scrollBy(int, int)
5546 * @see #scrollTo(int, int)
5547 * @see #isHorizontalScrollBarEnabled()
5548 * @see #isVerticalScrollBarEnabled()
5549 * @see #setHorizontalScrollBarEnabled(boolean)
5550 * @see #setVerticalScrollBarEnabled(boolean)
5551 */
5552 protected boolean awakenScrollBars() {
5553 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07005554 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07005555 }
5556
5557 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07005558 * Trigger the scrollbars to draw.
5559 * This method differs from awakenScrollBars() only in its default duration.
5560 * initialAwakenScrollBars() will show the scroll bars for longer than
5561 * usual to give the user more of a chance to notice them.
5562 *
5563 * @return true if the animation is played, false otherwise.
5564 */
5565 private boolean initialAwakenScrollBars() {
5566 return mScrollCache != null &&
5567 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
5568 }
5569
5570 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07005571 * <p>
5572 * Trigger the scrollbars to draw. When invoked this method starts an
5573 * animation to fade the scrollbars out after a fixed delay. If a subclass
5574 * provides animated scrolling, the start delay should equal the duration of
5575 * the scrolling animation.
5576 * </p>
5577 *
5578 * <p>
5579 * The animation starts only if at least one of the scrollbars is enabled,
5580 * as specified by {@link #isHorizontalScrollBarEnabled()} and
5581 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5582 * this method returns true, and false otherwise. If the animation is
5583 * started, this method calls {@link #invalidate()}; in that case the caller
5584 * should not call {@link #invalidate()}.
5585 * </p>
5586 *
5587 * <p>
5588 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07005589 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07005590 * </p>
5591 *
5592 * @param startDelay the delay, in milliseconds, after which the animation
5593 * should start; when the delay is 0, the animation starts
5594 * immediately
5595 * @return true if the animation is played, false otherwise
5596 *
Mike Cleronf116bf82009-09-27 19:14:12 -07005597 * @see #scrollBy(int, int)
5598 * @see #scrollTo(int, int)
5599 * @see #isHorizontalScrollBarEnabled()
5600 * @see #isVerticalScrollBarEnabled()
5601 * @see #setHorizontalScrollBarEnabled(boolean)
5602 * @see #setVerticalScrollBarEnabled(boolean)
5603 */
5604 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07005605 return awakenScrollBars(startDelay, true);
5606 }
5607
5608 /**
5609 * <p>
5610 * Trigger the scrollbars to draw. When invoked this method starts an
5611 * animation to fade the scrollbars out after a fixed delay. If a subclass
5612 * provides animated scrolling, the start delay should equal the duration of
5613 * the scrolling animation.
5614 * </p>
5615 *
5616 * <p>
5617 * The animation starts only if at least one of the scrollbars is enabled,
5618 * as specified by {@link #isHorizontalScrollBarEnabled()} and
5619 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5620 * this method returns true, and false otherwise. If the animation is
5621 * started, this method calls {@link #invalidate()} if the invalidate parameter
5622 * is set to true; in that case the caller
5623 * should not call {@link #invalidate()}.
5624 * </p>
5625 *
5626 * <p>
5627 * This method should be invoked everytime a subclass directly updates the
5628 * scroll parameters.
5629 * </p>
5630 *
5631 * @param startDelay the delay, in milliseconds, after which the animation
5632 * should start; when the delay is 0, the animation starts
5633 * immediately
5634 *
5635 * @param invalidate Wheter this method should call invalidate
5636 *
5637 * @return true if the animation is played, false otherwise
5638 *
5639 * @see #scrollBy(int, int)
5640 * @see #scrollTo(int, int)
5641 * @see #isHorizontalScrollBarEnabled()
5642 * @see #isVerticalScrollBarEnabled()
5643 * @see #setHorizontalScrollBarEnabled(boolean)
5644 * @see #setVerticalScrollBarEnabled(boolean)
5645 */
5646 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07005647 final ScrollabilityCache scrollCache = mScrollCache;
5648
5649 if (scrollCache == null || !scrollCache.fadeScrollBars) {
5650 return false;
5651 }
5652
5653 if (scrollCache.scrollBar == null) {
5654 scrollCache.scrollBar = new ScrollBarDrawable();
5655 }
5656
5657 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
5658
Mike Cleron290947b2009-09-29 18:34:32 -07005659 if (invalidate) {
5660 // Invalidate to show the scrollbars
5661 invalidate();
5662 }
Mike Cleronf116bf82009-09-27 19:14:12 -07005663
5664 if (scrollCache.state == ScrollabilityCache.OFF) {
5665 // FIXME: this is copied from WindowManagerService.
5666 // We should get this value from the system when it
5667 // is possible to do so.
5668 final int KEY_REPEAT_FIRST_DELAY = 750;
5669 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
5670 }
5671
5672 // Tell mScrollCache when we should start fading. This may
5673 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07005674 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07005675 scrollCache.fadeStartTime = fadeStartTime;
5676 scrollCache.state = ScrollabilityCache.ON;
5677
5678 // Schedule our fader to run, unscheduling any old ones first
5679 if (mAttachInfo != null) {
5680 mAttachInfo.mHandler.removeCallbacks(scrollCache);
5681 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
5682 }
5683
5684 return true;
5685 }
5686
5687 return false;
5688 }
5689
5690 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 * Mark the the area defined by dirty as needing to be drawn. If the view is
5692 * visible, {@link #onDraw} will be called at some point in the future.
5693 * This must be called from a UI thread. To call from a non-UI thread, call
5694 * {@link #postInvalidate()}.
5695 *
5696 * WARNING: This method is destructive to dirty.
5697 * @param dirty the rectangle representing the bounds of the dirty region
5698 */
5699 public void invalidate(Rect dirty) {
5700 if (ViewDebug.TRACE_HIERARCHY) {
5701 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5702 }
5703
5704 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5705 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5706 final ViewParent p = mParent;
5707 final AttachInfo ai = mAttachInfo;
5708 if (p != null && ai != null) {
5709 final int scrollX = mScrollX;
5710 final int scrollY = mScrollY;
5711 final Rect r = ai.mTmpInvalRect;
5712 r.set(dirty.left - scrollX, dirty.top - scrollY,
5713 dirty.right - scrollX, dirty.bottom - scrollY);
5714 mParent.invalidateChild(this, r);
5715 }
5716 }
5717 }
5718
5719 /**
5720 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
5721 * The coordinates of the dirty rect are relative to the view.
5722 * If the view is visible, {@link #onDraw} will be called at some point
5723 * in the future. This must be called from a UI thread. To call
5724 * from a non-UI thread, call {@link #postInvalidate()}.
5725 * @param l the left position of the dirty region
5726 * @param t the top position of the dirty region
5727 * @param r the right position of the dirty region
5728 * @param b the bottom position of the dirty region
5729 */
5730 public void invalidate(int l, int t, int r, int b) {
5731 if (ViewDebug.TRACE_HIERARCHY) {
5732 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5733 }
5734
5735 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5736 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5737 final ViewParent p = mParent;
5738 final AttachInfo ai = mAttachInfo;
5739 if (p != null && ai != null && l < r && t < b) {
5740 final int scrollX = mScrollX;
5741 final int scrollY = mScrollY;
5742 final Rect tmpr = ai.mTmpInvalRect;
5743 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
5744 p.invalidateChild(this, tmpr);
5745 }
5746 }
5747 }
5748
5749 /**
5750 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
5751 * be called at some point in the future. This must be called from a
5752 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
5753 */
5754 public void invalidate() {
5755 if (ViewDebug.TRACE_HIERARCHY) {
5756 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5757 }
5758
5759 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5760 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
5761 final ViewParent p = mParent;
5762 final AttachInfo ai = mAttachInfo;
5763 if (p != null && ai != null) {
5764 final Rect r = ai.mTmpInvalRect;
5765 r.set(0, 0, mRight - mLeft, mBottom - mTop);
5766 // Don't call invalidate -- we don't want to internally scroll
5767 // our own bounds
5768 p.invalidateChild(this, r);
5769 }
5770 }
5771 }
5772
5773 /**
Romain Guy24443ea2009-05-11 11:56:30 -07005774 * Indicates whether this View is opaque. An opaque View guarantees that it will
5775 * draw all the pixels overlapping its bounds using a fully opaque color.
5776 *
5777 * Subclasses of View should override this method whenever possible to indicate
5778 * whether an instance is opaque. Opaque Views are treated in a special way by
5779 * the View hierarchy, possibly allowing it to perform optimizations during
5780 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07005781 *
Romain Guy24443ea2009-05-11 11:56:30 -07005782 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07005783 */
Romain Guy83b21072009-05-12 10:54:51 -07005784 @ViewDebug.ExportedProperty
Romain Guy24443ea2009-05-11 11:56:30 -07005785 public boolean isOpaque() {
Romain Guy8f1344f52009-05-15 16:03:59 -07005786 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
5787 }
5788
5789 private void computeOpaqueFlags() {
5790 // Opaque if:
5791 // - Has a background
5792 // - Background is opaque
5793 // - Doesn't have scrollbars or scrollbars are inside overlay
5794
5795 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
5796 mPrivateFlags |= OPAQUE_BACKGROUND;
5797 } else {
5798 mPrivateFlags &= ~OPAQUE_BACKGROUND;
5799 }
5800
5801 final int flags = mViewFlags;
5802 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
5803 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
5804 mPrivateFlags |= OPAQUE_SCROLLBARS;
5805 } else {
5806 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
5807 }
5808 }
5809
5810 /**
5811 * @hide
5812 */
5813 protected boolean hasOpaqueScrollbars() {
5814 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07005815 }
5816
5817 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 * @return A handler associated with the thread running the View. This
5819 * handler can be used to pump events in the UI events queue.
5820 */
5821 public Handler getHandler() {
5822 if (mAttachInfo != null) {
5823 return mAttachInfo.mHandler;
5824 }
5825 return null;
5826 }
5827
5828 /**
5829 * Causes the Runnable to be added to the message queue.
5830 * The runnable will be run on the user interface thread.
5831 *
5832 * @param action The Runnable that will be executed.
5833 *
5834 * @return Returns true if the Runnable was successfully placed in to the
5835 * message queue. Returns false on failure, usually because the
5836 * looper processing the message queue is exiting.
5837 */
5838 public boolean post(Runnable action) {
5839 Handler handler;
5840 if (mAttachInfo != null) {
5841 handler = mAttachInfo.mHandler;
5842 } else {
5843 // Assume that post will succeed later
5844 ViewRoot.getRunQueue().post(action);
5845 return true;
5846 }
5847
5848 return handler.post(action);
5849 }
5850
5851 /**
5852 * Causes the Runnable to be added to the message queue, to be run
5853 * after the specified amount of time elapses.
5854 * The runnable will be run on the user interface thread.
5855 *
5856 * @param action The Runnable that will be executed.
5857 * @param delayMillis The delay (in milliseconds) until the Runnable
5858 * will be executed.
5859 *
5860 * @return true if the Runnable was successfully placed in to the
5861 * message queue. Returns false on failure, usually because the
5862 * looper processing the message queue is exiting. Note that a
5863 * result of true does not mean the Runnable will be processed --
5864 * if the looper is quit before the delivery time of the message
5865 * occurs then the message will be dropped.
5866 */
5867 public boolean postDelayed(Runnable action, long delayMillis) {
5868 Handler handler;
5869 if (mAttachInfo != null) {
5870 handler = mAttachInfo.mHandler;
5871 } else {
5872 // Assume that post will succeed later
5873 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
5874 return true;
5875 }
5876
5877 return handler.postDelayed(action, delayMillis);
5878 }
5879
5880 /**
5881 * Removes the specified Runnable from the message queue.
5882 *
5883 * @param action The Runnable to remove from the message handling queue
5884 *
5885 * @return true if this view could ask the Handler to remove the Runnable,
5886 * false otherwise. When the returned value is true, the Runnable
5887 * may or may not have been actually removed from the message queue
5888 * (for instance, if the Runnable was not in the queue already.)
5889 */
5890 public boolean removeCallbacks(Runnable action) {
5891 Handler handler;
5892 if (mAttachInfo != null) {
5893 handler = mAttachInfo.mHandler;
5894 } else {
5895 // Assume that post will succeed later
5896 ViewRoot.getRunQueue().removeCallbacks(action);
5897 return true;
5898 }
5899
5900 handler.removeCallbacks(action);
5901 return true;
5902 }
5903
5904 /**
5905 * Cause an invalidate to happen on a subsequent cycle through the event loop.
5906 * Use this to invalidate the View from a non-UI thread.
5907 *
5908 * @see #invalidate()
5909 */
5910 public void postInvalidate() {
5911 postInvalidateDelayed(0);
5912 }
5913
5914 /**
5915 * Cause an invalidate of the specified area to happen on a subsequent cycle
5916 * through the event loop. Use this to invalidate the View from a non-UI thread.
5917 *
5918 * @param left The left coordinate of the rectangle to invalidate.
5919 * @param top The top coordinate of the rectangle to invalidate.
5920 * @param right The right coordinate of the rectangle to invalidate.
5921 * @param bottom The bottom coordinate of the rectangle to invalidate.
5922 *
5923 * @see #invalidate(int, int, int, int)
5924 * @see #invalidate(Rect)
5925 */
5926 public void postInvalidate(int left, int top, int right, int bottom) {
5927 postInvalidateDelayed(0, left, top, right, bottom);
5928 }
5929
5930 /**
5931 * Cause an invalidate to happen on a subsequent cycle through the event
5932 * loop. Waits for the specified amount of time.
5933 *
5934 * @param delayMilliseconds the duration in milliseconds to delay the
5935 * invalidation by
5936 */
5937 public void postInvalidateDelayed(long delayMilliseconds) {
5938 // We try only with the AttachInfo because there's no point in invalidating
5939 // if we are not attached to our window
5940 if (mAttachInfo != null) {
5941 Message msg = Message.obtain();
5942 msg.what = AttachInfo.INVALIDATE_MSG;
5943 msg.obj = this;
5944 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
5945 }
5946 }
5947
5948 /**
5949 * Cause an invalidate of the specified area to happen on a subsequent cycle
5950 * through the event loop. Waits for the specified amount of time.
5951 *
5952 * @param delayMilliseconds the duration in milliseconds to delay the
5953 * invalidation by
5954 * @param left The left coordinate of the rectangle to invalidate.
5955 * @param top The top coordinate of the rectangle to invalidate.
5956 * @param right The right coordinate of the rectangle to invalidate.
5957 * @param bottom The bottom coordinate of the rectangle to invalidate.
5958 */
5959 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
5960 int right, int bottom) {
5961
5962 // We try only with the AttachInfo because there's no point in invalidating
5963 // if we are not attached to our window
5964 if (mAttachInfo != null) {
5965 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
5966 info.target = this;
5967 info.left = left;
5968 info.top = top;
5969 info.right = right;
5970 info.bottom = bottom;
5971
5972 final Message msg = Message.obtain();
5973 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
5974 msg.obj = info;
5975 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
5976 }
5977 }
5978
5979 /**
5980 * Called by a parent to request that a child update its values for mScrollX
5981 * and mScrollY if necessary. This will typically be done if the child is
5982 * animating a scroll using a {@link android.widget.Scroller Scroller}
5983 * object.
5984 */
5985 public void computeScroll() {
5986 }
5987
5988 /**
5989 * <p>Indicate whether the horizontal edges are faded when the view is
5990 * scrolled horizontally.</p>
5991 *
5992 * @return true if the horizontal edges should are faded on scroll, false
5993 * otherwise
5994 *
5995 * @see #setHorizontalFadingEdgeEnabled(boolean)
5996 * @attr ref android.R.styleable#View_fadingEdge
5997 */
5998 public boolean isHorizontalFadingEdgeEnabled() {
5999 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6000 }
6001
6002 /**
6003 * <p>Define whether the horizontal edges should be faded when this view
6004 * is scrolled horizontally.</p>
6005 *
6006 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6007 * be faded when the view is scrolled
6008 * horizontally
6009 *
6010 * @see #isHorizontalFadingEdgeEnabled()
6011 * @attr ref android.R.styleable#View_fadingEdge
6012 */
6013 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6014 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6015 if (horizontalFadingEdgeEnabled) {
6016 initScrollCache();
6017 }
6018
6019 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6020 }
6021 }
6022
6023 /**
6024 * <p>Indicate whether the vertical edges are faded when the view is
6025 * scrolled horizontally.</p>
6026 *
6027 * @return true if the vertical edges should are faded on scroll, false
6028 * otherwise
6029 *
6030 * @see #setVerticalFadingEdgeEnabled(boolean)
6031 * @attr ref android.R.styleable#View_fadingEdge
6032 */
6033 public boolean isVerticalFadingEdgeEnabled() {
6034 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6035 }
6036
6037 /**
6038 * <p>Define whether the vertical edges should be faded when this view
6039 * is scrolled vertically.</p>
6040 *
6041 * @param verticalFadingEdgeEnabled true if the vertical edges should
6042 * be faded when the view is scrolled
6043 * vertically
6044 *
6045 * @see #isVerticalFadingEdgeEnabled()
6046 * @attr ref android.R.styleable#View_fadingEdge
6047 */
6048 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6049 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6050 if (verticalFadingEdgeEnabled) {
6051 initScrollCache();
6052 }
6053
6054 mViewFlags ^= FADING_EDGE_VERTICAL;
6055 }
6056 }
6057
6058 /**
6059 * Returns the strength, or intensity, of the top faded edge. The strength is
6060 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6061 * returns 0.0 or 1.0 but no value in between.
6062 *
6063 * Subclasses should override this method to provide a smoother fade transition
6064 * when scrolling occurs.
6065 *
6066 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6067 */
6068 protected float getTopFadingEdgeStrength() {
6069 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6070 }
6071
6072 /**
6073 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6074 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6075 * returns 0.0 or 1.0 but no value in between.
6076 *
6077 * Subclasses should override this method to provide a smoother fade transition
6078 * when scrolling occurs.
6079 *
6080 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6081 */
6082 protected float getBottomFadingEdgeStrength() {
6083 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6084 computeVerticalScrollRange() ? 1.0f : 0.0f;
6085 }
6086
6087 /**
6088 * Returns the strength, or intensity, of the left faded edge. The strength is
6089 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6090 * returns 0.0 or 1.0 but no value in between.
6091 *
6092 * Subclasses should override this method to provide a smoother fade transition
6093 * when scrolling occurs.
6094 *
6095 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6096 */
6097 protected float getLeftFadingEdgeStrength() {
6098 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6099 }
6100
6101 /**
6102 * Returns the strength, or intensity, of the right faded edge. The strength is
6103 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6104 * returns 0.0 or 1.0 but no value in between.
6105 *
6106 * Subclasses should override this method to provide a smoother fade transition
6107 * when scrolling occurs.
6108 *
6109 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6110 */
6111 protected float getRightFadingEdgeStrength() {
6112 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6113 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6114 }
6115
6116 /**
6117 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6118 * scrollbar is not drawn by default.</p>
6119 *
6120 * @return true if the horizontal scrollbar should be painted, false
6121 * otherwise
6122 *
6123 * @see #setHorizontalScrollBarEnabled(boolean)
6124 */
6125 public boolean isHorizontalScrollBarEnabled() {
6126 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6127 }
6128
6129 /**
6130 * <p>Define whether the horizontal scrollbar should be drawn or not. The
6131 * scrollbar is not drawn by default.</p>
6132 *
6133 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
6134 * be painted
6135 *
6136 * @see #isHorizontalScrollBarEnabled()
6137 */
6138 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
6139 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
6140 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006141 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 recomputePadding();
6143 }
6144 }
6145
6146 /**
6147 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
6148 * scrollbar is not drawn by default.</p>
6149 *
6150 * @return true if the vertical scrollbar should be painted, false
6151 * otherwise
6152 *
6153 * @see #setVerticalScrollBarEnabled(boolean)
6154 */
6155 public boolean isVerticalScrollBarEnabled() {
6156 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
6157 }
6158
6159 /**
6160 * <p>Define whether the vertical scrollbar should be drawn or not. The
6161 * scrollbar is not drawn by default.</p>
6162 *
6163 * @param verticalScrollBarEnabled true if the vertical scrollbar should
6164 * be painted
6165 *
6166 * @see #isVerticalScrollBarEnabled()
6167 */
6168 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
6169 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
6170 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006171 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 recomputePadding();
6173 }
6174 }
6175
6176 private void recomputePadding() {
6177 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
6178 }
Mike Cleronfe81d382009-09-28 14:22:16 -07006179
6180 /**
6181 * Define whether scrollbars will fade when the view is not scrolling.
6182 *
6183 * @param fadeScrollbars wheter to enable fading
6184 *
6185 */
6186 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
6187 initScrollCache();
6188 final ScrollabilityCache scrollabilityCache = mScrollCache;
6189 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07006190 if (fadeScrollbars) {
6191 scrollabilityCache.state = ScrollabilityCache.OFF;
6192 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07006193 scrollabilityCache.state = ScrollabilityCache.ON;
6194 }
6195 }
6196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07006198 *
6199 * Returns true if scrollbars will fade when this view is not scrolling
6200 *
6201 * @return true if scrollbar fading is enabled
6202 */
6203 public boolean isScrollbarFadingEnabled() {
6204 return mScrollCache != null && mScrollCache.fadeScrollBars;
6205 }
6206
6207 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
6209 * inset. When inset, they add to the padding of the view. And the scrollbars
6210 * can be drawn inside the padding area or on the edge of the view. For example,
6211 * if a view has a background drawable and you want to draw the scrollbars
6212 * inside the padding specified by the drawable, you can use
6213 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
6214 * appear at the edge of the view, ignoring the padding, then you can use
6215 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
6216 * @param style the style of the scrollbars. Should be one of
6217 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
6218 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
6219 * @see #SCROLLBARS_INSIDE_OVERLAY
6220 * @see #SCROLLBARS_INSIDE_INSET
6221 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6222 * @see #SCROLLBARS_OUTSIDE_INSET
6223 */
6224 public void setScrollBarStyle(int style) {
6225 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
6226 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07006227 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006228 recomputePadding();
6229 }
6230 }
6231
6232 /**
6233 * <p>Returns the current scrollbar style.</p>
6234 * @return the current scrollbar style
6235 * @see #SCROLLBARS_INSIDE_OVERLAY
6236 * @see #SCROLLBARS_INSIDE_INSET
6237 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6238 * @see #SCROLLBARS_OUTSIDE_INSET
6239 */
6240 public int getScrollBarStyle() {
6241 return mViewFlags & SCROLLBARS_STYLE_MASK;
6242 }
6243
6244 /**
6245 * <p>Compute the horizontal range that the horizontal scrollbar
6246 * represents.</p>
6247 *
6248 * <p>The range is expressed in arbitrary units that must be the same as the
6249 * units used by {@link #computeHorizontalScrollExtent()} and
6250 * {@link #computeHorizontalScrollOffset()}.</p>
6251 *
6252 * <p>The default range is the drawing width of this view.</p>
6253 *
6254 * @return the total horizontal range represented by the horizontal
6255 * scrollbar
6256 *
6257 * @see #computeHorizontalScrollExtent()
6258 * @see #computeHorizontalScrollOffset()
6259 * @see android.widget.ScrollBarDrawable
6260 */
6261 protected int computeHorizontalScrollRange() {
6262 return getWidth();
6263 }
6264
6265 /**
6266 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
6267 * within the horizontal range. This value is used to compute the position
6268 * of the thumb within the scrollbar's track.</p>
6269 *
6270 * <p>The range is expressed in arbitrary units that must be the same as the
6271 * units used by {@link #computeHorizontalScrollRange()} and
6272 * {@link #computeHorizontalScrollExtent()}.</p>
6273 *
6274 * <p>The default offset is the scroll offset of this view.</p>
6275 *
6276 * @return the horizontal offset of the scrollbar's thumb
6277 *
6278 * @see #computeHorizontalScrollRange()
6279 * @see #computeHorizontalScrollExtent()
6280 * @see android.widget.ScrollBarDrawable
6281 */
6282 protected int computeHorizontalScrollOffset() {
6283 return mScrollX;
6284 }
6285
6286 /**
6287 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
6288 * within the horizontal range. This value is used to compute the length
6289 * of the thumb within the scrollbar's track.</p>
6290 *
6291 * <p>The range is expressed in arbitrary units that must be the same as the
6292 * units used by {@link #computeHorizontalScrollRange()} and
6293 * {@link #computeHorizontalScrollOffset()}.</p>
6294 *
6295 * <p>The default extent is the drawing width of this view.</p>
6296 *
6297 * @return the horizontal extent of the scrollbar's thumb
6298 *
6299 * @see #computeHorizontalScrollRange()
6300 * @see #computeHorizontalScrollOffset()
6301 * @see android.widget.ScrollBarDrawable
6302 */
6303 protected int computeHorizontalScrollExtent() {
6304 return getWidth();
6305 }
6306
6307 /**
6308 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
6309 *
6310 * <p>The range is expressed in arbitrary units that must be the same as the
6311 * units used by {@link #computeVerticalScrollExtent()} and
6312 * {@link #computeVerticalScrollOffset()}.</p>
6313 *
6314 * @return the total vertical range represented by the vertical scrollbar
6315 *
6316 * <p>The default range is the drawing height of this view.</p>
6317 *
6318 * @see #computeVerticalScrollExtent()
6319 * @see #computeVerticalScrollOffset()
6320 * @see android.widget.ScrollBarDrawable
6321 */
6322 protected int computeVerticalScrollRange() {
6323 return getHeight();
6324 }
6325
6326 /**
6327 * <p>Compute the vertical offset of the vertical scrollbar's thumb
6328 * within the horizontal range. This value is used to compute the position
6329 * of the thumb within the scrollbar's track.</p>
6330 *
6331 * <p>The range is expressed in arbitrary units that must be the same as the
6332 * units used by {@link #computeVerticalScrollRange()} and
6333 * {@link #computeVerticalScrollExtent()}.</p>
6334 *
6335 * <p>The default offset is the scroll offset of this view.</p>
6336 *
6337 * @return the vertical offset of the scrollbar's thumb
6338 *
6339 * @see #computeVerticalScrollRange()
6340 * @see #computeVerticalScrollExtent()
6341 * @see android.widget.ScrollBarDrawable
6342 */
6343 protected int computeVerticalScrollOffset() {
6344 return mScrollY;
6345 }
6346
6347 /**
6348 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
6349 * within the vertical range. This value is used to compute the length
6350 * of the thumb within the scrollbar's track.</p>
6351 *
6352 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08006353 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 * {@link #computeVerticalScrollOffset()}.</p>
6355 *
6356 * <p>The default extent is the drawing height of this view.</p>
6357 *
6358 * @return the vertical extent of the scrollbar's thumb
6359 *
6360 * @see #computeVerticalScrollRange()
6361 * @see #computeVerticalScrollOffset()
6362 * @see android.widget.ScrollBarDrawable
6363 */
6364 protected int computeVerticalScrollExtent() {
6365 return getHeight();
6366 }
6367
6368 /**
6369 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
6370 * scrollbars are painted only if they have been awakened first.</p>
6371 *
6372 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07006373 *
6374 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08006376 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 // scrollbars are drawn only when the animation is running
6378 final ScrollabilityCache cache = mScrollCache;
6379 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006380
6381 int state = cache.state;
6382
6383 if (state == ScrollabilityCache.OFF) {
6384 return;
6385 }
6386
6387 boolean invalidate = false;
6388
6389 if (state == ScrollabilityCache.FADING) {
6390 // We're fading -- get our fade interpolation
6391 if (cache.interpolatorValues == null) {
6392 cache.interpolatorValues = new float[1];
6393 }
6394
6395 float[] values = cache.interpolatorValues;
6396
6397 // Stops the animation if we're done
6398 if (cache.scrollBarInterpolator.timeToValues(values) ==
6399 Interpolator.Result.FREEZE_END) {
6400 cache.state = ScrollabilityCache.OFF;
6401 } else {
6402 cache.scrollBar.setAlpha(Math.round(values[0]));
6403 }
6404
6405 // This will make the scroll bars inval themselves after
6406 // drawing. We only want this when we're fading so that
6407 // we prevent excessive redraws
6408 invalidate = true;
6409 } else {
6410 // We're just on -- but we may have been fading before so
6411 // reset alpha
6412 cache.scrollBar.setAlpha(255);
6413 }
6414
6415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 final int viewFlags = mViewFlags;
6417
6418 final boolean drawHorizontalScrollBar =
6419 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6420 final boolean drawVerticalScrollBar =
6421 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
6422 && !isVerticalScrollBarHidden();
6423
6424 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
6425 final int width = mRight - mLeft;
6426 final int height = mBottom - mTop;
6427
6428 final ScrollBarDrawable scrollBar = cache.scrollBar;
6429 int size = scrollBar.getSize(false);
6430 if (size <= 0) {
6431 size = cache.scrollBarSize;
6432 }
6433
Mike Reede8853fc2009-09-04 14:01:48 -04006434 final int scrollX = mScrollX;
6435 final int scrollY = mScrollY;
6436 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
6437
Mike Cleronf116bf82009-09-27 19:14:12 -07006438 int left, top, right, bottom;
6439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006441 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04006442 computeHorizontalScrollOffset(),
6443 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04006444 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07006445 getVerticalScrollbarWidth() : 0;
6446 top = scrollY + height - size - (mUserPaddingBottom & inside);
6447 left = scrollX + (mPaddingLeft & inside);
6448 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
6449 bottom = top + size;
6450 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
6451 if (invalidate) {
6452 invalidate(left, top, right, bottom);
6453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 }
6455
6456 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04006457 scrollBar.setParameters(computeVerticalScrollRange(),
6458 computeVerticalScrollOffset(),
6459 computeVerticalScrollExtent(), true);
6460 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07006461 left = scrollX + width - size - (mUserPaddingRight & inside);
6462 top = scrollY + (mPaddingTop & inside);
6463 right = left + size;
6464 bottom = scrollY + height - (mUserPaddingBottom & inside);
6465 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
6466 if (invalidate) {
6467 invalidate(left, top, right, bottom);
6468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 }
6470 }
6471 }
6472 }
Romain Guy8506ab42009-06-11 17:35:47 -07006473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 /**
Romain Guy8506ab42009-06-11 17:35:47 -07006475 * 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 -08006476 * FastScroller is visible.
6477 * @return whether to temporarily hide the vertical scrollbar
6478 * @hide
6479 */
6480 protected boolean isVerticalScrollBarHidden() {
6481 return false;
6482 }
6483
6484 /**
6485 * <p>Draw the horizontal scrollbar if
6486 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
6487 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 * @param canvas the canvas on which to draw the scrollbar
6489 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 *
6491 * @see #isHorizontalScrollBarEnabled()
6492 * @see #computeHorizontalScrollRange()
6493 * @see #computeHorizontalScrollExtent()
6494 * @see #computeHorizontalScrollOffset()
6495 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07006496 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006497 */
Mike Reede8853fc2009-09-04 14:01:48 -04006498 protected void onDrawHorizontalScrollBar(Canvas canvas,
6499 Drawable scrollBar,
6500 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006501 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006502 scrollBar.draw(canvas);
6503 }
Mike Reede8853fc2009-09-04 14:01:48 -04006504
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006505 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
6507 * returns true.</p>
6508 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006509 * @param canvas the canvas on which to draw the scrollbar
6510 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 *
6512 * @see #isVerticalScrollBarEnabled()
6513 * @see #computeVerticalScrollRange()
6514 * @see #computeVerticalScrollExtent()
6515 * @see #computeVerticalScrollOffset()
6516 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04006517 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 */
Mike Reede8853fc2009-09-04 14:01:48 -04006519 protected void onDrawVerticalScrollBar(Canvas canvas,
6520 Drawable scrollBar,
6521 int l, int t, int r, int b) {
6522 scrollBar.setBounds(l, t, r, b);
6523 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 }
6525
6526 /**
6527 * Implement this to do your drawing.
6528 *
6529 * @param canvas the canvas on which the background will be drawn
6530 */
6531 protected void onDraw(Canvas canvas) {
6532 }
6533
6534 /*
6535 * Caller is responsible for calling requestLayout if necessary.
6536 * (This allows addViewInLayout to not request a new layout.)
6537 */
6538 void assignParent(ViewParent parent) {
6539 if (mParent == null) {
6540 mParent = parent;
6541 } else if (parent == null) {
6542 mParent = null;
6543 } else {
6544 throw new RuntimeException("view " + this + " being added, but"
6545 + " it already has a parent");
6546 }
6547 }
6548
6549 /**
6550 * This is called when the view is attached to a window. At this point it
6551 * has a Surface and will start drawing. Note that this function is
6552 * guaranteed to be called before {@link #onDraw}, however it may be called
6553 * any time before the first onDraw -- including before or after
6554 * {@link #onMeasure}.
6555 *
6556 * @see #onDetachedFromWindow()
6557 */
6558 protected void onAttachedToWindow() {
6559 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
6560 mParent.requestTransparentRegion(this);
6561 }
Adam Powell8568c3a2010-04-19 14:26:11 -07006562 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
6563 initialAwakenScrollBars();
6564 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
6565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 }
6567
6568 /**
6569 * This is called when the view is detached from a window. At this point it
6570 * no longer has a surface for drawing.
6571 *
6572 * @see #onAttachedToWindow()
6573 */
6574 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08006575 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08006576 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05006577 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 destroyDrawingCache();
6579 }
6580
6581 /**
6582 * @return The number of times this view has been attached to a window
6583 */
6584 protected int getWindowAttachCount() {
6585 return mWindowAttachCount;
6586 }
6587
6588 /**
6589 * Retrieve a unique token identifying the window this view is attached to.
6590 * @return Return the window's token for use in
6591 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
6592 */
6593 public IBinder getWindowToken() {
6594 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
6595 }
6596
6597 /**
6598 * Retrieve a unique token identifying the top-level "real" window of
6599 * the window that this view is attached to. That is, this is like
6600 * {@link #getWindowToken}, except if the window this view in is a panel
6601 * window (attached to another containing window), then the token of
6602 * the containing window is returned instead.
6603 *
6604 * @return Returns the associated window token, either
6605 * {@link #getWindowToken()} or the containing window's token.
6606 */
6607 public IBinder getApplicationWindowToken() {
6608 AttachInfo ai = mAttachInfo;
6609 if (ai != null) {
6610 IBinder appWindowToken = ai.mPanelParentWindowToken;
6611 if (appWindowToken == null) {
6612 appWindowToken = ai.mWindowToken;
6613 }
6614 return appWindowToken;
6615 }
6616 return null;
6617 }
6618
6619 /**
6620 * Retrieve private session object this view hierarchy is using to
6621 * communicate with the window manager.
6622 * @return the session object to communicate with the window manager
6623 */
6624 /*package*/ IWindowSession getWindowSession() {
6625 return mAttachInfo != null ? mAttachInfo.mSession : null;
6626 }
6627
6628 /**
6629 * @param info the {@link android.view.View.AttachInfo} to associated with
6630 * this view
6631 */
6632 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
6633 //System.out.println("Attached! " + this);
6634 mAttachInfo = info;
6635 mWindowAttachCount++;
6636 if (mFloatingTreeObserver != null) {
6637 info.mTreeObserver.merge(mFloatingTreeObserver);
6638 mFloatingTreeObserver = null;
6639 }
6640 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
6641 mAttachInfo.mScrollContainers.add(this);
6642 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
6643 }
6644 performCollectViewAttributes(visibility);
6645 onAttachedToWindow();
6646 int vis = info.mWindowVisibility;
6647 if (vis != GONE) {
6648 onWindowVisibilityChanged(vis);
6649 }
6650 }
6651
6652 void dispatchDetachedFromWindow() {
6653 //System.out.println("Detached! " + this);
6654 AttachInfo info = mAttachInfo;
6655 if (info != null) {
6656 int vis = info.mWindowVisibility;
6657 if (vis != GONE) {
6658 onWindowVisibilityChanged(GONE);
6659 }
6660 }
6661
6662 onDetachedFromWindow();
6663 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
6664 mAttachInfo.mScrollContainers.remove(this);
6665 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
6666 }
6667 mAttachInfo = null;
6668 }
6669
6670 /**
6671 * Store this view hierarchy's frozen state into the given container.
6672 *
6673 * @param container The SparseArray in which to save the view's state.
6674 *
6675 * @see #restoreHierarchyState
6676 * @see #dispatchSaveInstanceState
6677 * @see #onSaveInstanceState
6678 */
6679 public void saveHierarchyState(SparseArray<Parcelable> container) {
6680 dispatchSaveInstanceState(container);
6681 }
6682
6683 /**
6684 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
6685 * May be overridden to modify how freezing happens to a view's children; for example, some
6686 * views may want to not store state for their children.
6687 *
6688 * @param container The SparseArray in which to save the view's state.
6689 *
6690 * @see #dispatchRestoreInstanceState
6691 * @see #saveHierarchyState
6692 * @see #onSaveInstanceState
6693 */
6694 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
6695 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
6696 mPrivateFlags &= ~SAVE_STATE_CALLED;
6697 Parcelable state = onSaveInstanceState();
6698 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
6699 throw new IllegalStateException(
6700 "Derived class did not call super.onSaveInstanceState()");
6701 }
6702 if (state != null) {
6703 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
6704 // + ": " + state);
6705 container.put(mID, state);
6706 }
6707 }
6708 }
6709
6710 /**
6711 * Hook allowing a view to generate a representation of its internal state
6712 * that can later be used to create a new instance with that same state.
6713 * This state should only contain information that is not persistent or can
6714 * not be reconstructed later. For example, you will never store your
6715 * current position on screen because that will be computed again when a
6716 * new instance of the view is placed in its view hierarchy.
6717 * <p>
6718 * Some examples of things you may store here: the current cursor position
6719 * in a text view (but usually not the text itself since that is stored in a
6720 * content provider or other persistent storage), the currently selected
6721 * item in a list view.
6722 *
6723 * @return Returns a Parcelable object containing the view's current dynamic
6724 * state, or null if there is nothing interesting to save. The
6725 * default implementation returns null.
6726 * @see #onRestoreInstanceState
6727 * @see #saveHierarchyState
6728 * @see #dispatchSaveInstanceState
6729 * @see #setSaveEnabled(boolean)
6730 */
6731 protected Parcelable onSaveInstanceState() {
6732 mPrivateFlags |= SAVE_STATE_CALLED;
6733 return BaseSavedState.EMPTY_STATE;
6734 }
6735
6736 /**
6737 * Restore this view hierarchy's frozen state from the given container.
6738 *
6739 * @param container The SparseArray which holds previously frozen states.
6740 *
6741 * @see #saveHierarchyState
6742 * @see #dispatchRestoreInstanceState
6743 * @see #onRestoreInstanceState
6744 */
6745 public void restoreHierarchyState(SparseArray<Parcelable> container) {
6746 dispatchRestoreInstanceState(container);
6747 }
6748
6749 /**
6750 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
6751 * children. May be overridden to modify how restoreing happens to a view's children; for
6752 * example, some views may want to not store state for their children.
6753 *
6754 * @param container The SparseArray which holds previously saved state.
6755 *
6756 * @see #dispatchSaveInstanceState
6757 * @see #restoreHierarchyState
6758 * @see #onRestoreInstanceState
6759 */
6760 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
6761 if (mID != NO_ID) {
6762 Parcelable state = container.get(mID);
6763 if (state != null) {
6764 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
6765 // + ": " + state);
6766 mPrivateFlags &= ~SAVE_STATE_CALLED;
6767 onRestoreInstanceState(state);
6768 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
6769 throw new IllegalStateException(
6770 "Derived class did not call super.onRestoreInstanceState()");
6771 }
6772 }
6773 }
6774 }
6775
6776 /**
6777 * Hook allowing a view to re-apply a representation of its internal state that had previously
6778 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
6779 * null state.
6780 *
6781 * @param state The frozen state that had previously been returned by
6782 * {@link #onSaveInstanceState}.
6783 *
6784 * @see #onSaveInstanceState
6785 * @see #restoreHierarchyState
6786 * @see #dispatchRestoreInstanceState
6787 */
6788 protected void onRestoreInstanceState(Parcelable state) {
6789 mPrivateFlags |= SAVE_STATE_CALLED;
6790 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08006791 throw new IllegalArgumentException("Wrong state class, expecting View State but "
6792 + "received " + state.getClass().toString() + " instead. This usually happens "
6793 + "when two views of different type have the same id in the same hierarchy. "
6794 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
6795 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 }
6797 }
6798
6799 /**
6800 * <p>Return the time at which the drawing of the view hierarchy started.</p>
6801 *
6802 * @return the drawing start time in milliseconds
6803 */
6804 public long getDrawingTime() {
6805 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
6806 }
6807
6808 /**
6809 * <p>Enables or disables the duplication of the parent's state into this view. When
6810 * duplication is enabled, this view gets its drawable state from its parent rather
6811 * than from its own internal properties.</p>
6812 *
6813 * <p>Note: in the current implementation, setting this property to true after the
6814 * view was added to a ViewGroup might have no effect at all. This property should
6815 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
6816 *
6817 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
6818 * property is enabled, an exception will be thrown.</p>
6819 *
6820 * @param enabled True to enable duplication of the parent's drawable state, false
6821 * to disable it.
6822 *
6823 * @see #getDrawableState()
6824 * @see #isDuplicateParentStateEnabled()
6825 */
6826 public void setDuplicateParentStateEnabled(boolean enabled) {
6827 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
6828 }
6829
6830 /**
6831 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
6832 *
6833 * @return True if this view's drawable state is duplicated from the parent,
6834 * false otherwise
6835 *
6836 * @see #getDrawableState()
6837 * @see #setDuplicateParentStateEnabled(boolean)
6838 */
6839 public boolean isDuplicateParentStateEnabled() {
6840 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
6841 }
6842
6843 /**
6844 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
6845 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
6846 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
6847 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
6848 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
6849 * null.</p>
6850 *
6851 * @param enabled true to enable the drawing cache, false otherwise
6852 *
6853 * @see #isDrawingCacheEnabled()
6854 * @see #getDrawingCache()
6855 * @see #buildDrawingCache()
6856 */
6857 public void setDrawingCacheEnabled(boolean enabled) {
6858 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
6859 }
6860
6861 /**
6862 * <p>Indicates whether the drawing cache is enabled for this view.</p>
6863 *
6864 * @return true if the drawing cache is enabled
6865 *
6866 * @see #setDrawingCacheEnabled(boolean)
6867 * @see #getDrawingCache()
6868 */
6869 @ViewDebug.ExportedProperty
6870 public boolean isDrawingCacheEnabled() {
6871 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
6872 }
6873
6874 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07006875 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
6876 *
6877 * @return A non-scaled bitmap representing this view or null if cache is disabled.
6878 *
6879 * @see #getDrawingCache(boolean)
6880 */
6881 public Bitmap getDrawingCache() {
6882 return getDrawingCache(false);
6883 }
6884
6885 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
6887 * is null when caching is disabled. If caching is enabled and the cache is not ready,
6888 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
6889 * draw from the cache when the cache is enabled. To benefit from the cache, you must
6890 * request the drawing cache by calling this method and draw it on screen if the
6891 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07006892 *
6893 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
6894 * this method will create a bitmap of the same size as this view. Because this bitmap
6895 * will be drawn scaled by the parent ViewGroup, the result on screen might show
6896 * scaling artifacts. To avoid such artifacts, you should call this method by setting
6897 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
6898 * size than the view. This implies that your application must be able to handle this
6899 * size.</p>
6900 *
6901 * @param autoScale Indicates whether the generated bitmap should be scaled based on
6902 * the current density of the screen when the application is in compatibility
6903 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006904 *
Romain Guyfbd8f692009-06-26 14:51:58 -07006905 * @return A bitmap representing this view or null if cache is disabled.
6906 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006907 * @see #setDrawingCacheEnabled(boolean)
6908 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07006909 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006910 * @see #destroyDrawingCache()
6911 */
Romain Guyfbd8f692009-06-26 14:51:58 -07006912 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006913 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
6914 return null;
6915 }
6916 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07006917 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918 }
Romain Guyfbd8f692009-06-26 14:51:58 -07006919 return autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) :
6920 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006921 }
6922
6923 /**
6924 * <p>Frees the resources used by the drawing cache. If you call
6925 * {@link #buildDrawingCache()} manually without calling
6926 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
6927 * should cleanup the cache with this method afterwards.</p>
6928 *
6929 * @see #setDrawingCacheEnabled(boolean)
6930 * @see #buildDrawingCache()
6931 * @see #getDrawingCache()
6932 */
6933 public void destroyDrawingCache() {
6934 if (mDrawingCache != null) {
6935 final Bitmap bitmap = mDrawingCache.get();
6936 if (bitmap != null) bitmap.recycle();
6937 mDrawingCache = null;
6938 }
Romain Guyfbd8f692009-06-26 14:51:58 -07006939 if (mUnscaledDrawingCache != null) {
6940 final Bitmap bitmap = mUnscaledDrawingCache.get();
6941 if (bitmap != null) bitmap.recycle();
6942 mUnscaledDrawingCache = null;
6943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 }
6945
6946 /**
6947 * Setting a solid background color for the drawing cache's bitmaps will improve
6948 * perfromance and memory usage. Note, though that this should only be used if this
6949 * view will always be drawn on top of a solid color.
6950 *
6951 * @param color The background color to use for the drawing cache's bitmap
6952 *
6953 * @see #setDrawingCacheEnabled(boolean)
6954 * @see #buildDrawingCache()
6955 * @see #getDrawingCache()
6956 */
6957 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08006958 if (color != mDrawingCacheBackgroundColor) {
6959 mDrawingCacheBackgroundColor = color;
6960 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 }
6963
6964 /**
6965 * @see #setDrawingCacheBackgroundColor(int)
6966 *
6967 * @return The background color to used for the drawing cache's bitmap
6968 */
6969 public int getDrawingCacheBackgroundColor() {
6970 return mDrawingCacheBackgroundColor;
6971 }
6972
6973 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07006974 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
6975 *
6976 * @see #buildDrawingCache(boolean)
6977 */
6978 public void buildDrawingCache() {
6979 buildDrawingCache(false);
6980 }
6981
6982 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006983 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
6984 *
6985 * <p>If you call {@link #buildDrawingCache()} manually without calling
6986 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
6987 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07006988 *
6989 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
6990 * this method will create a bitmap of the same size as this view. Because this bitmap
6991 * will be drawn scaled by the parent ViewGroup, the result on screen might show
6992 * scaling artifacts. To avoid such artifacts, you should call this method by setting
6993 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
6994 * size than the view. This implies that your application must be able to handle this
6995 * size.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006996 *
6997 * @see #getDrawingCache()
6998 * @see #destroyDrawingCache()
6999 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007000 public void buildDrawingCache(boolean autoScale) {
7001 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
7002 (mDrawingCache == null || mDrawingCache.get() == null) :
7003 (mUnscaledDrawingCache == null || mUnscaledDrawingCache.get() == null))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007004
7005 if (ViewDebug.TRACE_HIERARCHY) {
7006 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7007 }
Romain Guy13922e02009-05-12 17:56:14 -07007008 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007009 EventLog.writeEvent(60002, hashCode());
7010 }
7011
Romain Guy8506ab42009-06-11 17:35:47 -07007012 int width = mRight - mLeft;
7013 int height = mBottom - mTop;
7014
7015 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007016 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007017
Romain Guye1123222009-06-29 14:24:56 -07007018 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007019 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7020 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022
7023 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007024 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Romain Guya62e4702009-10-08 10:48:54 -07007025 final boolean translucentWindow = attachInfo != null && attachInfo.mTranslucentWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007026
7027 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007028 // Projected bitmap size in bytes
7029 (width * height * (opaque && !translucentWindow ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007030 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7031 destroyDrawingCache();
7032 return;
7033 }
7034
7035 boolean clear = true;
Romain Guyfbd8f692009-06-26 14:51:58 -07007036 Bitmap bitmap = autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) :
7037 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007038
7039 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007040 Bitmap.Config quality;
7041 if (!opaque) {
7042 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7043 case DRAWING_CACHE_QUALITY_AUTO:
7044 quality = Bitmap.Config.ARGB_8888;
7045 break;
7046 case DRAWING_CACHE_QUALITY_LOW:
7047 quality = Bitmap.Config.ARGB_4444;
7048 break;
7049 case DRAWING_CACHE_QUALITY_HIGH:
7050 quality = Bitmap.Config.ARGB_8888;
7051 break;
7052 default:
7053 quality = Bitmap.Config.ARGB_8888;
7054 break;
7055 }
7056 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07007057 // Optimization for translucent windows
7058 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
7059 quality = translucentWindow ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007060 }
7061
7062 // Try to cleanup memory
7063 if (bitmap != null) bitmap.recycle();
7064
7065 try {
7066 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07007067 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07007068 if (autoScale) {
7069 mDrawingCache = new SoftReference<Bitmap>(bitmap);
7070 } else {
7071 mUnscaledDrawingCache = new SoftReference<Bitmap>(bitmap);
7072 }
Romain Guy35b38ce2009-10-07 13:38:55 -07007073 if (opaque && translucentWindow) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 } catch (OutOfMemoryError e) {
7075 // If there is not enough memory to create the bitmap cache, just
7076 // ignore the issue as bitmap caches are not required to draw the
7077 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07007078 if (autoScale) {
7079 mDrawingCache = null;
7080 } else {
7081 mUnscaledDrawingCache = null;
7082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 return;
7084 }
7085
7086 clear = drawingCacheBackgroundColor != 0;
7087 }
7088
7089 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007090 if (attachInfo != null) {
7091 canvas = attachInfo.mCanvas;
7092 if (canvas == null) {
7093 canvas = new Canvas();
7094 }
7095 canvas.setBitmap(bitmap);
7096 // Temporarily clobber the cached Canvas in case one of our children
7097 // is also using a drawing cache. Without this, the children would
7098 // steal the canvas by attaching their own bitmap to it and bad, bad
7099 // thing would happen (invisible views, corrupted drawings, etc.)
7100 attachInfo.mCanvas = null;
7101 } else {
7102 // This case should hopefully never or seldom happen
7103 canvas = new Canvas(bitmap);
7104 }
7105
7106 if (clear) {
7107 bitmap.eraseColor(drawingCacheBackgroundColor);
7108 }
7109
7110 computeScroll();
7111 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07007112
Romain Guye1123222009-06-29 14:24:56 -07007113 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007114 final float scale = attachInfo.mApplicationScale;
7115 canvas.scale(scale, scale);
7116 }
7117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 canvas.translate(-mScrollX, -mScrollY);
7119
Romain Guy5bcdff42009-05-14 21:27:18 -07007120 mPrivateFlags |= DRAWN;
Romain Guyecd80ee2009-12-03 17:13:02 -08007121 mPrivateFlags |= DRAWING_CACHE_VALID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007122
7123 // Fast path for layouts with no backgrounds
7124 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7125 if (ViewDebug.TRACE_HIERARCHY) {
7126 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7127 }
Romain Guy5bcdff42009-05-14 21:27:18 -07007128 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007129 dispatchDraw(canvas);
7130 } else {
7131 draw(canvas);
7132 }
7133
7134 canvas.restoreToCount(restoreCount);
7135
7136 if (attachInfo != null) {
7137 // Restore the cached Canvas for our siblings
7138 attachInfo.mCanvas = canvas;
7139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007140 }
7141 }
7142
7143 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007144 * Create a snapshot of the view into a bitmap. We should probably make
7145 * some form of this public, but should think about the API.
7146 */
Romain Guy223ff5c2010-03-02 17:07:47 -08007147 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007148 int width = mRight - mLeft;
7149 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007150
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007151 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07007152 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007153 width = (int) ((width * scale) + 0.5f);
7154 height = (int) ((height * scale) + 0.5f);
7155
Romain Guy8c11e312009-09-14 15:15:30 -07007156 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007157 if (bitmap == null) {
7158 throw new OutOfMemoryError();
7159 }
7160
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007161 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
7162
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007163 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007164 if (attachInfo != null) {
7165 canvas = attachInfo.mCanvas;
7166 if (canvas == null) {
7167 canvas = new Canvas();
7168 }
7169 canvas.setBitmap(bitmap);
7170 // Temporarily clobber the cached Canvas in case one of our children
7171 // is also using a drawing cache. Without this, the children would
7172 // steal the canvas by attaching their own bitmap to it and bad, bad
7173 // things would happen (invisible views, corrupted drawings, etc.)
7174 attachInfo.mCanvas = null;
7175 } else {
7176 // This case should hopefully never or seldom happen
7177 canvas = new Canvas(bitmap);
7178 }
7179
Romain Guy5bcdff42009-05-14 21:27:18 -07007180 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007181 bitmap.eraseColor(backgroundColor);
7182 }
7183
7184 computeScroll();
7185 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007186 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007187 canvas.translate(-mScrollX, -mScrollY);
7188
Romain Guy5bcdff42009-05-14 21:27:18 -07007189 // Temporarily remove the dirty mask
7190 int flags = mPrivateFlags;
7191 mPrivateFlags &= ~DIRTY_MASK;
7192
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007193 // Fast path for layouts with no backgrounds
7194 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7195 dispatchDraw(canvas);
7196 } else {
7197 draw(canvas);
7198 }
7199
Romain Guy5bcdff42009-05-14 21:27:18 -07007200 mPrivateFlags = flags;
7201
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007202 canvas.restoreToCount(restoreCount);
7203
7204 if (attachInfo != null) {
7205 // Restore the cached Canvas for our siblings
7206 attachInfo.mCanvas = canvas;
7207 }
Romain Guy8506ab42009-06-11 17:35:47 -07007208
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007209 return bitmap;
7210 }
7211
7212 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007213 * Indicates whether this View is currently in edit mode. A View is usually
7214 * in edit mode when displayed within a developer tool. For instance, if
7215 * this View is being drawn by a visual user interface builder, this method
7216 * should return true.
7217 *
7218 * Subclasses should check the return value of this method to provide
7219 * different behaviors if their normal behavior might interfere with the
7220 * host environment. For instance: the class spawns a thread in its
7221 * constructor, the drawing code relies on device-specific features, etc.
7222 *
7223 * This method is usually checked in the drawing code of custom widgets.
7224 *
7225 * @return True if this View is in edit mode, false otherwise.
7226 */
7227 public boolean isInEditMode() {
7228 return false;
7229 }
7230
7231 /**
7232 * If the View draws content inside its padding and enables fading edges,
7233 * it needs to support padding offsets. Padding offsets are added to the
7234 * fading edges to extend the length of the fade so that it covers pixels
7235 * drawn inside the padding.
7236 *
7237 * Subclasses of this class should override this method if they need
7238 * to draw content inside the padding.
7239 *
7240 * @return True if padding offset must be applied, false otherwise.
7241 *
7242 * @see #getLeftPaddingOffset()
7243 * @see #getRightPaddingOffset()
7244 * @see #getTopPaddingOffset()
7245 * @see #getBottomPaddingOffset()
7246 *
7247 * @since CURRENT
7248 */
7249 protected boolean isPaddingOffsetRequired() {
7250 return false;
7251 }
7252
7253 /**
7254 * Amount by which to extend the left fading region. Called only when
7255 * {@link #isPaddingOffsetRequired()} returns true.
7256 *
7257 * @return The left padding offset in pixels.
7258 *
7259 * @see #isPaddingOffsetRequired()
7260 *
7261 * @since CURRENT
7262 */
7263 protected int getLeftPaddingOffset() {
7264 return 0;
7265 }
7266
7267 /**
7268 * Amount by which to extend the right fading region. Called only when
7269 * {@link #isPaddingOffsetRequired()} returns true.
7270 *
7271 * @return The right padding offset in pixels.
7272 *
7273 * @see #isPaddingOffsetRequired()
7274 *
7275 * @since CURRENT
7276 */
7277 protected int getRightPaddingOffset() {
7278 return 0;
7279 }
7280
7281 /**
7282 * Amount by which to extend the top fading region. Called only when
7283 * {@link #isPaddingOffsetRequired()} returns true.
7284 *
7285 * @return The top padding offset in pixels.
7286 *
7287 * @see #isPaddingOffsetRequired()
7288 *
7289 * @since CURRENT
7290 */
7291 protected int getTopPaddingOffset() {
7292 return 0;
7293 }
7294
7295 /**
7296 * Amount by which to extend the bottom fading region. Called only when
7297 * {@link #isPaddingOffsetRequired()} returns true.
7298 *
7299 * @return The bottom padding offset in pixels.
7300 *
7301 * @see #isPaddingOffsetRequired()
7302 *
7303 * @since CURRENT
7304 */
7305 protected int getBottomPaddingOffset() {
7306 return 0;
7307 }
7308
7309 /**
7310 * Manually render this view (and all of its children) to the given Canvas.
7311 * The view must have already done a full layout before this function is
7312 * called. When implementing a view, do not override this method; instead,
7313 * you should implement {@link #onDraw}.
7314 *
7315 * @param canvas The Canvas to which the View is rendered.
7316 */
7317 public void draw(Canvas canvas) {
7318 if (ViewDebug.TRACE_HIERARCHY) {
7319 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7320 }
7321
Romain Guy5bcdff42009-05-14 21:27:18 -07007322 final int privateFlags = mPrivateFlags;
7323 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
7324 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
7325 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07007326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007327 /*
7328 * Draw traversal performs several drawing steps which must be executed
7329 * in the appropriate order:
7330 *
7331 * 1. Draw the background
7332 * 2. If necessary, save the canvas' layers to prepare for fading
7333 * 3. Draw view's content
7334 * 4. Draw children
7335 * 5. If necessary, draw the fading edges and restore layers
7336 * 6. Draw decorations (scrollbars for instance)
7337 */
7338
7339 // Step 1, draw the background, if needed
7340 int saveCount;
7341
Romain Guy24443ea2009-05-11 11:56:30 -07007342 if (!dirtyOpaque) {
7343 final Drawable background = mBGDrawable;
7344 if (background != null) {
7345 final int scrollX = mScrollX;
7346 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007347
Romain Guy24443ea2009-05-11 11:56:30 -07007348 if (mBackgroundSizeChanged) {
7349 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
7350 mBackgroundSizeChanged = false;
7351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007352
Romain Guy24443ea2009-05-11 11:56:30 -07007353 if ((scrollX | scrollY) == 0) {
7354 background.draw(canvas);
7355 } else {
7356 canvas.translate(scrollX, scrollY);
7357 background.draw(canvas);
7358 canvas.translate(-scrollX, -scrollY);
7359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007360 }
7361 }
7362
7363 // skip step 2 & 5 if possible (common case)
7364 final int viewFlags = mViewFlags;
7365 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
7366 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
7367 if (!verticalEdges && !horizontalEdges) {
7368 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007369 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007370
7371 // Step 4, draw the children
7372 dispatchDraw(canvas);
7373
7374 // Step 6, draw decorations (scrollbars)
7375 onDrawScrollBars(canvas);
7376
7377 // we're done...
7378 return;
7379 }
7380
7381 /*
7382 * Here we do the full fledged routine...
7383 * (this is an uncommon case where speed matters less,
7384 * this is why we repeat some of the tests that have been
7385 * done above)
7386 */
7387
7388 boolean drawTop = false;
7389 boolean drawBottom = false;
7390 boolean drawLeft = false;
7391 boolean drawRight = false;
7392
7393 float topFadeStrength = 0.0f;
7394 float bottomFadeStrength = 0.0f;
7395 float leftFadeStrength = 0.0f;
7396 float rightFadeStrength = 0.0f;
7397
7398 // Step 2, save the canvas' layers
7399 int paddingLeft = mPaddingLeft;
7400 int paddingTop = mPaddingTop;
7401
7402 final boolean offsetRequired = isPaddingOffsetRequired();
7403 if (offsetRequired) {
7404 paddingLeft += getLeftPaddingOffset();
7405 paddingTop += getTopPaddingOffset();
7406 }
7407
7408 int left = mScrollX + paddingLeft;
7409 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
7410 int top = mScrollY + paddingTop;
7411 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
7412
7413 if (offsetRequired) {
7414 right += getRightPaddingOffset();
7415 bottom += getBottomPaddingOffset();
7416 }
7417
7418 final ScrollabilityCache scrollabilityCache = mScrollCache;
7419 int length = scrollabilityCache.fadingEdgeLength;
7420
7421 // clip the fade length if top and bottom fades overlap
7422 // overlapping fades produce odd-looking artifacts
7423 if (verticalEdges && (top + length > bottom - length)) {
7424 length = (bottom - top) / 2;
7425 }
7426
7427 // also clip horizontal fades if necessary
7428 if (horizontalEdges && (left + length > right - length)) {
7429 length = (right - left) / 2;
7430 }
7431
7432 if (verticalEdges) {
7433 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007434 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007435 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007436 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007437 }
7438
7439 if (horizontalEdges) {
7440 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007441 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007442 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007443 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007444 }
7445
7446 saveCount = canvas.getSaveCount();
7447
7448 int solidColor = getSolidColor();
7449 if (solidColor == 0) {
7450 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
7451
7452 if (drawTop) {
7453 canvas.saveLayer(left, top, right, top + length, null, flags);
7454 }
7455
7456 if (drawBottom) {
7457 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
7458 }
7459
7460 if (drawLeft) {
7461 canvas.saveLayer(left, top, left + length, bottom, null, flags);
7462 }
7463
7464 if (drawRight) {
7465 canvas.saveLayer(right - length, top, right, bottom, null, flags);
7466 }
7467 } else {
7468 scrollabilityCache.setFadeColor(solidColor);
7469 }
7470
7471 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007472 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007473
7474 // Step 4, draw the children
7475 dispatchDraw(canvas);
7476
7477 // Step 5, draw the fade effect and restore layers
7478 final Paint p = scrollabilityCache.paint;
7479 final Matrix matrix = scrollabilityCache.matrix;
7480 final Shader fade = scrollabilityCache.shader;
7481 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
7482
7483 if (drawTop) {
7484 matrix.setScale(1, fadeHeight * topFadeStrength);
7485 matrix.postTranslate(left, top);
7486 fade.setLocalMatrix(matrix);
7487 canvas.drawRect(left, top, right, top + length, p);
7488 }
7489
7490 if (drawBottom) {
7491 matrix.setScale(1, fadeHeight * bottomFadeStrength);
7492 matrix.postRotate(180);
7493 matrix.postTranslate(left, bottom);
7494 fade.setLocalMatrix(matrix);
7495 canvas.drawRect(left, bottom - length, right, bottom, p);
7496 }
7497
7498 if (drawLeft) {
7499 matrix.setScale(1, fadeHeight * leftFadeStrength);
7500 matrix.postRotate(-90);
7501 matrix.postTranslate(left, top);
7502 fade.setLocalMatrix(matrix);
7503 canvas.drawRect(left, top, left + length, bottom, p);
7504 }
7505
7506 if (drawRight) {
7507 matrix.setScale(1, fadeHeight * rightFadeStrength);
7508 matrix.postRotate(90);
7509 matrix.postTranslate(right, top);
7510 fade.setLocalMatrix(matrix);
7511 canvas.drawRect(right - length, top, right, bottom, p);
7512 }
7513
7514 canvas.restoreToCount(saveCount);
7515
7516 // Step 6, draw decorations (scrollbars)
7517 onDrawScrollBars(canvas);
7518 }
7519
7520 /**
7521 * Override this if your view is known to always be drawn on top of a solid color background,
7522 * and needs to draw fading edges. Returning a non-zero color enables the view system to
7523 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
7524 * should be set to 0xFF.
7525 *
7526 * @see #setVerticalFadingEdgeEnabled
7527 * @see #setHorizontalFadingEdgeEnabled
7528 *
7529 * @return The known solid color background for this view, or 0 if the color may vary
7530 */
7531 public int getSolidColor() {
7532 return 0;
7533 }
7534
7535 /**
7536 * Build a human readable string representation of the specified view flags.
7537 *
7538 * @param flags the view flags to convert to a string
7539 * @return a String representing the supplied flags
7540 */
7541 private static String printFlags(int flags) {
7542 String output = "";
7543 int numFlags = 0;
7544 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
7545 output += "TAKES_FOCUS";
7546 numFlags++;
7547 }
7548
7549 switch (flags & VISIBILITY_MASK) {
7550 case INVISIBLE:
7551 if (numFlags > 0) {
7552 output += " ";
7553 }
7554 output += "INVISIBLE";
7555 // USELESS HERE numFlags++;
7556 break;
7557 case GONE:
7558 if (numFlags > 0) {
7559 output += " ";
7560 }
7561 output += "GONE";
7562 // USELESS HERE numFlags++;
7563 break;
7564 default:
7565 break;
7566 }
7567 return output;
7568 }
7569
7570 /**
7571 * Build a human readable string representation of the specified private
7572 * view flags.
7573 *
7574 * @param privateFlags the private view flags to convert to a string
7575 * @return a String representing the supplied flags
7576 */
7577 private static String printPrivateFlags(int privateFlags) {
7578 String output = "";
7579 int numFlags = 0;
7580
7581 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
7582 output += "WANTS_FOCUS";
7583 numFlags++;
7584 }
7585
7586 if ((privateFlags & FOCUSED) == FOCUSED) {
7587 if (numFlags > 0) {
7588 output += " ";
7589 }
7590 output += "FOCUSED";
7591 numFlags++;
7592 }
7593
7594 if ((privateFlags & SELECTED) == SELECTED) {
7595 if (numFlags > 0) {
7596 output += " ";
7597 }
7598 output += "SELECTED";
7599 numFlags++;
7600 }
7601
7602 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
7603 if (numFlags > 0) {
7604 output += " ";
7605 }
7606 output += "IS_ROOT_NAMESPACE";
7607 numFlags++;
7608 }
7609
7610 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
7611 if (numFlags > 0) {
7612 output += " ";
7613 }
7614 output += "HAS_BOUNDS";
7615 numFlags++;
7616 }
7617
7618 if ((privateFlags & DRAWN) == DRAWN) {
7619 if (numFlags > 0) {
7620 output += " ";
7621 }
7622 output += "DRAWN";
7623 // USELESS HERE numFlags++;
7624 }
7625 return output;
7626 }
7627
7628 /**
7629 * <p>Indicates whether or not this view's layout will be requested during
7630 * the next hierarchy layout pass.</p>
7631 *
7632 * @return true if the layout will be forced during next layout pass
7633 */
7634 public boolean isLayoutRequested() {
7635 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
7636 }
7637
7638 /**
7639 * Assign a size and position to a view and all of its
7640 * descendants
7641 *
7642 * <p>This is the second phase of the layout mechanism.
7643 * (The first is measuring). In this phase, each parent calls
7644 * layout on all of its children to position them.
7645 * This is typically done using the child measurements
7646 * that were stored in the measure pass().
7647 *
7648 * Derived classes with children should override
7649 * onLayout. In that method, they should
7650 * call layout on each of their their children.
7651 *
7652 * @param l Left position, relative to parent
7653 * @param t Top position, relative to parent
7654 * @param r Right position, relative to parent
7655 * @param b Bottom position, relative to parent
7656 */
7657 public final void layout(int l, int t, int r, int b) {
7658 boolean changed = setFrame(l, t, r, b);
7659 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
7660 if (ViewDebug.TRACE_HIERARCHY) {
7661 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
7662 }
7663
7664 onLayout(changed, l, t, r, b);
7665 mPrivateFlags &= ~LAYOUT_REQUIRED;
7666 }
7667 mPrivateFlags &= ~FORCE_LAYOUT;
7668 }
7669
7670 /**
7671 * Called from layout when this view should
7672 * assign a size and position to each of its children.
7673 *
7674 * Derived classes with children should override
7675 * this method and call layout on each of
7676 * their their children.
7677 * @param changed This is a new size or position for this view
7678 * @param left Left position, relative to parent
7679 * @param top Top position, relative to parent
7680 * @param right Right position, relative to parent
7681 * @param bottom Bottom position, relative to parent
7682 */
7683 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
7684 }
7685
7686 /**
7687 * Assign a size and position to this view.
7688 *
7689 * This is called from layout.
7690 *
7691 * @param left Left position, relative to parent
7692 * @param top Top position, relative to parent
7693 * @param right Right position, relative to parent
7694 * @param bottom Bottom position, relative to parent
7695 * @return true if the new size and position are different than the
7696 * previous ones
7697 * {@hide}
7698 */
7699 protected boolean setFrame(int left, int top, int right, int bottom) {
7700 boolean changed = false;
7701
7702 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07007703 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007704 + right + "," + bottom + ")");
7705 }
7706
7707 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
7708 changed = true;
7709
7710 // Remember our drawn bit
7711 int drawn = mPrivateFlags & DRAWN;
7712
7713 // Invalidate our old position
7714 invalidate();
7715
7716
7717 int oldWidth = mRight - mLeft;
7718 int oldHeight = mBottom - mTop;
7719
7720 mLeft = left;
7721 mTop = top;
7722 mRight = right;
7723 mBottom = bottom;
7724
7725 mPrivateFlags |= HAS_BOUNDS;
7726
7727 int newWidth = right - left;
7728 int newHeight = bottom - top;
7729
7730 if (newWidth != oldWidth || newHeight != oldHeight) {
7731 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
7732 }
7733
7734 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
7735 // If we are visible, force the DRAWN bit to on so that
7736 // this invalidate will go through (at least to our parent).
7737 // This is because someone may have invalidated this view
7738 // before this call to setFrame came in, therby clearing
7739 // the DRAWN bit.
7740 mPrivateFlags |= DRAWN;
7741 invalidate();
7742 }
7743
7744 // Reset drawn bit to original value (invalidate turns it off)
7745 mPrivateFlags |= drawn;
7746
7747 mBackgroundSizeChanged = true;
7748 }
7749 return changed;
7750 }
7751
7752 /**
7753 * Finalize inflating a view from XML. This is called as the last phase
7754 * of inflation, after all child views have been added.
7755 *
7756 * <p>Even if the subclass overrides onFinishInflate, they should always be
7757 * sure to call the super method, so that we get called.
7758 */
7759 protected void onFinishInflate() {
7760 }
7761
7762 /**
7763 * Returns the resources associated with this view.
7764 *
7765 * @return Resources object.
7766 */
7767 public Resources getResources() {
7768 return mResources;
7769 }
7770
7771 /**
7772 * Invalidates the specified Drawable.
7773 *
7774 * @param drawable the drawable to invalidate
7775 */
7776 public void invalidateDrawable(Drawable drawable) {
7777 if (verifyDrawable(drawable)) {
7778 final Rect dirty = drawable.getBounds();
7779 final int scrollX = mScrollX;
7780 final int scrollY = mScrollY;
7781
7782 invalidate(dirty.left + scrollX, dirty.top + scrollY,
7783 dirty.right + scrollX, dirty.bottom + scrollY);
7784 }
7785 }
7786
7787 /**
7788 * Schedules an action on a drawable to occur at a specified time.
7789 *
7790 * @param who the recipient of the action
7791 * @param what the action to run on the drawable
7792 * @param when the time at which the action must occur. Uses the
7793 * {@link SystemClock#uptimeMillis} timebase.
7794 */
7795 public void scheduleDrawable(Drawable who, Runnable what, long when) {
7796 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
7797 mAttachInfo.mHandler.postAtTime(what, who, when);
7798 }
7799 }
7800
7801 /**
7802 * Cancels a scheduled action on a drawable.
7803 *
7804 * @param who the recipient of the action
7805 * @param what the action to cancel
7806 */
7807 public void unscheduleDrawable(Drawable who, Runnable what) {
7808 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
7809 mAttachInfo.mHandler.removeCallbacks(what, who);
7810 }
7811 }
7812
7813 /**
7814 * Unschedule any events associated with the given Drawable. This can be
7815 * used when selecting a new Drawable into a view, so that the previous
7816 * one is completely unscheduled.
7817 *
7818 * @param who The Drawable to unschedule.
7819 *
7820 * @see #drawableStateChanged
7821 */
7822 public void unscheduleDrawable(Drawable who) {
7823 if (mAttachInfo != null) {
7824 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
7825 }
7826 }
7827
7828 /**
7829 * If your view subclass is displaying its own Drawable objects, it should
7830 * override this function and return true for any Drawable it is
7831 * displaying. This allows animations for those drawables to be
7832 * scheduled.
7833 *
7834 * <p>Be sure to call through to the super class when overriding this
7835 * function.
7836 *
7837 * @param who The Drawable to verify. Return true if it is one you are
7838 * displaying, else return the result of calling through to the
7839 * super class.
7840 *
7841 * @return boolean If true than the Drawable is being displayed in the
7842 * view; else false and it is not allowed to animate.
7843 *
7844 * @see #unscheduleDrawable
7845 * @see #drawableStateChanged
7846 */
7847 protected boolean verifyDrawable(Drawable who) {
7848 return who == mBGDrawable;
7849 }
7850
7851 /**
7852 * This function is called whenever the state of the view changes in such
7853 * a way that it impacts the state of drawables being shown.
7854 *
7855 * <p>Be sure to call through to the superclass when overriding this
7856 * function.
7857 *
7858 * @see Drawable#setState
7859 */
7860 protected void drawableStateChanged() {
7861 Drawable d = mBGDrawable;
7862 if (d != null && d.isStateful()) {
7863 d.setState(getDrawableState());
7864 }
7865 }
7866
7867 /**
7868 * Call this to force a view to update its drawable state. This will cause
7869 * drawableStateChanged to be called on this view. Views that are interested
7870 * in the new state should call getDrawableState.
7871 *
7872 * @see #drawableStateChanged
7873 * @see #getDrawableState
7874 */
7875 public void refreshDrawableState() {
7876 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
7877 drawableStateChanged();
7878
7879 ViewParent parent = mParent;
7880 if (parent != null) {
7881 parent.childDrawableStateChanged(this);
7882 }
7883 }
7884
7885 /**
7886 * Return an array of resource IDs of the drawable states representing the
7887 * current state of the view.
7888 *
7889 * @return The current drawable state
7890 *
7891 * @see Drawable#setState
7892 * @see #drawableStateChanged
7893 * @see #onCreateDrawableState
7894 */
7895 public final int[] getDrawableState() {
7896 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
7897 return mDrawableState;
7898 } else {
7899 mDrawableState = onCreateDrawableState(0);
7900 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
7901 return mDrawableState;
7902 }
7903 }
7904
7905 /**
7906 * Generate the new {@link android.graphics.drawable.Drawable} state for
7907 * this view. This is called by the view
7908 * system when the cached Drawable state is determined to be invalid. To
7909 * retrieve the current state, you should use {@link #getDrawableState}.
7910 *
7911 * @param extraSpace if non-zero, this is the number of extra entries you
7912 * would like in the returned array in which you can place your own
7913 * states.
7914 *
7915 * @return Returns an array holding the current {@link Drawable} state of
7916 * the view.
7917 *
7918 * @see #mergeDrawableStates
7919 */
7920 protected int[] onCreateDrawableState(int extraSpace) {
7921 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
7922 mParent instanceof View) {
7923 return ((View) mParent).onCreateDrawableState(extraSpace);
7924 }
7925
7926 int[] drawableState;
7927
7928 int privateFlags = mPrivateFlags;
7929
7930 int viewStateIndex = (((privateFlags & PRESSED) != 0) ? 1 : 0);
7931
7932 viewStateIndex = (viewStateIndex << 1)
7933 + (((mViewFlags & ENABLED_MASK) == ENABLED) ? 1 : 0);
7934
7935 viewStateIndex = (viewStateIndex << 1) + (isFocused() ? 1 : 0);
7936
7937 viewStateIndex = (viewStateIndex << 1)
7938 + (((privateFlags & SELECTED) != 0) ? 1 : 0);
7939
7940 final boolean hasWindowFocus = hasWindowFocus();
7941 viewStateIndex = (viewStateIndex << 1) + (hasWindowFocus ? 1 : 0);
7942
7943 drawableState = VIEW_STATE_SETS[viewStateIndex];
7944
7945 //noinspection ConstantIfStatement
7946 if (false) {
7947 Log.i("View", "drawableStateIndex=" + viewStateIndex);
7948 Log.i("View", toString()
7949 + " pressed=" + ((privateFlags & PRESSED) != 0)
7950 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
7951 + " fo=" + hasFocus()
7952 + " sl=" + ((privateFlags & SELECTED) != 0)
7953 + " wf=" + hasWindowFocus
7954 + ": " + Arrays.toString(drawableState));
7955 }
7956
7957 if (extraSpace == 0) {
7958 return drawableState;
7959 }
7960
7961 final int[] fullState;
7962 if (drawableState != null) {
7963 fullState = new int[drawableState.length + extraSpace];
7964 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
7965 } else {
7966 fullState = new int[extraSpace];
7967 }
7968
7969 return fullState;
7970 }
7971
7972 /**
7973 * Merge your own state values in <var>additionalState</var> into the base
7974 * state values <var>baseState</var> that were returned by
7975 * {@link #onCreateDrawableState}.
7976 *
7977 * @param baseState The base state values returned by
7978 * {@link #onCreateDrawableState}, which will be modified to also hold your
7979 * own additional state values.
7980 *
7981 * @param additionalState The additional state values you would like
7982 * added to <var>baseState</var>; this array is not modified.
7983 *
7984 * @return As a convenience, the <var>baseState</var> array you originally
7985 * passed into the function is returned.
7986 *
7987 * @see #onCreateDrawableState
7988 */
7989 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
7990 final int N = baseState.length;
7991 int i = N - 1;
7992 while (i >= 0 && baseState[i] == 0) {
7993 i--;
7994 }
7995 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
7996 return baseState;
7997 }
7998
7999 /**
8000 * Sets the background color for this view.
8001 * @param color the color of the background
8002 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008003 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008004 public void setBackgroundColor(int color) {
8005 setBackgroundDrawable(new ColorDrawable(color));
8006 }
8007
8008 /**
8009 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07008010 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008011 * @param resid The identifier of the resource.
8012 * @attr ref android.R.styleable#View_background
8013 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008014 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 public void setBackgroundResource(int resid) {
8016 if (resid != 0 && resid == mBackgroundResource) {
8017 return;
8018 }
8019
8020 Drawable d= null;
8021 if (resid != 0) {
8022 d = mResources.getDrawable(resid);
8023 }
8024 setBackgroundDrawable(d);
8025
8026 mBackgroundResource = resid;
8027 }
8028
8029 /**
8030 * Set the background to a given Drawable, or remove the background. If the
8031 * background has padding, this View's padding is set to the background's
8032 * padding. However, when a background is removed, this View's padding isn't
8033 * touched. If setting the padding is desired, please use
8034 * {@link #setPadding(int, int, int, int)}.
8035 *
8036 * @param d The Drawable to use as the background, or null to remove the
8037 * background
8038 */
8039 public void setBackgroundDrawable(Drawable d) {
8040 boolean requestLayout = false;
8041
8042 mBackgroundResource = 0;
8043
8044 /*
8045 * Regardless of whether we're setting a new background or not, we want
8046 * to clear the previous drawable.
8047 */
8048 if (mBGDrawable != null) {
8049 mBGDrawable.setCallback(null);
8050 unscheduleDrawable(mBGDrawable);
8051 }
8052
8053 if (d != null) {
8054 Rect padding = sThreadLocal.get();
8055 if (padding == null) {
8056 padding = new Rect();
8057 sThreadLocal.set(padding);
8058 }
8059 if (d.getPadding(padding)) {
8060 setPadding(padding.left, padding.top, padding.right, padding.bottom);
8061 }
8062
8063 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
8064 // if it has a different minimum size, we should layout again
8065 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
8066 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
8067 requestLayout = true;
8068 }
8069
8070 d.setCallback(this);
8071 if (d.isStateful()) {
8072 d.setState(getDrawableState());
8073 }
8074 d.setVisible(getVisibility() == VISIBLE, false);
8075 mBGDrawable = d;
8076
8077 if ((mPrivateFlags & SKIP_DRAW) != 0) {
8078 mPrivateFlags &= ~SKIP_DRAW;
8079 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8080 requestLayout = true;
8081 }
8082 } else {
8083 /* Remove the background */
8084 mBGDrawable = null;
8085
8086 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
8087 /*
8088 * This view ONLY drew the background before and we're removing
8089 * the background, so now it won't draw anything
8090 * (hence we SKIP_DRAW)
8091 */
8092 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
8093 mPrivateFlags |= SKIP_DRAW;
8094 }
8095
8096 /*
8097 * When the background is set, we try to apply its padding to this
8098 * View. When the background is removed, we don't touch this View's
8099 * padding. This is noted in the Javadocs. Hence, we don't need to
8100 * requestLayout(), the invalidate() below is sufficient.
8101 */
8102
8103 // The old background's minimum size could have affected this
8104 // View's layout, so let's requestLayout
8105 requestLayout = true;
8106 }
8107
Romain Guy8f1344f52009-05-15 16:03:59 -07008108 computeOpaqueFlags();
8109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 if (requestLayout) {
8111 requestLayout();
8112 }
8113
8114 mBackgroundSizeChanged = true;
8115 invalidate();
8116 }
8117
8118 /**
8119 * Gets the background drawable
8120 * @return The drawable used as the background for this view, if any.
8121 */
8122 public Drawable getBackground() {
8123 return mBGDrawable;
8124 }
8125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008126 /**
8127 * Sets the padding. The view may add on the space required to display
8128 * the scrollbars, depending on the style and visibility of the scrollbars.
8129 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
8130 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
8131 * from the values set in this call.
8132 *
8133 * @attr ref android.R.styleable#View_padding
8134 * @attr ref android.R.styleable#View_paddingBottom
8135 * @attr ref android.R.styleable#View_paddingLeft
8136 * @attr ref android.R.styleable#View_paddingRight
8137 * @attr ref android.R.styleable#View_paddingTop
8138 * @param left the left padding in pixels
8139 * @param top the top padding in pixels
8140 * @param right the right padding in pixels
8141 * @param bottom the bottom padding in pixels
8142 */
8143 public void setPadding(int left, int top, int right, int bottom) {
8144 boolean changed = false;
8145
8146 mUserPaddingRight = right;
8147 mUserPaddingBottom = bottom;
8148
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008149 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07008150
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008151 // Common case is there are no scroll bars.
8152 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
8153 // TODO: Deal with RTL languages to adjust left padding instead of right.
8154 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
8155 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8156 ? 0 : getVerticalScrollbarWidth();
8157 }
8158 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
8159 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8160 ? 0 : getHorizontalScrollbarHeight();
8161 }
8162 }
Romain Guy8506ab42009-06-11 17:35:47 -07008163
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008164 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 changed = true;
8166 mPaddingLeft = left;
8167 }
8168 if (mPaddingTop != top) {
8169 changed = true;
8170 mPaddingTop = top;
8171 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008172 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008174 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008176 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008178 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008179 }
8180
8181 if (changed) {
8182 requestLayout();
8183 }
8184 }
8185
8186 /**
8187 * Returns the top padding of this view.
8188 *
8189 * @return the top padding in pixels
8190 */
8191 public int getPaddingTop() {
8192 return mPaddingTop;
8193 }
8194
8195 /**
8196 * Returns the bottom padding of this view. If there are inset and enabled
8197 * scrollbars, this value may include the space required to display the
8198 * scrollbars as well.
8199 *
8200 * @return the bottom padding in pixels
8201 */
8202 public int getPaddingBottom() {
8203 return mPaddingBottom;
8204 }
8205
8206 /**
8207 * Returns the left padding of this view. If there are inset and enabled
8208 * scrollbars, this value may include the space required to display the
8209 * scrollbars as well.
8210 *
8211 * @return the left padding in pixels
8212 */
8213 public int getPaddingLeft() {
8214 return mPaddingLeft;
8215 }
8216
8217 /**
8218 * Returns the right padding of this view. If there are inset and enabled
8219 * scrollbars, this value may include the space required to display the
8220 * scrollbars as well.
8221 *
8222 * @return the right padding in pixels
8223 */
8224 public int getPaddingRight() {
8225 return mPaddingRight;
8226 }
8227
8228 /**
8229 * Changes the selection state of this view. A view can be selected or not.
8230 * Note that selection is not the same as focus. Views are typically
8231 * selected in the context of an AdapterView like ListView or GridView;
8232 * the selected view is the view that is highlighted.
8233 *
8234 * @param selected true if the view must be selected, false otherwise
8235 */
8236 public void setSelected(boolean selected) {
8237 if (((mPrivateFlags & SELECTED) != 0) != selected) {
8238 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07008239 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008240 invalidate();
8241 refreshDrawableState();
8242 dispatchSetSelected(selected);
8243 }
8244 }
8245
8246 /**
8247 * Dispatch setSelected to all of this View's children.
8248 *
8249 * @see #setSelected(boolean)
8250 *
8251 * @param selected The new selected state
8252 */
8253 protected void dispatchSetSelected(boolean selected) {
8254 }
8255
8256 /**
8257 * Indicates the selection state of this view.
8258 *
8259 * @return true if the view is selected, false otherwise
8260 */
8261 @ViewDebug.ExportedProperty
8262 public boolean isSelected() {
8263 return (mPrivateFlags & SELECTED) != 0;
8264 }
8265
8266 /**
8267 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
8268 * observer can be used to get notifications when global events, like
8269 * layout, happen.
8270 *
8271 * The returned ViewTreeObserver observer is not guaranteed to remain
8272 * valid for the lifetime of this View. If the caller of this method keeps
8273 * a long-lived reference to ViewTreeObserver, it should always check for
8274 * the return value of {@link ViewTreeObserver#isAlive()}.
8275 *
8276 * @return The ViewTreeObserver for this view's hierarchy.
8277 */
8278 public ViewTreeObserver getViewTreeObserver() {
8279 if (mAttachInfo != null) {
8280 return mAttachInfo.mTreeObserver;
8281 }
8282 if (mFloatingTreeObserver == null) {
8283 mFloatingTreeObserver = new ViewTreeObserver();
8284 }
8285 return mFloatingTreeObserver;
8286 }
8287
8288 /**
8289 * <p>Finds the topmost view in the current view hierarchy.</p>
8290 *
8291 * @return the topmost view containing this view
8292 */
8293 public View getRootView() {
8294 if (mAttachInfo != null) {
8295 final View v = mAttachInfo.mRootView;
8296 if (v != null) {
8297 return v;
8298 }
8299 }
Romain Guy8506ab42009-06-11 17:35:47 -07008300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008301 View parent = this;
8302
8303 while (parent.mParent != null && parent.mParent instanceof View) {
8304 parent = (View) parent.mParent;
8305 }
8306
8307 return parent;
8308 }
8309
8310 /**
8311 * <p>Computes the coordinates of this view on the screen. The argument
8312 * must be an array of two integers. After the method returns, the array
8313 * contains the x and y location in that order.</p>
8314 *
8315 * @param location an array of two integers in which to hold the coordinates
8316 */
8317 public void getLocationOnScreen(int[] location) {
8318 getLocationInWindow(location);
8319
8320 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07008321 if (info != null) {
8322 location[0] += info.mWindowLeft;
8323 location[1] += info.mWindowTop;
8324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008325 }
8326
8327 /**
8328 * <p>Computes the coordinates of this view in its window. The argument
8329 * must be an array of two integers. After the method returns, the array
8330 * contains the x and y location in that order.</p>
8331 *
8332 * @param location an array of two integers in which to hold the coordinates
8333 */
8334 public void getLocationInWindow(int[] location) {
8335 if (location == null || location.length < 2) {
8336 throw new IllegalArgumentException("location must be an array of "
8337 + "two integers");
8338 }
8339
8340 location[0] = mLeft;
8341 location[1] = mTop;
8342
8343 ViewParent viewParent = mParent;
8344 while (viewParent instanceof View) {
8345 final View view = (View)viewParent;
8346 location[0] += view.mLeft - view.mScrollX;
8347 location[1] += view.mTop - view.mScrollY;
8348 viewParent = view.mParent;
8349 }
Romain Guy8506ab42009-06-11 17:35:47 -07008350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008351 if (viewParent instanceof ViewRoot) {
8352 // *cough*
8353 final ViewRoot vr = (ViewRoot)viewParent;
8354 location[1] -= vr.mCurScrollY;
8355 }
8356 }
8357
8358 /**
8359 * {@hide}
8360 * @param id the id of the view to be found
8361 * @return the view of the specified id, null if cannot be found
8362 */
8363 protected View findViewTraversal(int id) {
8364 if (id == mID) {
8365 return this;
8366 }
8367 return null;
8368 }
8369
8370 /**
8371 * {@hide}
8372 * @param tag the tag of the view to be found
8373 * @return the view of specified tag, null if cannot be found
8374 */
8375 protected View findViewWithTagTraversal(Object tag) {
8376 if (tag != null && tag.equals(mTag)) {
8377 return this;
8378 }
8379 return null;
8380 }
8381
8382 /**
8383 * Look for a child view with the given id. If this view has the given
8384 * id, return this view.
8385 *
8386 * @param id The id to search for.
8387 * @return The view that has the given id in the hierarchy or null
8388 */
8389 public final View findViewById(int id) {
8390 if (id < 0) {
8391 return null;
8392 }
8393 return findViewTraversal(id);
8394 }
8395
8396 /**
8397 * Look for a child view with the given tag. If this view has the given
8398 * tag, return this view.
8399 *
8400 * @param tag The tag to search for, using "tag.equals(getTag())".
8401 * @return The View that has the given tag in the hierarchy or null
8402 */
8403 public final View findViewWithTag(Object tag) {
8404 if (tag == null) {
8405 return null;
8406 }
8407 return findViewWithTagTraversal(tag);
8408 }
8409
8410 /**
8411 * Sets the identifier for this view. The identifier does not have to be
8412 * unique in this view's hierarchy. The identifier should be a positive
8413 * number.
8414 *
8415 * @see #NO_ID
8416 * @see #getId
8417 * @see #findViewById
8418 *
8419 * @param id a number used to identify the view
8420 *
8421 * @attr ref android.R.styleable#View_id
8422 */
8423 public void setId(int id) {
8424 mID = id;
8425 }
8426
8427 /**
8428 * {@hide}
8429 *
8430 * @param isRoot true if the view belongs to the root namespace, false
8431 * otherwise
8432 */
8433 public void setIsRootNamespace(boolean isRoot) {
8434 if (isRoot) {
8435 mPrivateFlags |= IS_ROOT_NAMESPACE;
8436 } else {
8437 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
8438 }
8439 }
8440
8441 /**
8442 * {@hide}
8443 *
8444 * @return true if the view belongs to the root namespace, false otherwise
8445 */
8446 public boolean isRootNamespace() {
8447 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
8448 }
8449
8450 /**
8451 * Returns this view's identifier.
8452 *
8453 * @return a positive integer used to identify the view or {@link #NO_ID}
8454 * if the view has no ID
8455 *
8456 * @see #setId
8457 * @see #findViewById
8458 * @attr ref android.R.styleable#View_id
8459 */
8460 @ViewDebug.CapturedViewProperty
8461 public int getId() {
8462 return mID;
8463 }
8464
8465 /**
8466 * Returns this view's tag.
8467 *
8468 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07008469 *
8470 * @see #setTag(Object)
8471 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008472 */
8473 @ViewDebug.ExportedProperty
8474 public Object getTag() {
8475 return mTag;
8476 }
8477
8478 /**
8479 * Sets the tag associated with this view. A tag can be used to mark
8480 * a view in its hierarchy and does not have to be unique within the
8481 * hierarchy. Tags can also be used to store data within a view without
8482 * resorting to another data structure.
8483 *
8484 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07008485 *
8486 * @see #getTag()
8487 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008488 */
8489 public void setTag(final Object tag) {
8490 mTag = tag;
8491 }
8492
8493 /**
Romain Guyd90a3312009-05-06 14:54:28 -07008494 * Returns the tag associated with this view and the specified key.
8495 *
8496 * @param key The key identifying the tag
8497 *
8498 * @return the Object stored in this view as a tag
8499 *
8500 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07008501 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07008502 */
8503 public Object getTag(int key) {
8504 SparseArray<Object> tags = null;
8505 synchronized (sTagsLock) {
8506 if (sTags != null) {
8507 tags = sTags.get(this);
8508 }
8509 }
8510
8511 if (tags != null) return tags.get(key);
8512 return null;
8513 }
8514
8515 /**
8516 * Sets a tag associated with this view and a key. A tag can be used
8517 * to mark a view in its hierarchy and does not have to be unique within
8518 * the hierarchy. Tags can also be used to store data within a view
8519 * without resorting to another data structure.
8520 *
8521 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07008522 * application to ensure it is unique (see the <a
8523 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
8524 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07008525 * the Android framework or not associated with any package will cause
8526 * an {@link IllegalArgumentException} to be thrown.
8527 *
8528 * @param key The key identifying the tag
8529 * @param tag An Object to tag the view with
8530 *
8531 * @throws IllegalArgumentException If they specified key is not valid
8532 *
8533 * @see #setTag(Object)
8534 * @see #getTag(int)
8535 */
8536 public void setTag(int key, final Object tag) {
8537 // If the package id is 0x00 or 0x01, it's either an undefined package
8538 // or a framework id
8539 if ((key >>> 24) < 2) {
8540 throw new IllegalArgumentException("The key must be an application-specific "
8541 + "resource id.");
8542 }
8543
8544 setTagInternal(this, key, tag);
8545 }
8546
8547 /**
8548 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
8549 * framework id.
8550 *
8551 * @hide
8552 */
8553 public void setTagInternal(int key, Object tag) {
8554 if ((key >>> 24) != 0x1) {
8555 throw new IllegalArgumentException("The key must be a framework-specific "
8556 + "resource id.");
8557 }
8558
Romain Guy8506ab42009-06-11 17:35:47 -07008559 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07008560 }
8561
8562 private static void setTagInternal(View view, int key, Object tag) {
8563 SparseArray<Object> tags = null;
8564 synchronized (sTagsLock) {
8565 if (sTags == null) {
8566 sTags = new WeakHashMap<View, SparseArray<Object>>();
8567 } else {
8568 tags = sTags.get(view);
8569 }
8570 }
8571
8572 if (tags == null) {
8573 tags = new SparseArray<Object>(2);
8574 synchronized (sTagsLock) {
8575 sTags.put(view, tags);
8576 }
8577 }
8578
8579 tags.put(key, tag);
8580 }
8581
8582 /**
Romain Guy13922e02009-05-12 17:56:14 -07008583 * @param consistency The type of consistency. See ViewDebug for more information.
8584 *
8585 * @hide
8586 */
8587 protected boolean dispatchConsistencyCheck(int consistency) {
8588 return onConsistencyCheck(consistency);
8589 }
8590
8591 /**
8592 * Method that subclasses should implement to check their consistency. The type of
8593 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07008594 *
Romain Guy13922e02009-05-12 17:56:14 -07008595 * @param consistency The type of consistency. See ViewDebug for more information.
8596 *
8597 * @throws IllegalStateException if the view is in an inconsistent state.
8598 *
8599 * @hide
8600 */
8601 protected boolean onConsistencyCheck(int consistency) {
8602 boolean result = true;
8603
8604 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
8605 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
8606
8607 if (checkLayout) {
8608 if (getParent() == null) {
8609 result = false;
8610 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
8611 "View " + this + " does not have a parent.");
8612 }
8613
8614 if (mAttachInfo == null) {
8615 result = false;
8616 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
8617 "View " + this + " is not attached to a window.");
8618 }
8619 }
8620
8621 if (checkDrawing) {
8622 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
8623 // from their draw() method
8624
8625 if ((mPrivateFlags & DRAWN) != DRAWN &&
8626 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
8627 result = false;
8628 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
8629 "View " + this + " was invalidated but its drawing cache is valid.");
8630 }
8631 }
8632
8633 return result;
8634 }
8635
8636 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008637 * Prints information about this view in the log output, with the tag
8638 * {@link #VIEW_LOG_TAG}.
8639 *
8640 * @hide
8641 */
8642 public void debug() {
8643 debug(0);
8644 }
8645
8646 /**
8647 * Prints information about this view in the log output, with the tag
8648 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
8649 * indentation defined by the <code>depth</code>.
8650 *
8651 * @param depth the indentation level
8652 *
8653 * @hide
8654 */
8655 protected void debug(int depth) {
8656 String output = debugIndent(depth - 1);
8657
8658 output += "+ " + this;
8659 int id = getId();
8660 if (id != -1) {
8661 output += " (id=" + id + ")";
8662 }
8663 Object tag = getTag();
8664 if (tag != null) {
8665 output += " (tag=" + tag + ")";
8666 }
8667 Log.d(VIEW_LOG_TAG, output);
8668
8669 if ((mPrivateFlags & FOCUSED) != 0) {
8670 output = debugIndent(depth) + " FOCUSED";
8671 Log.d(VIEW_LOG_TAG, output);
8672 }
8673
8674 output = debugIndent(depth);
8675 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
8676 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
8677 + "} ";
8678 Log.d(VIEW_LOG_TAG, output);
8679
8680 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
8681 || mPaddingBottom != 0) {
8682 output = debugIndent(depth);
8683 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
8684 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
8685 Log.d(VIEW_LOG_TAG, output);
8686 }
8687
8688 output = debugIndent(depth);
8689 output += "mMeasureWidth=" + mMeasuredWidth +
8690 " mMeasureHeight=" + mMeasuredHeight;
8691 Log.d(VIEW_LOG_TAG, output);
8692
8693 output = debugIndent(depth);
8694 if (mLayoutParams == null) {
8695 output += "BAD! no layout params";
8696 } else {
8697 output = mLayoutParams.debug(output);
8698 }
8699 Log.d(VIEW_LOG_TAG, output);
8700
8701 output = debugIndent(depth);
8702 output += "flags={";
8703 output += View.printFlags(mViewFlags);
8704 output += "}";
8705 Log.d(VIEW_LOG_TAG, output);
8706
8707 output = debugIndent(depth);
8708 output += "privateFlags={";
8709 output += View.printPrivateFlags(mPrivateFlags);
8710 output += "}";
8711 Log.d(VIEW_LOG_TAG, output);
8712 }
8713
8714 /**
8715 * Creates an string of whitespaces used for indentation.
8716 *
8717 * @param depth the indentation level
8718 * @return a String containing (depth * 2 + 3) * 2 white spaces
8719 *
8720 * @hide
8721 */
8722 protected static String debugIndent(int depth) {
8723 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
8724 for (int i = 0; i < (depth * 2) + 3; i++) {
8725 spaces.append(' ').append(' ');
8726 }
8727 return spaces.toString();
8728 }
8729
8730 /**
8731 * <p>Return the offset of the widget's text baseline from the widget's top
8732 * boundary. If this widget does not support baseline alignment, this
8733 * method returns -1. </p>
8734 *
8735 * @return the offset of the baseline within the widget's bounds or -1
8736 * if baseline alignment is not supported
8737 */
8738 @ViewDebug.ExportedProperty
8739 public int getBaseline() {
8740 return -1;
8741 }
8742
8743 /**
8744 * Call this when something has changed which has invalidated the
8745 * layout of this view. This will schedule a layout pass of the view
8746 * tree.
8747 */
8748 public void requestLayout() {
8749 if (ViewDebug.TRACE_HIERARCHY) {
8750 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
8751 }
8752
8753 mPrivateFlags |= FORCE_LAYOUT;
8754
8755 if (mParent != null && !mParent.isLayoutRequested()) {
8756 mParent.requestLayout();
8757 }
8758 }
8759
8760 /**
8761 * Forces this view to be laid out during the next layout pass.
8762 * This method does not call requestLayout() or forceLayout()
8763 * on the parent.
8764 */
8765 public void forceLayout() {
8766 mPrivateFlags |= FORCE_LAYOUT;
8767 }
8768
8769 /**
8770 * <p>
8771 * This is called to find out how big a view should be. The parent
8772 * supplies constraint information in the width and height parameters.
8773 * </p>
8774 *
8775 * <p>
8776 * The actual mesurement work of a view is performed in
8777 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
8778 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
8779 * </p>
8780 *
8781 *
8782 * @param widthMeasureSpec Horizontal space requirements as imposed by the
8783 * parent
8784 * @param heightMeasureSpec Vertical space requirements as imposed by the
8785 * parent
8786 *
8787 * @see #onMeasure(int, int)
8788 */
8789 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
8790 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
8791 widthMeasureSpec != mOldWidthMeasureSpec ||
8792 heightMeasureSpec != mOldHeightMeasureSpec) {
8793
8794 // first clears the measured dimension flag
8795 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
8796
8797 if (ViewDebug.TRACE_HIERARCHY) {
8798 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
8799 }
8800
8801 // measure ourselves, this should set the measured dimension flag back
8802 onMeasure(widthMeasureSpec, heightMeasureSpec);
8803
8804 // flag not set, setMeasuredDimension() was not invoked, we raise
8805 // an exception to warn the developer
8806 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
8807 throw new IllegalStateException("onMeasure() did not set the"
8808 + " measured dimension by calling"
8809 + " setMeasuredDimension()");
8810 }
8811
8812 mPrivateFlags |= LAYOUT_REQUIRED;
8813 }
8814
8815 mOldWidthMeasureSpec = widthMeasureSpec;
8816 mOldHeightMeasureSpec = heightMeasureSpec;
8817 }
8818
8819 /**
8820 * <p>
8821 * Measure the view and its content to determine the measured width and the
8822 * measured height. This method is invoked by {@link #measure(int, int)} and
8823 * should be overriden by subclasses to provide accurate and efficient
8824 * measurement of their contents.
8825 * </p>
8826 *
8827 * <p>
8828 * <strong>CONTRACT:</strong> When overriding this method, you
8829 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
8830 * measured width and height of this view. Failure to do so will trigger an
8831 * <code>IllegalStateException</code>, thrown by
8832 * {@link #measure(int, int)}. Calling the superclass'
8833 * {@link #onMeasure(int, int)} is a valid use.
8834 * </p>
8835 *
8836 * <p>
8837 * The base class implementation of measure defaults to the background size,
8838 * unless a larger size is allowed by the MeasureSpec. Subclasses should
8839 * override {@link #onMeasure(int, int)} to provide better measurements of
8840 * their content.
8841 * </p>
8842 *
8843 * <p>
8844 * If this method is overridden, it is the subclass's responsibility to make
8845 * sure the measured height and width are at least the view's minimum height
8846 * and width ({@link #getSuggestedMinimumHeight()} and
8847 * {@link #getSuggestedMinimumWidth()}).
8848 * </p>
8849 *
8850 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
8851 * The requirements are encoded with
8852 * {@link android.view.View.MeasureSpec}.
8853 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
8854 * The requirements are encoded with
8855 * {@link android.view.View.MeasureSpec}.
8856 *
8857 * @see #getMeasuredWidth()
8858 * @see #getMeasuredHeight()
8859 * @see #setMeasuredDimension(int, int)
8860 * @see #getSuggestedMinimumHeight()
8861 * @see #getSuggestedMinimumWidth()
8862 * @see android.view.View.MeasureSpec#getMode(int)
8863 * @see android.view.View.MeasureSpec#getSize(int)
8864 */
8865 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
8866 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
8867 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
8868 }
8869
8870 /**
8871 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
8872 * measured width and measured height. Failing to do so will trigger an
8873 * exception at measurement time.</p>
8874 *
8875 * @param measuredWidth the measured width of this view
8876 * @param measuredHeight the measured height of this view
8877 */
8878 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
8879 mMeasuredWidth = measuredWidth;
8880 mMeasuredHeight = measuredHeight;
8881
8882 mPrivateFlags |= MEASURED_DIMENSION_SET;
8883 }
8884
8885 /**
8886 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
8887 * Will take the desired size, unless a different size is imposed by the constraints.
8888 *
8889 * @param size How big the view wants to be
8890 * @param measureSpec Constraints imposed by the parent
8891 * @return The size this view should be.
8892 */
8893 public static int resolveSize(int size, int measureSpec) {
8894 int result = size;
8895 int specMode = MeasureSpec.getMode(measureSpec);
8896 int specSize = MeasureSpec.getSize(measureSpec);
8897 switch (specMode) {
8898 case MeasureSpec.UNSPECIFIED:
8899 result = size;
8900 break;
8901 case MeasureSpec.AT_MOST:
8902 result = Math.min(size, specSize);
8903 break;
8904 case MeasureSpec.EXACTLY:
8905 result = specSize;
8906 break;
8907 }
8908 return result;
8909 }
8910
8911 /**
8912 * Utility to return a default size. Uses the supplied size if the
8913 * MeasureSpec imposed no contraints. Will get larger if allowed
8914 * by the MeasureSpec.
8915 *
8916 * @param size Default size for this view
8917 * @param measureSpec Constraints imposed by the parent
8918 * @return The size this view should be.
8919 */
8920 public static int getDefaultSize(int size, int measureSpec) {
8921 int result = size;
8922 int specMode = MeasureSpec.getMode(measureSpec);
8923 int specSize = MeasureSpec.getSize(measureSpec);
8924
8925 switch (specMode) {
8926 case MeasureSpec.UNSPECIFIED:
8927 result = size;
8928 break;
8929 case MeasureSpec.AT_MOST:
8930 case MeasureSpec.EXACTLY:
8931 result = specSize;
8932 break;
8933 }
8934 return result;
8935 }
8936
8937 /**
8938 * Returns the suggested minimum height that the view should use. This
8939 * returns the maximum of the view's minimum height
8940 * and the background's minimum height
8941 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
8942 * <p>
8943 * When being used in {@link #onMeasure(int, int)}, the caller should still
8944 * ensure the returned height is within the requirements of the parent.
8945 *
8946 * @return The suggested minimum height of the view.
8947 */
8948 protected int getSuggestedMinimumHeight() {
8949 int suggestedMinHeight = mMinHeight;
8950
8951 if (mBGDrawable != null) {
8952 final int bgMinHeight = mBGDrawable.getMinimumHeight();
8953 if (suggestedMinHeight < bgMinHeight) {
8954 suggestedMinHeight = bgMinHeight;
8955 }
8956 }
8957
8958 return suggestedMinHeight;
8959 }
8960
8961 /**
8962 * Returns the suggested minimum width that the view should use. This
8963 * returns the maximum of the view's minimum width)
8964 * and the background's minimum width
8965 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
8966 * <p>
8967 * When being used in {@link #onMeasure(int, int)}, the caller should still
8968 * ensure the returned width is within the requirements of the parent.
8969 *
8970 * @return The suggested minimum width of the view.
8971 */
8972 protected int getSuggestedMinimumWidth() {
8973 int suggestedMinWidth = mMinWidth;
8974
8975 if (mBGDrawable != null) {
8976 final int bgMinWidth = mBGDrawable.getMinimumWidth();
8977 if (suggestedMinWidth < bgMinWidth) {
8978 suggestedMinWidth = bgMinWidth;
8979 }
8980 }
8981
8982 return suggestedMinWidth;
8983 }
8984
8985 /**
8986 * Sets the minimum height of the view. It is not guaranteed the view will
8987 * be able to achieve this minimum height (for example, if its parent layout
8988 * constrains it with less available height).
8989 *
8990 * @param minHeight The minimum height the view will try to be.
8991 */
8992 public void setMinimumHeight(int minHeight) {
8993 mMinHeight = minHeight;
8994 }
8995
8996 /**
8997 * Sets the minimum width of the view. It is not guaranteed the view will
8998 * be able to achieve this minimum width (for example, if its parent layout
8999 * constrains it with less available width).
9000 *
9001 * @param minWidth The minimum width the view will try to be.
9002 */
9003 public void setMinimumWidth(int minWidth) {
9004 mMinWidth = minWidth;
9005 }
9006
9007 /**
9008 * Get the animation currently associated with this view.
9009 *
9010 * @return The animation that is currently playing or
9011 * scheduled to play for this view.
9012 */
9013 public Animation getAnimation() {
9014 return mCurrentAnimation;
9015 }
9016
9017 /**
9018 * Start the specified animation now.
9019 *
9020 * @param animation the animation to start now
9021 */
9022 public void startAnimation(Animation animation) {
9023 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
9024 setAnimation(animation);
9025 invalidate();
9026 }
9027
9028 /**
9029 * Cancels any animations for this view.
9030 */
9031 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08009032 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08009033 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08009034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 mCurrentAnimation = null;
9036 }
9037
9038 /**
9039 * Sets the next animation to play for this view.
9040 * If you want the animation to play immediately, use
9041 * startAnimation. This method provides allows fine-grained
9042 * control over the start time and invalidation, but you
9043 * must make sure that 1) the animation has a start time set, and
9044 * 2) the view will be invalidated when the animation is supposed to
9045 * start.
9046 *
9047 * @param animation The next animation, or null.
9048 */
9049 public void setAnimation(Animation animation) {
9050 mCurrentAnimation = animation;
9051 if (animation != null) {
9052 animation.reset();
9053 }
9054 }
9055
9056 /**
9057 * Invoked by a parent ViewGroup to notify the start of the animation
9058 * currently associated with this view. If you override this method,
9059 * always call super.onAnimationStart();
9060 *
9061 * @see #setAnimation(android.view.animation.Animation)
9062 * @see #getAnimation()
9063 */
9064 protected void onAnimationStart() {
9065 mPrivateFlags |= ANIMATION_STARTED;
9066 }
9067
9068 /**
9069 * Invoked by a parent ViewGroup to notify the end of the animation
9070 * currently associated with this view. If you override this method,
9071 * always call super.onAnimationEnd();
9072 *
9073 * @see #setAnimation(android.view.animation.Animation)
9074 * @see #getAnimation()
9075 */
9076 protected void onAnimationEnd() {
9077 mPrivateFlags &= ~ANIMATION_STARTED;
9078 }
9079
9080 /**
9081 * Invoked if there is a Transform that involves alpha. Subclass that can
9082 * draw themselves with the specified alpha should return true, and then
9083 * respect that alpha when their onDraw() is called. If this returns false
9084 * then the view may be redirected to draw into an offscreen buffer to
9085 * fulfill the request, which will look fine, but may be slower than if the
9086 * subclass handles it internally. The default implementation returns false.
9087 *
9088 * @param alpha The alpha (0..255) to apply to the view's drawing
9089 * @return true if the view can draw with the specified alpha.
9090 */
9091 protected boolean onSetAlpha(int alpha) {
9092 return false;
9093 }
9094
9095 /**
9096 * This is used by the RootView to perform an optimization when
9097 * the view hierarchy contains one or several SurfaceView.
9098 * SurfaceView is always considered transparent, but its children are not,
9099 * therefore all View objects remove themselves from the global transparent
9100 * region (passed as a parameter to this function).
9101 *
9102 * @param region The transparent region for this ViewRoot (window).
9103 *
9104 * @return Returns true if the effective visibility of the view at this
9105 * point is opaque, regardless of the transparent region; returns false
9106 * if it is possible for underlying windows to be seen behind the view.
9107 *
9108 * {@hide}
9109 */
9110 public boolean gatherTransparentRegion(Region region) {
9111 final AttachInfo attachInfo = mAttachInfo;
9112 if (region != null && attachInfo != null) {
9113 final int pflags = mPrivateFlags;
9114 if ((pflags & SKIP_DRAW) == 0) {
9115 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
9116 // remove it from the transparent region.
9117 final int[] location = attachInfo.mTransparentLocation;
9118 getLocationInWindow(location);
9119 region.op(location[0], location[1], location[0] + mRight - mLeft,
9120 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
9121 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
9122 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
9123 // exists, so we remove the background drawable's non-transparent
9124 // parts from this transparent region.
9125 applyDrawableToTransparentRegion(mBGDrawable, region);
9126 }
9127 }
9128 return true;
9129 }
9130
9131 /**
9132 * Play a sound effect for this view.
9133 *
9134 * <p>The framework will play sound effects for some built in actions, such as
9135 * clicking, but you may wish to play these effects in your widget,
9136 * for instance, for internal navigation.
9137 *
9138 * <p>The sound effect will only be played if sound effects are enabled by the user, and
9139 * {@link #isSoundEffectsEnabled()} is true.
9140 *
9141 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
9142 */
9143 public void playSoundEffect(int soundConstant) {
9144 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
9145 return;
9146 }
9147 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
9148 }
9149
9150 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009151 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009152 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009153 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009154 *
9155 * <p>The framework will provide haptic feedback for some built in actions,
9156 * such as long presses, but you may wish to provide feedback for your
9157 * own widget.
9158 *
9159 * <p>The feedback will only be performed if
9160 * {@link #isHapticFeedbackEnabled()} is true.
9161 *
9162 * @param feedbackConstant One of the constants defined in
9163 * {@link HapticFeedbackConstants}
9164 */
9165 public boolean performHapticFeedback(int feedbackConstant) {
9166 return performHapticFeedback(feedbackConstant, 0);
9167 }
9168
9169 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009170 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009171 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009172 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009173 *
9174 * @param feedbackConstant One of the constants defined in
9175 * {@link HapticFeedbackConstants}
9176 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
9177 */
9178 public boolean performHapticFeedback(int feedbackConstant, int flags) {
9179 if (mAttachInfo == null) {
9180 return false;
9181 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009182 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009183 && !isHapticFeedbackEnabled()) {
9184 return false;
9185 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009186 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
9187 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009188 }
9189
9190 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -07009191 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
9192 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -07009193 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -07009194 */
9195 public void onCloseSystemDialogs(String reason) {
9196 }
9197
9198 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009199 * Given a Drawable whose bounds have been set to draw into this view,
9200 * update a Region being computed for {@link #gatherTransparentRegion} so
9201 * that any non-transparent parts of the Drawable are removed from the
9202 * given transparent region.
9203 *
9204 * @param dr The Drawable whose transparency is to be applied to the region.
9205 * @param region A Region holding the current transparency information,
9206 * where any parts of the region that are set are considered to be
9207 * transparent. On return, this region will be modified to have the
9208 * transparency information reduced by the corresponding parts of the
9209 * Drawable that are not transparent.
9210 * {@hide}
9211 */
9212 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
9213 if (DBG) {
9214 Log.i("View", "Getting transparent region for: " + this);
9215 }
9216 final Region r = dr.getTransparentRegion();
9217 final Rect db = dr.getBounds();
9218 final AttachInfo attachInfo = mAttachInfo;
9219 if (r != null && attachInfo != null) {
9220 final int w = getRight()-getLeft();
9221 final int h = getBottom()-getTop();
9222 if (db.left > 0) {
9223 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
9224 r.op(0, 0, db.left, h, Region.Op.UNION);
9225 }
9226 if (db.right < w) {
9227 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
9228 r.op(db.right, 0, w, h, Region.Op.UNION);
9229 }
9230 if (db.top > 0) {
9231 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
9232 r.op(0, 0, w, db.top, Region.Op.UNION);
9233 }
9234 if (db.bottom < h) {
9235 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
9236 r.op(0, db.bottom, w, h, Region.Op.UNION);
9237 }
9238 final int[] location = attachInfo.mTransparentLocation;
9239 getLocationInWindow(location);
9240 r.translate(location[0], location[1]);
9241 region.op(r, Region.Op.INTERSECT);
9242 } else {
9243 region.op(db, Region.Op.DIFFERENCE);
9244 }
9245 }
9246
Adam Powelle14579b2009-12-16 18:39:52 -08009247 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009248 mHasPerformedLongPress = false;
9249
9250 if (mPendingCheckForLongPress == null) {
9251 mPendingCheckForLongPress = new CheckForLongPress();
9252 }
9253 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -08009254 postDelayed(mPendingCheckForLongPress,
9255 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009256 }
9257
Romain Guy812ccbe2010-06-01 14:07:24 -07009258 private static int[] stateSetUnion(final int[] stateSet1, final int[] stateSet2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009259 final int stateSet1Length = stateSet1.length;
9260 final int stateSet2Length = stateSet2.length;
9261 final int[] newSet = new int[stateSet1Length + stateSet2Length];
9262 int k = 0;
9263 int i = 0;
9264 int j = 0;
9265 // This is a merge of the two input state sets and assumes that the
9266 // input sets are sorted by the order imposed by ViewDrawableStates.
9267 for (int viewState : R.styleable.ViewDrawableStates) {
9268 if (i < stateSet1Length && stateSet1[i] == viewState) {
9269 newSet[k++] = viewState;
9270 i++;
9271 } else if (j < stateSet2Length && stateSet2[j] == viewState) {
9272 newSet[k++] = viewState;
9273 j++;
9274 }
9275 if (k > 1) {
9276 assert(newSet[k - 1] > newSet[k - 2]);
9277 }
9278 }
9279 return newSet;
9280 }
9281
9282 /**
9283 * Inflate a view from an XML resource. This convenience method wraps the {@link
9284 * LayoutInflater} class, which provides a full range of options for view inflation.
9285 *
9286 * @param context The Context object for your activity or application.
9287 * @param resource The resource ID to inflate
9288 * @param root A view group that will be the parent. Used to properly inflate the
9289 * layout_* parameters.
9290 * @see LayoutInflater
9291 */
9292 public static View inflate(Context context, int resource, ViewGroup root) {
9293 LayoutInflater factory = LayoutInflater.from(context);
9294 return factory.inflate(resource, root);
9295 }
Romain Guy33e72ae2010-07-17 12:40:29 -07009296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 /**
9298 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
9299 * Each MeasureSpec represents a requirement for either the width or the height.
9300 * A MeasureSpec is comprised of a size and a mode. There are three possible
9301 * modes:
9302 * <dl>
9303 * <dt>UNSPECIFIED</dt>
9304 * <dd>
9305 * The parent has not imposed any constraint on the child. It can be whatever size
9306 * it wants.
9307 * </dd>
9308 *
9309 * <dt>EXACTLY</dt>
9310 * <dd>
9311 * The parent has determined an exact size for the child. The child is going to be
9312 * given those bounds regardless of how big it wants to be.
9313 * </dd>
9314 *
9315 * <dt>AT_MOST</dt>
9316 * <dd>
9317 * The child can be as large as it wants up to the specified size.
9318 * </dd>
9319 * </dl>
9320 *
9321 * MeasureSpecs are implemented as ints to reduce object allocation. This class
9322 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
9323 */
9324 public static class MeasureSpec {
9325 private static final int MODE_SHIFT = 30;
9326 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
9327
9328 /**
9329 * Measure specification mode: The parent has not imposed any constraint
9330 * on the child. It can be whatever size it wants.
9331 */
9332 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
9333
9334 /**
9335 * Measure specification mode: The parent has determined an exact size
9336 * for the child. The child is going to be given those bounds regardless
9337 * of how big it wants to be.
9338 */
9339 public static final int EXACTLY = 1 << MODE_SHIFT;
9340
9341 /**
9342 * Measure specification mode: The child can be as large as it wants up
9343 * to the specified size.
9344 */
9345 public static final int AT_MOST = 2 << MODE_SHIFT;
9346
9347 /**
9348 * Creates a measure specification based on the supplied size and mode.
9349 *
9350 * The mode must always be one of the following:
9351 * <ul>
9352 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
9353 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
9354 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
9355 * </ul>
9356 *
9357 * @param size the size of the measure specification
9358 * @param mode the mode of the measure specification
9359 * @return the measure specification based on size and mode
9360 */
9361 public static int makeMeasureSpec(int size, int mode) {
9362 return size + mode;
9363 }
9364
9365 /**
9366 * Extracts the mode from the supplied measure specification.
9367 *
9368 * @param measureSpec the measure specification to extract the mode from
9369 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
9370 * {@link android.view.View.MeasureSpec#AT_MOST} or
9371 * {@link android.view.View.MeasureSpec#EXACTLY}
9372 */
9373 public static int getMode(int measureSpec) {
9374 return (measureSpec & MODE_MASK);
9375 }
9376
9377 /**
9378 * Extracts the size from the supplied measure specification.
9379 *
9380 * @param measureSpec the measure specification to extract the size from
9381 * @return the size in pixels defined in the supplied measure specification
9382 */
9383 public static int getSize(int measureSpec) {
9384 return (measureSpec & ~MODE_MASK);
9385 }
9386
9387 /**
9388 * Returns a String representation of the specified measure
9389 * specification.
9390 *
9391 * @param measureSpec the measure specification to convert to a String
9392 * @return a String with the following format: "MeasureSpec: MODE SIZE"
9393 */
9394 public static String toString(int measureSpec) {
9395 int mode = getMode(measureSpec);
9396 int size = getSize(measureSpec);
9397
9398 StringBuilder sb = new StringBuilder("MeasureSpec: ");
9399
9400 if (mode == UNSPECIFIED)
9401 sb.append("UNSPECIFIED ");
9402 else if (mode == EXACTLY)
9403 sb.append("EXACTLY ");
9404 else if (mode == AT_MOST)
9405 sb.append("AT_MOST ");
9406 else
9407 sb.append(mode).append(" ");
9408
9409 sb.append(size);
9410 return sb.toString();
9411 }
9412 }
9413
9414 class CheckForLongPress implements Runnable {
9415
9416 private int mOriginalWindowAttachCount;
9417
9418 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -07009419 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009420 && mOriginalWindowAttachCount == mWindowAttachCount) {
9421 if (performLongClick()) {
9422 mHasPerformedLongPress = true;
9423 }
9424 }
9425 }
9426
9427 public void rememberWindowAttachCount() {
9428 mOriginalWindowAttachCount = mWindowAttachCount;
9429 }
9430 }
Adam Powelle14579b2009-12-16 18:39:52 -08009431
9432 private final class CheckForTap implements Runnable {
9433 public void run() {
9434 mPrivateFlags &= ~PREPRESSED;
9435 mPrivateFlags |= PRESSED;
9436 refreshDrawableState();
9437 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
9438 postCheckForLongClick(ViewConfiguration.getTapTimeout());
9439 }
9440 }
9441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009442
Adam Powella35d7682010-03-12 14:48:13 -08009443 private final class PerformClick implements Runnable {
9444 public void run() {
9445 performClick();
9446 }
9447 }
9448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009449 /**
9450 * Interface definition for a callback to be invoked when a key event is
9451 * dispatched to this view. The callback will be invoked before the key
9452 * event is given to the view.
9453 */
9454 public interface OnKeyListener {
9455 /**
9456 * Called when a key is dispatched to a view. This allows listeners to
9457 * get a chance to respond before the target view.
9458 *
9459 * @param v The view the key has been dispatched to.
9460 * @param keyCode The code for the physical key that was pressed
9461 * @param event The KeyEvent object containing full information about
9462 * the event.
9463 * @return True if the listener has consumed the event, false otherwise.
9464 */
9465 boolean onKey(View v, int keyCode, KeyEvent event);
9466 }
9467
9468 /**
9469 * Interface definition for a callback to be invoked when a touch event is
9470 * dispatched to this view. The callback will be invoked before the touch
9471 * event is given to the view.
9472 */
9473 public interface OnTouchListener {
9474 /**
9475 * Called when a touch event is dispatched to a view. This allows listeners to
9476 * get a chance to respond before the target view.
9477 *
9478 * @param v The view the touch event has been dispatched to.
9479 * @param event The MotionEvent object containing full information about
9480 * the event.
9481 * @return True if the listener has consumed the event, false otherwise.
9482 */
9483 boolean onTouch(View v, MotionEvent event);
9484 }
9485
9486 /**
9487 * Interface definition for a callback to be invoked when a view has been clicked and held.
9488 */
9489 public interface OnLongClickListener {
9490 /**
9491 * Called when a view has been clicked and held.
9492 *
9493 * @param v The view that was clicked and held.
9494 *
9495 * return True if the callback consumed the long click, false otherwise
9496 */
9497 boolean onLongClick(View v);
9498 }
9499
9500 /**
9501 * Interface definition for a callback to be invoked when the focus state of
9502 * a view changed.
9503 */
9504 public interface OnFocusChangeListener {
9505 /**
9506 * Called when the focus state of a view has changed.
9507 *
9508 * @param v The view whose state has changed.
9509 * @param hasFocus The new focus state of v.
9510 */
9511 void onFocusChange(View v, boolean hasFocus);
9512 }
9513
9514 /**
9515 * Interface definition for a callback to be invoked when a view is clicked.
9516 */
9517 public interface OnClickListener {
9518 /**
9519 * Called when a view has been clicked.
9520 *
9521 * @param v The view that was clicked.
9522 */
9523 void onClick(View v);
9524 }
9525
9526 /**
9527 * Interface definition for a callback to be invoked when the context menu
9528 * for this view is being built.
9529 */
9530 public interface OnCreateContextMenuListener {
9531 /**
9532 * Called when the context menu for this view is being built. It is not
9533 * safe to hold onto the menu after this method returns.
9534 *
9535 * @param menu The context menu that is being built
9536 * @param v The view for which the context menu is being built
9537 * @param menuInfo Extra information about the item for which the
9538 * context menu should be shown. This information will vary
9539 * depending on the class of v.
9540 */
9541 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
9542 }
9543
9544 private final class UnsetPressedState implements Runnable {
9545 public void run() {
9546 setPressed(false);
9547 }
9548 }
9549
9550 /**
9551 * Base class for derived classes that want to save and restore their own
9552 * state in {@link android.view.View#onSaveInstanceState()}.
9553 */
9554 public static class BaseSavedState extends AbsSavedState {
9555 /**
9556 * Constructor used when reading from a parcel. Reads the state of the superclass.
9557 *
9558 * @param source
9559 */
9560 public BaseSavedState(Parcel source) {
9561 super(source);
9562 }
9563
9564 /**
9565 * Constructor called by derived classes when creating their SavedState objects
9566 *
9567 * @param superState The state of the superclass of this view
9568 */
9569 public BaseSavedState(Parcelable superState) {
9570 super(superState);
9571 }
9572
9573 public static final Parcelable.Creator<BaseSavedState> CREATOR =
9574 new Parcelable.Creator<BaseSavedState>() {
9575 public BaseSavedState createFromParcel(Parcel in) {
9576 return new BaseSavedState(in);
9577 }
9578
9579 public BaseSavedState[] newArray(int size) {
9580 return new BaseSavedState[size];
9581 }
9582 };
9583 }
9584
9585 /**
9586 * A set of information given to a view when it is attached to its parent
9587 * window.
9588 */
9589 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009590 interface Callbacks {
9591 void playSoundEffect(int effectId);
9592 boolean performHapticFeedback(int effectId, boolean always);
9593 }
9594
9595 /**
9596 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
9597 * to a Handler. This class contains the target (View) to invalidate and
9598 * the coordinates of the dirty rectangle.
9599 *
9600 * For performance purposes, this class also implements a pool of up to
9601 * POOL_LIMIT objects that get reused. This reduces memory allocations
9602 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009603 */
Romain Guyd928d682009-03-31 17:52:16 -07009604 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009605 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -07009606 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
9607 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -07009608 public InvalidateInfo newInstance() {
9609 return new InvalidateInfo();
9610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009611
Romain Guyd928d682009-03-31 17:52:16 -07009612 public void onAcquired(InvalidateInfo element) {
9613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009614
Romain Guyd928d682009-03-31 17:52:16 -07009615 public void onReleased(InvalidateInfo element) {
9616 }
9617 }, POOL_LIMIT)
9618 );
9619
9620 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009621
9622 View target;
9623
9624 int left;
9625 int top;
9626 int right;
9627 int bottom;
9628
Romain Guyd928d682009-03-31 17:52:16 -07009629 public void setNextPoolable(InvalidateInfo element) {
9630 mNext = element;
9631 }
9632
9633 public InvalidateInfo getNextPoolable() {
9634 return mNext;
9635 }
9636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009637 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -07009638 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009639 }
9640
9641 void release() {
Romain Guyd928d682009-03-31 17:52:16 -07009642 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009643 }
9644 }
9645
9646 final IWindowSession mSession;
9647
9648 final IWindow mWindow;
9649
9650 final IBinder mWindowToken;
9651
9652 final Callbacks mRootCallbacks;
9653
9654 /**
9655 * The top view of the hierarchy.
9656 */
9657 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -07009658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009659 IBinder mPanelParentWindowToken;
9660 Surface mSurface;
9661
9662 /**
Romain Guy8506ab42009-06-11 17:35:47 -07009663 * Scale factor used by the compatibility mode
9664 */
9665 float mApplicationScale;
9666
9667 /**
9668 * Indicates whether the application is in compatibility mode
9669 */
9670 boolean mScalingRequired;
9671
9672 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009673 * Left position of this view's window
9674 */
9675 int mWindowLeft;
9676
9677 /**
9678 * Top position of this view's window
9679 */
9680 int mWindowTop;
9681
9682 /**
Romain Guy35b38ce2009-10-07 13:38:55 -07009683 * Indicates whether the window is translucent/transparent
9684 */
9685 boolean mTranslucentWindow;
9686
9687 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009688 * For windows that are full-screen but using insets to layout inside
9689 * of the screen decorations, these are the current insets for the
9690 * content of the window.
9691 */
9692 final Rect mContentInsets = new Rect();
9693
9694 /**
9695 * For windows that are full-screen but using insets to layout inside
9696 * of the screen decorations, these are the current insets for the
9697 * actual visible parts of the window.
9698 */
9699 final Rect mVisibleInsets = new Rect();
9700
9701 /**
9702 * The internal insets given by this window. This value is
9703 * supplied by the client (through
9704 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
9705 * be given to the window manager when changed to be used in laying
9706 * out windows behind it.
9707 */
9708 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
9709 = new ViewTreeObserver.InternalInsetsInfo();
9710
9711 /**
9712 * All views in the window's hierarchy that serve as scroll containers,
9713 * used to determine if the window can be resized or must be panned
9714 * to adjust for a soft input area.
9715 */
9716 final ArrayList<View> mScrollContainers = new ArrayList<View>();
9717
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07009718 final KeyEvent.DispatcherState mKeyDispatchState
9719 = new KeyEvent.DispatcherState();
9720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009721 /**
9722 * Indicates whether the view's window currently has the focus.
9723 */
9724 boolean mHasWindowFocus;
9725
9726 /**
9727 * The current visibility of the window.
9728 */
9729 int mWindowVisibility;
9730
9731 /**
9732 * Indicates the time at which drawing started to occur.
9733 */
9734 long mDrawingTime;
9735
9736 /**
Romain Guy5bcdff42009-05-14 21:27:18 -07009737 * Indicates whether or not ignoring the DIRTY_MASK flags.
9738 */
9739 boolean mIgnoreDirtyState;
9740
9741 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009742 * Indicates whether the view's window is currently in touch mode.
9743 */
9744 boolean mInTouchMode;
9745
9746 /**
9747 * Indicates that ViewRoot should trigger a global layout change
9748 * the next time it performs a traversal
9749 */
9750 boolean mRecomputeGlobalAttributes;
9751
9752 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009753 * Set during a traveral if any views want to keep the screen on.
9754 */
9755 boolean mKeepScreenOn;
9756
9757 /**
9758 * Set if the visibility of any views has changed.
9759 */
9760 boolean mViewVisibilityChanged;
9761
9762 /**
9763 * Set to true if a view has been scrolled.
9764 */
9765 boolean mViewScrollChanged;
9766
9767 /**
9768 * Global to the view hierarchy used as a temporary for dealing with
9769 * x/y points in the transparent region computations.
9770 */
9771 final int[] mTransparentLocation = new int[2];
9772
9773 /**
9774 * Global to the view hierarchy used as a temporary for dealing with
9775 * x/y points in the ViewGroup.invalidateChild implementation.
9776 */
9777 final int[] mInvalidateChildLocation = new int[2];
9778
Chet Haasec3aa3612010-06-17 08:50:37 -07009779
9780 /**
9781 * Global to the view hierarchy used as a temporary for dealing with
9782 * x/y location when view is transformed.
9783 */
9784 final float[] mTmpTransformLocation = new float[2];
9785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009786 /**
9787 * The view tree observer used to dispatch global events like
9788 * layout, pre-draw, touch mode change, etc.
9789 */
9790 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
9791
9792 /**
9793 * A Canvas used by the view hierarchy to perform bitmap caching.
9794 */
9795 Canvas mCanvas;
9796
9797 /**
9798 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
9799 * handler can be used to pump events in the UI events queue.
9800 */
9801 final Handler mHandler;
9802
9803 /**
9804 * Identifier for messages requesting the view to be invalidated.
9805 * Such messages should be sent to {@link #mHandler}.
9806 */
9807 static final int INVALIDATE_MSG = 0x1;
9808
9809 /**
9810 * Identifier for messages requesting the view to invalidate a region.
9811 * Such messages should be sent to {@link #mHandler}.
9812 */
9813 static final int INVALIDATE_RECT_MSG = 0x2;
9814
9815 /**
9816 * Temporary for use in computing invalidate rectangles while
9817 * calling up the hierarchy.
9818 */
9819 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -07009820
9821 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07009822 * Temporary for use in computing hit areas with transformed views
9823 */
9824 final RectF mTmpTransformRect = new RectF();
9825
9826 /**
9827 * Temporary for use in computing invalidation areas with transformed views
9828 */
9829 final float[] mTmpTransformBounds = new float[8];
9830
9831 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07009832 * Temporary list for use in collecting focusable descendents of a view.
9833 */
9834 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
9835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009836 /**
9837 * Creates a new set of attachment information with the specified
9838 * events handler and thread.
9839 *
9840 * @param handler the events handler the view must use
9841 */
9842 AttachInfo(IWindowSession session, IWindow window,
9843 Handler handler, Callbacks effectPlayer) {
9844 mSession = session;
9845 mWindow = window;
9846 mWindowToken = window.asBinder();
9847 mHandler = handler;
9848 mRootCallbacks = effectPlayer;
9849 }
9850 }
9851
9852 /**
9853 * <p>ScrollabilityCache holds various fields used by a View when scrolling
9854 * is supported. This avoids keeping too many unused fields in most
9855 * instances of View.</p>
9856 */
Mike Cleronf116bf82009-09-27 19:14:12 -07009857 private static class ScrollabilityCache implements Runnable {
9858
9859 /**
9860 * Scrollbars are not visible
9861 */
9862 public static final int OFF = 0;
9863
9864 /**
9865 * Scrollbars are visible
9866 */
9867 public static final int ON = 1;
9868
9869 /**
9870 * Scrollbars are fading away
9871 */
9872 public static final int FADING = 2;
9873
9874 public boolean fadeScrollBars;
9875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009876 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -07009877 public int scrollBarDefaultDelayBeforeFade;
9878 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009879
9880 public int scrollBarSize;
9881 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -07009882 public float[] interpolatorValues;
9883 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009884
9885 public final Paint paint;
9886 public final Matrix matrix;
9887 public Shader shader;
9888
Mike Cleronf116bf82009-09-27 19:14:12 -07009889 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
9890
9891 private final float[] mOpaque = {255.0f};
9892 private final float[] mTransparent = {0.0f};
9893
9894 /**
9895 * When fading should start. This time moves into the future every time
9896 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
9897 */
9898 public long fadeStartTime;
9899
9900
9901 /**
9902 * The current state of the scrollbars: ON, OFF, or FADING
9903 */
9904 public int state = OFF;
9905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009906 private int mLastColor;
9907
Mike Cleronf116bf82009-09-27 19:14:12 -07009908 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009909 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
9910 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -07009911 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
9912 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009913
9914 paint = new Paint();
9915 matrix = new Matrix();
9916 // use use a height of 1, and then wack the matrix each time we
9917 // actually use it.
9918 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -07009919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009920 paint.setShader(shader);
9921 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -07009922 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009923 }
Romain Guy8506ab42009-06-11 17:35:47 -07009924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009925 public void setFadeColor(int color) {
9926 if (color != 0 && color != mLastColor) {
9927 mLastColor = color;
9928 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -07009929
Romain Guye55e1a72009-08-27 10:42:26 -07009930 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
9931 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -07009932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009933 paint.setShader(shader);
9934 // Restore the default transfer mode (src_over)
9935 paint.setXfermode(null);
9936 }
9937 }
Mike Cleronf116bf82009-09-27 19:14:12 -07009938
9939 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -07009940 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -07009941 if (now >= fadeStartTime) {
9942
9943 // the animation fades the scrollbars out by changing
9944 // the opacity (alpha) from fully opaque to fully
9945 // transparent
9946 int nextFrame = (int) now;
9947 int framesCount = 0;
9948
9949 Interpolator interpolator = scrollBarInterpolator;
9950
9951 // Start opaque
9952 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
9953
9954 // End transparent
9955 nextFrame += scrollBarFadeDuration;
9956 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
9957
9958 state = FADING;
9959
9960 // Kick off the fade animation
9961 host.invalidate();
9962 }
9963 }
9964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009965 }
9966}