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