blob: 1d0f1856acba00cfee27298dfc14d53eec94bd1a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Christopher Tatea53146c2010-09-07 11:57:52 -070019import android.content.ClipData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080021import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070025import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070027import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.graphics.LinearGradient;
29import android.graphics.Matrix;
30import android.graphics.Paint;
31import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070032import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
35import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070036import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.graphics.Region;
38import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Message;
44import android.os.Parcel;
45import android.os.Parcelable;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.os.SystemProperties;
49import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070051import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070052import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070053import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070054import android.util.Pools;
55import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.view.ContextMenu.ContextMenuInfo;
svetoslavganov75986cf2009-05-14 22:28:01 -070057import android.view.accessibility.AccessibilityEvent;
58import android.view.accessibility.AccessibilityEventSource;
59import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070061import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070062import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.view.inputmethod.InputConnection;
64import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.widget.ScrollBarDrawable;
Romain Guyf607bdc2010-09-10 19:20:06 -070066import com.android.internal.R;
67import com.android.internal.view.menu.MenuBuilder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
Christopher Tatea0374192010-10-05 13:06:41 -070069import java.lang.ref.WeakReference;
svetoslavganov75986cf2009-05-14 22:28:01 -070070import java.lang.reflect.InvocationTargetException;
71import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.util.ArrayList;
73import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070074import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070075import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
77/**
78 * <p>
79 * This class represents the basic building block for user interface components. A View
80 * occupies a rectangular area on the screen and is responsible for drawing and
81 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070082 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
84 * are invisible containers that hold other Views (or other ViewGroups) and define
85 * their layout properties.
86 * </p>
87 *
88 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070089 * <p>For an introduction to using this class to develop your
90 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070092 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
94 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
95 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
101 * </p>
102 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700103 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 * <a name="Using"></a>
105 * <h3>Using Views</h3>
106 * <p>
107 * All of the views in a window are arranged in a single tree. You can add views
108 * either from code or by specifying a tree of views in one or more XML layout
109 * files. There are many specialized subclasses of views that act as controls or
110 * are capable of displaying text, images, or other content.
111 * </p>
112 * <p>
113 * Once you have created a tree of views, there are typically a few types of
114 * common operations you may wish to perform:
115 * <ul>
116 * <li><strong>Set properties:</strong> for example setting the text of a
117 * {@link android.widget.TextView}. The available properties and the methods
118 * that set them will vary among the different subclasses of views. Note that
119 * properties that are known at build time can be set in the XML layout
120 * files.</li>
121 * <li><strong>Set focus:</strong> The framework will handled moving focus in
122 * response to user input. To force focus to a specific view, call
123 * {@link #requestFocus}.</li>
124 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
125 * that will be notified when something interesting happens to the view. For
126 * example, all views will let you set a listener to be notified when the view
127 * gains or loses focus. You can register such a listener using
128 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
129 * specialized listeners. For example, a Button exposes a listener to notify
130 * clients when the button is clicked.</li>
131 * <li><strong>Set visibility:</strong> You can hide or show views using
132 * {@link #setVisibility}.</li>
133 * </ul>
134 * </p>
135 * <p><em>
136 * Note: The Android framework is responsible for measuring, laying out and
137 * drawing views. You should not call methods that perform these actions on
138 * views yourself unless you are actually implementing a
139 * {@link android.view.ViewGroup}.
140 * </em></p>
141 *
142 * <a name="Lifecycle"></a>
143 * <h3>Implementing a Custom View</h3>
144 *
145 * <p>
146 * To implement a custom view, you will usually begin by providing overrides for
147 * some of the standard methods that the framework calls on all views. You do
148 * not need to override all of these methods. In fact, you can start by just
149 * overriding {@link #onDraw(android.graphics.Canvas)}.
150 * <table border="2" width="85%" align="center" cellpadding="5">
151 * <thead>
152 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
153 * </thead>
154 *
155 * <tbody>
156 * <tr>
157 * <td rowspan="2">Creation</td>
158 * <td>Constructors</td>
159 * <td>There is a form of the constructor that are called when the view
160 * is created from code and a form that is called when the view is
161 * inflated from a layout file. The second form should parse and apply
162 * any attributes defined in the layout file.
163 * </td>
164 * </tr>
165 * <tr>
166 * <td><code>{@link #onFinishInflate()}</code></td>
167 * <td>Called after a view and all of its children has been inflated
168 * from XML.</td>
169 * </tr>
170 *
171 * <tr>
172 * <td rowspan="3">Layout</td>
173 * <td><code>{@link #onMeasure}</code></td>
174 * <td>Called to determine the size requirements for this view and all
175 * of its children.
176 * </td>
177 * </tr>
178 * <tr>
179 * <td><code>{@link #onLayout}</code></td>
180 * <td>Called when this view should assign a size and position to all
181 * of its children.
182 * </td>
183 * </tr>
184 * <tr>
185 * <td><code>{@link #onSizeChanged}</code></td>
186 * <td>Called when the size of this view has changed.
187 * </td>
188 * </tr>
189 *
190 * <tr>
191 * <td>Drawing</td>
192 * <td><code>{@link #onDraw}</code></td>
193 * <td>Called when the view should render its content.
194 * </td>
195 * </tr>
196 *
197 * <tr>
198 * <td rowspan="4">Event processing</td>
199 * <td><code>{@link #onKeyDown}</code></td>
200 * <td>Called when a new key event occurs.
201 * </td>
202 * </tr>
203 * <tr>
204 * <td><code>{@link #onKeyUp}</code></td>
205 * <td>Called when a key up event occurs.
206 * </td>
207 * </tr>
208 * <tr>
209 * <td><code>{@link #onTrackballEvent}</code></td>
210 * <td>Called when a trackball motion event occurs.
211 * </td>
212 * </tr>
213 * <tr>
214 * <td><code>{@link #onTouchEvent}</code></td>
215 * <td>Called when a touch screen motion event occurs.
216 * </td>
217 * </tr>
218 *
219 * <tr>
220 * <td rowspan="2">Focus</td>
221 * <td><code>{@link #onFocusChanged}</code></td>
222 * <td>Called when the view gains or loses focus.
223 * </td>
224 * </tr>
225 *
226 * <tr>
227 * <td><code>{@link #onWindowFocusChanged}</code></td>
228 * <td>Called when the window containing the view gains or loses focus.
229 * </td>
230 * </tr>
231 *
232 * <tr>
233 * <td rowspan="3">Attaching</td>
234 * <td><code>{@link #onAttachedToWindow()}</code></td>
235 * <td>Called when the view is attached to a window.
236 * </td>
237 * </tr>
238 *
239 * <tr>
240 * <td><code>{@link #onDetachedFromWindow}</code></td>
241 * <td>Called when the view is detached from its window.
242 * </td>
243 * </tr>
244 *
245 * <tr>
246 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
247 * <td>Called when the visibility of the window containing the view
248 * has changed.
249 * </td>
250 * </tr>
251 * </tbody>
252 *
253 * </table>
254 * </p>
255 *
256 * <a name="IDs"></a>
257 * <h3>IDs</h3>
258 * Views may have an integer id associated with them. These ids are typically
259 * assigned in the layout XML files, and are used to find specific views within
260 * the view tree. A common pattern is to:
261 * <ul>
262 * <li>Define a Button in the layout file and assign it a unique ID.
263 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700264 * &lt;Button
265 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 * android:layout_width="wrap_content"
267 * android:layout_height="wrap_content"
268 * android:text="@string/my_button_text"/&gt;
269 * </pre></li>
270 * <li>From the onCreate method of an Activity, find the Button
271 * <pre class="prettyprint">
272 * Button myButton = (Button) findViewById(R.id.my_button);
273 * </pre></li>
274 * </ul>
275 * <p>
276 * View IDs need not be unique throughout the tree, but it is good practice to
277 * ensure that they are at least unique within the part of the tree you are
278 * searching.
279 * </p>
280 *
281 * <a name="Position"></a>
282 * <h3>Position</h3>
283 * <p>
284 * The geometry of a view is that of a rectangle. A view has a location,
285 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
286 * two dimensions, expressed as a width and a height. The unit for location
287 * and dimensions is the pixel.
288 * </p>
289 *
290 * <p>
291 * It is possible to retrieve the location of a view by invoking the methods
292 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
293 * coordinate of the rectangle representing the view. The latter returns the
294 * top, or Y, coordinate of the rectangle representing the view. These methods
295 * both return the location of the view relative to its parent. For instance,
296 * when getLeft() returns 20, that means the view is located 20 pixels to the
297 * right of the left edge of its direct parent.
298 * </p>
299 *
300 * <p>
301 * In addition, several convenience methods are offered to avoid unnecessary
302 * computations, namely {@link #getRight()} and {@link #getBottom()}.
303 * These methods return the coordinates of the right and bottom edges of the
304 * rectangle representing the view. For instance, calling {@link #getRight()}
305 * is similar to the following computation: <code>getLeft() + getWidth()</code>
306 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
307 * </p>
308 *
309 * <a name="SizePaddingMargins"></a>
310 * <h3>Size, padding and margins</h3>
311 * <p>
312 * The size of a view is expressed with a width and a height. A view actually
313 * possess two pairs of width and height values.
314 * </p>
315 *
316 * <p>
317 * The first pair is known as <em>measured width</em> and
318 * <em>measured height</em>. These dimensions define how big a view wants to be
319 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
320 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
321 * and {@link #getMeasuredHeight()}.
322 * </p>
323 *
324 * <p>
325 * The second pair is simply known as <em>width</em> and <em>height</em>, or
326 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
327 * dimensions define the actual size of the view on screen, at drawing time and
328 * after layout. These values may, but do not have to, be different from the
329 * measured width and height. The width and height can be obtained by calling
330 * {@link #getWidth()} and {@link #getHeight()}.
331 * </p>
332 *
333 * <p>
334 * To measure its dimensions, a view takes into account its padding. The padding
335 * is expressed in pixels for the left, top, right and bottom parts of the view.
336 * Padding can be used to offset the content of the view by a specific amount of
337 * pixels. For instance, a left padding of 2 will push the view's content by
338 * 2 pixels to the right of the left edge. Padding can be set using the
339 * {@link #setPadding(int, int, int, int)} method and queried by calling
340 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
341 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
342 * </p>
343 *
344 * <p>
345 * Even though a view can define a padding, it does not provide any support for
346 * margins. However, view groups provide such a support. Refer to
347 * {@link android.view.ViewGroup} and
348 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
349 * </p>
350 *
351 * <a name="Layout"></a>
352 * <h3>Layout</h3>
353 * <p>
354 * Layout is a two pass process: a measure pass and a layout pass. The measuring
355 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
356 * of the view tree. Each view pushes dimension specifications down the tree
357 * during the recursion. At the end of the measure pass, every view has stored
358 * its measurements. The second pass happens in
359 * {@link #layout(int,int,int,int)} and is also top-down. During
360 * this pass each parent is responsible for positioning all of its children
361 * using the sizes computed in the measure pass.
362 * </p>
363 *
364 * <p>
365 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
366 * {@link #getMeasuredHeight()} values must be set, along with those for all of
367 * that view's descendants. A view's measured width and measured height values
368 * must respect the constraints imposed by the view's parents. This guarantees
369 * that at the end of the measure pass, all parents accept all of their
370 * children's measurements. A parent view may call measure() more than once on
371 * its children. For example, the parent may measure each child once with
372 * unspecified dimensions to find out how big they want to be, then call
373 * measure() on them again with actual numbers if the sum of all the children's
374 * unconstrained sizes is too big or too small.
375 * </p>
376 *
377 * <p>
378 * The measure pass uses two classes to communicate dimensions. The
379 * {@link MeasureSpec} class is used by views to tell their parents how they
380 * want to be measured and positioned. The base LayoutParams class just
381 * describes how big the view wants to be for both width and height. For each
382 * dimension, it can specify one of:
383 * <ul>
384 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800385 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 * (minus padding)
387 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
388 * enclose its content (plus padding).
389 * </ul>
390 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
391 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
392 * an X and Y value.
393 * </p>
394 *
395 * <p>
396 * MeasureSpecs are used to push requirements down the tree from parent to
397 * child. A MeasureSpec can be in one of three modes:
398 * <ul>
399 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
400 * of a child view. For example, a LinearLayout may call measure() on its child
401 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
402 * tall the child view wants to be given a width of 240 pixels.
403 * <li>EXACTLY: This is used by the parent to impose an exact size on the
404 * child. The child must use this size, and guarantee that all of its
405 * descendants will fit within this size.
406 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
407 * child. The child must gurantee that it and all of its descendants will fit
408 * within this size.
409 * </ul>
410 * </p>
411 *
412 * <p>
413 * To intiate a layout, call {@link #requestLayout}. This method is typically
414 * called by a view on itself when it believes that is can no longer fit within
415 * its current bounds.
416 * </p>
417 *
418 * <a name="Drawing"></a>
419 * <h3>Drawing</h3>
420 * <p>
421 * Drawing is handled by walking the tree and rendering each view that
422 * intersects the the invalid region. Because the tree is traversed in-order,
423 * this means that parents will draw before (i.e., behind) their children, with
424 * siblings drawn in the order they appear in the tree.
425 * If you set a background drawable for a View, then the View will draw it for you
426 * before calling back to its <code>onDraw()</code> method.
427 * </p>
428 *
429 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700430 * Note that the framework will not draw views that are not in the invalid region.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 * </p>
432 *
433 * <p>
434 * To force a view to draw, call {@link #invalidate()}.
435 * </p>
436 *
437 * <a name="EventHandlingThreading"></a>
438 * <h3>Event Handling and Threading</h3>
439 * <p>
440 * The basic cycle of a view is as follows:
441 * <ol>
442 * <li>An event comes in and is dispatched to the appropriate view. The view
443 * handles the event and notifies any listeners.</li>
444 * <li>If in the course of processing the event, the view's bounds may need
445 * to be changed, the view will call {@link #requestLayout()}.</li>
446 * <li>Similarly, if in the course of processing the event the view's appearance
447 * may need to be changed, the view will call {@link #invalidate()}.</li>
448 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
449 * the framework will take care of measuring, laying out, and drawing the tree
450 * as appropriate.</li>
451 * </ol>
452 * </p>
453 *
454 * <p><em>Note: The entire view tree is single threaded. You must always be on
455 * the UI thread when calling any method on any view.</em>
456 * If you are doing work on other threads and want to update the state of a view
457 * from that thread, you should use a {@link Handler}.
458 * </p>
459 *
460 * <a name="FocusHandling"></a>
461 * <h3>Focus Handling</h3>
462 * <p>
463 * The framework will handle routine focus movement in response to user input.
464 * This includes changing the focus as views are removed or hidden, or as new
465 * views become available. Views indicate their willingness to take focus
466 * through the {@link #isFocusable} method. To change whether a view can take
467 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
468 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
469 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
470 * </p>
471 * <p>
472 * Focus movement is based on an algorithm which finds the nearest neighbor in a
473 * given direction. In rare cases, the default algorithm may not match the
474 * intended behavior of the developer. In these situations, you can provide
475 * explicit overrides by using these XML attributes in the layout file:
476 * <pre>
477 * nextFocusDown
478 * nextFocusLeft
479 * nextFocusRight
480 * nextFocusUp
481 * </pre>
482 * </p>
483 *
484 *
485 * <p>
486 * To get a particular view to take focus, call {@link #requestFocus()}.
487 * </p>
488 *
489 * <a name="TouchMode"></a>
490 * <h3>Touch Mode</h3>
491 * <p>
492 * When a user is navigating a user interface via directional keys such as a D-pad, it is
493 * necessary to give focus to actionable items such as buttons so the user can see
494 * what will take input. If the device has touch capabilities, however, and the user
495 * begins interacting with the interface by touching it, it is no longer necessary to
496 * always highlight, or give focus to, a particular view. This motivates a mode
497 * for interaction named 'touch mode'.
498 * </p>
499 * <p>
500 * For a touch capable device, once the user touches the screen, the device
501 * will enter touch mode. From this point onward, only views for which
502 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
503 * Other views that are touchable, like buttons, will not take focus when touched; they will
504 * only fire the on click listeners.
505 * </p>
506 * <p>
507 * Any time a user hits a directional key, such as a D-pad direction, the view device will
508 * exit touch mode, and find a view to take focus, so that the user may resume interacting
509 * with the user interface without touching the screen again.
510 * </p>
511 * <p>
512 * The touch mode state is maintained across {@link android.app.Activity}s. Call
513 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
514 * </p>
515 *
516 * <a name="Scrolling"></a>
517 * <h3>Scrolling</h3>
518 * <p>
519 * The framework provides basic support for views that wish to internally
520 * scroll their content. This includes keeping track of the X and Y scroll
521 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700522 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
523 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 * </p>
525 *
526 * <a name="Tags"></a>
527 * <h3>Tags</h3>
528 * <p>
529 * Unlike IDs, tags are not used to identify views. Tags are essentially an
530 * extra piece of information that can be associated with a view. They are most
531 * often used as a convenience to store data related to views in the views
532 * themselves rather than by putting them in a separate structure.
533 * </p>
534 *
535 * <a name="Animation"></a>
536 * <h3>Animation</h3>
537 * <p>
538 * You can attach an {@link Animation} object to a view using
539 * {@link #setAnimation(Animation)} or
540 * {@link #startAnimation(Animation)}. The animation can alter the scale,
541 * rotation, translation and alpha of a view over time. If the animation is
542 * attached to a view that has children, the animation will affect the entire
543 * subtree rooted by that node. When an animation is started, the framework will
544 * take care of redrawing the appropriate views until the animation completes.
545 * </p>
546 *
Jeff Brown85a31762010-09-01 17:01:00 -0700547 * <a name="Security"></a>
548 * <h3>Security</h3>
549 * <p>
550 * Sometimes it is essential that an application be able to verify that an action
551 * is being performed with the full knowledge and consent of the user, such as
552 * granting a permission request, making a purchase or clicking on an advertisement.
553 * Unfortunately, a malicious application could try to spoof the user into
554 * performing these actions, unaware, by concealing the intended purpose of the view.
555 * As a remedy, the framework offers a touch filtering mechanism that can be used to
556 * improve the security of views that provide access to sensitive functionality.
557 * </p><p>
558 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
559 * andoird:filterTouchesWhenObscured attribute to true. When enabled, the framework
560 * will discard touches that are received whenever the view's window is obscured by
561 * another visible window. As a result, the view will not receive touches whenever a
562 * toast, dialog or other window appears above the view's window.
563 * </p><p>
564 * For more fine-grained control over security, consider overriding the
565 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
566 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
567 * </p>
568 *
Romain Guyd6a463a2009-05-21 23:10:10 -0700569 * @attr ref android.R.styleable#View_background
570 * @attr ref android.R.styleable#View_clickable
571 * @attr ref android.R.styleable#View_contentDescription
572 * @attr ref android.R.styleable#View_drawingCacheQuality
573 * @attr ref android.R.styleable#View_duplicateParentState
574 * @attr ref android.R.styleable#View_id
575 * @attr ref android.R.styleable#View_fadingEdge
576 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700577 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700579 * @attr ref android.R.styleable#View_isScrollContainer
580 * @attr ref android.R.styleable#View_focusable
581 * @attr ref android.R.styleable#View_focusableInTouchMode
582 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
583 * @attr ref android.R.styleable#View_keepScreenOn
584 * @attr ref android.R.styleable#View_longClickable
585 * @attr ref android.R.styleable#View_minHeight
586 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 * @attr ref android.R.styleable#View_nextFocusDown
588 * @attr ref android.R.styleable#View_nextFocusLeft
589 * @attr ref android.R.styleable#View_nextFocusRight
590 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700591 * @attr ref android.R.styleable#View_onClick
592 * @attr ref android.R.styleable#View_padding
593 * @attr ref android.R.styleable#View_paddingBottom
594 * @attr ref android.R.styleable#View_paddingLeft
595 * @attr ref android.R.styleable#View_paddingRight
596 * @attr ref android.R.styleable#View_paddingTop
597 * @attr ref android.R.styleable#View_saveEnabled
Chet Haase73066682010-11-29 15:55:32 -0800598 * @attr ref android.R.styleable#View_rotation
599 * @attr ref android.R.styleable#View_rotationX
600 * @attr ref android.R.styleable#View_rotationY
601 * @attr ref android.R.styleable#View_scaleX
602 * @attr ref android.R.styleable#View_scaleY
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 * @attr ref android.R.styleable#View_scrollX
604 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700605 * @attr ref android.R.styleable#View_scrollbarSize
606 * @attr ref android.R.styleable#View_scrollbarStyle
607 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700608 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
609 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
611 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 * @attr ref android.R.styleable#View_scrollbarThumbVertical
613 * @attr ref android.R.styleable#View_scrollbarTrackVertical
614 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
615 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700616 * @attr ref android.R.styleable#View_soundEffectsEnabled
617 * @attr ref android.R.styleable#View_tag
Chet Haase73066682010-11-29 15:55:32 -0800618 * @attr ref android.R.styleable#View_transformPivotX
619 * @attr ref android.R.styleable#View_transformPivotY
620 * @attr ref android.R.styleable#View_translationX
621 * @attr ref android.R.styleable#View_translationY
Romain Guyd6a463a2009-05-21 23:10:10 -0700622 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 *
624 * @see android.view.ViewGroup
625 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700626public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 private static final boolean DBG = false;
628
629 /**
630 * The logging tag used by this class with android.util.Log.
631 */
632 protected static final String VIEW_LOG_TAG = "View";
633
634 /**
635 * Used to mark a View that has no ID.
636 */
637 public static final int NO_ID = -1;
638
639 /**
640 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
641 * calling setFlags.
642 */
643 private static final int NOT_FOCUSABLE = 0x00000000;
644
645 /**
646 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
647 * setFlags.
648 */
649 private static final int FOCUSABLE = 0x00000001;
650
651 /**
652 * Mask for use with setFlags indicating bits used for focus.
653 */
654 private static final int FOCUSABLE_MASK = 0x00000001;
655
656 /**
657 * This view will adjust its padding to fit sytem windows (e.g. status bar)
658 */
659 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
660
661 /**
662 * This view is visible. Use with {@link #setVisibility}.
663 */
664 public static final int VISIBLE = 0x00000000;
665
666 /**
667 * This view is invisible, but it still takes up space for layout purposes.
668 * Use with {@link #setVisibility}.
669 */
670 public static final int INVISIBLE = 0x00000004;
671
672 /**
673 * This view is invisible, and it doesn't take any space for layout
674 * purposes. Use with {@link #setVisibility}.
675 */
676 public static final int GONE = 0x00000008;
677
678 /**
679 * Mask for use with setFlags indicating bits used for visibility.
680 * {@hide}
681 */
682 static final int VISIBILITY_MASK = 0x0000000C;
683
684 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
685
686 /**
687 * This view is enabled. Intrepretation varies by subclass.
688 * Use with ENABLED_MASK when calling setFlags.
689 * {@hide}
690 */
691 static final int ENABLED = 0x00000000;
692
693 /**
694 * This view is disabled. Intrepretation varies by subclass.
695 * Use with ENABLED_MASK when calling setFlags.
696 * {@hide}
697 */
698 static final int DISABLED = 0x00000020;
699
700 /**
701 * Mask for use with setFlags indicating bits used for indicating whether
702 * this view is enabled
703 * {@hide}
704 */
705 static final int ENABLED_MASK = 0x00000020;
706
707 /**
708 * This view won't draw. {@link #onDraw} won't be called and further
709 * optimizations
710 * will be performed. It is okay to have this flag set and a background.
711 * Use with DRAW_MASK when calling setFlags.
712 * {@hide}
713 */
714 static final int WILL_NOT_DRAW = 0x00000080;
715
716 /**
717 * Mask for use with setFlags indicating bits used for indicating whether
718 * this view is will draw
719 * {@hide}
720 */
721 static final int DRAW_MASK = 0x00000080;
722
723 /**
724 * <p>This view doesn't show scrollbars.</p>
725 * {@hide}
726 */
727 static final int SCROLLBARS_NONE = 0x00000000;
728
729 /**
730 * <p>This view shows horizontal scrollbars.</p>
731 * {@hide}
732 */
733 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
734
735 /**
736 * <p>This view shows vertical scrollbars.</p>
737 * {@hide}
738 */
739 static final int SCROLLBARS_VERTICAL = 0x00000200;
740
741 /**
742 * <p>Mask for use with setFlags indicating bits used for indicating which
743 * scrollbars are enabled.</p>
744 * {@hide}
745 */
746 static final int SCROLLBARS_MASK = 0x00000300;
747
Jeff Brown85a31762010-09-01 17:01:00 -0700748 /**
749 * Indicates that the view should filter touches when its window is obscured.
750 * Refer to the class comments for more information about this security feature.
751 * {@hide}
752 */
753 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
754
755 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756
757 /**
758 * <p>This view doesn't show fading edges.</p>
759 * {@hide}
760 */
761 static final int FADING_EDGE_NONE = 0x00000000;
762
763 /**
764 * <p>This view shows horizontal fading edges.</p>
765 * {@hide}
766 */
767 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
768
769 /**
770 * <p>This view shows vertical fading edges.</p>
771 * {@hide}
772 */
773 static final int FADING_EDGE_VERTICAL = 0x00002000;
774
775 /**
776 * <p>Mask for use with setFlags indicating bits used for indicating which
777 * fading edges are enabled.</p>
778 * {@hide}
779 */
780 static final int FADING_EDGE_MASK = 0x00003000;
781
782 /**
783 * <p>Indicates this view can be clicked. When clickable, a View reacts
784 * to clicks by notifying the OnClickListener.<p>
785 * {@hide}
786 */
787 static final int CLICKABLE = 0x00004000;
788
789 /**
790 * <p>Indicates this view is caching its drawing into a bitmap.</p>
791 * {@hide}
792 */
793 static final int DRAWING_CACHE_ENABLED = 0x00008000;
794
795 /**
796 * <p>Indicates that no icicle should be saved for this view.<p>
797 * {@hide}
798 */
799 static final int SAVE_DISABLED = 0x000010000;
800
801 /**
802 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
803 * property.</p>
804 * {@hide}
805 */
806 static final int SAVE_DISABLED_MASK = 0x000010000;
807
808 /**
809 * <p>Indicates that no drawing cache should ever be created for this view.<p>
810 * {@hide}
811 */
812 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
813
814 /**
815 * <p>Indicates this view can take / keep focus when int touch mode.</p>
816 * {@hide}
817 */
818 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
819
820 /**
821 * <p>Enables low quality mode for the drawing cache.</p>
822 */
823 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
824
825 /**
826 * <p>Enables high quality mode for the drawing cache.</p>
827 */
828 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
829
830 /**
831 * <p>Enables automatic quality mode for the drawing cache.</p>
832 */
833 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
834
835 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
836 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
837 };
838
839 /**
840 * <p>Mask for use with setFlags indicating bits used for the cache
841 * quality property.</p>
842 * {@hide}
843 */
844 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
845
846 /**
847 * <p>
848 * Indicates this view can be long clicked. When long clickable, a View
849 * reacts to long clicks by notifying the OnLongClickListener or showing a
850 * context menu.
851 * </p>
852 * {@hide}
853 */
854 static final int LONG_CLICKABLE = 0x00200000;
855
856 /**
857 * <p>Indicates that this view gets its drawable states from its direct parent
858 * and ignores its original internal states.</p>
859 *
860 * @hide
861 */
862 static final int DUPLICATE_PARENT_STATE = 0x00400000;
863
864 /**
865 * The scrollbar style to display the scrollbars inside the content area,
866 * without increasing the padding. The scrollbars will be overlaid with
867 * translucency on the view's content.
868 */
869 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
870
871 /**
872 * The scrollbar style to display the scrollbars inside the padded area,
873 * increasing the padding of the view. The scrollbars will not overlap the
874 * content area of the view.
875 */
876 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
877
878 /**
879 * The scrollbar style to display the scrollbars at the edge of the view,
880 * without increasing the padding. The scrollbars will be overlaid with
881 * translucency.
882 */
883 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
884
885 /**
886 * The scrollbar style to display the scrollbars at the edge of the view,
887 * increasing the padding of the view. The scrollbars will only overlap the
888 * background, if any.
889 */
890 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
891
892 /**
893 * Mask to check if the scrollbar style is overlay or inset.
894 * {@hide}
895 */
896 static final int SCROLLBARS_INSET_MASK = 0x01000000;
897
898 /**
899 * Mask to check if the scrollbar style is inside or outside.
900 * {@hide}
901 */
902 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
903
904 /**
905 * Mask for scrollbar style.
906 * {@hide}
907 */
908 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
909
910 /**
911 * View flag indicating that the screen should remain on while the
912 * window containing this view is visible to the user. This effectively
913 * takes care of automatically setting the WindowManager's
914 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
915 */
916 public static final int KEEP_SCREEN_ON = 0x04000000;
917
918 /**
919 * View flag indicating whether this view should have sound effects enabled
920 * for events such as clicking and touching.
921 */
922 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
923
924 /**
925 * View flag indicating whether this view should have haptic feedback
926 * enabled for events such as long presses.
927 */
928 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
929
930 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700931 * <p>Indicates that the view hierarchy should stop saving state when
932 * it reaches this view. If state saving is initiated immediately at
933 * the view, it will be allowed.
934 * {@hide}
935 */
936 static final int PARENT_SAVE_DISABLED = 0x20000000;
937
938 /**
939 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
940 * {@hide}
941 */
942 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
943
944 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700945 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
946 * should add all focusable Views regardless if they are focusable in touch mode.
947 */
948 public static final int FOCUSABLES_ALL = 0x00000000;
949
950 /**
951 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
952 * should add only Views focusable in touch mode.
953 */
954 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
955
956 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 * Use with {@link #focusSearch}. Move focus to the previous selectable
958 * item.
959 */
960 public static final int FOCUS_BACKWARD = 0x00000001;
961
962 /**
963 * Use with {@link #focusSearch}. Move focus to the next selectable
964 * item.
965 */
966 public static final int FOCUS_FORWARD = 0x00000002;
967
968 /**
969 * Use with {@link #focusSearch}. Move focus to the left.
970 */
971 public static final int FOCUS_LEFT = 0x00000011;
972
973 /**
974 * Use with {@link #focusSearch}. Move focus up.
975 */
976 public static final int FOCUS_UP = 0x00000021;
977
978 /**
979 * Use with {@link #focusSearch}. Move focus to the right.
980 */
981 public static final int FOCUS_RIGHT = 0x00000042;
982
983 /**
984 * Use with {@link #focusSearch}. Move focus down.
985 */
986 public static final int FOCUS_DOWN = 0x00000082;
987
988 /**
989 * Base View state sets
990 */
991 // Singles
992 /**
993 * Indicates the view has no states set. States are used with
994 * {@link android.graphics.drawable.Drawable} to change the drawing of the
995 * view depending on its state.
996 *
997 * @see android.graphics.drawable.Drawable
998 * @see #getDrawableState()
999 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001000 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 /**
1002 * Indicates the view is enabled. States are used with
1003 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1004 * view depending on its state.
1005 *
1006 * @see android.graphics.drawable.Drawable
1007 * @see #getDrawableState()
1008 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001009 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 /**
1011 * Indicates the view is focused. States are used with
1012 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1013 * view depending on its state.
1014 *
1015 * @see android.graphics.drawable.Drawable
1016 * @see #getDrawableState()
1017 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001018 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 /**
1020 * Indicates the view is selected. States are used with
1021 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1022 * view depending on its state.
1023 *
1024 * @see android.graphics.drawable.Drawable
1025 * @see #getDrawableState()
1026 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001027 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 /**
1029 * Indicates the view is pressed. States are used with
1030 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1031 * view depending on its state.
1032 *
1033 * @see android.graphics.drawable.Drawable
1034 * @see #getDrawableState()
1035 * @hide
1036 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001037 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 /**
1039 * Indicates the view's window has focus. States are used with
1040 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1041 * view depending on its state.
1042 *
1043 * @see android.graphics.drawable.Drawable
1044 * @see #getDrawableState()
1045 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001046 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 // Doubles
1048 /**
1049 * Indicates the view is enabled and has the focus.
1050 *
1051 * @see #ENABLED_STATE_SET
1052 * @see #FOCUSED_STATE_SET
1053 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001054 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 /**
1056 * Indicates the view is enabled and selected.
1057 *
1058 * @see #ENABLED_STATE_SET
1059 * @see #SELECTED_STATE_SET
1060 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001061 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 /**
1063 * Indicates the view is enabled and that its window has focus.
1064 *
1065 * @see #ENABLED_STATE_SET
1066 * @see #WINDOW_FOCUSED_STATE_SET
1067 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001068 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 /**
1070 * Indicates the view is focused and selected.
1071 *
1072 * @see #FOCUSED_STATE_SET
1073 * @see #SELECTED_STATE_SET
1074 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001075 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 /**
1077 * Indicates the view has the focus and that its window has the focus.
1078 *
1079 * @see #FOCUSED_STATE_SET
1080 * @see #WINDOW_FOCUSED_STATE_SET
1081 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001082 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 /**
1084 * Indicates the view is selected and that its window has the focus.
1085 *
1086 * @see #SELECTED_STATE_SET
1087 * @see #WINDOW_FOCUSED_STATE_SET
1088 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001089 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 // Triples
1091 /**
1092 * Indicates the view is enabled, focused and selected.
1093 *
1094 * @see #ENABLED_STATE_SET
1095 * @see #FOCUSED_STATE_SET
1096 * @see #SELECTED_STATE_SET
1097 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001098 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 /**
1100 * Indicates the view is enabled, focused and its window has the focus.
1101 *
1102 * @see #ENABLED_STATE_SET
1103 * @see #FOCUSED_STATE_SET
1104 * @see #WINDOW_FOCUSED_STATE_SET
1105 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001106 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 /**
1108 * Indicates the view is enabled, selected and its window has the focus.
1109 *
1110 * @see #ENABLED_STATE_SET
1111 * @see #SELECTED_STATE_SET
1112 * @see #WINDOW_FOCUSED_STATE_SET
1113 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001114 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 /**
1116 * Indicates the view is focused, selected and its window has the focus.
1117 *
1118 * @see #FOCUSED_STATE_SET
1119 * @see #SELECTED_STATE_SET
1120 * @see #WINDOW_FOCUSED_STATE_SET
1121 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001122 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 /**
1124 * Indicates the view is enabled, focused, selected and its window
1125 * has the focus.
1126 *
1127 * @see #ENABLED_STATE_SET
1128 * @see #FOCUSED_STATE_SET
1129 * @see #SELECTED_STATE_SET
1130 * @see #WINDOW_FOCUSED_STATE_SET
1131 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001132 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 /**
1134 * Indicates the view is pressed and its window has the focus.
1135 *
1136 * @see #PRESSED_STATE_SET
1137 * @see #WINDOW_FOCUSED_STATE_SET
1138 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001139 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 /**
1141 * Indicates the view is pressed and selected.
1142 *
1143 * @see #PRESSED_STATE_SET
1144 * @see #SELECTED_STATE_SET
1145 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001146 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 /**
1148 * Indicates the view is pressed, selected and its window has the focus.
1149 *
1150 * @see #PRESSED_STATE_SET
1151 * @see #SELECTED_STATE_SET
1152 * @see #WINDOW_FOCUSED_STATE_SET
1153 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001154 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 /**
1156 * Indicates the view is pressed and focused.
1157 *
1158 * @see #PRESSED_STATE_SET
1159 * @see #FOCUSED_STATE_SET
1160 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001161 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 /**
1163 * Indicates the view is pressed, focused and its window has the focus.
1164 *
1165 * @see #PRESSED_STATE_SET
1166 * @see #FOCUSED_STATE_SET
1167 * @see #WINDOW_FOCUSED_STATE_SET
1168 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001169 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 /**
1171 * Indicates the view is pressed, focused and selected.
1172 *
1173 * @see #PRESSED_STATE_SET
1174 * @see #SELECTED_STATE_SET
1175 * @see #FOCUSED_STATE_SET
1176 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001177 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 /**
1179 * Indicates the view is pressed, focused, selected and its window has the focus.
1180 *
1181 * @see #PRESSED_STATE_SET
1182 * @see #FOCUSED_STATE_SET
1183 * @see #SELECTED_STATE_SET
1184 * @see #WINDOW_FOCUSED_STATE_SET
1185 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001186 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 /**
1188 * Indicates the view is pressed and enabled.
1189 *
1190 * @see #PRESSED_STATE_SET
1191 * @see #ENABLED_STATE_SET
1192 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001193 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 /**
1195 * Indicates the view is pressed, enabled and its window has the focus.
1196 *
1197 * @see #PRESSED_STATE_SET
1198 * @see #ENABLED_STATE_SET
1199 * @see #WINDOW_FOCUSED_STATE_SET
1200 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001201 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 /**
1203 * Indicates the view is pressed, enabled and selected.
1204 *
1205 * @see #PRESSED_STATE_SET
1206 * @see #ENABLED_STATE_SET
1207 * @see #SELECTED_STATE_SET
1208 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001209 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 /**
1211 * Indicates the view is pressed, enabled, selected and its window has the
1212 * focus.
1213 *
1214 * @see #PRESSED_STATE_SET
1215 * @see #ENABLED_STATE_SET
1216 * @see #SELECTED_STATE_SET
1217 * @see #WINDOW_FOCUSED_STATE_SET
1218 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001219 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 /**
1221 * Indicates the view is pressed, enabled and focused.
1222 *
1223 * @see #PRESSED_STATE_SET
1224 * @see #ENABLED_STATE_SET
1225 * @see #FOCUSED_STATE_SET
1226 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001227 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 /**
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 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001237 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 /**
1239 * Indicates the view is pressed, enabled, focused and selected.
1240 *
1241 * @see #PRESSED_STATE_SET
1242 * @see #ENABLED_STATE_SET
1243 * @see #SELECTED_STATE_SET
1244 * @see #FOCUSED_STATE_SET
1245 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001246 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 /**
1248 * Indicates the view is pressed, enabled, focused, selected and its window
1249 * has the focus.
1250 *
1251 * @see #PRESSED_STATE_SET
1252 * @see #ENABLED_STATE_SET
1253 * @see #SELECTED_STATE_SET
1254 * @see #FOCUSED_STATE_SET
1255 * @see #WINDOW_FOCUSED_STATE_SET
1256 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001257 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258
1259 /**
1260 * The order here is very important to {@link #getDrawableState()}
1261 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001262 private static final int[][] VIEW_STATE_SETS;
1263
Romain Guyb051e892010-09-28 19:09:36 -07001264 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1265 static final int VIEW_STATE_SELECTED = 1 << 1;
1266 static final int VIEW_STATE_FOCUSED = 1 << 2;
1267 static final int VIEW_STATE_ENABLED = 1 << 3;
1268 static final int VIEW_STATE_PRESSED = 1 << 4;
1269 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001270 static final int VIEW_STATE_ACCELERATED = 1 << 6;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001271
1272 static final int[] VIEW_STATE_IDS = new int[] {
1273 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1274 R.attr.state_selected, VIEW_STATE_SELECTED,
1275 R.attr.state_focused, VIEW_STATE_FOCUSED,
1276 R.attr.state_enabled, VIEW_STATE_ENABLED,
1277 R.attr.state_pressed, VIEW_STATE_PRESSED,
1278 R.attr.state_activated, VIEW_STATE_ACTIVATED,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001279 R.attr.state_accelerated, VIEW_STATE_ACCELERATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 };
1281
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001282 static {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001283 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1284 throw new IllegalStateException(
1285 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1286 }
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001287 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001288 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001289 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001290 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001291 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001292 orderedIds[i * 2] = viewState;
1293 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001294 }
1295 }
1296 }
Romain Guyb051e892010-09-28 19:09:36 -07001297 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1298 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1299 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001300 int numBits = Integer.bitCount(i);
1301 int[] set = new int[numBits];
1302 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001303 for (int j = 0; j < orderedIds.length; j += 2) {
1304 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001305 set[pos++] = orderedIds[j];
1306 }
1307 }
1308 VIEW_STATE_SETS[i] = set;
1309 }
1310
1311 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1312 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1313 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1314 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1315 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1316 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1317 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1318 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1319 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1320 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1321 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1322 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1323 | VIEW_STATE_FOCUSED];
1324 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1325 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1326 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1327 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1328 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1329 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1330 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1331 | VIEW_STATE_ENABLED];
1332 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1333 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1334 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1335 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1336 | VIEW_STATE_ENABLED];
1337 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1338 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1339 | VIEW_STATE_ENABLED];
1340 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1341 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1342 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1343
1344 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1345 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1346 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1347 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1348 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1349 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1350 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1351 | VIEW_STATE_PRESSED];
1352 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1353 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1354 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1355 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1356 | VIEW_STATE_PRESSED];
1357 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1358 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1359 | VIEW_STATE_PRESSED];
1360 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1361 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1362 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1363 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1364 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1365 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1366 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1367 | VIEW_STATE_PRESSED];
1368 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1369 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1370 | VIEW_STATE_PRESSED];
1371 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1372 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1373 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1374 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1375 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1376 | VIEW_STATE_PRESSED];
1377 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1378 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1379 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1380 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1381 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1382 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1383 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1384 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1385 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1386 | VIEW_STATE_PRESSED];
1387 }
1388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 /**
1390 * Used by views that contain lists of items. This state indicates that
1391 * the view is showing the last item.
1392 * @hide
1393 */
1394 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1395 /**
1396 * Used by views that contain lists of items. This state indicates that
1397 * the view is showing the first item.
1398 * @hide
1399 */
1400 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1401 /**
1402 * Used by views that contain lists of items. This state indicates that
1403 * the view is showing the middle item.
1404 * @hide
1405 */
1406 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1407 /**
1408 * Used by views that contain lists of items. This state indicates that
1409 * the view is showing only one item.
1410 * @hide
1411 */
1412 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1413 /**
1414 * Used by views that contain lists of items. This state indicates that
1415 * the view is pressed and showing the last item.
1416 * @hide
1417 */
1418 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1419 /**
1420 * Used by views that contain lists of items. This state indicates that
1421 * the view is pressed and showing the first item.
1422 * @hide
1423 */
1424 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1425 /**
1426 * Used by views that contain lists of items. This state indicates that
1427 * the view is pressed and showing the middle item.
1428 * @hide
1429 */
1430 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1431 /**
1432 * Used by views that contain lists of items. This state indicates that
1433 * the view is pressed and showing only one item.
1434 * @hide
1435 */
1436 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1437
1438 /**
1439 * Temporary Rect currently for use in setBackground(). This will probably
1440 * be extended in the future to hold our own class with more than just
1441 * a Rect. :)
1442 */
1443 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001444
1445 /**
1446 * Map used to store views' tags.
1447 */
1448 private static WeakHashMap<View, SparseArray<Object>> sTags;
1449
1450 /**
1451 * Lock used to access sTags.
1452 */
1453 private static final Object sTagsLock = new Object();
1454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 /**
1456 * The animation currently associated with this view.
1457 * @hide
1458 */
1459 protected Animation mCurrentAnimation = null;
1460
1461 /**
1462 * Width as measured during measure pass.
1463 * {@hide}
1464 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001465 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 protected int mMeasuredWidth;
1467
1468 /**
1469 * Height as measured during measure pass.
1470 * {@hide}
1471 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001472 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 protected int mMeasuredHeight;
1474
1475 /**
1476 * The view's identifier.
1477 * {@hide}
1478 *
1479 * @see #setId(int)
1480 * @see #getId()
1481 */
1482 @ViewDebug.ExportedProperty(resolveId = true)
1483 int mID = NO_ID;
1484
1485 /**
1486 * The view's tag.
1487 * {@hide}
1488 *
1489 * @see #setTag(Object)
1490 * @see #getTag()
1491 */
1492 protected Object mTag;
1493
1494 // for mPrivateFlags:
1495 /** {@hide} */
1496 static final int WANTS_FOCUS = 0x00000001;
1497 /** {@hide} */
1498 static final int FOCUSED = 0x00000002;
1499 /** {@hide} */
1500 static final int SELECTED = 0x00000004;
1501 /** {@hide} */
1502 static final int IS_ROOT_NAMESPACE = 0x00000008;
1503 /** {@hide} */
1504 static final int HAS_BOUNDS = 0x00000010;
1505 /** {@hide} */
1506 static final int DRAWN = 0x00000020;
1507 /**
1508 * When this flag is set, this view is running an animation on behalf of its
1509 * children and should therefore not cancel invalidate requests, even if they
1510 * lie outside of this view's bounds.
1511 *
1512 * {@hide}
1513 */
1514 static final int DRAW_ANIMATION = 0x00000040;
1515 /** {@hide} */
1516 static final int SKIP_DRAW = 0x00000080;
1517 /** {@hide} */
1518 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1519 /** {@hide} */
1520 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1521 /** {@hide} */
1522 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1523 /** {@hide} */
1524 static final int MEASURED_DIMENSION_SET = 0x00000800;
1525 /** {@hide} */
1526 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001527 /** {@hide} */
1528 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529
1530 private static final int PRESSED = 0x00004000;
1531
1532 /** {@hide} */
1533 static final int DRAWING_CACHE_VALID = 0x00008000;
1534 /**
1535 * Flag used to indicate that this view should be drawn once more (and only once
1536 * more) after its animation has completed.
1537 * {@hide}
1538 */
1539 static final int ANIMATION_STARTED = 0x00010000;
1540
1541 private static final int SAVE_STATE_CALLED = 0x00020000;
1542
1543 /**
1544 * Indicates that the View returned true when onSetAlpha() was called and that
1545 * the alpha must be restored.
1546 * {@hide}
1547 */
1548 static final int ALPHA_SET = 0x00040000;
1549
1550 /**
1551 * Set by {@link #setScrollContainer(boolean)}.
1552 */
1553 static final int SCROLL_CONTAINER = 0x00080000;
1554
1555 /**
1556 * Set by {@link #setScrollContainer(boolean)}.
1557 */
1558 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1559
1560 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001561 * View flag indicating whether this view was invalidated (fully or partially.)
1562 *
1563 * @hide
1564 */
1565 static final int DIRTY = 0x00200000;
1566
1567 /**
1568 * View flag indicating whether this view was invalidated by an opaque
1569 * invalidate request.
1570 *
1571 * @hide
1572 */
1573 static final int DIRTY_OPAQUE = 0x00400000;
1574
1575 /**
1576 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1577 *
1578 * @hide
1579 */
1580 static final int DIRTY_MASK = 0x00600000;
1581
1582 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001583 * Indicates whether the background is opaque.
1584 *
1585 * @hide
1586 */
1587 static final int OPAQUE_BACKGROUND = 0x00800000;
1588
1589 /**
1590 * Indicates whether the scrollbars are opaque.
1591 *
1592 * @hide
1593 */
1594 static final int OPAQUE_SCROLLBARS = 0x01000000;
1595
1596 /**
1597 * Indicates whether the view is opaque.
1598 *
1599 * @hide
1600 */
1601 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001602
1603 /**
1604 * Indicates a prepressed state;
1605 * the short time between ACTION_DOWN and recognizing
1606 * a 'real' press. Prepressed is used to recognize quick taps
1607 * even when they are shorter than ViewConfiguration.getTapTimeout().
1608 *
1609 * @hide
1610 */
1611 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001612
1613 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001614 * Indicates whether the view is temporarily detached.
1615 *
1616 * @hide
1617 */
1618 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001619
1620 /**
1621 * Indicates that we should awaken scroll bars once attached
1622 *
1623 * @hide
1624 */
1625 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001626
1627 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001628 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1629 * for transform operations
1630 *
1631 * @hide
1632 */
Adam Powellf37df072010-09-17 16:22:49 -07001633 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001634
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001635 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001636 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001637
Chet Haasefd2b0022010-08-06 13:08:56 -07001638 /**
Adam Powell637d3372010-08-25 14:37:03 -07001639 * Always allow a user to over-scroll this view, provided it is a
1640 * view that can scroll.
1641 *
1642 * @see #getOverScrollMode()
1643 * @see #setOverScrollMode(int)
1644 */
1645 public static final int OVER_SCROLL_ALWAYS = 0;
1646
1647 /**
1648 * Allow a user to over-scroll this view only if the content is large
1649 * enough to meaningfully scroll, provided it is a view that can scroll.
1650 *
1651 * @see #getOverScrollMode()
1652 * @see #setOverScrollMode(int)
1653 */
1654 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1655
1656 /**
1657 * Never allow a user to over-scroll this view.
1658 *
1659 * @see #getOverScrollMode()
1660 * @see #setOverScrollMode(int)
1661 */
1662 public static final int OVER_SCROLL_NEVER = 2;
1663
1664 /**
1665 * Controls the over-scroll mode for this view.
1666 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1667 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1668 * and {@link #OVER_SCROLL_NEVER}.
1669 */
1670 private int mOverScrollMode;
1671
1672 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 * The parent this view is attached to.
1674 * {@hide}
1675 *
1676 * @see #getParent()
1677 */
1678 protected ViewParent mParent;
1679
1680 /**
1681 * {@hide}
1682 */
1683 AttachInfo mAttachInfo;
1684
1685 /**
1686 * {@hide}
1687 */
Romain Guy809a7f62009-05-14 15:44:42 -07001688 @ViewDebug.ExportedProperty(flagMapping = {
1689 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1690 name = "FORCE_LAYOUT"),
1691 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1692 name = "LAYOUT_REQUIRED"),
1693 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001694 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001695 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1696 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1697 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1698 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1699 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 int mPrivateFlags;
1701
1702 /**
1703 * Count of how many windows this view has been attached to.
1704 */
1705 int mWindowAttachCount;
1706
1707 /**
1708 * The layout parameters associated with this view and used by the parent
1709 * {@link android.view.ViewGroup} to determine how this view should be
1710 * laid out.
1711 * {@hide}
1712 */
1713 protected ViewGroup.LayoutParams mLayoutParams;
1714
1715 /**
1716 * The view flags hold various views states.
1717 * {@hide}
1718 */
1719 @ViewDebug.ExportedProperty
1720 int mViewFlags;
1721
1722 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001723 * The transform matrix for the View. This transform is calculated internally
1724 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1725 * is used by default. Do *not* use this variable directly; instead call
1726 * getMatrix(), which will automatically recalculate the matrix if necessary
1727 * to get the correct matrix based on the latest rotation and scale properties.
1728 */
1729 private final Matrix mMatrix = new Matrix();
1730
1731 /**
1732 * The transform matrix for the View. This transform is calculated internally
1733 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1734 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001735 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001736 * to get the correct matrix based on the latest rotation and scale properties.
1737 */
1738 private Matrix mInverseMatrix;
1739
1740 /**
1741 * An internal variable that tracks whether we need to recalculate the
1742 * transform matrix, based on whether the rotation or scaleX/Y properties
1743 * have changed since the matrix was last calculated.
1744 */
1745 private boolean mMatrixDirty = false;
1746
1747 /**
1748 * An internal variable that tracks whether we need to recalculate the
1749 * transform matrix, based on whether the rotation or scaleX/Y properties
1750 * have changed since the matrix was last calculated.
1751 */
1752 private boolean mInverseMatrixDirty = true;
1753
1754 /**
1755 * A variable that tracks whether we need to recalculate the
1756 * transform matrix, based on whether the rotation or scaleX/Y properties
1757 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001758 * is only valid after a call to updateMatrix() or to a function that
1759 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001760 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001761 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001762
1763 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001764 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1765 */
1766 private Camera mCamera = null;
1767
1768 /**
1769 * This matrix is used when computing the matrix for 3D rotations.
1770 */
1771 private Matrix matrix3D = null;
1772
1773 /**
1774 * These prev values are used to recalculate a centered pivot point when necessary. The
1775 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1776 * set), so thes values are only used then as well.
1777 */
1778 private int mPrevWidth = -1;
1779 private int mPrevHeight = -1;
1780
1781 /**
1782 * Convenience value to check for float values that are close enough to zero to be considered
1783 * zero.
1784 */
Romain Guy2542d192010-08-18 11:47:12 -07001785 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001786
1787 /**
1788 * The degrees rotation around the vertical axis through the pivot point.
1789 */
1790 @ViewDebug.ExportedProperty
1791 private float mRotationY = 0f;
1792
1793 /**
1794 * The degrees rotation around the horizontal axis through the pivot point.
1795 */
1796 @ViewDebug.ExportedProperty
1797 private float mRotationX = 0f;
1798
1799 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001800 * The degrees rotation around the pivot point.
1801 */
1802 @ViewDebug.ExportedProperty
1803 private float mRotation = 0f;
1804
1805 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001806 * The amount of translation of the object away from its left property (post-layout).
1807 */
1808 @ViewDebug.ExportedProperty
1809 private float mTranslationX = 0f;
1810
1811 /**
1812 * The amount of translation of the object away from its top property (post-layout).
1813 */
1814 @ViewDebug.ExportedProperty
1815 private float mTranslationY = 0f;
1816
1817 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001818 * The amount of scale in the x direction around the pivot point. A
1819 * value of 1 means no scaling is applied.
1820 */
1821 @ViewDebug.ExportedProperty
1822 private float mScaleX = 1f;
1823
1824 /**
1825 * The amount of scale in the y direction around the pivot point. A
1826 * value of 1 means no scaling is applied.
1827 */
1828 @ViewDebug.ExportedProperty
1829 private float mScaleY = 1f;
1830
1831 /**
1832 * The amount of scale in the x direction around the pivot point. A
1833 * value of 1 means no scaling is applied.
1834 */
1835 @ViewDebug.ExportedProperty
1836 private float mPivotX = 0f;
1837
1838 /**
1839 * The amount of scale in the y direction around the pivot point. A
1840 * value of 1 means no scaling is applied.
1841 */
1842 @ViewDebug.ExportedProperty
1843 private float mPivotY = 0f;
1844
1845 /**
1846 * The opacity of the View. This is a value from 0 to 1, where 0 means
1847 * completely transparent and 1 means completely opaque.
1848 */
1849 @ViewDebug.ExportedProperty
1850 private float mAlpha = 1f;
1851
1852 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 * The distance in pixels from the left edge of this view's parent
1854 * to the left edge of this view.
1855 * {@hide}
1856 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001857 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 protected int mLeft;
1859 /**
1860 * The distance in pixels from the left edge of this view's parent
1861 * to the right edge of this view.
1862 * {@hide}
1863 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001864 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 protected int mRight;
1866 /**
1867 * The distance in pixels from the top edge of this view's parent
1868 * to the top edge of this view.
1869 * {@hide}
1870 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001871 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 protected int mTop;
1873 /**
1874 * The distance in pixels from the top edge of this view's parent
1875 * to the bottom edge of this view.
1876 * {@hide}
1877 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001878 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 protected int mBottom;
1880
1881 /**
1882 * The offset, in pixels, by which the content of this view is scrolled
1883 * horizontally.
1884 * {@hide}
1885 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001886 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 protected int mScrollX;
1888 /**
1889 * The offset, in pixels, by which the content of this view is scrolled
1890 * vertically.
1891 * {@hide}
1892 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001893 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 protected int mScrollY;
1895
1896 /**
1897 * The left padding in pixels, that is the distance in pixels between the
1898 * left edge of this view and the left edge of its content.
1899 * {@hide}
1900 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001901 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 protected int mPaddingLeft;
1903 /**
1904 * The right padding in pixels, that is the distance in pixels between the
1905 * right edge of this view and the right edge of its content.
1906 * {@hide}
1907 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001908 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 protected int mPaddingRight;
1910 /**
1911 * The top padding in pixels, that is the distance in pixels between the
1912 * top edge of this view and the top edge of its content.
1913 * {@hide}
1914 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001915 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 protected int mPaddingTop;
1917 /**
1918 * The bottom padding in pixels, that is the distance in pixels between the
1919 * bottom edge of this view and the bottom edge of its content.
1920 * {@hide}
1921 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001922 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 protected int mPaddingBottom;
1924
1925 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001926 * Briefly describes the view and is primarily used for accessibility support.
1927 */
1928 private CharSequence mContentDescription;
1929
1930 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 * Cache the paddingRight set by the user to append to the scrollbar's size.
1932 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001933 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 int mUserPaddingRight;
1935
1936 /**
1937 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1938 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001939 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 int mUserPaddingBottom;
1941
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001942 /**
1943 * @hide
1944 */
1945 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1946 /**
1947 * @hide
1948 */
1949 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950
1951 private Resources mResources = null;
1952
1953 private Drawable mBGDrawable;
1954
1955 private int mBackgroundResource;
1956 private boolean mBackgroundSizeChanged;
1957
1958 /**
1959 * Listener used to dispatch focus change events.
1960 * This field should be made private, so it is hidden from the SDK.
1961 * {@hide}
1962 */
1963 protected OnFocusChangeListener mOnFocusChangeListener;
1964
1965 /**
Chet Haase21cd1382010-09-01 17:42:29 -07001966 * Listeners for layout change events.
1967 */
1968 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
1969
1970 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 * Listener used to dispatch click events.
1972 * This field should be made private, so it is hidden from the SDK.
1973 * {@hide}
1974 */
1975 protected OnClickListener mOnClickListener;
1976
1977 /**
1978 * Listener used to dispatch long click events.
1979 * This field should be made private, so it is hidden from the SDK.
1980 * {@hide}
1981 */
1982 protected OnLongClickListener mOnLongClickListener;
1983
1984 /**
1985 * Listener used to build the context menu.
1986 * This field should be made private, so it is hidden from the SDK.
1987 * {@hide}
1988 */
1989 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
1990
1991 private OnKeyListener mOnKeyListener;
1992
1993 private OnTouchListener mOnTouchListener;
1994
Chris Tate32affef2010-10-18 15:29:21 -07001995 private OnDragListener mOnDragListener;
1996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 /**
1998 * The application environment this view lives in.
1999 * This field should be made private, so it is hidden from the SDK.
2000 * {@hide}
2001 */
2002 protected Context mContext;
2003
2004 private ScrollabilityCache mScrollCache;
2005
2006 private int[] mDrawableState = null;
2007
Romain Guy02890fd2010-08-06 17:58:44 -07002008 private Bitmap mDrawingCache;
2009 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07002010 private DisplayList mDisplayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011
2012 /**
2013 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2014 * the user may specify which view to go to next.
2015 */
2016 private int mNextFocusLeftId = View.NO_ID;
2017
2018 /**
2019 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2020 * the user may specify which view to go to next.
2021 */
2022 private int mNextFocusRightId = View.NO_ID;
2023
2024 /**
2025 * When this view has focus and the next focus is {@link #FOCUS_UP},
2026 * the user may specify which view to go to next.
2027 */
2028 private int mNextFocusUpId = View.NO_ID;
2029
2030 /**
2031 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2032 * the user may specify which view to go to next.
2033 */
2034 private int mNextFocusDownId = View.NO_ID;
2035
2036 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08002037 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08002038 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08002039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 private UnsetPressedState mUnsetPressedState;
2041
2042 /**
2043 * Whether the long press's action has been invoked. The tap's action is invoked on the
2044 * up event while a long press is invoked as soon as the long press duration is reached, so
2045 * a long press could be performed before the tap is checked, in which case the tap's action
2046 * should not be invoked.
2047 */
2048 private boolean mHasPerformedLongPress;
2049
2050 /**
2051 * The minimum height of the view. We'll try our best to have the height
2052 * of this view to at least this amount.
2053 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002054 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 private int mMinHeight;
2056
2057 /**
2058 * The minimum width of the view. We'll try our best to have the width
2059 * of this view to at least this amount.
2060 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002061 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 private int mMinWidth;
2063
2064 /**
2065 * The delegate to handle touch events that are physically in this view
2066 * but should be handled by another view.
2067 */
2068 private TouchDelegate mTouchDelegate = null;
2069
2070 /**
2071 * Solid color to use as a background when creating the drawing cache. Enables
2072 * the cache to use 16 bit bitmaps instead of 32 bit.
2073 */
2074 private int mDrawingCacheBackgroundColor = 0;
2075
2076 /**
2077 * Special tree observer used when mAttachInfo is null.
2078 */
2079 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002080
2081 /**
2082 * Cache the touch slop from the context that created the view.
2083 */
2084 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002087 * Cache drag/drop state
2088 *
2089 */
2090 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002091
2092 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 * Simple constructor to use when creating a view from code.
2094 *
2095 * @param context The Context the view is running in, through which it can
2096 * access the current theme, resources, etc.
2097 */
2098 public View(Context context) {
2099 mContext = context;
2100 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002101 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002102 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Adam Powell637d3372010-08-25 14:37:03 -07002103 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 }
2105
2106 /**
2107 * Constructor that is called when inflating a view from XML. This is called
2108 * when a view is being constructed from an XML file, supplying attributes
2109 * that were specified in the XML file. This version uses a default style of
2110 * 0, so the only attribute values applied are those in the Context's Theme
2111 * and the given AttributeSet.
2112 *
2113 * <p>
2114 * The method onFinishInflate() will be called after all children have been
2115 * added.
2116 *
2117 * @param context The Context the view is running in, through which it can
2118 * access the current theme, resources, etc.
2119 * @param attrs The attributes of the XML tag that is inflating the view.
2120 * @see #View(Context, AttributeSet, int)
2121 */
2122 public View(Context context, AttributeSet attrs) {
2123 this(context, attrs, 0);
2124 }
2125
2126 /**
2127 * Perform inflation from XML and apply a class-specific base style. This
2128 * constructor of View allows subclasses to use their own base style when
2129 * they are inflating. For example, a Button class's constructor would call
2130 * this version of the super class constructor and supply
2131 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2132 * the theme's button style to modify all of the base view attributes (in
2133 * particular its background) as well as the Button class's attributes.
2134 *
2135 * @param context The Context the view is running in, through which it can
2136 * access the current theme, resources, etc.
2137 * @param attrs The attributes of the XML tag that is inflating the view.
2138 * @param defStyle The default style to apply to this view. If 0, no style
2139 * will be applied (beyond what is included in the theme). This may
2140 * either be an attribute resource, whose value will be retrieved
2141 * from the current theme, or an explicit style resource.
2142 * @see #View(Context, AttributeSet)
2143 */
2144 public View(Context context, AttributeSet attrs, int defStyle) {
2145 this(context);
2146
2147 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2148 defStyle, 0);
2149
2150 Drawable background = null;
2151
2152 int leftPadding = -1;
2153 int topPadding = -1;
2154 int rightPadding = -1;
2155 int bottomPadding = -1;
2156
2157 int padding = -1;
2158
2159 int viewFlagValues = 0;
2160 int viewFlagMasks = 0;
2161
2162 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 int x = 0;
2165 int y = 0;
2166
Chet Haase73066682010-11-29 15:55:32 -08002167 float tx = 0;
2168 float ty = 0;
2169 float rotation = 0;
2170 float rotationX = 0;
2171 float rotationY = 0;
2172 float sx = 1f;
2173 float sy = 1f;
2174 boolean transformSet = false;
2175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2177
Adam Powell637d3372010-08-25 14:37:03 -07002178 int overScrollMode = mOverScrollMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 final int N = a.getIndexCount();
2180 for (int i = 0; i < N; i++) {
2181 int attr = a.getIndex(i);
2182 switch (attr) {
2183 case com.android.internal.R.styleable.View_background:
2184 background = a.getDrawable(attr);
2185 break;
2186 case com.android.internal.R.styleable.View_padding:
2187 padding = a.getDimensionPixelSize(attr, -1);
2188 break;
2189 case com.android.internal.R.styleable.View_paddingLeft:
2190 leftPadding = a.getDimensionPixelSize(attr, -1);
2191 break;
2192 case com.android.internal.R.styleable.View_paddingTop:
2193 topPadding = a.getDimensionPixelSize(attr, -1);
2194 break;
2195 case com.android.internal.R.styleable.View_paddingRight:
2196 rightPadding = a.getDimensionPixelSize(attr, -1);
2197 break;
2198 case com.android.internal.R.styleable.View_paddingBottom:
2199 bottomPadding = a.getDimensionPixelSize(attr, -1);
2200 break;
2201 case com.android.internal.R.styleable.View_scrollX:
2202 x = a.getDimensionPixelOffset(attr, 0);
2203 break;
2204 case com.android.internal.R.styleable.View_scrollY:
2205 y = a.getDimensionPixelOffset(attr, 0);
2206 break;
Chet Haase73066682010-11-29 15:55:32 -08002207 case com.android.internal.R.styleable.View_alpha:
2208 setAlpha(a.getFloat(attr, 1f));
2209 break;
2210 case com.android.internal.R.styleable.View_transformPivotX:
2211 setPivotX(a.getDimensionPixelOffset(attr, 0));
2212 break;
2213 case com.android.internal.R.styleable.View_transformPivotY:
2214 setPivotY(a.getDimensionPixelOffset(attr, 0));
2215 break;
2216 case com.android.internal.R.styleable.View_translationX:
2217 tx = a.getDimensionPixelOffset(attr, 0);
2218 transformSet = true;
2219 break;
2220 case com.android.internal.R.styleable.View_translationY:
2221 ty = a.getDimensionPixelOffset(attr, 0);
2222 transformSet = true;
2223 break;
2224 case com.android.internal.R.styleable.View_rotation:
2225 rotation = a.getFloat(attr, 0);
2226 transformSet = true;
2227 break;
2228 case com.android.internal.R.styleable.View_rotationX:
2229 rotationX = a.getFloat(attr, 0);
2230 transformSet = true;
2231 break;
2232 case com.android.internal.R.styleable.View_rotationY:
2233 rotationY = a.getFloat(attr, 0);
2234 transformSet = true;
2235 break;
2236 case com.android.internal.R.styleable.View_scaleX:
2237 sx = a.getFloat(attr, 1f);
2238 transformSet = true;
2239 break;
2240 case com.android.internal.R.styleable.View_scaleY:
2241 sy = a.getFloat(attr, 1f);
2242 transformSet = true;
2243 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 case com.android.internal.R.styleable.View_id:
2245 mID = a.getResourceId(attr, NO_ID);
2246 break;
2247 case com.android.internal.R.styleable.View_tag:
2248 mTag = a.getText(attr);
2249 break;
2250 case com.android.internal.R.styleable.View_fitsSystemWindows:
2251 if (a.getBoolean(attr, false)) {
2252 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2253 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2254 }
2255 break;
2256 case com.android.internal.R.styleable.View_focusable:
2257 if (a.getBoolean(attr, false)) {
2258 viewFlagValues |= FOCUSABLE;
2259 viewFlagMasks |= FOCUSABLE_MASK;
2260 }
2261 break;
2262 case com.android.internal.R.styleable.View_focusableInTouchMode:
2263 if (a.getBoolean(attr, false)) {
2264 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2265 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2266 }
2267 break;
2268 case com.android.internal.R.styleable.View_clickable:
2269 if (a.getBoolean(attr, false)) {
2270 viewFlagValues |= CLICKABLE;
2271 viewFlagMasks |= CLICKABLE;
2272 }
2273 break;
2274 case com.android.internal.R.styleable.View_longClickable:
2275 if (a.getBoolean(attr, false)) {
2276 viewFlagValues |= LONG_CLICKABLE;
2277 viewFlagMasks |= LONG_CLICKABLE;
2278 }
2279 break;
2280 case com.android.internal.R.styleable.View_saveEnabled:
2281 if (!a.getBoolean(attr, true)) {
2282 viewFlagValues |= SAVE_DISABLED;
2283 viewFlagMasks |= SAVE_DISABLED_MASK;
2284 }
2285 break;
2286 case com.android.internal.R.styleable.View_duplicateParentState:
2287 if (a.getBoolean(attr, false)) {
2288 viewFlagValues |= DUPLICATE_PARENT_STATE;
2289 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2290 }
2291 break;
2292 case com.android.internal.R.styleable.View_visibility:
2293 final int visibility = a.getInt(attr, 0);
2294 if (visibility != 0) {
2295 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2296 viewFlagMasks |= VISIBILITY_MASK;
2297 }
2298 break;
2299 case com.android.internal.R.styleable.View_drawingCacheQuality:
2300 final int cacheQuality = a.getInt(attr, 0);
2301 if (cacheQuality != 0) {
2302 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2303 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2304 }
2305 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002306 case com.android.internal.R.styleable.View_contentDescription:
2307 mContentDescription = a.getString(attr);
2308 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2310 if (!a.getBoolean(attr, true)) {
2311 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2312 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2313 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002314 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2316 if (!a.getBoolean(attr, true)) {
2317 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2318 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2319 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002320 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 case R.styleable.View_scrollbars:
2322 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2323 if (scrollbars != SCROLLBARS_NONE) {
2324 viewFlagValues |= scrollbars;
2325 viewFlagMasks |= SCROLLBARS_MASK;
2326 initializeScrollbars(a);
2327 }
2328 break;
2329 case R.styleable.View_fadingEdge:
2330 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2331 if (fadingEdge != FADING_EDGE_NONE) {
2332 viewFlagValues |= fadingEdge;
2333 viewFlagMasks |= FADING_EDGE_MASK;
2334 initializeFadingEdge(a);
2335 }
2336 break;
2337 case R.styleable.View_scrollbarStyle:
2338 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2339 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2340 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2341 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2342 }
2343 break;
2344 case R.styleable.View_isScrollContainer:
2345 setScrollContainer = true;
2346 if (a.getBoolean(attr, false)) {
2347 setScrollContainer(true);
2348 }
2349 break;
2350 case com.android.internal.R.styleable.View_keepScreenOn:
2351 if (a.getBoolean(attr, false)) {
2352 viewFlagValues |= KEEP_SCREEN_ON;
2353 viewFlagMasks |= KEEP_SCREEN_ON;
2354 }
2355 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002356 case R.styleable.View_filterTouchesWhenObscured:
2357 if (a.getBoolean(attr, false)) {
2358 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2359 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2360 }
2361 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 case R.styleable.View_nextFocusLeft:
2363 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2364 break;
2365 case R.styleable.View_nextFocusRight:
2366 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2367 break;
2368 case R.styleable.View_nextFocusUp:
2369 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2370 break;
2371 case R.styleable.View_nextFocusDown:
2372 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2373 break;
2374 case R.styleable.View_minWidth:
2375 mMinWidth = a.getDimensionPixelSize(attr, 0);
2376 break;
2377 case R.styleable.View_minHeight:
2378 mMinHeight = a.getDimensionPixelSize(attr, 0);
2379 break;
Romain Guy9a817362009-05-01 10:57:14 -07002380 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002381 if (context.isRestricted()) {
2382 throw new IllegalStateException("The android:onClick attribute cannot "
2383 + "be used within a restricted context");
2384 }
2385
Romain Guy9a817362009-05-01 10:57:14 -07002386 final String handlerName = a.getString(attr);
2387 if (handlerName != null) {
2388 setOnClickListener(new OnClickListener() {
2389 private Method mHandler;
2390
2391 public void onClick(View v) {
2392 if (mHandler == null) {
2393 try {
2394 mHandler = getContext().getClass().getMethod(handlerName,
2395 View.class);
2396 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002397 int id = getId();
2398 String idText = id == NO_ID ? "" : " with id '"
2399 + getContext().getResources().getResourceEntryName(
2400 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002401 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002402 handlerName + "(View) in the activity "
2403 + getContext().getClass() + " for onClick handler"
2404 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002405 }
2406 }
2407
2408 try {
2409 mHandler.invoke(getContext(), View.this);
2410 } catch (IllegalAccessException e) {
2411 throw new IllegalStateException("Could not execute non "
2412 + "public method of the activity", e);
2413 } catch (InvocationTargetException e) {
2414 throw new IllegalStateException("Could not execute "
2415 + "method of the activity", e);
2416 }
2417 }
2418 });
2419 }
2420 break;
Adam Powell637d3372010-08-25 14:37:03 -07002421 case R.styleable.View_overScrollMode:
2422 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2423 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 }
2425 }
2426
Adam Powell637d3372010-08-25 14:37:03 -07002427 setOverScrollMode(overScrollMode);
2428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 if (background != null) {
2430 setBackgroundDrawable(background);
2431 }
2432
2433 if (padding >= 0) {
2434 leftPadding = padding;
2435 topPadding = padding;
2436 rightPadding = padding;
2437 bottomPadding = padding;
2438 }
2439
2440 // If the user specified the padding (either with android:padding or
2441 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2442 // use the default padding or the padding from the background drawable
2443 // (stored at this point in mPadding*)
2444 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2445 topPadding >= 0 ? topPadding : mPaddingTop,
2446 rightPadding >= 0 ? rightPadding : mPaddingRight,
2447 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2448
2449 if (viewFlagMasks != 0) {
2450 setFlags(viewFlagValues, viewFlagMasks);
2451 }
2452
2453 // Needs to be called after mViewFlags is set
2454 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2455 recomputePadding();
2456 }
2457
2458 if (x != 0 || y != 0) {
2459 scrollTo(x, y);
2460 }
2461
Chet Haase73066682010-11-29 15:55:32 -08002462 if (transformSet) {
2463 setTranslationX(tx);
2464 setTranslationY(ty);
2465 setRotation(rotation);
2466 setRotationX(rotationX);
2467 setRotationY(rotationY);
2468 setScaleX(sx);
2469 setScaleY(sy);
2470 }
2471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2473 setScrollContainer(true);
2474 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002475
2476 computeOpaqueFlags();
2477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 a.recycle();
2479 }
2480
2481 /**
2482 * Non-public constructor for use in testing
2483 */
2484 View() {
2485 }
2486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 /**
2488 * <p>
2489 * Initializes the fading edges from a given set of styled attributes. This
2490 * method should be called by subclasses that need fading edges and when an
2491 * instance of these subclasses is created programmatically rather than
2492 * being inflated from XML. This method is automatically called when the XML
2493 * is inflated.
2494 * </p>
2495 *
2496 * @param a the styled attributes set to initialize the fading edges from
2497 */
2498 protected void initializeFadingEdge(TypedArray a) {
2499 initScrollCache();
2500
2501 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2502 R.styleable.View_fadingEdgeLength,
2503 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2504 }
2505
2506 /**
2507 * Returns the size of the vertical faded edges used to indicate that more
2508 * content in this view is visible.
2509 *
2510 * @return The size in pixels of the vertical faded edge or 0 if vertical
2511 * faded edges are not enabled for this view.
2512 * @attr ref android.R.styleable#View_fadingEdgeLength
2513 */
2514 public int getVerticalFadingEdgeLength() {
2515 if (isVerticalFadingEdgeEnabled()) {
2516 ScrollabilityCache cache = mScrollCache;
2517 if (cache != null) {
2518 return cache.fadingEdgeLength;
2519 }
2520 }
2521 return 0;
2522 }
2523
2524 /**
2525 * Set the size of the faded edge used to indicate that more content in this
2526 * view is available. Will not change whether the fading edge is enabled; use
2527 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2528 * to enable the fading edge for the vertical or horizontal fading edges.
2529 *
2530 * @param length The size in pixels of the faded edge used to indicate that more
2531 * content in this view is visible.
2532 */
2533 public void setFadingEdgeLength(int length) {
2534 initScrollCache();
2535 mScrollCache.fadingEdgeLength = length;
2536 }
2537
2538 /**
2539 * Returns the size of the horizontal faded edges used to indicate that more
2540 * content in this view is visible.
2541 *
2542 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2543 * faded edges are not enabled for this view.
2544 * @attr ref android.R.styleable#View_fadingEdgeLength
2545 */
2546 public int getHorizontalFadingEdgeLength() {
2547 if (isHorizontalFadingEdgeEnabled()) {
2548 ScrollabilityCache cache = mScrollCache;
2549 if (cache != null) {
2550 return cache.fadingEdgeLength;
2551 }
2552 }
2553 return 0;
2554 }
2555
2556 /**
2557 * Returns the width of the vertical scrollbar.
2558 *
2559 * @return The width in pixels of the vertical scrollbar or 0 if there
2560 * is no vertical scrollbar.
2561 */
2562 public int getVerticalScrollbarWidth() {
2563 ScrollabilityCache cache = mScrollCache;
2564 if (cache != null) {
2565 ScrollBarDrawable scrollBar = cache.scrollBar;
2566 if (scrollBar != null) {
2567 int size = scrollBar.getSize(true);
2568 if (size <= 0) {
2569 size = cache.scrollBarSize;
2570 }
2571 return size;
2572 }
2573 return 0;
2574 }
2575 return 0;
2576 }
2577
2578 /**
2579 * Returns the height of the horizontal scrollbar.
2580 *
2581 * @return The height in pixels of the horizontal scrollbar or 0 if
2582 * there is no horizontal scrollbar.
2583 */
2584 protected int getHorizontalScrollbarHeight() {
2585 ScrollabilityCache cache = mScrollCache;
2586 if (cache != null) {
2587 ScrollBarDrawable scrollBar = cache.scrollBar;
2588 if (scrollBar != null) {
2589 int size = scrollBar.getSize(false);
2590 if (size <= 0) {
2591 size = cache.scrollBarSize;
2592 }
2593 return size;
2594 }
2595 return 0;
2596 }
2597 return 0;
2598 }
2599
2600 /**
2601 * <p>
2602 * Initializes the scrollbars from a given set of styled attributes. This
2603 * method should be called by subclasses that need scrollbars and when an
2604 * instance of these subclasses is created programmatically rather than
2605 * being inflated from XML. This method is automatically called when the XML
2606 * is inflated.
2607 * </p>
2608 *
2609 * @param a the styled attributes set to initialize the scrollbars from
2610 */
2611 protected void initializeScrollbars(TypedArray a) {
2612 initScrollCache();
2613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002615
2616 if (scrollabilityCache.scrollBar == null) {
2617 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2618 }
2619
Romain Guy8bda2482010-03-02 11:42:11 -08002620 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621
Mike Cleronf116bf82009-09-27 19:14:12 -07002622 if (!fadeScrollbars) {
2623 scrollabilityCache.state = ScrollabilityCache.ON;
2624 }
2625 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2626
2627
2628 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2629 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2630 .getScrollBarFadeDuration());
2631 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2632 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2633 ViewConfiguration.getScrollDefaultDelay());
2634
2635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2637 com.android.internal.R.styleable.View_scrollbarSize,
2638 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2639
2640 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2641 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2642
2643 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2644 if (thumb != null) {
2645 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2646 }
2647
2648 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2649 false);
2650 if (alwaysDraw) {
2651 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2652 }
2653
2654 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2655 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2656
2657 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2658 if (thumb != null) {
2659 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2660 }
2661
2662 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2663 false);
2664 if (alwaysDraw) {
2665 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2666 }
2667
2668 // Re-apply user/background padding so that scrollbar(s) get added
2669 recomputePadding();
2670 }
2671
2672 /**
2673 * <p>
2674 * Initalizes the scrollability cache if necessary.
2675 * </p>
2676 */
2677 private void initScrollCache() {
2678 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002679 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 }
2681 }
2682
2683 /**
2684 * Register a callback to be invoked when focus of this view changed.
2685 *
2686 * @param l The callback that will run.
2687 */
2688 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2689 mOnFocusChangeListener = l;
2690 }
2691
2692 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002693 * Add a listener that will be called when the bounds of the view change due to
2694 * layout processing.
2695 *
2696 * @param listener The listener that will be called when layout bounds change.
2697 */
2698 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2699 if (mOnLayoutChangeListeners == null) {
2700 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2701 }
2702 mOnLayoutChangeListeners.add(listener);
2703 }
2704
2705 /**
2706 * Remove a listener for layout changes.
2707 *
2708 * @param listener The listener for layout bounds change.
2709 */
2710 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2711 if (mOnLayoutChangeListeners == null) {
2712 return;
2713 }
2714 mOnLayoutChangeListeners.remove(listener);
2715 }
2716
2717 /**
2718 * Gets the current list of listeners for layout changes.
2719 * @return
2720 */
2721 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2722 return mOnLayoutChangeListeners;
2723 }
2724
2725 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 * Returns the focus-change callback registered for this view.
2727 *
2728 * @return The callback, or null if one is not registered.
2729 */
2730 public OnFocusChangeListener getOnFocusChangeListener() {
2731 return mOnFocusChangeListener;
2732 }
2733
2734 /**
2735 * Register a callback to be invoked when this view is clicked. If this view is not
2736 * clickable, it becomes clickable.
2737 *
2738 * @param l The callback that will run
2739 *
2740 * @see #setClickable(boolean)
2741 */
2742 public void setOnClickListener(OnClickListener l) {
2743 if (!isClickable()) {
2744 setClickable(true);
2745 }
2746 mOnClickListener = l;
2747 }
2748
2749 /**
2750 * Register a callback to be invoked when this view is clicked and held. If this view is not
2751 * long clickable, it becomes long clickable.
2752 *
2753 * @param l The callback that will run
2754 *
2755 * @see #setLongClickable(boolean)
2756 */
2757 public void setOnLongClickListener(OnLongClickListener l) {
2758 if (!isLongClickable()) {
2759 setLongClickable(true);
2760 }
2761 mOnLongClickListener = l;
2762 }
2763
2764 /**
2765 * Register a callback to be invoked when the context menu for this view is
2766 * being built. If this view is not long clickable, it becomes long clickable.
2767 *
2768 * @param l The callback that will run
2769 *
2770 */
2771 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2772 if (!isLongClickable()) {
2773 setLongClickable(true);
2774 }
2775 mOnCreateContextMenuListener = l;
2776 }
2777
2778 /**
2779 * Call this view's OnClickListener, if it is defined.
2780 *
2781 * @return True there was an assigned OnClickListener that was called, false
2782 * otherwise is returned.
2783 */
2784 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002785 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 if (mOnClickListener != null) {
2788 playSoundEffect(SoundEffectConstants.CLICK);
2789 mOnClickListener.onClick(this);
2790 return true;
2791 }
2792
2793 return false;
2794 }
2795
2796 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002797 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2798 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002800 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 */
2802 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002803 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 boolean handled = false;
2806 if (mOnLongClickListener != null) {
2807 handled = mOnLongClickListener.onLongClick(View.this);
2808 }
2809 if (!handled) {
2810 handled = showContextMenu();
2811 }
2812 if (handled) {
2813 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2814 }
2815 return handled;
2816 }
2817
2818 /**
2819 * Bring up the context menu for this view.
2820 *
2821 * @return Whether a context menu was displayed.
2822 */
2823 public boolean showContextMenu() {
2824 return getParent().showContextMenuForChild(this);
2825 }
2826
2827 /**
Adam Powell6e346362010-07-23 10:18:23 -07002828 * Start an action mode.
2829 *
2830 * @param callback Callback that will control the lifecycle of the action mode
2831 * @return The new action mode if it is started, null otherwise
2832 *
2833 * @see ActionMode
2834 */
2835 public ActionMode startActionMode(ActionMode.Callback callback) {
2836 return getParent().startActionModeForChild(this, callback);
2837 }
2838
2839 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 * Register a callback to be invoked when a key is pressed in this view.
2841 * @param l the key listener to attach to this view
2842 */
2843 public void setOnKeyListener(OnKeyListener l) {
2844 mOnKeyListener = l;
2845 }
2846
2847 /**
2848 * Register a callback to be invoked when a touch event is sent to this view.
2849 * @param l the touch listener to attach to this view
2850 */
2851 public void setOnTouchListener(OnTouchListener l) {
2852 mOnTouchListener = l;
2853 }
2854
2855 /**
Chris Tate32affef2010-10-18 15:29:21 -07002856 * Register a callback to be invoked when a drag event is sent to this view.
2857 * @param l The drag listener to attach to this view
2858 */
2859 public void setOnDragListener(OnDragListener l) {
2860 mOnDragListener = l;
2861 }
2862
2863 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2865 *
2866 * Note: this does not check whether this {@link View} should get focus, it just
2867 * gives it focus no matter what. It should only be called internally by framework
2868 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2869 *
2870 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2871 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2872 * focus moved when requestFocus() is called. It may not always
2873 * apply, in which case use the default View.FOCUS_DOWN.
2874 * @param previouslyFocusedRect The rectangle of the view that had focus
2875 * prior in this View's coordinate system.
2876 */
2877 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2878 if (DBG) {
2879 System.out.println(this + " requestFocus()");
2880 }
2881
2882 if ((mPrivateFlags & FOCUSED) == 0) {
2883 mPrivateFlags |= FOCUSED;
2884
2885 if (mParent != null) {
2886 mParent.requestChildFocus(this, this);
2887 }
2888
2889 onFocusChanged(true, direction, previouslyFocusedRect);
2890 refreshDrawableState();
2891 }
2892 }
2893
2894 /**
2895 * Request that a rectangle of this view be visible on the screen,
2896 * scrolling if necessary just enough.
2897 *
2898 * <p>A View should call this if it maintains some notion of which part
2899 * of its content is interesting. For example, a text editing view
2900 * should call this when its cursor moves.
2901 *
2902 * @param rectangle The rectangle.
2903 * @return Whether any parent scrolled.
2904 */
2905 public boolean requestRectangleOnScreen(Rect rectangle) {
2906 return requestRectangleOnScreen(rectangle, false);
2907 }
2908
2909 /**
2910 * Request that a rectangle of this view be visible on the screen,
2911 * scrolling if necessary just enough.
2912 *
2913 * <p>A View should call this if it maintains some notion of which part
2914 * of its content is interesting. For example, a text editing view
2915 * should call this when its cursor moves.
2916 *
2917 * <p>When <code>immediate</code> is set to true, scrolling will not be
2918 * animated.
2919 *
2920 * @param rectangle The rectangle.
2921 * @param immediate True to forbid animated scrolling, false otherwise
2922 * @return Whether any parent scrolled.
2923 */
2924 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
2925 View child = this;
2926 ViewParent parent = mParent;
2927 boolean scrolled = false;
2928 while (parent != null) {
2929 scrolled |= parent.requestChildRectangleOnScreen(child,
2930 rectangle, immediate);
2931
2932 // offset rect so next call has the rectangle in the
2933 // coordinate system of its direct child.
2934 rectangle.offset(child.getLeft(), child.getTop());
2935 rectangle.offset(-child.getScrollX(), -child.getScrollY());
2936
2937 if (!(parent instanceof View)) {
2938 break;
2939 }
Romain Guy8506ab42009-06-11 17:35:47 -07002940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 child = (View) parent;
2942 parent = child.getParent();
2943 }
2944 return scrolled;
2945 }
2946
2947 /**
2948 * Called when this view wants to give up focus. This will cause
2949 * {@link #onFocusChanged} to be called.
2950 */
2951 public void clearFocus() {
2952 if (DBG) {
2953 System.out.println(this + " clearFocus()");
2954 }
2955
2956 if ((mPrivateFlags & FOCUSED) != 0) {
2957 mPrivateFlags &= ~FOCUSED;
2958
2959 if (mParent != null) {
2960 mParent.clearChildFocus(this);
2961 }
2962
2963 onFocusChanged(false, 0, null);
2964 refreshDrawableState();
2965 }
2966 }
2967
2968 /**
2969 * Called to clear the focus of a view that is about to be removed.
2970 * Doesn't call clearChildFocus, which prevents this view from taking
2971 * focus again before it has been removed from the parent
2972 */
2973 void clearFocusForRemoval() {
2974 if ((mPrivateFlags & FOCUSED) != 0) {
2975 mPrivateFlags &= ~FOCUSED;
2976
2977 onFocusChanged(false, 0, null);
2978 refreshDrawableState();
2979 }
2980 }
2981
2982 /**
2983 * Called internally by the view system when a new view is getting focus.
2984 * This is what clears the old focus.
2985 */
2986 void unFocus() {
2987 if (DBG) {
2988 System.out.println(this + " unFocus()");
2989 }
2990
2991 if ((mPrivateFlags & FOCUSED) != 0) {
2992 mPrivateFlags &= ~FOCUSED;
2993
2994 onFocusChanged(false, 0, null);
2995 refreshDrawableState();
2996 }
2997 }
2998
2999 /**
3000 * Returns true if this view has focus iteself, or is the ancestor of the
3001 * view that has focus.
3002 *
3003 * @return True if this view has or contains focus, false otherwise.
3004 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003005 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 public boolean hasFocus() {
3007 return (mPrivateFlags & FOCUSED) != 0;
3008 }
3009
3010 /**
3011 * Returns true if this view is focusable or if it contains a reachable View
3012 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3013 * is a View whose parents do not block descendants focus.
3014 *
3015 * Only {@link #VISIBLE} views are considered focusable.
3016 *
3017 * @return True if the view is focusable or if the view contains a focusable
3018 * View, false otherwise.
3019 *
3020 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3021 */
3022 public boolean hasFocusable() {
3023 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3024 }
3025
3026 /**
3027 * Called by the view system when the focus state of this view changes.
3028 * When the focus change event is caused by directional navigation, direction
3029 * and previouslyFocusedRect provide insight into where the focus is coming from.
3030 * When overriding, be sure to call up through to the super class so that
3031 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07003032 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 * @param gainFocus True if the View has focus; false otherwise.
3034 * @param direction The direction focus has moved when requestFocus()
3035 * is called to give this view focus. Values are
Romain Guyea4823c2009-12-08 15:03:39 -08003036 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT} or
3037 * {@link #FOCUS_RIGHT}. It may not always apply, in which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 * case use the default.
3039 * @param previouslyFocusedRect The rectangle, in this view's coordinate
3040 * system, of the previously focused view. If applicable, this will be
3041 * passed in as finer grained information about where the focus is coming
3042 * from (in addition to direction). Will be <code>null</code> otherwise.
3043 */
3044 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003045 if (gainFocus) {
3046 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3047 }
3048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 InputMethodManager imm = InputMethodManager.peekInstance();
3050 if (!gainFocus) {
3051 if (isPressed()) {
3052 setPressed(false);
3053 }
3054 if (imm != null && mAttachInfo != null
3055 && mAttachInfo.mHasWindowFocus) {
3056 imm.focusOut(this);
3057 }
Romain Guya2431d02009-04-30 16:30:00 -07003058 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 } else if (imm != null && mAttachInfo != null
3060 && mAttachInfo.mHasWindowFocus) {
3061 imm.focusIn(this);
3062 }
Romain Guy8506ab42009-06-11 17:35:47 -07003063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 invalidate();
3065 if (mOnFocusChangeListener != null) {
3066 mOnFocusChangeListener.onFocusChange(this, gainFocus);
3067 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003068
3069 if (mAttachInfo != null) {
3070 mAttachInfo.mKeyDispatchState.reset(this);
3071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003072 }
3073
3074 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07003075 * {@inheritDoc}
3076 */
3077 public void sendAccessibilityEvent(int eventType) {
3078 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3079 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3080 }
3081 }
3082
3083 /**
3084 * {@inheritDoc}
3085 */
3086 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3087 event.setClassName(getClass().getName());
3088 event.setPackageName(getContext().getPackageName());
3089 event.setEnabled(isEnabled());
3090 event.setContentDescription(mContentDescription);
3091
3092 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3093 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3094 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3095 event.setItemCount(focusablesTempList.size());
3096 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3097 focusablesTempList.clear();
3098 }
3099
3100 dispatchPopulateAccessibilityEvent(event);
3101
3102 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3103 }
3104
3105 /**
3106 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3107 * to be populated.
3108 *
3109 * @param event The event.
3110 *
3111 * @return True if the event population was completed.
3112 */
3113 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3114 return false;
3115 }
3116
3117 /**
3118 * Gets the {@link View} description. It briefly describes the view and is
3119 * primarily used for accessibility support. Set this property to enable
3120 * better accessibility support for your application. This is especially
3121 * true for views that do not have textual representation (For example,
3122 * ImageButton).
3123 *
3124 * @return The content descriptiopn.
3125 *
3126 * @attr ref android.R.styleable#View_contentDescription
3127 */
3128 public CharSequence getContentDescription() {
3129 return mContentDescription;
3130 }
3131
3132 /**
3133 * Sets the {@link View} description. It briefly describes the view and is
3134 * primarily used for accessibility support. Set this property to enable
3135 * better accessibility support for your application. This is especially
3136 * true for views that do not have textual representation (For example,
3137 * ImageButton).
3138 *
3139 * @param contentDescription The content description.
3140 *
3141 * @attr ref android.R.styleable#View_contentDescription
3142 */
3143 public void setContentDescription(CharSequence contentDescription) {
3144 mContentDescription = contentDescription;
3145 }
3146
3147 /**
Romain Guya2431d02009-04-30 16:30:00 -07003148 * Invoked whenever this view loses focus, either by losing window focus or by losing
3149 * focus within its window. This method can be used to clear any state tied to the
3150 * focus. For instance, if a button is held pressed with the trackball and the window
3151 * loses focus, this method can be used to cancel the press.
3152 *
3153 * Subclasses of View overriding this method should always call super.onFocusLost().
3154 *
3155 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003156 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003157 *
3158 * @hide pending API council approval
3159 */
3160 protected void onFocusLost() {
3161 resetPressedState();
3162 }
3163
3164 private void resetPressedState() {
3165 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3166 return;
3167 }
3168
3169 if (isPressed()) {
3170 setPressed(false);
3171
3172 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003173 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003174 }
3175 }
3176 }
3177
3178 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 * Returns true if this view has focus
3180 *
3181 * @return True if this view has focus, false otherwise.
3182 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003183 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 public boolean isFocused() {
3185 return (mPrivateFlags & FOCUSED) != 0;
3186 }
3187
3188 /**
3189 * Find the view in the hierarchy rooted at this view that currently has
3190 * focus.
3191 *
3192 * @return The view that currently has focus, or null if no focused view can
3193 * be found.
3194 */
3195 public View findFocus() {
3196 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3197 }
3198
3199 /**
3200 * Change whether this view is one of the set of scrollable containers in
3201 * its window. This will be used to determine whether the window can
3202 * resize or must pan when a soft input area is open -- scrollable
3203 * containers allow the window to use resize mode since the container
3204 * will appropriately shrink.
3205 */
3206 public void setScrollContainer(boolean isScrollContainer) {
3207 if (isScrollContainer) {
3208 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3209 mAttachInfo.mScrollContainers.add(this);
3210 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3211 }
3212 mPrivateFlags |= SCROLL_CONTAINER;
3213 } else {
3214 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3215 mAttachInfo.mScrollContainers.remove(this);
3216 }
3217 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3218 }
3219 }
3220
3221 /**
3222 * Returns the quality of the drawing cache.
3223 *
3224 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3225 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3226 *
3227 * @see #setDrawingCacheQuality(int)
3228 * @see #setDrawingCacheEnabled(boolean)
3229 * @see #isDrawingCacheEnabled()
3230 *
3231 * @attr ref android.R.styleable#View_drawingCacheQuality
3232 */
3233 public int getDrawingCacheQuality() {
3234 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3235 }
3236
3237 /**
3238 * Set the drawing cache quality of this view. This value is used only when the
3239 * drawing cache is enabled
3240 *
3241 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3242 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3243 *
3244 * @see #getDrawingCacheQuality()
3245 * @see #setDrawingCacheEnabled(boolean)
3246 * @see #isDrawingCacheEnabled()
3247 *
3248 * @attr ref android.R.styleable#View_drawingCacheQuality
3249 */
3250 public void setDrawingCacheQuality(int quality) {
3251 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3252 }
3253
3254 /**
3255 * Returns whether the screen should remain on, corresponding to the current
3256 * value of {@link #KEEP_SCREEN_ON}.
3257 *
3258 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3259 *
3260 * @see #setKeepScreenOn(boolean)
3261 *
3262 * @attr ref android.R.styleable#View_keepScreenOn
3263 */
3264 public boolean getKeepScreenOn() {
3265 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3266 }
3267
3268 /**
3269 * Controls whether the screen should remain on, modifying the
3270 * value of {@link #KEEP_SCREEN_ON}.
3271 *
3272 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3273 *
3274 * @see #getKeepScreenOn()
3275 *
3276 * @attr ref android.R.styleable#View_keepScreenOn
3277 */
3278 public void setKeepScreenOn(boolean keepScreenOn) {
3279 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3280 }
3281
3282 /**
3283 * @return The user specified next focus ID.
3284 *
3285 * @attr ref android.R.styleable#View_nextFocusLeft
3286 */
3287 public int getNextFocusLeftId() {
3288 return mNextFocusLeftId;
3289 }
3290
3291 /**
3292 * Set the id of the view to use for the next focus
3293 *
3294 * @param nextFocusLeftId
3295 *
3296 * @attr ref android.R.styleable#View_nextFocusLeft
3297 */
3298 public void setNextFocusLeftId(int nextFocusLeftId) {
3299 mNextFocusLeftId = nextFocusLeftId;
3300 }
3301
3302 /**
3303 * @return The user specified next focus ID.
3304 *
3305 * @attr ref android.R.styleable#View_nextFocusRight
3306 */
3307 public int getNextFocusRightId() {
3308 return mNextFocusRightId;
3309 }
3310
3311 /**
3312 * Set the id of the view to use for the next focus
3313 *
3314 * @param nextFocusRightId
3315 *
3316 * @attr ref android.R.styleable#View_nextFocusRight
3317 */
3318 public void setNextFocusRightId(int nextFocusRightId) {
3319 mNextFocusRightId = nextFocusRightId;
3320 }
3321
3322 /**
3323 * @return The user specified next focus ID.
3324 *
3325 * @attr ref android.R.styleable#View_nextFocusUp
3326 */
3327 public int getNextFocusUpId() {
3328 return mNextFocusUpId;
3329 }
3330
3331 /**
3332 * Set the id of the view to use for the next focus
3333 *
3334 * @param nextFocusUpId
3335 *
3336 * @attr ref android.R.styleable#View_nextFocusUp
3337 */
3338 public void setNextFocusUpId(int nextFocusUpId) {
3339 mNextFocusUpId = nextFocusUpId;
3340 }
3341
3342 /**
3343 * @return The user specified next focus ID.
3344 *
3345 * @attr ref android.R.styleable#View_nextFocusDown
3346 */
3347 public int getNextFocusDownId() {
3348 return mNextFocusDownId;
3349 }
3350
3351 /**
3352 * Set the id of the view to use for the next focus
3353 *
3354 * @param nextFocusDownId
3355 *
3356 * @attr ref android.R.styleable#View_nextFocusDown
3357 */
3358 public void setNextFocusDownId(int nextFocusDownId) {
3359 mNextFocusDownId = nextFocusDownId;
3360 }
3361
3362 /**
3363 * Returns the visibility of this view and all of its ancestors
3364 *
3365 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3366 */
3367 public boolean isShown() {
3368 View current = this;
3369 //noinspection ConstantConditions
3370 do {
3371 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3372 return false;
3373 }
3374 ViewParent parent = current.mParent;
3375 if (parent == null) {
3376 return false; // We are not attached to the view root
3377 }
3378 if (!(parent instanceof View)) {
3379 return true;
3380 }
3381 current = (View) parent;
3382 } while (current != null);
3383
3384 return false;
3385 }
3386
3387 /**
3388 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3389 * is set
3390 *
3391 * @param insets Insets for system windows
3392 *
3393 * @return True if this view applied the insets, false otherwise
3394 */
3395 protected boolean fitSystemWindows(Rect insets) {
3396 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3397 mPaddingLeft = insets.left;
3398 mPaddingTop = insets.top;
3399 mPaddingRight = insets.right;
3400 mPaddingBottom = insets.bottom;
3401 requestLayout();
3402 return true;
3403 }
3404 return false;
3405 }
3406
3407 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003408 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3409 * @return True if window has FITS_SYSTEM_WINDOWS set
3410 *
3411 * @hide
3412 */
3413 public boolean isFitsSystemWindowsFlagSet() {
3414 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3415 }
3416
3417 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 * Returns the visibility status for this view.
3419 *
3420 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3421 * @attr ref android.R.styleable#View_visibility
3422 */
3423 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003424 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3425 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3426 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 })
3428 public int getVisibility() {
3429 return mViewFlags & VISIBILITY_MASK;
3430 }
3431
3432 /**
3433 * Set the enabled state of this view.
3434 *
3435 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3436 * @attr ref android.R.styleable#View_visibility
3437 */
3438 @RemotableViewMethod
3439 public void setVisibility(int visibility) {
3440 setFlags(visibility, VISIBILITY_MASK);
3441 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3442 }
3443
3444 /**
3445 * Returns the enabled status for this view. The interpretation of the
3446 * enabled state varies by subclass.
3447 *
3448 * @return True if this view is enabled, false otherwise.
3449 */
3450 @ViewDebug.ExportedProperty
3451 public boolean isEnabled() {
3452 return (mViewFlags & ENABLED_MASK) == ENABLED;
3453 }
3454
3455 /**
3456 * Set the enabled state of this view. The interpretation of the enabled
3457 * state varies by subclass.
3458 *
3459 * @param enabled True if this view is enabled, false otherwise.
3460 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003461 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003463 if (enabled == isEnabled()) return;
3464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3466
3467 /*
3468 * The View most likely has to change its appearance, so refresh
3469 * the drawable state.
3470 */
3471 refreshDrawableState();
3472
3473 // Invalidate too, since the default behavior for views is to be
3474 // be drawn at 50% alpha rather than to change the drawable.
3475 invalidate();
3476 }
3477
3478 /**
3479 * Set whether this view can receive the focus.
3480 *
3481 * Setting this to false will also ensure that this view is not focusable
3482 * in touch mode.
3483 *
3484 * @param focusable If true, this view can receive the focus.
3485 *
3486 * @see #setFocusableInTouchMode(boolean)
3487 * @attr ref android.R.styleable#View_focusable
3488 */
3489 public void setFocusable(boolean focusable) {
3490 if (!focusable) {
3491 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3492 }
3493 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3494 }
3495
3496 /**
3497 * Set whether this view can receive focus while in touch mode.
3498 *
3499 * Setting this to true will also ensure that this view is focusable.
3500 *
3501 * @param focusableInTouchMode If true, this view can receive the focus while
3502 * in touch mode.
3503 *
3504 * @see #setFocusable(boolean)
3505 * @attr ref android.R.styleable#View_focusableInTouchMode
3506 */
3507 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3508 // Focusable in touch mode should always be set before the focusable flag
3509 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3510 // which, in touch mode, will not successfully request focus on this view
3511 // because the focusable in touch mode flag is not set
3512 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3513 if (focusableInTouchMode) {
3514 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3515 }
3516 }
3517
3518 /**
3519 * Set whether this view should have sound effects enabled for events such as
3520 * clicking and touching.
3521 *
3522 * <p>You may wish to disable sound effects for a view if you already play sounds,
3523 * for instance, a dial key that plays dtmf tones.
3524 *
3525 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3526 * @see #isSoundEffectsEnabled()
3527 * @see #playSoundEffect(int)
3528 * @attr ref android.R.styleable#View_soundEffectsEnabled
3529 */
3530 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3531 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3532 }
3533
3534 /**
3535 * @return whether this view should have sound effects enabled for events such as
3536 * clicking and touching.
3537 *
3538 * @see #setSoundEffectsEnabled(boolean)
3539 * @see #playSoundEffect(int)
3540 * @attr ref android.R.styleable#View_soundEffectsEnabled
3541 */
3542 @ViewDebug.ExportedProperty
3543 public boolean isSoundEffectsEnabled() {
3544 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3545 }
3546
3547 /**
3548 * Set whether this view should have haptic feedback for events such as
3549 * long presses.
3550 *
3551 * <p>You may wish to disable haptic feedback if your view already controls
3552 * its own haptic feedback.
3553 *
3554 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3555 * @see #isHapticFeedbackEnabled()
3556 * @see #performHapticFeedback(int)
3557 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3558 */
3559 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3560 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3561 }
3562
3563 /**
3564 * @return whether this view should have haptic feedback enabled for events
3565 * long presses.
3566 *
3567 * @see #setHapticFeedbackEnabled(boolean)
3568 * @see #performHapticFeedback(int)
3569 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3570 */
3571 @ViewDebug.ExportedProperty
3572 public boolean isHapticFeedbackEnabled() {
3573 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3574 }
3575
3576 /**
3577 * If this view doesn't do any drawing on its own, set this flag to
3578 * allow further optimizations. By default, this flag is not set on
3579 * View, but could be set on some View subclasses such as ViewGroup.
3580 *
3581 * Typically, if you override {@link #onDraw} you should clear this flag.
3582 *
3583 * @param willNotDraw whether or not this View draw on its own
3584 */
3585 public void setWillNotDraw(boolean willNotDraw) {
3586 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3587 }
3588
3589 /**
3590 * Returns whether or not this View draws on its own.
3591 *
3592 * @return true if this view has nothing to draw, false otherwise
3593 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003594 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 public boolean willNotDraw() {
3596 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3597 }
3598
3599 /**
3600 * When a View's drawing cache is enabled, drawing is redirected to an
3601 * offscreen bitmap. Some views, like an ImageView, must be able to
3602 * bypass this mechanism if they already draw a single bitmap, to avoid
3603 * unnecessary usage of the memory.
3604 *
3605 * @param willNotCacheDrawing true if this view does not cache its
3606 * drawing, false otherwise
3607 */
3608 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3609 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3610 }
3611
3612 /**
3613 * Returns whether or not this View can cache its drawing or not.
3614 *
3615 * @return true if this view does not cache its drawing, false otherwise
3616 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003617 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 public boolean willNotCacheDrawing() {
3619 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3620 }
3621
3622 /**
3623 * Indicates whether this view reacts to click events or not.
3624 *
3625 * @return true if the view is clickable, false otherwise
3626 *
3627 * @see #setClickable(boolean)
3628 * @attr ref android.R.styleable#View_clickable
3629 */
3630 @ViewDebug.ExportedProperty
3631 public boolean isClickable() {
3632 return (mViewFlags & CLICKABLE) == CLICKABLE;
3633 }
3634
3635 /**
3636 * Enables or disables click events for this view. When a view
3637 * is clickable it will change its state to "pressed" on every click.
3638 * Subclasses should set the view clickable to visually react to
3639 * user's clicks.
3640 *
3641 * @param clickable true to make the view clickable, false otherwise
3642 *
3643 * @see #isClickable()
3644 * @attr ref android.R.styleable#View_clickable
3645 */
3646 public void setClickable(boolean clickable) {
3647 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3648 }
3649
3650 /**
3651 * Indicates whether this view reacts to long click events or not.
3652 *
3653 * @return true if the view is long clickable, false otherwise
3654 *
3655 * @see #setLongClickable(boolean)
3656 * @attr ref android.R.styleable#View_longClickable
3657 */
3658 public boolean isLongClickable() {
3659 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3660 }
3661
3662 /**
3663 * Enables or disables long click events for this view. When a view is long
3664 * clickable it reacts to the user holding down the button for a longer
3665 * duration than a tap. This event can either launch the listener or a
3666 * context menu.
3667 *
3668 * @param longClickable true to make the view long clickable, false otherwise
3669 * @see #isLongClickable()
3670 * @attr ref android.R.styleable#View_longClickable
3671 */
3672 public void setLongClickable(boolean longClickable) {
3673 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3674 }
3675
3676 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003677 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 *
3679 * @see #isClickable()
3680 * @see #setClickable(boolean)
3681 *
3682 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3683 * the View's internal state from a previously set "pressed" state.
3684 */
3685 public void setPressed(boolean pressed) {
3686 if (pressed) {
3687 mPrivateFlags |= PRESSED;
3688 } else {
3689 mPrivateFlags &= ~PRESSED;
3690 }
3691 refreshDrawableState();
3692 dispatchSetPressed(pressed);
3693 }
3694
3695 /**
3696 * Dispatch setPressed to all of this View's children.
3697 *
3698 * @see #setPressed(boolean)
3699 *
3700 * @param pressed The new pressed state
3701 */
3702 protected void dispatchSetPressed(boolean pressed) {
3703 }
3704
3705 /**
3706 * Indicates whether the view is currently in pressed state. Unless
3707 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3708 * the pressed state.
3709 *
3710 * @see #setPressed
3711 * @see #isClickable()
3712 * @see #setClickable(boolean)
3713 *
3714 * @return true if the view is currently pressed, false otherwise
3715 */
3716 public boolean isPressed() {
3717 return (mPrivateFlags & PRESSED) == PRESSED;
3718 }
3719
3720 /**
3721 * Indicates whether this view will save its state (that is,
3722 * whether its {@link #onSaveInstanceState} method will be called).
3723 *
3724 * @return Returns true if the view state saving is enabled, else false.
3725 *
3726 * @see #setSaveEnabled(boolean)
3727 * @attr ref android.R.styleable#View_saveEnabled
3728 */
3729 public boolean isSaveEnabled() {
3730 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3731 }
3732
3733 /**
3734 * Controls whether the saving of this view's state is
3735 * enabled (that is, whether its {@link #onSaveInstanceState} method
3736 * will be called). Note that even if freezing is enabled, the
3737 * view still must have an id assigned to it (via {@link #setId setId()})
3738 * for its state to be saved. This flag can only disable the
3739 * saving of this view; any child views may still have their state saved.
3740 *
3741 * @param enabled Set to false to <em>disable</em> state saving, or true
3742 * (the default) to allow it.
3743 *
3744 * @see #isSaveEnabled()
3745 * @see #setId(int)
3746 * @see #onSaveInstanceState()
3747 * @attr ref android.R.styleable#View_saveEnabled
3748 */
3749 public void setSaveEnabled(boolean enabled) {
3750 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3751 }
3752
Jeff Brown85a31762010-09-01 17:01:00 -07003753 /**
3754 * Gets whether the framework should discard touches when the view's
3755 * window is obscured by another visible window.
3756 * Refer to the {@link View} security documentation for more details.
3757 *
3758 * @return True if touch filtering is enabled.
3759 *
3760 * @see #setFilterTouchesWhenObscured(boolean)
3761 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3762 */
3763 @ViewDebug.ExportedProperty
3764 public boolean getFilterTouchesWhenObscured() {
3765 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3766 }
3767
3768 /**
3769 * Sets whether the framework should discard touches when the view's
3770 * window is obscured by another visible window.
3771 * Refer to the {@link View} security documentation for more details.
3772 *
3773 * @param enabled True if touch filtering should be enabled.
3774 *
3775 * @see #getFilterTouchesWhenObscured
3776 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3777 */
3778 public void setFilterTouchesWhenObscured(boolean enabled) {
3779 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3780 FILTER_TOUCHES_WHEN_OBSCURED);
3781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782
3783 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003784 * Indicates whether the entire hierarchy under this view will save its
3785 * state when a state saving traversal occurs from its parent. The default
3786 * is true; if false, these views will not be saved unless
3787 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3788 *
3789 * @return Returns true if the view state saving from parent is enabled, else false.
3790 *
3791 * @see #setSaveFromParentEnabled(boolean)
3792 */
3793 public boolean isSaveFromParentEnabled() {
3794 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3795 }
3796
3797 /**
3798 * Controls whether the entire hierarchy under this view will save its
3799 * state when a state saving traversal occurs from its parent. The default
3800 * is true; if false, these views will not be saved unless
3801 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3802 *
3803 * @param enabled Set to false to <em>disable</em> state saving, or true
3804 * (the default) to allow it.
3805 *
3806 * @see #isSaveFromParentEnabled()
3807 * @see #setId(int)
3808 * @see #onSaveInstanceState()
3809 */
3810 public void setSaveFromParentEnabled(boolean enabled) {
3811 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
3812 }
3813
3814
3815 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 * Returns whether this View is able to take focus.
3817 *
3818 * @return True if this view can take focus, or false otherwise.
3819 * @attr ref android.R.styleable#View_focusable
3820 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003821 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 public final boolean isFocusable() {
3823 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3824 }
3825
3826 /**
3827 * When a view is focusable, it may not want to take focus when in touch mode.
3828 * For example, a button would like focus when the user is navigating via a D-pad
3829 * so that the user can click on it, but once the user starts touching the screen,
3830 * the button shouldn't take focus
3831 * @return Whether the view is focusable in touch mode.
3832 * @attr ref android.R.styleable#View_focusableInTouchMode
3833 */
3834 @ViewDebug.ExportedProperty
3835 public final boolean isFocusableInTouchMode() {
3836 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3837 }
3838
3839 /**
3840 * Find the nearest view in the specified direction that can take focus.
3841 * This does not actually give focus to that view.
3842 *
3843 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3844 *
3845 * @return The nearest focusable in the specified direction, or null if none
3846 * can be found.
3847 */
3848 public View focusSearch(int direction) {
3849 if (mParent != null) {
3850 return mParent.focusSearch(this, direction);
3851 } else {
3852 return null;
3853 }
3854 }
3855
3856 /**
3857 * This method is the last chance for the focused view and its ancestors to
3858 * respond to an arrow key. This is called when the focused view did not
3859 * consume the key internally, nor could the view system find a new view in
3860 * the requested direction to give focus to.
3861 *
3862 * @param focused The currently focused view.
3863 * @param direction The direction focus wants to move. One of FOCUS_UP,
3864 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3865 * @return True if the this view consumed this unhandled move.
3866 */
3867 public boolean dispatchUnhandledMove(View focused, int direction) {
3868 return false;
3869 }
3870
3871 /**
3872 * If a user manually specified the next view id for a particular direction,
3873 * use the root to look up the view. Once a view is found, it is cached
3874 * for future lookups.
3875 * @param root The root view of the hierarchy containing this view.
3876 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3877 * @return The user specified next view, or null if there is none.
3878 */
3879 View findUserSetNextFocus(View root, int direction) {
3880 switch (direction) {
3881 case FOCUS_LEFT:
3882 if (mNextFocusLeftId == View.NO_ID) return null;
3883 return findViewShouldExist(root, mNextFocusLeftId);
3884 case FOCUS_RIGHT:
3885 if (mNextFocusRightId == View.NO_ID) return null;
3886 return findViewShouldExist(root, mNextFocusRightId);
3887 case FOCUS_UP:
3888 if (mNextFocusUpId == View.NO_ID) return null;
3889 return findViewShouldExist(root, mNextFocusUpId);
3890 case FOCUS_DOWN:
3891 if (mNextFocusDownId == View.NO_ID) return null;
3892 return findViewShouldExist(root, mNextFocusDownId);
3893 }
3894 return null;
3895 }
3896
3897 private static View findViewShouldExist(View root, int childViewId) {
3898 View result = root.findViewById(childViewId);
3899 if (result == null) {
3900 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3901 + "by user for id " + childViewId);
3902 }
3903 return result;
3904 }
3905
3906 /**
3907 * Find and return all focusable views that are descendants of this view,
3908 * possibly including this view if it is focusable itself.
3909 *
3910 * @param direction The direction of the focus
3911 * @return A list of focusable views
3912 */
3913 public ArrayList<View> getFocusables(int direction) {
3914 ArrayList<View> result = new ArrayList<View>(24);
3915 addFocusables(result, direction);
3916 return result;
3917 }
3918
3919 /**
3920 * Add any focusable views that are descendants of this view (possibly
3921 * including this view if it is focusable itself) to views. If we are in touch mode,
3922 * only add views that are also focusable in touch mode.
3923 *
3924 * @param views Focusable views found so far
3925 * @param direction The direction of the focus
3926 */
3927 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003928 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930
svetoslavganov75986cf2009-05-14 22:28:01 -07003931 /**
3932 * Adds any focusable views that are descendants of this view (possibly
3933 * including this view if it is focusable itself) to views. This method
3934 * adds all focusable views regardless if we are in touch mode or
3935 * only views focusable in touch mode if we are in touch mode depending on
3936 * the focusable mode paramater.
3937 *
3938 * @param views Focusable views found so far or null if all we are interested is
3939 * the number of focusables.
3940 * @param direction The direction of the focus.
3941 * @param focusableMode The type of focusables to be added.
3942 *
3943 * @see #FOCUSABLES_ALL
3944 * @see #FOCUSABLES_TOUCH_MODE
3945 */
3946 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3947 if (!isFocusable()) {
3948 return;
3949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950
svetoslavganov75986cf2009-05-14 22:28:01 -07003951 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3952 isInTouchMode() && !isFocusableInTouchMode()) {
3953 return;
3954 }
3955
3956 if (views != null) {
3957 views.add(this);
3958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 }
3960
3961 /**
3962 * Find and return all touchable views that are descendants of this view,
3963 * possibly including this view if it is touchable itself.
3964 *
3965 * @return A list of touchable views
3966 */
3967 public ArrayList<View> getTouchables() {
3968 ArrayList<View> result = new ArrayList<View>();
3969 addTouchables(result);
3970 return result;
3971 }
3972
3973 /**
3974 * Add any touchable views that are descendants of this view (possibly
3975 * including this view if it is touchable itself) to views.
3976 *
3977 * @param views Touchable views found so far
3978 */
3979 public void addTouchables(ArrayList<View> views) {
3980 final int viewFlags = mViewFlags;
3981
3982 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
3983 && (viewFlags & ENABLED_MASK) == ENABLED) {
3984 views.add(this);
3985 }
3986 }
3987
3988 /**
3989 * Call this to try to give focus to a specific view or to one of its
3990 * descendants.
3991 *
3992 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3993 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3994 * while the device is in touch mode.
3995 *
3996 * See also {@link #focusSearch}, which is what you call to say that you
3997 * have focus, and you want your parent to look for the next one.
3998 *
3999 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4000 * {@link #FOCUS_DOWN} and <code>null</code>.
4001 *
4002 * @return Whether this view or one of its descendants actually took focus.
4003 */
4004 public final boolean requestFocus() {
4005 return requestFocus(View.FOCUS_DOWN);
4006 }
4007
4008
4009 /**
4010 * Call this to try to give focus to a specific view or to one of its
4011 * descendants and give it a hint about what direction focus is heading.
4012 *
4013 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4014 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4015 * while the device is in touch mode.
4016 *
4017 * See also {@link #focusSearch}, which is what you call to say that you
4018 * have focus, and you want your parent to look for the next one.
4019 *
4020 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4021 * <code>null</code> set for the previously focused rectangle.
4022 *
4023 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4024 * @return Whether this view or one of its descendants actually took focus.
4025 */
4026 public final boolean requestFocus(int direction) {
4027 return requestFocus(direction, null);
4028 }
4029
4030 /**
4031 * Call this to try to give focus to a specific view or to one of its descendants
4032 * and give it hints about the direction and a specific rectangle that the focus
4033 * is coming from. The rectangle can help give larger views a finer grained hint
4034 * about where focus is coming from, and therefore, where to show selection, or
4035 * forward focus change internally.
4036 *
4037 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4038 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4039 * while the device is in touch mode.
4040 *
4041 * A View will not take focus if it is not visible.
4042 *
4043 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4044 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4045 *
4046 * See also {@link #focusSearch}, which is what you call to say that you
4047 * have focus, and you want your parent to look for the next one.
4048 *
4049 * You may wish to override this method if your custom {@link View} has an internal
4050 * {@link View} that it wishes to forward the request to.
4051 *
4052 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4053 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4054 * to give a finer grained hint about where focus is coming from. May be null
4055 * if there is no hint.
4056 * @return Whether this view or one of its descendants actually took focus.
4057 */
4058 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4059 // need to be focusable
4060 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4061 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4062 return false;
4063 }
4064
4065 // need to be focusable in touch mode if in touch mode
4066 if (isInTouchMode() &&
4067 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4068 return false;
4069 }
4070
4071 // need to not have any parents blocking us
4072 if (hasAncestorThatBlocksDescendantFocus()) {
4073 return false;
4074 }
4075
4076 handleFocusGainInternal(direction, previouslyFocusedRect);
4077 return true;
4078 }
4079
Christopher Tate2c095f32010-10-04 14:13:40 -07004080 /** Gets the ViewRoot, or null if not attached. */
4081 /*package*/ ViewRoot getViewRoot() {
4082 View root = getRootView();
4083 return root != null ? (ViewRoot)root.getParent() : null;
4084 }
4085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 /**
4087 * Call this to try to give focus to a specific view or to one of its descendants. This is a
4088 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4089 * touch mode to request focus when they are touched.
4090 *
4091 * @return Whether this view or one of its descendants actually took focus.
4092 *
4093 * @see #isInTouchMode()
4094 *
4095 */
4096 public final boolean requestFocusFromTouch() {
4097 // Leave touch mode if we need to
4098 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07004099 ViewRoot viewRoot = getViewRoot();
4100 if (viewRoot != null) {
4101 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 }
4103 }
4104 return requestFocus(View.FOCUS_DOWN);
4105 }
4106
4107 /**
4108 * @return Whether any ancestor of this view blocks descendant focus.
4109 */
4110 private boolean hasAncestorThatBlocksDescendantFocus() {
4111 ViewParent ancestor = mParent;
4112 while (ancestor instanceof ViewGroup) {
4113 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4114 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4115 return true;
4116 } else {
4117 ancestor = vgAncestor.getParent();
4118 }
4119 }
4120 return false;
4121 }
4122
4123 /**
Romain Guya440b002010-02-24 15:57:54 -08004124 * @hide
4125 */
4126 public void dispatchStartTemporaryDetach() {
4127 onStartTemporaryDetach();
4128 }
4129
4130 /**
4131 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4133 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004134 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 */
4136 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004137 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004138 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004139 }
4140
4141 /**
4142 * @hide
4143 */
4144 public void dispatchFinishTemporaryDetach() {
4145 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 }
Romain Guy8506ab42009-06-11 17:35:47 -07004147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 /**
4149 * Called after {@link #onStartTemporaryDetach} when the container is done
4150 * changing the view.
4151 */
4152 public void onFinishTemporaryDetach() {
4153 }
Romain Guy8506ab42009-06-11 17:35:47 -07004154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 /**
4156 * capture information of this view for later analysis: developement only
4157 * check dynamic switch to make sure we only dump view
4158 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4159 */
4160 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004161 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 return;
4163 }
4164 ViewDebug.dumpCapturedView(subTag, v);
4165 }
4166
4167 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004168 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4169 * for this view's window. Returns null if the view is not currently attached
4170 * to the window. Normally you will not need to use this directly, but
4171 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4172 */
4173 public KeyEvent.DispatcherState getKeyDispatcherState() {
4174 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4175 }
4176
4177 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 * Dispatch a key event before it is processed by any input method
4179 * associated with the view hierarchy. This can be used to intercept
4180 * key events in special situations before the IME consumes them; a
4181 * typical example would be handling the BACK key to update the application's
4182 * UI instead of allowing the IME to see it and close itself.
4183 *
4184 * @param event The key event to be dispatched.
4185 * @return True if the event was handled, false otherwise.
4186 */
4187 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4188 return onKeyPreIme(event.getKeyCode(), event);
4189 }
4190
4191 /**
4192 * Dispatch a key event to the next view on the focus path. This path runs
4193 * from the top of the view tree down to the currently focused view. If this
4194 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4195 * the next node down the focus path. This method also fires any key
4196 * listeners.
4197 *
4198 * @param event The key event to be dispatched.
4199 * @return True if the event was handled, false otherwise.
4200 */
4201 public boolean dispatchKeyEvent(KeyEvent event) {
4202 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004203
Romain Guyf607bdc2010-09-10 19:20:06 -07004204 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 if (android.util.Config.LOGV) {
4206 captureViewInfo("captureViewKeyEvent", this);
4207 }
4208
Romain Guyf607bdc2010-09-10 19:20:06 -07004209 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004210 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4211 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4212 return true;
4213 }
4214
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004215 return event.dispatch(this, mAttachInfo != null
4216 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 }
4218
4219 /**
4220 * Dispatches a key shortcut event.
4221 *
4222 * @param event The key event to be dispatched.
4223 * @return True if the event was handled by the view, false otherwise.
4224 */
4225 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4226 return onKeyShortcut(event.getKeyCode(), event);
4227 }
4228
4229 /**
4230 * Pass the touch screen motion event down to the target view, or this
4231 * view if it is the target.
4232 *
4233 * @param event The motion event to be dispatched.
4234 * @return True if the event was handled by the view, false otherwise.
4235 */
4236 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004237 if (!onFilterTouchEventForSecurity(event)) {
4238 return false;
4239 }
4240
Romain Guyf607bdc2010-09-10 19:20:06 -07004241 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4243 mOnTouchListener.onTouch(this, event)) {
4244 return true;
4245 }
4246 return onTouchEvent(event);
4247 }
4248
4249 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004250 * Filter the touch event to apply security policies.
4251 *
4252 * @param event The motion event to be filtered.
4253 * @return True if the event should be dispatched, false if the event should be dropped.
4254 *
4255 * @see #getFilterTouchesWhenObscured
4256 */
4257 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004258 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004259 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4260 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4261 // Window is obscured, drop this touch.
4262 return false;
4263 }
4264 return true;
4265 }
4266
4267 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 * Pass a trackball motion event down to the focused view.
4269 *
4270 * @param event The motion event to be dispatched.
4271 * @return True if the event was handled by the view, false otherwise.
4272 */
4273 public boolean dispatchTrackballEvent(MotionEvent event) {
4274 //Log.i("view", "view=" + this + ", " + event.toString());
4275 return onTrackballEvent(event);
4276 }
4277
4278 /**
4279 * Called when the window containing this view gains or loses window focus.
4280 * ViewGroups should override to route to their children.
4281 *
4282 * @param hasFocus True if the window containing this view now has focus,
4283 * false otherwise.
4284 */
4285 public void dispatchWindowFocusChanged(boolean hasFocus) {
4286 onWindowFocusChanged(hasFocus);
4287 }
4288
4289 /**
4290 * Called when the window containing this view gains or loses focus. Note
4291 * that this is separate from view focus: to receive key events, both
4292 * your view and its window must have focus. If a window is displayed
4293 * on top of yours that takes input focus, then your own window will lose
4294 * focus but the view focus will remain unchanged.
4295 *
4296 * @param hasWindowFocus True if the window containing this view now has
4297 * focus, false otherwise.
4298 */
4299 public void onWindowFocusChanged(boolean hasWindowFocus) {
4300 InputMethodManager imm = InputMethodManager.peekInstance();
4301 if (!hasWindowFocus) {
4302 if (isPressed()) {
4303 setPressed(false);
4304 }
4305 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4306 imm.focusOut(this);
4307 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004308 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004309 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004310 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4312 imm.focusIn(this);
4313 }
4314 refreshDrawableState();
4315 }
4316
4317 /**
4318 * Returns true if this view is in a window that currently has window focus.
4319 * Note that this is not the same as the view itself having focus.
4320 *
4321 * @return True if this view is in a window that currently has window focus.
4322 */
4323 public boolean hasWindowFocus() {
4324 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4325 }
4326
4327 /**
Adam Powell326d8082009-12-09 15:10:07 -08004328 * Dispatch a view visibility change down the view hierarchy.
4329 * ViewGroups should override to route to their children.
4330 * @param changedView The view whose visibility changed. Could be 'this' or
4331 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004332 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4333 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004334 */
4335 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4336 onVisibilityChanged(changedView, visibility);
4337 }
4338
4339 /**
4340 * Called when the visibility of the view or an ancestor of the view is changed.
4341 * @param changedView The view whose visibility changed. Could be 'this' or
4342 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004343 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4344 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004345 */
4346 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004347 if (visibility == VISIBLE) {
4348 if (mAttachInfo != null) {
4349 initialAwakenScrollBars();
4350 } else {
4351 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4352 }
4353 }
Adam Powell326d8082009-12-09 15:10:07 -08004354 }
4355
4356 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004357 * Dispatch a hint about whether this view is displayed. For instance, when
4358 * a View moves out of the screen, it might receives a display hint indicating
4359 * the view is not displayed. Applications should not <em>rely</em> on this hint
4360 * as there is no guarantee that they will receive one.
4361 *
4362 * @param hint A hint about whether or not this view is displayed:
4363 * {@link #VISIBLE} or {@link #INVISIBLE}.
4364 */
4365 public void dispatchDisplayHint(int hint) {
4366 onDisplayHint(hint);
4367 }
4368
4369 /**
4370 * Gives this view a hint about whether is displayed or not. For instance, when
4371 * a View moves out of the screen, it might receives a display hint indicating
4372 * the view is not displayed. Applications should not <em>rely</em> on this hint
4373 * as there is no guarantee that they will receive one.
4374 *
4375 * @param hint A hint about whether or not this view is displayed:
4376 * {@link #VISIBLE} or {@link #INVISIBLE}.
4377 */
4378 protected void onDisplayHint(int hint) {
4379 }
4380
4381 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 * Dispatch a window visibility change down the view hierarchy.
4383 * ViewGroups should override to route to their children.
4384 *
4385 * @param visibility The new visibility of the window.
4386 *
4387 * @see #onWindowVisibilityChanged
4388 */
4389 public void dispatchWindowVisibilityChanged(int visibility) {
4390 onWindowVisibilityChanged(visibility);
4391 }
4392
4393 /**
4394 * Called when the window containing has change its visibility
4395 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4396 * that this tells you whether or not your window is being made visible
4397 * to the window manager; this does <em>not</em> tell you whether or not
4398 * your window is obscured by other windows on the screen, even if it
4399 * is itself visible.
4400 *
4401 * @param visibility The new visibility of the window.
4402 */
4403 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004404 if (visibility == VISIBLE) {
4405 initialAwakenScrollBars();
4406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004407 }
4408
4409 /**
4410 * Returns the current visibility of the window this view is attached to
4411 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4412 *
4413 * @return Returns the current visibility of the view's window.
4414 */
4415 public int getWindowVisibility() {
4416 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4417 }
4418
4419 /**
4420 * Retrieve the overall visible display size in which the window this view is
4421 * attached to has been positioned in. This takes into account screen
4422 * decorations above the window, for both cases where the window itself
4423 * is being position inside of them or the window is being placed under
4424 * then and covered insets are used for the window to position its content
4425 * inside. In effect, this tells you the available area where content can
4426 * be placed and remain visible to users.
4427 *
4428 * <p>This function requires an IPC back to the window manager to retrieve
4429 * the requested information, so should not be used in performance critical
4430 * code like drawing.
4431 *
4432 * @param outRect Filled in with the visible display frame. If the view
4433 * is not attached to a window, this is simply the raw display size.
4434 */
4435 public void getWindowVisibleDisplayFrame(Rect outRect) {
4436 if (mAttachInfo != null) {
4437 try {
4438 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4439 } catch (RemoteException e) {
4440 return;
4441 }
4442 // XXX This is really broken, and probably all needs to be done
4443 // in the window manager, and we need to know more about whether
4444 // we want the area behind or in front of the IME.
4445 final Rect insets = mAttachInfo.mVisibleInsets;
4446 outRect.left += insets.left;
4447 outRect.top += insets.top;
4448 outRect.right -= insets.right;
4449 outRect.bottom -= insets.bottom;
4450 return;
4451 }
4452 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4453 outRect.set(0, 0, d.getWidth(), d.getHeight());
4454 }
4455
4456 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004457 * Dispatch a notification about a resource configuration change down
4458 * the view hierarchy.
4459 * ViewGroups should override to route to their children.
4460 *
4461 * @param newConfig The new resource configuration.
4462 *
4463 * @see #onConfigurationChanged
4464 */
4465 public void dispatchConfigurationChanged(Configuration newConfig) {
4466 onConfigurationChanged(newConfig);
4467 }
4468
4469 /**
4470 * Called when the current configuration of the resources being used
4471 * by the application have changed. You can use this to decide when
4472 * to reload resources that can changed based on orientation and other
4473 * configuration characterstics. You only need to use this if you are
4474 * not relying on the normal {@link android.app.Activity} mechanism of
4475 * recreating the activity instance upon a configuration change.
4476 *
4477 * @param newConfig The new resource configuration.
4478 */
4479 protected void onConfigurationChanged(Configuration newConfig) {
4480 }
4481
4482 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483 * Private function to aggregate all per-view attributes in to the view
4484 * root.
4485 */
4486 void dispatchCollectViewAttributes(int visibility) {
4487 performCollectViewAttributes(visibility);
4488 }
4489
4490 void performCollectViewAttributes(int visibility) {
4491 //noinspection PointlessBitwiseExpression
4492 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4493 == (VISIBLE | KEEP_SCREEN_ON)) {
4494 mAttachInfo.mKeepScreenOn = true;
4495 }
4496 }
4497
4498 void needGlobalAttributesUpdate(boolean force) {
4499 AttachInfo ai = mAttachInfo;
4500 if (ai != null) {
4501 if (ai.mKeepScreenOn || force) {
4502 ai.mRecomputeGlobalAttributes = true;
4503 }
4504 }
4505 }
4506
4507 /**
4508 * Returns whether the device is currently in touch mode. Touch mode is entered
4509 * once the user begins interacting with the device by touch, and affects various
4510 * things like whether focus is always visible to the user.
4511 *
4512 * @return Whether the device is in touch mode.
4513 */
4514 @ViewDebug.ExportedProperty
4515 public boolean isInTouchMode() {
4516 if (mAttachInfo != null) {
4517 return mAttachInfo.mInTouchMode;
4518 } else {
4519 return ViewRoot.isInTouchMode();
4520 }
4521 }
4522
4523 /**
4524 * Returns the context the view is running in, through which it can
4525 * access the current theme, resources, etc.
4526 *
4527 * @return The view's Context.
4528 */
4529 @ViewDebug.CapturedViewProperty
4530 public final Context getContext() {
4531 return mContext;
4532 }
4533
4534 /**
4535 * Handle a key event before it is processed by any input method
4536 * associated with the view hierarchy. This can be used to intercept
4537 * key events in special situations before the IME consumes them; a
4538 * typical example would be handling the BACK key to update the application's
4539 * UI instead of allowing the IME to see it and close itself.
4540 *
4541 * @param keyCode The value in event.getKeyCode().
4542 * @param event Description of the key event.
4543 * @return If you handled the event, return true. If you want to allow the
4544 * event to be handled by the next receiver, return false.
4545 */
4546 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4547 return false;
4548 }
4549
4550 /**
4551 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4552 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4553 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4554 * is released, if the view is enabled and clickable.
4555 *
4556 * @param keyCode A key code that represents the button pressed, from
4557 * {@link android.view.KeyEvent}.
4558 * @param event The KeyEvent object that defines the button action.
4559 */
4560 public boolean onKeyDown(int keyCode, KeyEvent event) {
4561 boolean result = false;
4562
4563 switch (keyCode) {
4564 case KeyEvent.KEYCODE_DPAD_CENTER:
4565 case KeyEvent.KEYCODE_ENTER: {
4566 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4567 return true;
4568 }
4569 // Long clickable items don't necessarily have to be clickable
4570 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4571 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4572 (event.getRepeatCount() == 0)) {
4573 setPressed(true);
4574 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004575 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 }
4577 return true;
4578 }
4579 break;
4580 }
4581 }
4582 return result;
4583 }
4584
4585 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004586 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4587 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4588 * the event).
4589 */
4590 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4591 return false;
4592 }
4593
4594 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4596 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4597 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4598 * {@link KeyEvent#KEYCODE_ENTER} is released.
4599 *
4600 * @param keyCode A key code that represents the button pressed, from
4601 * {@link android.view.KeyEvent}.
4602 * @param event The KeyEvent object that defines the button action.
4603 */
4604 public boolean onKeyUp(int keyCode, KeyEvent event) {
4605 boolean result = false;
4606
4607 switch (keyCode) {
4608 case KeyEvent.KEYCODE_DPAD_CENTER:
4609 case KeyEvent.KEYCODE_ENTER: {
4610 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4611 return true;
4612 }
4613 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4614 setPressed(false);
4615
4616 if (!mHasPerformedLongPress) {
4617 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004618 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004619
4620 result = performClick();
4621 }
4622 }
4623 break;
4624 }
4625 }
4626 return result;
4627 }
4628
4629 /**
4630 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4631 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4632 * the event).
4633 *
4634 * @param keyCode A key code that represents the button pressed, from
4635 * {@link android.view.KeyEvent}.
4636 * @param repeatCount The number of times the action was made.
4637 * @param event The KeyEvent object that defines the button action.
4638 */
4639 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4640 return false;
4641 }
4642
4643 /**
4644 * Called when an unhandled key shortcut event occurs.
4645 *
4646 * @param keyCode The value in event.getKeyCode().
4647 * @param event Description of the key event.
4648 * @return If you handled the event, return true. If you want to allow the
4649 * event to be handled by the next receiver, return false.
4650 */
4651 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4652 return false;
4653 }
4654
4655 /**
4656 * Check whether the called view is a text editor, in which case it
4657 * would make sense to automatically display a soft input window for
4658 * it. Subclasses should override this if they implement
4659 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004660 * a call on that method would return a non-null InputConnection, and
4661 * they are really a first-class editor that the user would normally
4662 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004663 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004664 * <p>The default implementation always returns false. This does
4665 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4666 * will not be called or the user can not otherwise perform edits on your
4667 * view; it is just a hint to the system that this is not the primary
4668 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004669 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004670 * @return Returns true if this view is a text editor, else false.
4671 */
4672 public boolean onCheckIsTextEditor() {
4673 return false;
4674 }
Romain Guy8506ab42009-06-11 17:35:47 -07004675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676 /**
4677 * Create a new InputConnection for an InputMethod to interact
4678 * with the view. The default implementation returns null, since it doesn't
4679 * support input methods. You can override this to implement such support.
4680 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004681 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 * <p>When implementing this, you probably also want to implement
4683 * {@link #onCheckIsTextEditor()} to indicate you will return a
4684 * non-null InputConnection.
4685 *
4686 * @param outAttrs Fill in with attribute information about the connection.
4687 */
4688 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4689 return null;
4690 }
4691
4692 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004693 * Called by the {@link android.view.inputmethod.InputMethodManager}
4694 * when a view who is not the current
4695 * input connection target is trying to make a call on the manager. The
4696 * default implementation returns false; you can override this to return
4697 * true for certain views if you are performing InputConnection proxying
4698 * to them.
4699 * @param view The View that is making the InputMethodManager call.
4700 * @return Return true to allow the call, false to reject.
4701 */
4702 public boolean checkInputConnectionProxy(View view) {
4703 return false;
4704 }
Romain Guy8506ab42009-06-11 17:35:47 -07004705
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004706 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 * Show the context menu for this view. It is not safe to hold on to the
4708 * menu after returning from this method.
4709 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004710 * You should normally not overload this method. Overload
4711 * {@link #onCreateContextMenu(ContextMenu)} or define an
4712 * {@link OnCreateContextMenuListener} to add items to the context menu.
4713 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004714 * @param menu The context menu to populate
4715 */
4716 public void createContextMenu(ContextMenu menu) {
4717 ContextMenuInfo menuInfo = getContextMenuInfo();
4718
4719 // Sets the current menu info so all items added to menu will have
4720 // my extra info set.
4721 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4722
4723 onCreateContextMenu(menu);
4724 if (mOnCreateContextMenuListener != null) {
4725 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4726 }
4727
4728 // Clear the extra information so subsequent items that aren't mine don't
4729 // have my extra info.
4730 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4731
4732 if (mParent != null) {
4733 mParent.createContextMenu(menu);
4734 }
4735 }
4736
4737 /**
4738 * Views should implement this if they have extra information to associate
4739 * with the context menu. The return result is supplied as a parameter to
4740 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4741 * callback.
4742 *
4743 * @return Extra information about the item for which the context menu
4744 * should be shown. This information will vary across different
4745 * subclasses of View.
4746 */
4747 protected ContextMenuInfo getContextMenuInfo() {
4748 return null;
4749 }
4750
4751 /**
4752 * Views should implement this if the view itself is going to add items to
4753 * the context menu.
4754 *
4755 * @param menu the context menu to populate
4756 */
4757 protected void onCreateContextMenu(ContextMenu menu) {
4758 }
4759
4760 /**
4761 * Implement this method to handle trackball motion events. The
4762 * <em>relative</em> movement of the trackball since the last event
4763 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4764 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4765 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4766 * they will often be fractional values, representing the more fine-grained
4767 * movement information available from a trackball).
4768 *
4769 * @param event The motion event.
4770 * @return True if the event was handled, false otherwise.
4771 */
4772 public boolean onTrackballEvent(MotionEvent event) {
4773 return false;
4774 }
4775
4776 /**
4777 * Implement this method to handle touch screen motion events.
4778 *
4779 * @param event The motion event.
4780 * @return True if the event was handled, false otherwise.
4781 */
4782 public boolean onTouchEvent(MotionEvent event) {
4783 final int viewFlags = mViewFlags;
4784
4785 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4786 // A disabled view that is clickable still consumes the touch
4787 // events, it just doesn't respond to them.
4788 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4789 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4790 }
4791
4792 if (mTouchDelegate != null) {
4793 if (mTouchDelegate.onTouchEvent(event)) {
4794 return true;
4795 }
4796 }
4797
4798 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4799 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4800 switch (event.getAction()) {
4801 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004802 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4803 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004804 // take focus if we don't have it already and we should in
4805 // touch mode.
4806 boolean focusTaken = false;
4807 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4808 focusTaken = requestFocus();
4809 }
4810
4811 if (!mHasPerformedLongPress) {
4812 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004813 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004814
4815 // Only perform take click actions if we were in the pressed state
4816 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004817 // Use a Runnable and post this rather than calling
4818 // performClick directly. This lets other visual state
4819 // of the view update before click actions start.
4820 if (mPerformClick == null) {
4821 mPerformClick = new PerformClick();
4822 }
4823 if (!post(mPerformClick)) {
4824 performClick();
4825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826 }
4827 }
4828
4829 if (mUnsetPressedState == null) {
4830 mUnsetPressedState = new UnsetPressedState();
4831 }
4832
Adam Powelle14579b2009-12-16 18:39:52 -08004833 if (prepressed) {
4834 mPrivateFlags |= PRESSED;
4835 refreshDrawableState();
4836 postDelayed(mUnsetPressedState,
4837 ViewConfiguration.getPressedStateDuration());
4838 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839 // If the post failed, unpress right now
4840 mUnsetPressedState.run();
4841 }
Adam Powelle14579b2009-12-16 18:39:52 -08004842 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004843 }
4844 break;
4845
4846 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004847 if (mPendingCheckForTap == null) {
4848 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004849 }
Adam Powelle14579b2009-12-16 18:39:52 -08004850 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004851 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004852 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004853 break;
4854
4855 case MotionEvent.ACTION_CANCEL:
4856 mPrivateFlags &= ~PRESSED;
4857 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004858 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004859 break;
4860
4861 case MotionEvent.ACTION_MOVE:
4862 final int x = (int) event.getX();
4863 final int y = (int) event.getY();
4864
4865 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004866 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004868 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004869 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004870 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004871 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004872
4873 // Need to switch from pressed to not pressed
4874 mPrivateFlags &= ~PRESSED;
4875 refreshDrawableState();
4876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004877 }
4878 break;
4879 }
4880 return true;
4881 }
4882
4883 return false;
4884 }
4885
4886 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004887 * Remove the longpress detection timer.
4888 */
4889 private void removeLongPressCallback() {
4890 if (mPendingCheckForLongPress != null) {
4891 removeCallbacks(mPendingCheckForLongPress);
4892 }
4893 }
Adam Powelle14579b2009-12-16 18:39:52 -08004894
4895 /**
Romain Guya440b002010-02-24 15:57:54 -08004896 * Remove the prepress detection timer.
4897 */
4898 private void removeUnsetPressCallback() {
4899 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4900 setPressed(false);
4901 removeCallbacks(mUnsetPressedState);
4902 }
4903 }
4904
4905 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004906 * Remove the tap detection timer.
4907 */
4908 private void removeTapCallback() {
4909 if (mPendingCheckForTap != null) {
4910 mPrivateFlags &= ~PREPRESSED;
4911 removeCallbacks(mPendingCheckForTap);
4912 }
4913 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004914
4915 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004916 * Cancels a pending long press. Your subclass can use this if you
4917 * want the context menu to come up if the user presses and holds
4918 * at the same place, but you don't want it to come up if they press
4919 * and then move around enough to cause scrolling.
4920 */
4921 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004922 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004923
4924 /*
4925 * The prepressed state handled by the tap callback is a display
4926 * construct, but the tap callback will post a long press callback
4927 * less its own timeout. Remove it here.
4928 */
4929 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004930 }
4931
4932 /**
4933 * Sets the TouchDelegate for this View.
4934 */
4935 public void setTouchDelegate(TouchDelegate delegate) {
4936 mTouchDelegate = delegate;
4937 }
4938
4939 /**
4940 * Gets the TouchDelegate for this View.
4941 */
4942 public TouchDelegate getTouchDelegate() {
4943 return mTouchDelegate;
4944 }
4945
4946 /**
4947 * Set flags controlling behavior of this view.
4948 *
4949 * @param flags Constant indicating the value which should be set
4950 * @param mask Constant indicating the bit range that should be changed
4951 */
4952 void setFlags(int flags, int mask) {
4953 int old = mViewFlags;
4954 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4955
4956 int changed = mViewFlags ^ old;
4957 if (changed == 0) {
4958 return;
4959 }
4960 int privateFlags = mPrivateFlags;
4961
4962 /* Check if the FOCUSABLE bit has changed */
4963 if (((changed & FOCUSABLE_MASK) != 0) &&
4964 ((privateFlags & HAS_BOUNDS) !=0)) {
4965 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4966 && ((privateFlags & FOCUSED) != 0)) {
4967 /* Give up focus if we are no longer focusable */
4968 clearFocus();
4969 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4970 && ((privateFlags & FOCUSED) == 0)) {
4971 /*
4972 * Tell the view system that we are now available to take focus
4973 * if no one else already has it.
4974 */
4975 if (mParent != null) mParent.focusableViewAvailable(this);
4976 }
4977 }
4978
4979 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4980 if ((changed & VISIBILITY_MASK) != 0) {
4981 /*
4982 * If this view is becoming visible, set the DRAWN flag so that
4983 * the next invalidate() will not be skipped.
4984 */
4985 mPrivateFlags |= DRAWN;
4986
4987 needGlobalAttributesUpdate(true);
4988
4989 // a view becoming visible is worth notifying the parent
4990 // about in case nothing has focus. even if this specific view
4991 // isn't focusable, it may contain something that is, so let
4992 // the root view try to give this focus if nothing else does.
4993 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4994 mParent.focusableViewAvailable(this);
4995 }
4996 }
4997 }
4998
4999 /* Check if the GONE bit has changed */
5000 if ((changed & GONE) != 0) {
5001 needGlobalAttributesUpdate(false);
5002 requestLayout();
5003 invalidate();
5004
Romain Guyecd80ee2009-12-03 17:13:02 -08005005 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5006 if (hasFocus()) clearFocus();
5007 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005008 }
5009 if (mAttachInfo != null) {
5010 mAttachInfo.mViewVisibilityChanged = true;
5011 }
5012 }
5013
5014 /* Check if the VISIBLE bit has changed */
5015 if ((changed & INVISIBLE) != 0) {
5016 needGlobalAttributesUpdate(false);
5017 invalidate();
5018
5019 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5020 // root view becoming invisible shouldn't clear focus
5021 if (getRootView() != this) {
5022 clearFocus();
5023 }
5024 }
5025 if (mAttachInfo != null) {
5026 mAttachInfo.mViewVisibilityChanged = true;
5027 }
5028 }
5029
Adam Powell326d8082009-12-09 15:10:07 -08005030 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07005031 if (mParent instanceof ViewGroup) {
5032 ((ViewGroup)mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
5033 }
Adam Powell326d8082009-12-09 15:10:07 -08005034 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5035 }
5036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005037 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5038 destroyDrawingCache();
5039 }
5040
5041 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5042 destroyDrawingCache();
5043 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5044 }
5045
5046 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5047 destroyDrawingCache();
5048 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5049 }
5050
5051 if ((changed & DRAW_MASK) != 0) {
5052 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5053 if (mBGDrawable != null) {
5054 mPrivateFlags &= ~SKIP_DRAW;
5055 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5056 } else {
5057 mPrivateFlags |= SKIP_DRAW;
5058 }
5059 } else {
5060 mPrivateFlags &= ~SKIP_DRAW;
5061 }
5062 requestLayout();
5063 invalidate();
5064 }
5065
5066 if ((changed & KEEP_SCREEN_ON) != 0) {
5067 if (mParent != null) {
5068 mParent.recomputeViewAttributes(this);
5069 }
5070 }
5071 }
5072
5073 /**
5074 * Change the view's z order in the tree, so it's on top of other sibling
5075 * views
5076 */
5077 public void bringToFront() {
5078 if (mParent != null) {
5079 mParent.bringChildToFront(this);
5080 }
5081 }
5082
5083 /**
5084 * This is called in response to an internal scroll in this view (i.e., the
5085 * view scrolled its own contents). This is typically as a result of
5086 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5087 * called.
5088 *
5089 * @param l Current horizontal scroll origin.
5090 * @param t Current vertical scroll origin.
5091 * @param oldl Previous horizontal scroll origin.
5092 * @param oldt Previous vertical scroll origin.
5093 */
5094 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5095 mBackgroundSizeChanged = true;
5096
5097 final AttachInfo ai = mAttachInfo;
5098 if (ai != null) {
5099 ai.mViewScrollChanged = true;
5100 }
5101 }
5102
5103 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005104 * Interface definition for a callback to be invoked when the layout bounds of a view
5105 * changes due to layout processing.
5106 */
5107 public interface OnLayoutChangeListener {
5108 /**
5109 * Called when the focus state of a view has changed.
5110 *
5111 * @param v The view whose state has changed.
5112 * @param left The new value of the view's left property.
5113 * @param top The new value of the view's top property.
5114 * @param right The new value of the view's right property.
5115 * @param bottom The new value of the view's bottom property.
5116 * @param oldLeft The previous value of the view's left property.
5117 * @param oldTop The previous value of the view's top property.
5118 * @param oldRight The previous value of the view's right property.
5119 * @param oldBottom The previous value of the view's bottom property.
5120 */
5121 void onLayoutChange(View v, int left, int top, int right, int bottom,
5122 int oldLeft, int oldTop, int oldRight, int oldBottom);
5123 }
5124
5125 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005126 * This is called during layout when the size of this view has changed. If
5127 * you were just added to the view hierarchy, you're called with the old
5128 * values of 0.
5129 *
5130 * @param w Current width of this view.
5131 * @param h Current height of this view.
5132 * @param oldw Old width of this view.
5133 * @param oldh Old height of this view.
5134 */
5135 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5136 }
5137
5138 /**
5139 * Called by draw to draw the child views. This may be overridden
5140 * by derived classes to gain control just before its children are drawn
5141 * (but after its own view has been drawn).
5142 * @param canvas the canvas on which to draw the view
5143 */
5144 protected void dispatchDraw(Canvas canvas) {
5145 }
5146
5147 /**
5148 * Gets the parent of this view. Note that the parent is a
5149 * ViewParent and not necessarily a View.
5150 *
5151 * @return Parent of this view.
5152 */
5153 public final ViewParent getParent() {
5154 return mParent;
5155 }
5156
5157 /**
5158 * Return the scrolled left position of this view. This is the left edge of
5159 * the displayed part of your view. You do not need to draw any pixels
5160 * farther left, since those are outside of the frame of your view on
5161 * screen.
5162 *
5163 * @return The left edge of the displayed part of your view, in pixels.
5164 */
5165 public final int getScrollX() {
5166 return mScrollX;
5167 }
5168
5169 /**
5170 * Return the scrolled top position of this view. This is the top edge of
5171 * the displayed part of your view. You do not need to draw any pixels above
5172 * it, since those are outside of the frame of your view on screen.
5173 *
5174 * @return The top edge of the displayed part of your view, in pixels.
5175 */
5176 public final int getScrollY() {
5177 return mScrollY;
5178 }
5179
5180 /**
5181 * Return the width of the your view.
5182 *
5183 * @return The width of your view, in pixels.
5184 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005185 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 public final int getWidth() {
5187 return mRight - mLeft;
5188 }
5189
5190 /**
5191 * Return the height of your view.
5192 *
5193 * @return The height of your view, in pixels.
5194 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005195 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 public final int getHeight() {
5197 return mBottom - mTop;
5198 }
5199
5200 /**
5201 * Return the visible drawing bounds of your view. Fills in the output
5202 * rectangle with the values from getScrollX(), getScrollY(),
5203 * getWidth(), and getHeight().
5204 *
5205 * @param outRect The (scrolled) drawing bounds of the view.
5206 */
5207 public void getDrawingRect(Rect outRect) {
5208 outRect.left = mScrollX;
5209 outRect.top = mScrollY;
5210 outRect.right = mScrollX + (mRight - mLeft);
5211 outRect.bottom = mScrollY + (mBottom - mTop);
5212 }
5213
5214 /**
5215 * The width of this view as measured in the most recent call to measure().
5216 * This should be used during measurement and layout calculations only. Use
5217 * {@link #getWidth()} to see how wide a view is after layout.
5218 *
5219 * @return The measured width of this view.
5220 */
5221 public final int getMeasuredWidth() {
5222 return mMeasuredWidth;
5223 }
5224
5225 /**
5226 * The height of this view as measured in the most recent call to measure().
5227 * This should be used during measurement and layout calculations only. Use
5228 * {@link #getHeight()} to see how tall a view is after layout.
5229 *
5230 * @return The measured height of this view.
5231 */
5232 public final int getMeasuredHeight() {
5233 return mMeasuredHeight;
5234 }
5235
5236 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005237 * The transform matrix of this view, which is calculated based on the current
5238 * roation, scale, and pivot properties.
5239 *
5240 * @see #getRotation()
5241 * @see #getScaleX()
5242 * @see #getScaleY()
5243 * @see #getPivotX()
5244 * @see #getPivotY()
5245 * @return The current transform matrix for the view
5246 */
5247 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005248 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005249 return mMatrix;
5250 }
5251
5252 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005253 * Utility function to determine if the value is far enough away from zero to be
5254 * considered non-zero.
5255 * @param value A floating point value to check for zero-ness
5256 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5257 */
5258 private static boolean nonzero(float value) {
5259 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5260 }
5261
5262 /**
Jeff Brown86671742010-09-30 20:00:15 -07005263 * Returns true if the transform matrix is the identity matrix.
5264 * Recomputes the matrix if necessary.
Romain Guy33e72ae2010-07-17 12:40:29 -07005265 *
5266 * @return True if the transform matrix is the identity matrix, false otherwise.
5267 */
Jeff Brown86671742010-09-30 20:00:15 -07005268 final boolean hasIdentityMatrix() {
5269 updateMatrix();
5270 return mMatrixIsIdentity;
5271 }
5272
5273 /**
5274 * Recomputes the transform matrix if necessary.
5275 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005276 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005277 if (mMatrixDirty) {
5278 // transform-related properties have changed since the last time someone
5279 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005280
5281 // Figure out if we need to update the pivot point
5282 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5283 if ((mRight - mLeft) != mPrevWidth && (mBottom - mTop) != mPrevHeight) {
5284 mPrevWidth = mRight - mLeft;
5285 mPrevHeight = mBottom - mTop;
5286 mPivotX = (float) mPrevWidth / 2f;
5287 mPivotY = (float) mPrevHeight / 2f;
5288 }
5289 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005290 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005291 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5292 mMatrix.setTranslate(mTranslationX, mTranslationY);
5293 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5294 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5295 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005296 if (mCamera == null) {
5297 mCamera = new Camera();
5298 matrix3D = new Matrix();
5299 }
5300 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005301 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005302 mCamera.rotateX(mRotationX);
5303 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005304 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005305 mCamera.getMatrix(matrix3D);
5306 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005307 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005308 mMatrix.postConcat(matrix3D);
5309 mCamera.restore();
5310 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005311 mMatrixDirty = false;
5312 mMatrixIsIdentity = mMatrix.isIdentity();
5313 mInverseMatrixDirty = true;
5314 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005315 }
5316
5317 /**
5318 * Utility method to retrieve the inverse of the current mMatrix property.
5319 * We cache the matrix to avoid recalculating it when transform properties
5320 * have not changed.
5321 *
5322 * @return The inverse of the current matrix of this view.
5323 */
Jeff Brown86671742010-09-30 20:00:15 -07005324 final Matrix getInverseMatrix() {
5325 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005326 if (mInverseMatrixDirty) {
5327 if (mInverseMatrix == null) {
5328 mInverseMatrix = new Matrix();
5329 }
5330 mMatrix.invert(mInverseMatrix);
5331 mInverseMatrixDirty = false;
5332 }
5333 return mInverseMatrix;
5334 }
5335
5336 /**
5337 * The degrees that the view is rotated around the pivot point.
5338 *
5339 * @see #getPivotX()
5340 * @see #getPivotY()
5341 * @return The degrees of rotation.
5342 */
5343 public float getRotation() {
5344 return mRotation;
5345 }
5346
5347 /**
Chet Haase897247b2010-09-09 14:54:47 -07005348 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5349 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005350 *
5351 * @param rotation The degrees of rotation.
5352 * @see #getPivotX()
5353 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005354 *
5355 * @attr ref android.R.styleable#View_rotation
Chet Haasec3aa3612010-06-17 08:50:37 -07005356 */
5357 public void setRotation(float rotation) {
5358 if (mRotation != rotation) {
5359 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005360 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005361 mRotation = rotation;
5362 mMatrixDirty = true;
5363 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005364 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005365 }
5366 }
5367
5368 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005369 * The degrees that the view is rotated around the vertical axis through the pivot point.
5370 *
5371 * @see #getPivotX()
5372 * @see #getPivotY()
5373 * @return The degrees of Y rotation.
5374 */
5375 public float getRotationY() {
5376 return mRotationY;
5377 }
5378
5379 /**
Chet Haase897247b2010-09-09 14:54:47 -07005380 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5381 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5382 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005383 *
5384 * @param rotationY The degrees of Y rotation.
5385 * @see #getPivotX()
5386 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005387 *
5388 * @attr ref android.R.styleable#View_rotationY
Chet Haasefd2b0022010-08-06 13:08:56 -07005389 */
5390 public void setRotationY(float rotationY) {
5391 if (mRotationY != rotationY) {
5392 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005393 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005394 mRotationY = rotationY;
5395 mMatrixDirty = true;
5396 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005397 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005398 }
5399 }
5400
5401 /**
5402 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5403 *
5404 * @see #getPivotX()
5405 * @see #getPivotY()
5406 * @return The degrees of X rotation.
5407 */
5408 public float getRotationX() {
5409 return mRotationX;
5410 }
5411
5412 /**
Chet Haase897247b2010-09-09 14:54:47 -07005413 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5414 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5415 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005416 *
5417 * @param rotationX The degrees of X rotation.
5418 * @see #getPivotX()
5419 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005420 *
5421 * @attr ref android.R.styleable#View_rotationX
Chet Haasefd2b0022010-08-06 13:08:56 -07005422 */
5423 public void setRotationX(float rotationX) {
5424 if (mRotationX != rotationX) {
5425 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005426 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005427 mRotationX = rotationX;
5428 mMatrixDirty = true;
5429 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005430 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005431 }
5432 }
5433
5434 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005435 * The amount that the view is scaled in x around the pivot point, as a proportion of
5436 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5437 *
Joe Onorato93162322010-09-16 15:42:01 -04005438 * <p>By default, this is 1.0f.
5439 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005440 * @see #getPivotX()
5441 * @see #getPivotY()
5442 * @return The scaling factor.
5443 */
5444 public float getScaleX() {
5445 return mScaleX;
5446 }
5447
5448 /**
5449 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5450 * the view's unscaled width. A value of 1 means that no scaling is applied.
5451 *
5452 * @param scaleX The scaling factor.
5453 * @see #getPivotX()
5454 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005455 *
5456 * @attr ref android.R.styleable#View_scaleX
Chet Haasec3aa3612010-06-17 08:50:37 -07005457 */
5458 public void setScaleX(float scaleX) {
5459 if (mScaleX != scaleX) {
5460 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005461 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005462 mScaleX = scaleX;
5463 mMatrixDirty = true;
5464 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005465 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005466 }
5467 }
5468
5469 /**
5470 * The amount that the view is scaled in y around the pivot point, as a proportion of
5471 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5472 *
Joe Onorato93162322010-09-16 15:42:01 -04005473 * <p>By default, this is 1.0f.
5474 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005475 * @see #getPivotX()
5476 * @see #getPivotY()
5477 * @return The scaling factor.
5478 */
5479 public float getScaleY() {
5480 return mScaleY;
5481 }
5482
5483 /**
5484 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5485 * the view's unscaled width. A value of 1 means that no scaling is applied.
5486 *
5487 * @param scaleY The scaling factor.
5488 * @see #getPivotX()
5489 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005490 *
5491 * @attr ref android.R.styleable#View_scaleY
Chet Haasec3aa3612010-06-17 08:50:37 -07005492 */
5493 public void setScaleY(float scaleY) {
5494 if (mScaleY != scaleY) {
5495 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005496 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005497 mScaleY = scaleY;
5498 mMatrixDirty = true;
5499 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005500 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005501 }
5502 }
5503
5504 /**
5505 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5506 * and {@link #setScaleX(float) scaled}.
5507 *
5508 * @see #getRotation()
5509 * @see #getScaleX()
5510 * @see #getScaleY()
5511 * @see #getPivotY()
5512 * @return The x location of the pivot point.
5513 */
5514 public float getPivotX() {
5515 return mPivotX;
5516 }
5517
5518 /**
5519 * Sets the x location of the point around which the view is
5520 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005521 * By default, the pivot point is centered on the object.
5522 * Setting this property disables this behavior and causes the view to use only the
5523 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005524 *
5525 * @param pivotX The x location of the pivot point.
5526 * @see #getRotation()
5527 * @see #getScaleX()
5528 * @see #getScaleY()
5529 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005530 *
5531 * @attr ref android.R.styleable#View_transformPivotX
Chet Haasec3aa3612010-06-17 08:50:37 -07005532 */
5533 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005534 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005535 if (mPivotX != pivotX) {
5536 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005537 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005538 mPivotX = pivotX;
5539 mMatrixDirty = true;
5540 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005541 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005542 }
5543 }
5544
5545 /**
5546 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5547 * and {@link #setScaleY(float) scaled}.
5548 *
5549 * @see #getRotation()
5550 * @see #getScaleX()
5551 * @see #getScaleY()
5552 * @see #getPivotY()
5553 * @return The y location of the pivot point.
5554 */
5555 public float getPivotY() {
5556 return mPivotY;
5557 }
5558
5559 /**
5560 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005561 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5562 * Setting this property disables this behavior and causes the view to use only the
5563 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005564 *
5565 * @param pivotY The y location of the pivot point.
5566 * @see #getRotation()
5567 * @see #getScaleX()
5568 * @see #getScaleY()
5569 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005570 *
5571 * @attr ref android.R.styleable#View_transformPivotY
Chet Haasec3aa3612010-06-17 08:50:37 -07005572 */
5573 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005574 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005575 if (mPivotY != pivotY) {
5576 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005577 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005578 mPivotY = pivotY;
5579 mMatrixDirty = true;
5580 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005581 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005582 }
5583 }
5584
5585 /**
5586 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5587 * completely transparent and 1 means the view is completely opaque.
5588 *
Joe Onorato93162322010-09-16 15:42:01 -04005589 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005590 * @return The opacity of the view.
5591 */
5592 public float getAlpha() {
5593 return mAlpha;
5594 }
5595
5596 /**
5597 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5598 * completely transparent and 1 means the view is completely opaque.
5599 *
5600 * @param alpha The opacity of the view.
Chet Haase73066682010-11-29 15:55:32 -08005601 *
5602 * @attr ref android.R.styleable#View_alpha
Chet Haasec3aa3612010-06-17 08:50:37 -07005603 */
5604 public void setAlpha(float alpha) {
5605 mAlpha = alpha;
Chet Haaseed032702010-10-01 14:05:54 -07005606 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07005607 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005608 // subclass is handling alpha - don't optimize rendering cache invalidation
5609 invalidate();
5610 } else {
Romain Guya3496a92010-10-12 11:53:24 -07005611 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005612 invalidate(false);
5613 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005614 }
5615
5616 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005617 * Top position of this view relative to its parent.
5618 *
5619 * @return The top of this view, in pixels.
5620 */
5621 @ViewDebug.CapturedViewProperty
5622 public final int getTop() {
5623 return mTop;
5624 }
5625
5626 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005627 * Sets the top position of this view relative to its parent. This method is meant to be called
5628 * by the layout system and should not generally be called otherwise, because the property
5629 * may be changed at any time by the layout.
5630 *
5631 * @param top The top of this view, in pixels.
5632 */
5633 public final void setTop(int top) {
5634 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07005635 updateMatrix();
5636 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005637 final ViewParent p = mParent;
5638 if (p != null && mAttachInfo != null) {
5639 final Rect r = mAttachInfo.mTmpInvalRect;
5640 int minTop;
5641 int yLoc;
5642 if (top < mTop) {
5643 minTop = top;
5644 yLoc = top - mTop;
5645 } else {
5646 minTop = mTop;
5647 yLoc = 0;
5648 }
5649 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5650 p.invalidateChild(this, r);
5651 }
5652 } else {
5653 // Double-invalidation is necessary to capture view's old and new areas
5654 invalidate();
5655 }
5656
Chet Haaseed032702010-10-01 14:05:54 -07005657 int width = mRight - mLeft;
5658 int oldHeight = mBottom - mTop;
5659
Chet Haase21cd1382010-09-01 17:42:29 -07005660 mTop = top;
5661
Chet Haaseed032702010-10-01 14:05:54 -07005662 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5663
Chet Haase21cd1382010-09-01 17:42:29 -07005664 if (!mMatrixIsIdentity) {
5665 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5666 invalidate();
5667 }
5668 }
5669 }
5670
5671 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 * Bottom position of this view relative to its parent.
5673 *
5674 * @return The bottom of this view, in pixels.
5675 */
5676 @ViewDebug.CapturedViewProperty
5677 public final int getBottom() {
5678 return mBottom;
5679 }
5680
5681 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005682 * Sets the bottom position of this view relative to its parent. This method is meant to be
5683 * called by the layout system and should not generally be called otherwise, because the
5684 * property may be changed at any time by the layout.
5685 *
5686 * @param bottom The bottom of this view, in pixels.
5687 */
5688 public final void setBottom(int bottom) {
5689 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07005690 updateMatrix();
5691 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005692 final ViewParent p = mParent;
5693 if (p != null && mAttachInfo != null) {
5694 final Rect r = mAttachInfo.mTmpInvalRect;
5695 int maxBottom;
5696 if (bottom < mBottom) {
5697 maxBottom = mBottom;
5698 } else {
5699 maxBottom = bottom;
5700 }
5701 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5702 p.invalidateChild(this, r);
5703 }
5704 } else {
5705 // Double-invalidation is necessary to capture view's old and new areas
5706 invalidate();
5707 }
5708
Chet Haaseed032702010-10-01 14:05:54 -07005709 int width = mRight - mLeft;
5710 int oldHeight = mBottom - mTop;
5711
Chet Haase21cd1382010-09-01 17:42:29 -07005712 mBottom = bottom;
5713
Chet Haaseed032702010-10-01 14:05:54 -07005714 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5715
Chet Haase21cd1382010-09-01 17:42:29 -07005716 if (!mMatrixIsIdentity) {
5717 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5718 invalidate();
5719 }
5720 }
5721 }
5722
5723 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 * Left position of this view relative to its parent.
5725 *
5726 * @return The left edge of this view, in pixels.
5727 */
5728 @ViewDebug.CapturedViewProperty
5729 public final int getLeft() {
5730 return mLeft;
5731 }
5732
5733 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005734 * Sets the left position of this view relative to its parent. This method is meant to be called
5735 * by the layout system and should not generally be called otherwise, because the property
5736 * may be changed at any time by the layout.
5737 *
5738 * @param left The bottom of this view, in pixels.
5739 */
5740 public final void setLeft(int left) {
5741 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07005742 updateMatrix();
5743 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005744 final ViewParent p = mParent;
5745 if (p != null && mAttachInfo != null) {
5746 final Rect r = mAttachInfo.mTmpInvalRect;
5747 int minLeft;
5748 int xLoc;
5749 if (left < mLeft) {
5750 minLeft = left;
5751 xLoc = left - mLeft;
5752 } else {
5753 minLeft = mLeft;
5754 xLoc = 0;
5755 }
5756 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
5757 p.invalidateChild(this, r);
5758 }
5759 } else {
5760 // Double-invalidation is necessary to capture view's old and new areas
5761 invalidate();
5762 }
5763
Chet Haaseed032702010-10-01 14:05:54 -07005764 int oldWidth = mRight - mLeft;
5765 int height = mBottom - mTop;
5766
Chet Haase21cd1382010-09-01 17:42:29 -07005767 mLeft = left;
5768
Chet Haaseed032702010-10-01 14:05:54 -07005769 onSizeChanged(mRight - mLeft, height, oldWidth, height);
5770
Chet Haase21cd1382010-09-01 17:42:29 -07005771 if (!mMatrixIsIdentity) {
5772 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5773 invalidate();
5774 }
Chet Haaseed032702010-10-01 14:05:54 -07005775
Chet Haase21cd1382010-09-01 17:42:29 -07005776 }
5777 }
5778
5779 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 * Right position of this view relative to its parent.
5781 *
5782 * @return The right edge of this view, in pixels.
5783 */
5784 @ViewDebug.CapturedViewProperty
5785 public final int getRight() {
5786 return mRight;
5787 }
5788
5789 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005790 * Sets the right position of this view relative to its parent. This method is meant to be called
5791 * by the layout system and should not generally be called otherwise, because the property
5792 * may be changed at any time by the layout.
5793 *
5794 * @param right The bottom of this view, in pixels.
5795 */
5796 public final void setRight(int right) {
5797 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07005798 updateMatrix();
5799 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005800 final ViewParent p = mParent;
5801 if (p != null && mAttachInfo != null) {
5802 final Rect r = mAttachInfo.mTmpInvalRect;
5803 int maxRight;
5804 if (right < mRight) {
5805 maxRight = mRight;
5806 } else {
5807 maxRight = right;
5808 }
5809 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
5810 p.invalidateChild(this, r);
5811 }
5812 } else {
5813 // Double-invalidation is necessary to capture view's old and new areas
5814 invalidate();
5815 }
5816
Chet Haaseed032702010-10-01 14:05:54 -07005817 int oldWidth = mRight - mLeft;
5818 int height = mBottom - mTop;
5819
Chet Haase21cd1382010-09-01 17:42:29 -07005820 mRight = right;
5821
Chet Haaseed032702010-10-01 14:05:54 -07005822 onSizeChanged(mRight - mLeft, height, oldWidth, height);
5823
Chet Haase21cd1382010-09-01 17:42:29 -07005824 if (!mMatrixIsIdentity) {
5825 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5826 invalidate();
5827 }
5828 }
5829 }
5830
5831 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005832 * The visual x position of this view, in pixels. This is equivalent to the
5833 * {@link #setTranslationX(float) translationX} property plus the current
5834 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07005835 *
Chet Haasedf030d22010-07-30 17:22:38 -07005836 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005837 */
Chet Haasedf030d22010-07-30 17:22:38 -07005838 public float getX() {
5839 return mLeft + mTranslationX;
5840 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005841
Chet Haasedf030d22010-07-30 17:22:38 -07005842 /**
5843 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
5844 * {@link #setTranslationX(float) translationX} property to be the difference between
5845 * the x value passed in and the current {@link #getLeft() left} property.
5846 *
5847 * @param x The visual x position of this view, in pixels.
5848 */
5849 public void setX(float x) {
5850 setTranslationX(x - mLeft);
5851 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005852
Chet Haasedf030d22010-07-30 17:22:38 -07005853 /**
5854 * The visual y position of this view, in pixels. This is equivalent to the
5855 * {@link #setTranslationY(float) translationY} property plus the current
5856 * {@link #getTop() top} property.
5857 *
5858 * @return The visual y position of this view, in pixels.
5859 */
5860 public float getY() {
5861 return mTop + mTranslationY;
5862 }
5863
5864 /**
5865 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
5866 * {@link #setTranslationY(float) translationY} property to be the difference between
5867 * the y value passed in and the current {@link #getTop() top} property.
5868 *
5869 * @param y The visual y position of this view, in pixels.
5870 */
5871 public void setY(float y) {
5872 setTranslationY(y - mTop);
5873 }
5874
5875
5876 /**
5877 * The horizontal location of this view relative to its {@link #getLeft() left} position.
5878 * This position is post-layout, in addition to wherever the object's
5879 * layout placed it.
5880 *
5881 * @return The horizontal position of this view relative to its left position, in pixels.
5882 */
5883 public float getTranslationX() {
5884 return mTranslationX;
5885 }
5886
5887 /**
5888 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
5889 * This effectively positions the object post-layout, in addition to wherever the object's
5890 * layout placed it.
5891 *
5892 * @param translationX The horizontal position of this view relative to its left position,
5893 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08005894 *
5895 * @attr ref android.R.styleable#View_translationX
Chet Haasedf030d22010-07-30 17:22:38 -07005896 */
5897 public void setTranslationX(float translationX) {
5898 if (mTranslationX != translationX) {
5899 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005900 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07005901 mTranslationX = translationX;
5902 mMatrixDirty = true;
5903 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005904 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005905 }
5906 }
5907
5908 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005909 * The horizontal location of this view relative to its {@link #getTop() top} position.
5910 * This position is post-layout, in addition to wherever the object's
5911 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005912 *
Chet Haasedf030d22010-07-30 17:22:38 -07005913 * @return The vertical position of this view relative to its top position,
5914 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005915 */
Chet Haasedf030d22010-07-30 17:22:38 -07005916 public float getTranslationY() {
5917 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07005918 }
5919
5920 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005921 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
5922 * This effectively positions the object post-layout, in addition to wherever the object's
5923 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005924 *
Chet Haasedf030d22010-07-30 17:22:38 -07005925 * @param translationY The vertical position of this view relative to its top position,
5926 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08005927 *
5928 * @attr ref android.R.styleable#View_translationY
Chet Haasec3aa3612010-06-17 08:50:37 -07005929 */
Chet Haasedf030d22010-07-30 17:22:38 -07005930 public void setTranslationY(float translationY) {
5931 if (mTranslationY != translationY) {
5932 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005933 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07005934 mTranslationY = translationY;
5935 mMatrixDirty = true;
5936 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005937 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07005938 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005939 }
5940
5941 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 * Hit rectangle in parent's coordinates
5943 *
5944 * @param outRect The hit rectangle of the view.
5945 */
5946 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07005947 updateMatrix();
5948 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005949 outRect.set(mLeft, mTop, mRight, mBottom);
5950 } else {
5951 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07005952 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07005953 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07005954 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
5955 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07005956 }
5957 }
5958
5959 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07005960 * Determines whether the given point, in local coordinates is inside the view.
5961 */
5962 /*package*/ final boolean pointInView(float localX, float localY) {
5963 return localX >= 0 && localX < (mRight - mLeft)
5964 && localY >= 0 && localY < (mBottom - mTop);
5965 }
5966
5967 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005968 * Utility method to determine whether the given point, in local coordinates,
5969 * is inside the view, where the area of the view is expanded by the slop factor.
5970 * This method is called while processing touch-move events to determine if the event
5971 * is still within the view.
5972 */
5973 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07005974 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07005975 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 }
5977
5978 /**
5979 * When a view has focus and the user navigates away from it, the next view is searched for
5980 * starting from the rectangle filled in by this method.
5981 *
5982 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
5983 * view maintains some idea of internal selection, such as a cursor, or a selected row
5984 * or column, you should override this method and fill in a more specific rectangle.
5985 *
5986 * @param r The rectangle to fill in, in this view's coordinates.
5987 */
5988 public void getFocusedRect(Rect r) {
5989 getDrawingRect(r);
5990 }
5991
5992 /**
5993 * If some part of this view is not clipped by any of its parents, then
5994 * return that area in r in global (root) coordinates. To convert r to local
5995 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
5996 * -globalOffset.y)) If the view is completely clipped or translated out,
5997 * return false.
5998 *
5999 * @param r If true is returned, r holds the global coordinates of the
6000 * visible portion of this view.
6001 * @param globalOffset If true is returned, globalOffset holds the dx,dy
6002 * between this view and its root. globalOffet may be null.
6003 * @return true if r is non-empty (i.e. part of the view is visible at the
6004 * root level.
6005 */
6006 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6007 int width = mRight - mLeft;
6008 int height = mBottom - mTop;
6009 if (width > 0 && height > 0) {
6010 r.set(0, 0, width, height);
6011 if (globalOffset != null) {
6012 globalOffset.set(-mScrollX, -mScrollY);
6013 }
6014 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6015 }
6016 return false;
6017 }
6018
6019 public final boolean getGlobalVisibleRect(Rect r) {
6020 return getGlobalVisibleRect(r, null);
6021 }
6022
6023 public final boolean getLocalVisibleRect(Rect r) {
6024 Point offset = new Point();
6025 if (getGlobalVisibleRect(r, offset)) {
6026 r.offset(-offset.x, -offset.y); // make r local
6027 return true;
6028 }
6029 return false;
6030 }
6031
6032 /**
6033 * Offset this view's vertical location by the specified number of pixels.
6034 *
6035 * @param offset the number of pixels to offset the view by
6036 */
6037 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006038 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006039 updateMatrix();
6040 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006041 final ViewParent p = mParent;
6042 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006043 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006044 int minTop;
6045 int maxBottom;
6046 int yLoc;
6047 if (offset < 0) {
6048 minTop = mTop + offset;
6049 maxBottom = mBottom;
6050 yLoc = offset;
6051 } else {
6052 minTop = mTop;
6053 maxBottom = mBottom + offset;
6054 yLoc = 0;
6055 }
6056 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6057 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006058 }
6059 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006060 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006061 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006062
Chet Haasec3aa3612010-06-17 08:50:37 -07006063 mTop += offset;
6064 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006065
Chet Haasec3aa3612010-06-17 08:50:37 -07006066 if (!mMatrixIsIdentity) {
6067 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006068 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006069 }
6070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 }
6072
6073 /**
6074 * Offset this view's horizontal location by the specified amount of pixels.
6075 *
6076 * @param offset the numer of pixels to offset the view by
6077 */
6078 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006079 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006080 updateMatrix();
6081 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006082 final ViewParent p = mParent;
6083 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006084 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006085 int minLeft;
6086 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006087 if (offset < 0) {
6088 minLeft = mLeft + offset;
6089 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006090 } else {
6091 minLeft = mLeft;
6092 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006093 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006094 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07006095 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006096 }
6097 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006098 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006099 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006100
Chet Haasec3aa3612010-06-17 08:50:37 -07006101 mLeft += offset;
6102 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006103
Chet Haasec3aa3612010-06-17 08:50:37 -07006104 if (!mMatrixIsIdentity) {
6105 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006106 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006107 }
6108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 }
6110
6111 /**
6112 * Get the LayoutParams associated with this view. All views should have
6113 * layout parameters. These supply parameters to the <i>parent</i> of this
6114 * view specifying how it should be arranged. There are many subclasses of
6115 * ViewGroup.LayoutParams, and these correspond to the different subclasses
6116 * of ViewGroup that are responsible for arranging their children.
6117 * @return The LayoutParams associated with this view
6118 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07006119 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 public ViewGroup.LayoutParams getLayoutParams() {
6121 return mLayoutParams;
6122 }
6123
6124 /**
6125 * Set the layout parameters associated with this view. These supply
6126 * parameters to the <i>parent</i> of this view specifying how it should be
6127 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6128 * correspond to the different subclasses of ViewGroup that are responsible
6129 * for arranging their children.
6130 *
6131 * @param params the layout parameters for this view
6132 */
6133 public void setLayoutParams(ViewGroup.LayoutParams params) {
6134 if (params == null) {
6135 throw new NullPointerException("params == null");
6136 }
6137 mLayoutParams = params;
6138 requestLayout();
6139 }
6140
6141 /**
6142 * Set the scrolled position of your view. This will cause a call to
6143 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6144 * invalidated.
6145 * @param x the x position to scroll to
6146 * @param y the y position to scroll to
6147 */
6148 public void scrollTo(int x, int y) {
6149 if (mScrollX != x || mScrollY != y) {
6150 int oldX = mScrollX;
6151 int oldY = mScrollY;
6152 mScrollX = x;
6153 mScrollY = y;
6154 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006155 if (!awakenScrollBars()) {
6156 invalidate();
6157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 }
6159 }
6160
6161 /**
6162 * Move the scrolled position of your view. This will cause a call to
6163 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6164 * invalidated.
6165 * @param x the amount of pixels to scroll by horizontally
6166 * @param y the amount of pixels to scroll by vertically
6167 */
6168 public void scrollBy(int x, int y) {
6169 scrollTo(mScrollX + x, mScrollY + y);
6170 }
6171
6172 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006173 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6174 * animation to fade the scrollbars out after a default delay. If a subclass
6175 * provides animated scrolling, the start delay should equal the duration
6176 * of the scrolling animation.</p>
6177 *
6178 * <p>The animation starts only if at least one of the scrollbars is
6179 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6180 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6181 * this method returns true, and false otherwise. If the animation is
6182 * started, this method calls {@link #invalidate()}; in that case the
6183 * caller should not call {@link #invalidate()}.</p>
6184 *
6185 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006186 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006187 *
6188 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6189 * and {@link #scrollTo(int, int)}.</p>
6190 *
6191 * @return true if the animation is played, false otherwise
6192 *
6193 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006194 * @see #scrollBy(int, int)
6195 * @see #scrollTo(int, int)
6196 * @see #isHorizontalScrollBarEnabled()
6197 * @see #isVerticalScrollBarEnabled()
6198 * @see #setHorizontalScrollBarEnabled(boolean)
6199 * @see #setVerticalScrollBarEnabled(boolean)
6200 */
6201 protected boolean awakenScrollBars() {
6202 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006203 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006204 }
6205
6206 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006207 * Trigger the scrollbars to draw.
6208 * This method differs from awakenScrollBars() only in its default duration.
6209 * initialAwakenScrollBars() will show the scroll bars for longer than
6210 * usual to give the user more of a chance to notice them.
6211 *
6212 * @return true if the animation is played, false otherwise.
6213 */
6214 private boolean initialAwakenScrollBars() {
6215 return mScrollCache != null &&
6216 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6217 }
6218
6219 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006220 * <p>
6221 * Trigger the scrollbars to draw. When invoked this method starts an
6222 * animation to fade the scrollbars out after a fixed delay. If a subclass
6223 * provides animated scrolling, the start delay should equal the duration of
6224 * the scrolling animation.
6225 * </p>
6226 *
6227 * <p>
6228 * The animation starts only if at least one of the scrollbars is enabled,
6229 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6230 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6231 * this method returns true, and false otherwise. If the animation is
6232 * started, this method calls {@link #invalidate()}; in that case the caller
6233 * should not call {@link #invalidate()}.
6234 * </p>
6235 *
6236 * <p>
6237 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006238 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006239 * </p>
6240 *
6241 * @param startDelay the delay, in milliseconds, after which the animation
6242 * should start; when the delay is 0, the animation starts
6243 * immediately
6244 * @return true if the animation is played, false otherwise
6245 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006246 * @see #scrollBy(int, int)
6247 * @see #scrollTo(int, int)
6248 * @see #isHorizontalScrollBarEnabled()
6249 * @see #isVerticalScrollBarEnabled()
6250 * @see #setHorizontalScrollBarEnabled(boolean)
6251 * @see #setVerticalScrollBarEnabled(boolean)
6252 */
6253 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006254 return awakenScrollBars(startDelay, true);
6255 }
6256
6257 /**
6258 * <p>
6259 * Trigger the scrollbars to draw. When invoked this method starts an
6260 * animation to fade the scrollbars out after a fixed delay. If a subclass
6261 * provides animated scrolling, the start delay should equal the duration of
6262 * the scrolling animation.
6263 * </p>
6264 *
6265 * <p>
6266 * The animation starts only if at least one of the scrollbars is enabled,
6267 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6268 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6269 * this method returns true, and false otherwise. If the animation is
6270 * started, this method calls {@link #invalidate()} if the invalidate parameter
6271 * is set to true; in that case the caller
6272 * should not call {@link #invalidate()}.
6273 * </p>
6274 *
6275 * <p>
6276 * This method should be invoked everytime a subclass directly updates the
6277 * scroll parameters.
6278 * </p>
6279 *
6280 * @param startDelay the delay, in milliseconds, after which the animation
6281 * should start; when the delay is 0, the animation starts
6282 * immediately
6283 *
6284 * @param invalidate Wheter this method should call invalidate
6285 *
6286 * @return true if the animation is played, false otherwise
6287 *
6288 * @see #scrollBy(int, int)
6289 * @see #scrollTo(int, int)
6290 * @see #isHorizontalScrollBarEnabled()
6291 * @see #isVerticalScrollBarEnabled()
6292 * @see #setHorizontalScrollBarEnabled(boolean)
6293 * @see #setVerticalScrollBarEnabled(boolean)
6294 */
6295 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006296 final ScrollabilityCache scrollCache = mScrollCache;
6297
6298 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6299 return false;
6300 }
6301
6302 if (scrollCache.scrollBar == null) {
6303 scrollCache.scrollBar = new ScrollBarDrawable();
6304 }
6305
6306 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6307
Mike Cleron290947b2009-09-29 18:34:32 -07006308 if (invalidate) {
6309 // Invalidate to show the scrollbars
6310 invalidate();
6311 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006312
6313 if (scrollCache.state == ScrollabilityCache.OFF) {
6314 // FIXME: this is copied from WindowManagerService.
6315 // We should get this value from the system when it
6316 // is possible to do so.
6317 final int KEY_REPEAT_FIRST_DELAY = 750;
6318 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6319 }
6320
6321 // Tell mScrollCache when we should start fading. This may
6322 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006323 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006324 scrollCache.fadeStartTime = fadeStartTime;
6325 scrollCache.state = ScrollabilityCache.ON;
6326
6327 // Schedule our fader to run, unscheduling any old ones first
6328 if (mAttachInfo != null) {
6329 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6330 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6331 }
6332
6333 return true;
6334 }
6335
6336 return false;
6337 }
6338
6339 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 * Mark the the area defined by dirty as needing to be drawn. If the view is
6341 * visible, {@link #onDraw} will be called at some point in the future.
6342 * This must be called from a UI thread. To call from a non-UI thread, call
6343 * {@link #postInvalidate()}.
6344 *
6345 * WARNING: This method is destructive to dirty.
6346 * @param dirty the rectangle representing the bounds of the dirty region
6347 */
6348 public void invalidate(Rect dirty) {
6349 if (ViewDebug.TRACE_HIERARCHY) {
6350 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6351 }
6352
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006353 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6354 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6356 final ViewParent p = mParent;
6357 final AttachInfo ai = mAttachInfo;
6358 if (p != null && ai != null) {
6359 final int scrollX = mScrollX;
6360 final int scrollY = mScrollY;
6361 final Rect r = ai.mTmpInvalRect;
6362 r.set(dirty.left - scrollX, dirty.top - scrollY,
6363 dirty.right - scrollX, dirty.bottom - scrollY);
6364 mParent.invalidateChild(this, r);
6365 }
6366 }
6367 }
6368
6369 /**
6370 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6371 * The coordinates of the dirty rect are relative to the view.
6372 * If the view is visible, {@link #onDraw} will be called at some point
6373 * in the future. This must be called from a UI thread. To call
6374 * from a non-UI thread, call {@link #postInvalidate()}.
6375 * @param l the left position of the dirty region
6376 * @param t the top position of the dirty region
6377 * @param r the right position of the dirty region
6378 * @param b the bottom position of the dirty region
6379 */
6380 public void invalidate(int l, int t, int r, int b) {
6381 if (ViewDebug.TRACE_HIERARCHY) {
6382 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6383 }
6384
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006385 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6386 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6388 final ViewParent p = mParent;
6389 final AttachInfo ai = mAttachInfo;
6390 if (p != null && ai != null && l < r && t < b) {
6391 final int scrollX = mScrollX;
6392 final int scrollY = mScrollY;
6393 final Rect tmpr = ai.mTmpInvalRect;
6394 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6395 p.invalidateChild(this, tmpr);
6396 }
6397 }
6398 }
6399
6400 /**
6401 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6402 * be called at some point in the future. This must be called from a
6403 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6404 */
6405 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006406 invalidate(true);
6407 }
6408
6409 /**
6410 * This is where the invalidate() work actually happens. A full invalidate()
6411 * causes the drawing cache to be invalidated, but this function can be called with
6412 * invalidateCache set to false to skip that invalidation step for cases that do not
6413 * need it (for example, a component that remains at the same dimensions with the same
6414 * content).
6415 *
6416 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6417 * well. This is usually true for a full invalidate, but may be set to false if the
6418 * View's contents or dimensions have not changed.
6419 */
6420 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 if (ViewDebug.TRACE_HIERARCHY) {
6422 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6423 }
6424
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006425 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6426 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID)) {
Chet Haaseed032702010-10-01 14:05:54 -07006427 mPrivateFlags &= ~DRAWN;
6428 if (invalidateCache) {
6429 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006432 final ViewParent p = mParent;
Michael Jurkaebefea42010-11-15 16:04:01 -08006433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 if (p != null && ai != null) {
6435 final Rect r = ai.mTmpInvalRect;
6436 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6437 // Don't call invalidate -- we don't want to internally scroll
6438 // our own bounds
6439 p.invalidateChild(this, r);
6440 }
6441 }
6442 }
6443
6444 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006445 * Indicates whether this View is opaque. An opaque View guarantees that it will
6446 * draw all the pixels overlapping its bounds using a fully opaque color.
6447 *
6448 * Subclasses of View should override this method whenever possible to indicate
6449 * whether an instance is opaque. Opaque Views are treated in a special way by
6450 * the View hierarchy, possibly allowing it to perform optimizations during
6451 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006452 *
Romain Guy24443ea2009-05-11 11:56:30 -07006453 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006454 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006455 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006456 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006457 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6458 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006459 }
6460
6461 private void computeOpaqueFlags() {
6462 // Opaque if:
6463 // - Has a background
6464 // - Background is opaque
6465 // - Doesn't have scrollbars or scrollbars are inside overlay
6466
6467 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6468 mPrivateFlags |= OPAQUE_BACKGROUND;
6469 } else {
6470 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6471 }
6472
6473 final int flags = mViewFlags;
6474 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6475 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6476 mPrivateFlags |= OPAQUE_SCROLLBARS;
6477 } else {
6478 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6479 }
6480 }
6481
6482 /**
6483 * @hide
6484 */
6485 protected boolean hasOpaqueScrollbars() {
6486 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006487 }
6488
6489 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 * @return A handler associated with the thread running the View. This
6491 * handler can be used to pump events in the UI events queue.
6492 */
6493 public Handler getHandler() {
6494 if (mAttachInfo != null) {
6495 return mAttachInfo.mHandler;
6496 }
6497 return null;
6498 }
6499
6500 /**
6501 * Causes the Runnable to be added to the message queue.
6502 * The runnable will be run on the user interface thread.
6503 *
6504 * @param action The Runnable that will be executed.
6505 *
6506 * @return Returns true if the Runnable was successfully placed in to the
6507 * message queue. Returns false on failure, usually because the
6508 * looper processing the message queue is exiting.
6509 */
6510 public boolean post(Runnable action) {
6511 Handler handler;
6512 if (mAttachInfo != null) {
6513 handler = mAttachInfo.mHandler;
6514 } else {
6515 // Assume that post will succeed later
6516 ViewRoot.getRunQueue().post(action);
6517 return true;
6518 }
6519
6520 return handler.post(action);
6521 }
6522
6523 /**
6524 * Causes the Runnable to be added to the message queue, to be run
6525 * after the specified amount of time elapses.
6526 * The runnable will be run on the user interface thread.
6527 *
6528 * @param action The Runnable that will be executed.
6529 * @param delayMillis The delay (in milliseconds) until the Runnable
6530 * will be executed.
6531 *
6532 * @return true if the Runnable was successfully placed in to the
6533 * message queue. Returns false on failure, usually because the
6534 * looper processing the message queue is exiting. Note that a
6535 * result of true does not mean the Runnable will be processed --
6536 * if the looper is quit before the delivery time of the message
6537 * occurs then the message will be dropped.
6538 */
6539 public boolean postDelayed(Runnable action, long delayMillis) {
6540 Handler handler;
6541 if (mAttachInfo != null) {
6542 handler = mAttachInfo.mHandler;
6543 } else {
6544 // Assume that post will succeed later
6545 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6546 return true;
6547 }
6548
6549 return handler.postDelayed(action, delayMillis);
6550 }
6551
6552 /**
6553 * Removes the specified Runnable from the message queue.
6554 *
6555 * @param action The Runnable to remove from the message handling queue
6556 *
6557 * @return true if this view could ask the Handler to remove the Runnable,
6558 * false otherwise. When the returned value is true, the Runnable
6559 * may or may not have been actually removed from the message queue
6560 * (for instance, if the Runnable was not in the queue already.)
6561 */
6562 public boolean removeCallbacks(Runnable action) {
6563 Handler handler;
6564 if (mAttachInfo != null) {
6565 handler = mAttachInfo.mHandler;
6566 } else {
6567 // Assume that post will succeed later
6568 ViewRoot.getRunQueue().removeCallbacks(action);
6569 return true;
6570 }
6571
6572 handler.removeCallbacks(action);
6573 return true;
6574 }
6575
6576 /**
6577 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6578 * Use this to invalidate the View from a non-UI thread.
6579 *
6580 * @see #invalidate()
6581 */
6582 public void postInvalidate() {
6583 postInvalidateDelayed(0);
6584 }
6585
6586 /**
6587 * Cause an invalidate of the specified area to happen on a subsequent cycle
6588 * through the event loop. Use this to invalidate the View from a non-UI thread.
6589 *
6590 * @param left The left coordinate of the rectangle to invalidate.
6591 * @param top The top coordinate of the rectangle to invalidate.
6592 * @param right The right coordinate of the rectangle to invalidate.
6593 * @param bottom The bottom coordinate of the rectangle to invalidate.
6594 *
6595 * @see #invalidate(int, int, int, int)
6596 * @see #invalidate(Rect)
6597 */
6598 public void postInvalidate(int left, int top, int right, int bottom) {
6599 postInvalidateDelayed(0, left, top, right, bottom);
6600 }
6601
6602 /**
6603 * Cause an invalidate to happen on a subsequent cycle through the event
6604 * loop. Waits for the specified amount of time.
6605 *
6606 * @param delayMilliseconds the duration in milliseconds to delay the
6607 * invalidation by
6608 */
6609 public void postInvalidateDelayed(long delayMilliseconds) {
6610 // We try only with the AttachInfo because there's no point in invalidating
6611 // if we are not attached to our window
6612 if (mAttachInfo != null) {
6613 Message msg = Message.obtain();
6614 msg.what = AttachInfo.INVALIDATE_MSG;
6615 msg.obj = this;
6616 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6617 }
6618 }
6619
6620 /**
6621 * Cause an invalidate of the specified area to happen on a subsequent cycle
6622 * through the event loop. Waits for the specified amount of time.
6623 *
6624 * @param delayMilliseconds the duration in milliseconds to delay the
6625 * invalidation by
6626 * @param left The left coordinate of the rectangle to invalidate.
6627 * @param top The top coordinate of the rectangle to invalidate.
6628 * @param right The right coordinate of the rectangle to invalidate.
6629 * @param bottom The bottom coordinate of the rectangle to invalidate.
6630 */
6631 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6632 int right, int bottom) {
6633
6634 // We try only with the AttachInfo because there's no point in invalidating
6635 // if we are not attached to our window
6636 if (mAttachInfo != null) {
6637 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6638 info.target = this;
6639 info.left = left;
6640 info.top = top;
6641 info.right = right;
6642 info.bottom = bottom;
6643
6644 final Message msg = Message.obtain();
6645 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6646 msg.obj = info;
6647 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6648 }
6649 }
6650
6651 /**
6652 * Called by a parent to request that a child update its values for mScrollX
6653 * and mScrollY if necessary. This will typically be done if the child is
6654 * animating a scroll using a {@link android.widget.Scroller Scroller}
6655 * object.
6656 */
6657 public void computeScroll() {
6658 }
6659
6660 /**
6661 * <p>Indicate whether the horizontal edges are faded when the view is
6662 * scrolled horizontally.</p>
6663 *
6664 * @return true if the horizontal edges should are faded on scroll, false
6665 * otherwise
6666 *
6667 * @see #setHorizontalFadingEdgeEnabled(boolean)
6668 * @attr ref android.R.styleable#View_fadingEdge
6669 */
6670 public boolean isHorizontalFadingEdgeEnabled() {
6671 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6672 }
6673
6674 /**
6675 * <p>Define whether the horizontal edges should be faded when this view
6676 * is scrolled horizontally.</p>
6677 *
6678 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6679 * be faded when the view is scrolled
6680 * horizontally
6681 *
6682 * @see #isHorizontalFadingEdgeEnabled()
6683 * @attr ref android.R.styleable#View_fadingEdge
6684 */
6685 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6686 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6687 if (horizontalFadingEdgeEnabled) {
6688 initScrollCache();
6689 }
6690
6691 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6692 }
6693 }
6694
6695 /**
6696 * <p>Indicate whether the vertical edges are faded when the view is
6697 * scrolled horizontally.</p>
6698 *
6699 * @return true if the vertical edges should are faded on scroll, false
6700 * otherwise
6701 *
6702 * @see #setVerticalFadingEdgeEnabled(boolean)
6703 * @attr ref android.R.styleable#View_fadingEdge
6704 */
6705 public boolean isVerticalFadingEdgeEnabled() {
6706 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6707 }
6708
6709 /**
6710 * <p>Define whether the vertical edges should be faded when this view
6711 * is scrolled vertically.</p>
6712 *
6713 * @param verticalFadingEdgeEnabled true if the vertical edges should
6714 * be faded when the view is scrolled
6715 * vertically
6716 *
6717 * @see #isVerticalFadingEdgeEnabled()
6718 * @attr ref android.R.styleable#View_fadingEdge
6719 */
6720 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6721 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6722 if (verticalFadingEdgeEnabled) {
6723 initScrollCache();
6724 }
6725
6726 mViewFlags ^= FADING_EDGE_VERTICAL;
6727 }
6728 }
6729
6730 /**
6731 * Returns the strength, or intensity, of the top faded edge. The strength is
6732 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6733 * returns 0.0 or 1.0 but no value in between.
6734 *
6735 * Subclasses should override this method to provide a smoother fade transition
6736 * when scrolling occurs.
6737 *
6738 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6739 */
6740 protected float getTopFadingEdgeStrength() {
6741 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6742 }
6743
6744 /**
6745 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6746 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6747 * returns 0.0 or 1.0 but no value in between.
6748 *
6749 * Subclasses should override this method to provide a smoother fade transition
6750 * when scrolling occurs.
6751 *
6752 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6753 */
6754 protected float getBottomFadingEdgeStrength() {
6755 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6756 computeVerticalScrollRange() ? 1.0f : 0.0f;
6757 }
6758
6759 /**
6760 * Returns the strength, or intensity, of the left faded edge. The strength is
6761 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6762 * returns 0.0 or 1.0 but no value in between.
6763 *
6764 * Subclasses should override this method to provide a smoother fade transition
6765 * when scrolling occurs.
6766 *
6767 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6768 */
6769 protected float getLeftFadingEdgeStrength() {
6770 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6771 }
6772
6773 /**
6774 * Returns the strength, or intensity, of the right faded edge. The strength is
6775 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6776 * returns 0.0 or 1.0 but no value in between.
6777 *
6778 * Subclasses should override this method to provide a smoother fade transition
6779 * when scrolling occurs.
6780 *
6781 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6782 */
6783 protected float getRightFadingEdgeStrength() {
6784 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6785 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6786 }
6787
6788 /**
6789 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6790 * scrollbar is not drawn by default.</p>
6791 *
6792 * @return true if the horizontal scrollbar should be painted, false
6793 * otherwise
6794 *
6795 * @see #setHorizontalScrollBarEnabled(boolean)
6796 */
6797 public boolean isHorizontalScrollBarEnabled() {
6798 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6799 }
6800
6801 /**
6802 * <p>Define whether the horizontal scrollbar should be drawn or not. The
6803 * scrollbar is not drawn by default.</p>
6804 *
6805 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
6806 * be painted
6807 *
6808 * @see #isHorizontalScrollBarEnabled()
6809 */
6810 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
6811 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
6812 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006813 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006814 recomputePadding();
6815 }
6816 }
6817
6818 /**
6819 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
6820 * scrollbar is not drawn by default.</p>
6821 *
6822 * @return true if the vertical scrollbar should be painted, false
6823 * otherwise
6824 *
6825 * @see #setVerticalScrollBarEnabled(boolean)
6826 */
6827 public boolean isVerticalScrollBarEnabled() {
6828 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
6829 }
6830
6831 /**
6832 * <p>Define whether the vertical scrollbar should be drawn or not. The
6833 * scrollbar is not drawn by default.</p>
6834 *
6835 * @param verticalScrollBarEnabled true if the vertical scrollbar should
6836 * be painted
6837 *
6838 * @see #isVerticalScrollBarEnabled()
6839 */
6840 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
6841 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
6842 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006843 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844 recomputePadding();
6845 }
6846 }
6847
6848 private void recomputePadding() {
6849 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
6850 }
Mike Cleronfe81d382009-09-28 14:22:16 -07006851
6852 /**
6853 * Define whether scrollbars will fade when the view is not scrolling.
6854 *
6855 * @param fadeScrollbars wheter to enable fading
6856 *
6857 */
6858 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
6859 initScrollCache();
6860 final ScrollabilityCache scrollabilityCache = mScrollCache;
6861 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07006862 if (fadeScrollbars) {
6863 scrollabilityCache.state = ScrollabilityCache.OFF;
6864 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07006865 scrollabilityCache.state = ScrollabilityCache.ON;
6866 }
6867 }
6868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006869 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07006870 *
6871 * Returns true if scrollbars will fade when this view is not scrolling
6872 *
6873 * @return true if scrollbar fading is enabled
6874 */
6875 public boolean isScrollbarFadingEnabled() {
6876 return mScrollCache != null && mScrollCache.fadeScrollBars;
6877 }
6878
6879 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006880 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
6881 * inset. When inset, they add to the padding of the view. And the scrollbars
6882 * can be drawn inside the padding area or on the edge of the view. For example,
6883 * if a view has a background drawable and you want to draw the scrollbars
6884 * inside the padding specified by the drawable, you can use
6885 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
6886 * appear at the edge of the view, ignoring the padding, then you can use
6887 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
6888 * @param style the style of the scrollbars. Should be one of
6889 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
6890 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
6891 * @see #SCROLLBARS_INSIDE_OVERLAY
6892 * @see #SCROLLBARS_INSIDE_INSET
6893 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6894 * @see #SCROLLBARS_OUTSIDE_INSET
6895 */
6896 public void setScrollBarStyle(int style) {
6897 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
6898 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07006899 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006900 recomputePadding();
6901 }
6902 }
6903
6904 /**
6905 * <p>Returns the current scrollbar style.</p>
6906 * @return the current scrollbar style
6907 * @see #SCROLLBARS_INSIDE_OVERLAY
6908 * @see #SCROLLBARS_INSIDE_INSET
6909 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6910 * @see #SCROLLBARS_OUTSIDE_INSET
6911 */
6912 public int getScrollBarStyle() {
6913 return mViewFlags & SCROLLBARS_STYLE_MASK;
6914 }
6915
6916 /**
6917 * <p>Compute the horizontal range that the horizontal scrollbar
6918 * represents.</p>
6919 *
6920 * <p>The range is expressed in arbitrary units that must be the same as the
6921 * units used by {@link #computeHorizontalScrollExtent()} and
6922 * {@link #computeHorizontalScrollOffset()}.</p>
6923 *
6924 * <p>The default range is the drawing width of this view.</p>
6925 *
6926 * @return the total horizontal range represented by the horizontal
6927 * scrollbar
6928 *
6929 * @see #computeHorizontalScrollExtent()
6930 * @see #computeHorizontalScrollOffset()
6931 * @see android.widget.ScrollBarDrawable
6932 */
6933 protected int computeHorizontalScrollRange() {
6934 return getWidth();
6935 }
6936
6937 /**
6938 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
6939 * within the horizontal range. This value is used to compute the position
6940 * of the thumb within the scrollbar's track.</p>
6941 *
6942 * <p>The range is expressed in arbitrary units that must be the same as the
6943 * units used by {@link #computeHorizontalScrollRange()} and
6944 * {@link #computeHorizontalScrollExtent()}.</p>
6945 *
6946 * <p>The default offset is the scroll offset of this view.</p>
6947 *
6948 * @return the horizontal offset of the scrollbar's thumb
6949 *
6950 * @see #computeHorizontalScrollRange()
6951 * @see #computeHorizontalScrollExtent()
6952 * @see android.widget.ScrollBarDrawable
6953 */
6954 protected int computeHorizontalScrollOffset() {
6955 return mScrollX;
6956 }
6957
6958 /**
6959 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
6960 * within the horizontal range. This value is used to compute the length
6961 * of the thumb within the scrollbar's track.</p>
6962 *
6963 * <p>The range is expressed in arbitrary units that must be the same as the
6964 * units used by {@link #computeHorizontalScrollRange()} and
6965 * {@link #computeHorizontalScrollOffset()}.</p>
6966 *
6967 * <p>The default extent is the drawing width of this view.</p>
6968 *
6969 * @return the horizontal extent of the scrollbar's thumb
6970 *
6971 * @see #computeHorizontalScrollRange()
6972 * @see #computeHorizontalScrollOffset()
6973 * @see android.widget.ScrollBarDrawable
6974 */
6975 protected int computeHorizontalScrollExtent() {
6976 return getWidth();
6977 }
6978
6979 /**
6980 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
6981 *
6982 * <p>The range is expressed in arbitrary units that must be the same as the
6983 * units used by {@link #computeVerticalScrollExtent()} and
6984 * {@link #computeVerticalScrollOffset()}.</p>
6985 *
6986 * @return the total vertical range represented by the vertical scrollbar
6987 *
6988 * <p>The default range is the drawing height of this view.</p>
6989 *
6990 * @see #computeVerticalScrollExtent()
6991 * @see #computeVerticalScrollOffset()
6992 * @see android.widget.ScrollBarDrawable
6993 */
6994 protected int computeVerticalScrollRange() {
6995 return getHeight();
6996 }
6997
6998 /**
6999 * <p>Compute the vertical offset of the vertical scrollbar's thumb
7000 * within the horizontal range. This value is used to compute the position
7001 * of the thumb within the scrollbar's track.</p>
7002 *
7003 * <p>The range is expressed in arbitrary units that must be the same as the
7004 * units used by {@link #computeVerticalScrollRange()} and
7005 * {@link #computeVerticalScrollExtent()}.</p>
7006 *
7007 * <p>The default offset is the scroll offset of this view.</p>
7008 *
7009 * @return the vertical offset of the scrollbar's thumb
7010 *
7011 * @see #computeVerticalScrollRange()
7012 * @see #computeVerticalScrollExtent()
7013 * @see android.widget.ScrollBarDrawable
7014 */
7015 protected int computeVerticalScrollOffset() {
7016 return mScrollY;
7017 }
7018
7019 /**
7020 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7021 * within the vertical range. This value is used to compute the length
7022 * of the thumb within the scrollbar's track.</p>
7023 *
7024 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08007025 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007026 * {@link #computeVerticalScrollOffset()}.</p>
7027 *
7028 * <p>The default extent is the drawing height of this view.</p>
7029 *
7030 * @return the vertical extent of the scrollbar's thumb
7031 *
7032 * @see #computeVerticalScrollRange()
7033 * @see #computeVerticalScrollOffset()
7034 * @see android.widget.ScrollBarDrawable
7035 */
7036 protected int computeVerticalScrollExtent() {
7037 return getHeight();
7038 }
7039
7040 /**
7041 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7042 * scrollbars are painted only if they have been awakened first.</p>
7043 *
7044 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07007045 *
7046 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007047 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08007048 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007049 // scrollbars are drawn only when the animation is running
7050 final ScrollabilityCache cache = mScrollCache;
7051 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007052
7053 int state = cache.state;
7054
7055 if (state == ScrollabilityCache.OFF) {
7056 return;
7057 }
7058
7059 boolean invalidate = false;
7060
7061 if (state == ScrollabilityCache.FADING) {
7062 // We're fading -- get our fade interpolation
7063 if (cache.interpolatorValues == null) {
7064 cache.interpolatorValues = new float[1];
7065 }
7066
7067 float[] values = cache.interpolatorValues;
7068
7069 // Stops the animation if we're done
7070 if (cache.scrollBarInterpolator.timeToValues(values) ==
7071 Interpolator.Result.FREEZE_END) {
7072 cache.state = ScrollabilityCache.OFF;
7073 } else {
7074 cache.scrollBar.setAlpha(Math.round(values[0]));
7075 }
7076
7077 // This will make the scroll bars inval themselves after
7078 // drawing. We only want this when we're fading so that
7079 // we prevent excessive redraws
7080 invalidate = true;
7081 } else {
7082 // We're just on -- but we may have been fading before so
7083 // reset alpha
7084 cache.scrollBar.setAlpha(255);
7085 }
7086
7087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007088 final int viewFlags = mViewFlags;
7089
7090 final boolean drawHorizontalScrollBar =
7091 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7092 final boolean drawVerticalScrollBar =
7093 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7094 && !isVerticalScrollBarHidden();
7095
7096 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7097 final int width = mRight - mLeft;
7098 final int height = mBottom - mTop;
7099
7100 final ScrollBarDrawable scrollBar = cache.scrollBar;
7101 int size = scrollBar.getSize(false);
7102 if (size <= 0) {
7103 size = cache.scrollBarSize;
7104 }
7105
Mike Reede8853fc2009-09-04 14:01:48 -04007106 final int scrollX = mScrollX;
7107 final int scrollY = mScrollY;
7108 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7109
Mike Cleronf116bf82009-09-27 19:14:12 -07007110 int left, top, right, bottom;
7111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007112 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007113 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04007114 computeHorizontalScrollOffset(),
7115 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04007116 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07007117 getVerticalScrollbarWidth() : 0;
7118 top = scrollY + height - size - (mUserPaddingBottom & inside);
7119 left = scrollX + (mPaddingLeft & inside);
7120 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7121 bottom = top + size;
7122 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7123 if (invalidate) {
7124 invalidate(left, top, right, bottom);
7125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007126 }
7127
7128 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04007129 scrollBar.setParameters(computeVerticalScrollRange(),
7130 computeVerticalScrollOffset(),
7131 computeVerticalScrollExtent(), true);
7132 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07007133 left = scrollX + width - size - (mUserPaddingRight & inside);
7134 top = scrollY + (mPaddingTop & inside);
7135 right = left + size;
7136 bottom = scrollY + height - (mUserPaddingBottom & inside);
7137 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7138 if (invalidate) {
7139 invalidate(left, top, right, bottom);
7140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007141 }
7142 }
7143 }
7144 }
Romain Guy8506ab42009-06-11 17:35:47 -07007145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007146 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007147 * 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 -08007148 * FastScroller is visible.
7149 * @return whether to temporarily hide the vertical scrollbar
7150 * @hide
7151 */
7152 protected boolean isVerticalScrollBarHidden() {
7153 return false;
7154 }
7155
7156 /**
7157 * <p>Draw the horizontal scrollbar if
7158 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7159 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007160 * @param canvas the canvas on which to draw the scrollbar
7161 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007162 *
7163 * @see #isHorizontalScrollBarEnabled()
7164 * @see #computeHorizontalScrollRange()
7165 * @see #computeHorizontalScrollExtent()
7166 * @see #computeHorizontalScrollOffset()
7167 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007168 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007169 */
Romain Guy8fb95422010-08-17 18:38:51 -07007170 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7171 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007172 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007173 scrollBar.draw(canvas);
7174 }
Mike Reede8853fc2009-09-04 14:01:48 -04007175
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007176 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7178 * returns true.</p>
7179 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007180 * @param canvas the canvas on which to draw the scrollbar
7181 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 *
7183 * @see #isVerticalScrollBarEnabled()
7184 * @see #computeVerticalScrollRange()
7185 * @see #computeVerticalScrollExtent()
7186 * @see #computeVerticalScrollOffset()
7187 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007188 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007189 */
Romain Guy8fb95422010-08-17 18:38:51 -07007190 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7191 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007192 scrollBar.setBounds(l, t, r, b);
7193 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007194 }
7195
7196 /**
7197 * Implement this to do your drawing.
7198 *
7199 * @param canvas the canvas on which the background will be drawn
7200 */
7201 protected void onDraw(Canvas canvas) {
7202 }
7203
7204 /*
7205 * Caller is responsible for calling requestLayout if necessary.
7206 * (This allows addViewInLayout to not request a new layout.)
7207 */
7208 void assignParent(ViewParent parent) {
7209 if (mParent == null) {
7210 mParent = parent;
7211 } else if (parent == null) {
7212 mParent = null;
7213 } else {
7214 throw new RuntimeException("view " + this + " being added, but"
7215 + " it already has a parent");
7216 }
7217 }
7218
7219 /**
7220 * This is called when the view is attached to a window. At this point it
7221 * has a Surface and will start drawing. Note that this function is
7222 * guaranteed to be called before {@link #onDraw}, however it may be called
7223 * any time before the first onDraw -- including before or after
7224 * {@link #onMeasure}.
7225 *
7226 * @see #onDetachedFromWindow()
7227 */
7228 protected void onAttachedToWindow() {
7229 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7230 mParent.requestTransparentRegion(this);
7231 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007232 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7233 initialAwakenScrollBars();
7234 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007236 }
7237
7238 /**
7239 * This is called when the view is detached from a window. At this point it
7240 * no longer has a surface for drawing.
7241 *
7242 * @see #onAttachedToWindow()
7243 */
7244 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007245 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08007246 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007247 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007248 destroyDrawingCache();
7249 }
7250
7251 /**
7252 * @return The number of times this view has been attached to a window
7253 */
7254 protected int getWindowAttachCount() {
7255 return mWindowAttachCount;
7256 }
7257
7258 /**
7259 * Retrieve a unique token identifying the window this view is attached to.
7260 * @return Return the window's token for use in
7261 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7262 */
7263 public IBinder getWindowToken() {
7264 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7265 }
7266
7267 /**
7268 * Retrieve a unique token identifying the top-level "real" window of
7269 * the window that this view is attached to. That is, this is like
7270 * {@link #getWindowToken}, except if the window this view in is a panel
7271 * window (attached to another containing window), then the token of
7272 * the containing window is returned instead.
7273 *
7274 * @return Returns the associated window token, either
7275 * {@link #getWindowToken()} or the containing window's token.
7276 */
7277 public IBinder getApplicationWindowToken() {
7278 AttachInfo ai = mAttachInfo;
7279 if (ai != null) {
7280 IBinder appWindowToken = ai.mPanelParentWindowToken;
7281 if (appWindowToken == null) {
7282 appWindowToken = ai.mWindowToken;
7283 }
7284 return appWindowToken;
7285 }
7286 return null;
7287 }
7288
7289 /**
7290 * Retrieve private session object this view hierarchy is using to
7291 * communicate with the window manager.
7292 * @return the session object to communicate with the window manager
7293 */
7294 /*package*/ IWindowSession getWindowSession() {
7295 return mAttachInfo != null ? mAttachInfo.mSession : null;
7296 }
7297
7298 /**
7299 * @param info the {@link android.view.View.AttachInfo} to associated with
7300 * this view
7301 */
7302 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7303 //System.out.println("Attached! " + this);
7304 mAttachInfo = info;
7305 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007306 // We will need to evaluate the drawable state at least once.
7307 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007308 if (mFloatingTreeObserver != null) {
7309 info.mTreeObserver.merge(mFloatingTreeObserver);
7310 mFloatingTreeObserver = null;
7311 }
7312 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7313 mAttachInfo.mScrollContainers.add(this);
7314 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7315 }
7316 performCollectViewAttributes(visibility);
7317 onAttachedToWindow();
7318 int vis = info.mWindowVisibility;
7319 if (vis != GONE) {
7320 onWindowVisibilityChanged(vis);
7321 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007322 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7323 // If nobody has evaluated the drawable state yet, then do it now.
7324 refreshDrawableState();
7325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 }
7327
7328 void dispatchDetachedFromWindow() {
7329 //System.out.println("Detached! " + this);
7330 AttachInfo info = mAttachInfo;
7331 if (info != null) {
7332 int vis = info.mWindowVisibility;
7333 if (vis != GONE) {
7334 onWindowVisibilityChanged(GONE);
7335 }
7336 }
7337
7338 onDetachedFromWindow();
7339 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7340 mAttachInfo.mScrollContainers.remove(this);
7341 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7342 }
7343 mAttachInfo = null;
7344 }
7345
7346 /**
7347 * Store this view hierarchy's frozen state into the given container.
7348 *
7349 * @param container The SparseArray in which to save the view's state.
7350 *
7351 * @see #restoreHierarchyState
7352 * @see #dispatchSaveInstanceState
7353 * @see #onSaveInstanceState
7354 */
7355 public void saveHierarchyState(SparseArray<Parcelable> container) {
7356 dispatchSaveInstanceState(container);
7357 }
7358
7359 /**
7360 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7361 * May be overridden to modify how freezing happens to a view's children; for example, some
7362 * views may want to not store state for their children.
7363 *
7364 * @param container The SparseArray in which to save the view's state.
7365 *
7366 * @see #dispatchRestoreInstanceState
7367 * @see #saveHierarchyState
7368 * @see #onSaveInstanceState
7369 */
7370 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7371 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7372 mPrivateFlags &= ~SAVE_STATE_CALLED;
7373 Parcelable state = onSaveInstanceState();
7374 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7375 throw new IllegalStateException(
7376 "Derived class did not call super.onSaveInstanceState()");
7377 }
7378 if (state != null) {
7379 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7380 // + ": " + state);
7381 container.put(mID, state);
7382 }
7383 }
7384 }
7385
7386 /**
7387 * Hook allowing a view to generate a representation of its internal state
7388 * that can later be used to create a new instance with that same state.
7389 * This state should only contain information that is not persistent or can
7390 * not be reconstructed later. For example, you will never store your
7391 * current position on screen because that will be computed again when a
7392 * new instance of the view is placed in its view hierarchy.
7393 * <p>
7394 * Some examples of things you may store here: the current cursor position
7395 * in a text view (but usually not the text itself since that is stored in a
7396 * content provider or other persistent storage), the currently selected
7397 * item in a list view.
7398 *
7399 * @return Returns a Parcelable object containing the view's current dynamic
7400 * state, or null if there is nothing interesting to save. The
7401 * default implementation returns null.
7402 * @see #onRestoreInstanceState
7403 * @see #saveHierarchyState
7404 * @see #dispatchSaveInstanceState
7405 * @see #setSaveEnabled(boolean)
7406 */
7407 protected Parcelable onSaveInstanceState() {
7408 mPrivateFlags |= SAVE_STATE_CALLED;
7409 return BaseSavedState.EMPTY_STATE;
7410 }
7411
7412 /**
7413 * Restore this view hierarchy's frozen state from the given container.
7414 *
7415 * @param container The SparseArray which holds previously frozen states.
7416 *
7417 * @see #saveHierarchyState
7418 * @see #dispatchRestoreInstanceState
7419 * @see #onRestoreInstanceState
7420 */
7421 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7422 dispatchRestoreInstanceState(container);
7423 }
7424
7425 /**
7426 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7427 * children. May be overridden to modify how restoreing happens to a view's children; for
7428 * example, some views may want to not store state for their children.
7429 *
7430 * @param container The SparseArray which holds previously saved state.
7431 *
7432 * @see #dispatchSaveInstanceState
7433 * @see #restoreHierarchyState
7434 * @see #onRestoreInstanceState
7435 */
7436 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7437 if (mID != NO_ID) {
7438 Parcelable state = container.get(mID);
7439 if (state != null) {
7440 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7441 // + ": " + state);
7442 mPrivateFlags &= ~SAVE_STATE_CALLED;
7443 onRestoreInstanceState(state);
7444 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7445 throw new IllegalStateException(
7446 "Derived class did not call super.onRestoreInstanceState()");
7447 }
7448 }
7449 }
7450 }
7451
7452 /**
7453 * Hook allowing a view to re-apply a representation of its internal state that had previously
7454 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7455 * null state.
7456 *
7457 * @param state The frozen state that had previously been returned by
7458 * {@link #onSaveInstanceState}.
7459 *
7460 * @see #onSaveInstanceState
7461 * @see #restoreHierarchyState
7462 * @see #dispatchRestoreInstanceState
7463 */
7464 protected void onRestoreInstanceState(Parcelable state) {
7465 mPrivateFlags |= SAVE_STATE_CALLED;
7466 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007467 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7468 + "received " + state.getClass().toString() + " instead. This usually happens "
7469 + "when two views of different type have the same id in the same hierarchy. "
7470 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7471 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007472 }
7473 }
7474
7475 /**
7476 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7477 *
7478 * @return the drawing start time in milliseconds
7479 */
7480 public long getDrawingTime() {
7481 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7482 }
7483
7484 /**
7485 * <p>Enables or disables the duplication of the parent's state into this view. When
7486 * duplication is enabled, this view gets its drawable state from its parent rather
7487 * than from its own internal properties.</p>
7488 *
7489 * <p>Note: in the current implementation, setting this property to true after the
7490 * view was added to a ViewGroup might have no effect at all. This property should
7491 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7492 *
7493 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7494 * property is enabled, an exception will be thrown.</p>
7495 *
7496 * @param enabled True to enable duplication of the parent's drawable state, false
7497 * to disable it.
7498 *
7499 * @see #getDrawableState()
7500 * @see #isDuplicateParentStateEnabled()
7501 */
7502 public void setDuplicateParentStateEnabled(boolean enabled) {
7503 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7504 }
7505
7506 /**
7507 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7508 *
7509 * @return True if this view's drawable state is duplicated from the parent,
7510 * false otherwise
7511 *
7512 * @see #getDrawableState()
7513 * @see #setDuplicateParentStateEnabled(boolean)
7514 */
7515 public boolean isDuplicateParentStateEnabled() {
7516 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7517 }
7518
7519 /**
7520 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
7521 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
7522 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
7523 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
7524 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
7525 * null.</p>
7526 *
7527 * @param enabled true to enable the drawing cache, false otherwise
7528 *
7529 * @see #isDrawingCacheEnabled()
7530 * @see #getDrawingCache()
7531 * @see #buildDrawingCache()
7532 */
7533 public void setDrawingCacheEnabled(boolean enabled) {
7534 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
7535 }
7536
7537 /**
7538 * <p>Indicates whether the drawing cache is enabled for this view.</p>
7539 *
7540 * @return true if the drawing cache is enabled
7541 *
7542 * @see #setDrawingCacheEnabled(boolean)
7543 * @see #getDrawingCache()
7544 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07007545 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 public boolean isDrawingCacheEnabled() {
7547 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
7548 }
7549
7550 /**
Romain Guyb051e892010-09-28 19:09:36 -07007551 * <p>Returns a display list that can be used to draw this view again
7552 * without executing its draw method.</p>
7553 *
7554 * @return A DisplayList ready to replay, or null if caching is not enabled.
7555 */
7556 DisplayList getDisplayList() {
7557 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7558 return null;
7559 }
Romain Guyb051e892010-09-28 19:09:36 -07007560 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
7561 return null;
7562 }
7563
7564 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
7565 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mDisplayList == null)) {
7566
Romain Guyb051e892010-09-28 19:09:36 -07007567 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
7568
7569 final HardwareCanvas canvas = mDisplayList.start();
7570 try {
7571 int width = mRight - mLeft;
7572 int height = mBottom - mTop;
7573
7574 canvas.setViewport(width, height);
7575 canvas.onPreDraw();
7576
7577 final int restoreCount = canvas.save();
7578
Romain Guy2fe9a8f2010-10-04 20:17:01 -07007579 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07007580
7581 // Fast path for layouts with no backgrounds
7582 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7583 mPrivateFlags &= ~DIRTY_MASK;
7584 dispatchDraw(canvas);
7585 } else {
7586 draw(canvas);
7587 }
7588
7589 canvas.restoreToCount(restoreCount);
7590 } finally {
7591 canvas.onPostDraw();
7592
7593 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07007594 }
7595 }
7596
7597 return mDisplayList;
7598 }
7599
7600 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007601 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
7602 *
7603 * @return A non-scaled bitmap representing this view or null if cache is disabled.
7604 *
7605 * @see #getDrawingCache(boolean)
7606 */
7607 public Bitmap getDrawingCache() {
7608 return getDrawingCache(false);
7609 }
7610
7611 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007612 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
7613 * is null when caching is disabled. If caching is enabled and the cache is not ready,
7614 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
7615 * draw from the cache when the cache is enabled. To benefit from the cache, you must
7616 * request the drawing cache by calling this method and draw it on screen if the
7617 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007618 *
7619 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7620 * this method will create a bitmap of the same size as this view. Because this bitmap
7621 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7622 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7623 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7624 * size than the view. This implies that your application must be able to handle this
7625 * size.</p>
7626 *
7627 * @param autoScale Indicates whether the generated bitmap should be scaled based on
7628 * the current density of the screen when the application is in compatibility
7629 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007630 *
Romain Guyfbd8f692009-06-26 14:51:58 -07007631 * @return A bitmap representing this view or null if cache is disabled.
7632 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007633 * @see #setDrawingCacheEnabled(boolean)
7634 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07007635 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 * @see #destroyDrawingCache()
7637 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007638 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007639 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7640 return null;
7641 }
7642 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007643 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007644 }
Romain Guy02890fd2010-08-06 17:58:44 -07007645 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007646 }
7647
7648 /**
7649 * <p>Frees the resources used by the drawing cache. If you call
7650 * {@link #buildDrawingCache()} manually without calling
7651 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7652 * should cleanup the cache with this method afterwards.</p>
7653 *
7654 * @see #setDrawingCacheEnabled(boolean)
7655 * @see #buildDrawingCache()
7656 * @see #getDrawingCache()
7657 */
7658 public void destroyDrawingCache() {
7659 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007660 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007661 mDrawingCache = null;
7662 }
Romain Guyfbd8f692009-06-26 14:51:58 -07007663 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007664 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07007665 mUnscaledDrawingCache = null;
7666 }
Romain Guyb051e892010-09-28 19:09:36 -07007667 if (mDisplayList != null) {
Romain Guyb051e892010-09-28 19:09:36 -07007668 mDisplayList = null;
7669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 }
7671
7672 /**
7673 * Setting a solid background color for the drawing cache's bitmaps will improve
7674 * perfromance and memory usage. Note, though that this should only be used if this
7675 * view will always be drawn on top of a solid color.
7676 *
7677 * @param color The background color to use for the drawing cache's bitmap
7678 *
7679 * @see #setDrawingCacheEnabled(boolean)
7680 * @see #buildDrawingCache()
7681 * @see #getDrawingCache()
7682 */
7683 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08007684 if (color != mDrawingCacheBackgroundColor) {
7685 mDrawingCacheBackgroundColor = color;
7686 mPrivateFlags &= ~DRAWING_CACHE_VALID;
7687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 }
7689
7690 /**
7691 * @see #setDrawingCacheBackgroundColor(int)
7692 *
7693 * @return The background color to used for the drawing cache's bitmap
7694 */
7695 public int getDrawingCacheBackgroundColor() {
7696 return mDrawingCacheBackgroundColor;
7697 }
7698
7699 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007700 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
7701 *
7702 * @see #buildDrawingCache(boolean)
7703 */
7704 public void buildDrawingCache() {
7705 buildDrawingCache(false);
7706 }
7707
7708 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007709 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
7710 *
7711 * <p>If you call {@link #buildDrawingCache()} manually without calling
7712 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7713 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007714 *
7715 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7716 * this method will create a bitmap of the same size as this view. Because this bitmap
7717 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7718 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7719 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7720 * size than the view. This implies that your application must be able to handle this
7721 * size.</p>
Romain Guy0d9275e2010-10-26 14:22:30 -07007722 *
7723 * <p>You should avoid calling this method when hardware acceleration is enabled. If
7724 * you do not need the drawing cache bitmap, calling this method will increase memory
7725 * usage and cause the view to be rendered in software once, thus negatively impacting
7726 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007727 *
7728 * @see #getDrawingCache()
7729 * @see #destroyDrawingCache()
7730 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007731 public void buildDrawingCache(boolean autoScale) {
7732 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07007733 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007734
7735 if (ViewDebug.TRACE_HIERARCHY) {
7736 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738
Romain Guy8506ab42009-06-11 17:35:47 -07007739 int width = mRight - mLeft;
7740 int height = mBottom - mTop;
7741
7742 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007743 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007744
Romain Guye1123222009-06-29 14:24:56 -07007745 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007746 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7747 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007749
7750 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007751 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08007752 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753
7754 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007755 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08007756 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007757 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7758 destroyDrawingCache();
7759 return;
7760 }
7761
7762 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07007763 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764
7765 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007766 Bitmap.Config quality;
7767 if (!opaque) {
7768 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7769 case DRAWING_CACHE_QUALITY_AUTO:
7770 quality = Bitmap.Config.ARGB_8888;
7771 break;
7772 case DRAWING_CACHE_QUALITY_LOW:
7773 quality = Bitmap.Config.ARGB_4444;
7774 break;
7775 case DRAWING_CACHE_QUALITY_HIGH:
7776 quality = Bitmap.Config.ARGB_8888;
7777 break;
7778 default:
7779 quality = Bitmap.Config.ARGB_8888;
7780 break;
7781 }
7782 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07007783 // Optimization for translucent windows
7784 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08007785 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786 }
7787
7788 // Try to cleanup memory
7789 if (bitmap != null) bitmap.recycle();
7790
7791 try {
7792 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07007793 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07007794 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07007795 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007796 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07007797 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007798 }
Adam Powell26153a32010-11-08 15:22:27 -08007799 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 } catch (OutOfMemoryError e) {
7801 // If there is not enough memory to create the bitmap cache, just
7802 // ignore the issue as bitmap caches are not required to draw the
7803 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07007804 if (autoScale) {
7805 mDrawingCache = null;
7806 } else {
7807 mUnscaledDrawingCache = null;
7808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 return;
7810 }
7811
7812 clear = drawingCacheBackgroundColor != 0;
7813 }
7814
7815 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 if (attachInfo != null) {
7817 canvas = attachInfo.mCanvas;
7818 if (canvas == null) {
7819 canvas = new Canvas();
7820 }
7821 canvas.setBitmap(bitmap);
7822 // Temporarily clobber the cached Canvas in case one of our children
7823 // is also using a drawing cache. Without this, the children would
7824 // steal the canvas by attaching their own bitmap to it and bad, bad
7825 // thing would happen (invisible views, corrupted drawings, etc.)
7826 attachInfo.mCanvas = null;
7827 } else {
7828 // This case should hopefully never or seldom happen
7829 canvas = new Canvas(bitmap);
7830 }
7831
7832 if (clear) {
7833 bitmap.eraseColor(drawingCacheBackgroundColor);
7834 }
7835
7836 computeScroll();
7837 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07007838
Romain Guye1123222009-06-29 14:24:56 -07007839 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007840 final float scale = attachInfo.mApplicationScale;
7841 canvas.scale(scale, scale);
7842 }
7843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 canvas.translate(-mScrollX, -mScrollY);
7845
Romain Guy5bcdff42009-05-14 21:27:18 -07007846 mPrivateFlags |= DRAWN;
Romain Guy0d9275e2010-10-26 14:22:30 -07007847 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated) {
7848 mPrivateFlags |= DRAWING_CACHE_VALID;
7849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007850
7851 // Fast path for layouts with no backgrounds
7852 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7853 if (ViewDebug.TRACE_HIERARCHY) {
7854 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7855 }
Romain Guy5bcdff42009-05-14 21:27:18 -07007856 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 dispatchDraw(canvas);
7858 } else {
7859 draw(canvas);
7860 }
7861
7862 canvas.restoreToCount(restoreCount);
7863
7864 if (attachInfo != null) {
7865 // Restore the cached Canvas for our siblings
7866 attachInfo.mCanvas = canvas;
7867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007868 }
7869 }
7870
7871 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007872 * Create a snapshot of the view into a bitmap. We should probably make
7873 * some form of this public, but should think about the API.
7874 */
Romain Guy223ff5c2010-03-02 17:07:47 -08007875 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007876 int width = mRight - mLeft;
7877 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007878
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007879 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07007880 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007881 width = (int) ((width * scale) + 0.5f);
7882 height = (int) ((height * scale) + 0.5f);
7883
Romain Guy8c11e312009-09-14 15:15:30 -07007884 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007885 if (bitmap == null) {
7886 throw new OutOfMemoryError();
7887 }
7888
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007889 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
7890
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007891 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007892 if (attachInfo != null) {
7893 canvas = attachInfo.mCanvas;
7894 if (canvas == null) {
7895 canvas = new Canvas();
7896 }
7897 canvas.setBitmap(bitmap);
7898 // Temporarily clobber the cached Canvas in case one of our children
7899 // is also using a drawing cache. Without this, the children would
7900 // steal the canvas by attaching their own bitmap to it and bad, bad
7901 // things would happen (invisible views, corrupted drawings, etc.)
7902 attachInfo.mCanvas = null;
7903 } else {
7904 // This case should hopefully never or seldom happen
7905 canvas = new Canvas(bitmap);
7906 }
7907
Romain Guy5bcdff42009-05-14 21:27:18 -07007908 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007909 bitmap.eraseColor(backgroundColor);
7910 }
7911
7912 computeScroll();
7913 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007914 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007915 canvas.translate(-mScrollX, -mScrollY);
7916
Romain Guy5bcdff42009-05-14 21:27:18 -07007917 // Temporarily remove the dirty mask
7918 int flags = mPrivateFlags;
7919 mPrivateFlags &= ~DIRTY_MASK;
7920
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007921 // Fast path for layouts with no backgrounds
7922 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7923 dispatchDraw(canvas);
7924 } else {
7925 draw(canvas);
7926 }
7927
Romain Guy5bcdff42009-05-14 21:27:18 -07007928 mPrivateFlags = flags;
7929
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007930 canvas.restoreToCount(restoreCount);
7931
7932 if (attachInfo != null) {
7933 // Restore the cached Canvas for our siblings
7934 attachInfo.mCanvas = canvas;
7935 }
Romain Guy8506ab42009-06-11 17:35:47 -07007936
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007937 return bitmap;
7938 }
7939
7940 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007941 * Indicates whether this View is currently in edit mode. A View is usually
7942 * in edit mode when displayed within a developer tool. For instance, if
7943 * this View is being drawn by a visual user interface builder, this method
7944 * should return true.
7945 *
7946 * Subclasses should check the return value of this method to provide
7947 * different behaviors if their normal behavior might interfere with the
7948 * host environment. For instance: the class spawns a thread in its
7949 * constructor, the drawing code relies on device-specific features, etc.
7950 *
7951 * This method is usually checked in the drawing code of custom widgets.
7952 *
7953 * @return True if this View is in edit mode, false otherwise.
7954 */
7955 public boolean isInEditMode() {
7956 return false;
7957 }
7958
7959 /**
7960 * If the View draws content inside its padding and enables fading edges,
7961 * it needs to support padding offsets. Padding offsets are added to the
7962 * fading edges to extend the length of the fade so that it covers pixels
7963 * drawn inside the padding.
7964 *
7965 * Subclasses of this class should override this method if they need
7966 * to draw content inside the padding.
7967 *
7968 * @return True if padding offset must be applied, false otherwise.
7969 *
7970 * @see #getLeftPaddingOffset()
7971 * @see #getRightPaddingOffset()
7972 * @see #getTopPaddingOffset()
7973 * @see #getBottomPaddingOffset()
7974 *
7975 * @since CURRENT
7976 */
7977 protected boolean isPaddingOffsetRequired() {
7978 return false;
7979 }
7980
7981 /**
7982 * Amount by which to extend the left fading region. Called only when
7983 * {@link #isPaddingOffsetRequired()} returns true.
7984 *
7985 * @return The left padding offset in pixels.
7986 *
7987 * @see #isPaddingOffsetRequired()
7988 *
7989 * @since CURRENT
7990 */
7991 protected int getLeftPaddingOffset() {
7992 return 0;
7993 }
7994
7995 /**
7996 * Amount by which to extend the right fading region. Called only when
7997 * {@link #isPaddingOffsetRequired()} returns true.
7998 *
7999 * @return The right padding offset in pixels.
8000 *
8001 * @see #isPaddingOffsetRequired()
8002 *
8003 * @since CURRENT
8004 */
8005 protected int getRightPaddingOffset() {
8006 return 0;
8007 }
8008
8009 /**
8010 * Amount by which to extend the top fading region. Called only when
8011 * {@link #isPaddingOffsetRequired()} returns true.
8012 *
8013 * @return The top padding offset in pixels.
8014 *
8015 * @see #isPaddingOffsetRequired()
8016 *
8017 * @since CURRENT
8018 */
8019 protected int getTopPaddingOffset() {
8020 return 0;
8021 }
8022
8023 /**
8024 * Amount by which to extend the bottom fading region. Called only when
8025 * {@link #isPaddingOffsetRequired()} returns true.
8026 *
8027 * @return The bottom padding offset in pixels.
8028 *
8029 * @see #isPaddingOffsetRequired()
8030 *
8031 * @since CURRENT
8032 */
8033 protected int getBottomPaddingOffset() {
8034 return 0;
8035 }
8036
8037 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008038 * <p>Indicates whether this view is attached to an hardware accelerated
8039 * window or not.</p>
8040 *
8041 * <p>Even if this method returns true, it does not mean that every call
8042 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8043 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8044 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8045 * window is hardware accelerated,
8046 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8047 * return false, and this method will return true.</p>
8048 *
8049 * @return True if the view is attached to a window and the window is
8050 * hardware accelerated; false in any other case.
8051 */
8052 public boolean isHardwareAccelerated() {
8053 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8054 }
8055
8056 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 * Manually render this view (and all of its children) to the given Canvas.
8058 * The view must have already done a full layout before this function is
8059 * called. When implementing a view, do not override this method; instead,
8060 * you should implement {@link #onDraw}.
8061 *
8062 * @param canvas The Canvas to which the View is rendered.
8063 */
8064 public void draw(Canvas canvas) {
8065 if (ViewDebug.TRACE_HIERARCHY) {
8066 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8067 }
8068
Romain Guy5bcdff42009-05-14 21:27:18 -07008069 final int privateFlags = mPrivateFlags;
8070 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8071 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8072 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 /*
8075 * Draw traversal performs several drawing steps which must be executed
8076 * in the appropriate order:
8077 *
8078 * 1. Draw the background
8079 * 2. If necessary, save the canvas' layers to prepare for fading
8080 * 3. Draw view's content
8081 * 4. Draw children
8082 * 5. If necessary, draw the fading edges and restore layers
8083 * 6. Draw decorations (scrollbars for instance)
8084 */
8085
8086 // Step 1, draw the background, if needed
8087 int saveCount;
8088
Romain Guy24443ea2009-05-11 11:56:30 -07008089 if (!dirtyOpaque) {
8090 final Drawable background = mBGDrawable;
8091 if (background != null) {
8092 final int scrollX = mScrollX;
8093 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008094
Romain Guy24443ea2009-05-11 11:56:30 -07008095 if (mBackgroundSizeChanged) {
8096 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8097 mBackgroundSizeChanged = false;
8098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099
Romain Guy24443ea2009-05-11 11:56:30 -07008100 if ((scrollX | scrollY) == 0) {
8101 background.draw(canvas);
8102 } else {
8103 canvas.translate(scrollX, scrollY);
8104 background.draw(canvas);
8105 canvas.translate(-scrollX, -scrollY);
8106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008107 }
8108 }
8109
8110 // skip step 2 & 5 if possible (common case)
8111 final int viewFlags = mViewFlags;
8112 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8113 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8114 if (!verticalEdges && !horizontalEdges) {
8115 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008116 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117
8118 // Step 4, draw the children
8119 dispatchDraw(canvas);
8120
8121 // Step 6, draw decorations (scrollbars)
8122 onDrawScrollBars(canvas);
8123
8124 // we're done...
8125 return;
8126 }
8127
8128 /*
8129 * Here we do the full fledged routine...
8130 * (this is an uncommon case where speed matters less,
8131 * this is why we repeat some of the tests that have been
8132 * done above)
8133 */
8134
8135 boolean drawTop = false;
8136 boolean drawBottom = false;
8137 boolean drawLeft = false;
8138 boolean drawRight = false;
8139
8140 float topFadeStrength = 0.0f;
8141 float bottomFadeStrength = 0.0f;
8142 float leftFadeStrength = 0.0f;
8143 float rightFadeStrength = 0.0f;
8144
8145 // Step 2, save the canvas' layers
8146 int paddingLeft = mPaddingLeft;
8147 int paddingTop = mPaddingTop;
8148
8149 final boolean offsetRequired = isPaddingOffsetRequired();
8150 if (offsetRequired) {
8151 paddingLeft += getLeftPaddingOffset();
8152 paddingTop += getTopPaddingOffset();
8153 }
8154
8155 int left = mScrollX + paddingLeft;
8156 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8157 int top = mScrollY + paddingTop;
8158 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8159
8160 if (offsetRequired) {
8161 right += getRightPaddingOffset();
8162 bottom += getBottomPaddingOffset();
8163 }
8164
8165 final ScrollabilityCache scrollabilityCache = mScrollCache;
8166 int length = scrollabilityCache.fadingEdgeLength;
8167
8168 // clip the fade length if top and bottom fades overlap
8169 // overlapping fades produce odd-looking artifacts
8170 if (verticalEdges && (top + length > bottom - length)) {
8171 length = (bottom - top) / 2;
8172 }
8173
8174 // also clip horizontal fades if necessary
8175 if (horizontalEdges && (left + length > right - length)) {
8176 length = (right - left) / 2;
8177 }
8178
8179 if (verticalEdges) {
8180 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008181 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008182 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008183 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008184 }
8185
8186 if (horizontalEdges) {
8187 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008188 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008189 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008190 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008191 }
8192
8193 saveCount = canvas.getSaveCount();
8194
8195 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008196 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008197 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8198
8199 if (drawTop) {
8200 canvas.saveLayer(left, top, right, top + length, null, flags);
8201 }
8202
8203 if (drawBottom) {
8204 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8205 }
8206
8207 if (drawLeft) {
8208 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8209 }
8210
8211 if (drawRight) {
8212 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8213 }
8214 } else {
8215 scrollabilityCache.setFadeColor(solidColor);
8216 }
8217
8218 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008219 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220
8221 // Step 4, draw the children
8222 dispatchDraw(canvas);
8223
8224 // Step 5, draw the fade effect and restore layers
8225 final Paint p = scrollabilityCache.paint;
8226 final Matrix matrix = scrollabilityCache.matrix;
8227 final Shader fade = scrollabilityCache.shader;
8228 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8229
8230 if (drawTop) {
8231 matrix.setScale(1, fadeHeight * topFadeStrength);
8232 matrix.postTranslate(left, top);
8233 fade.setLocalMatrix(matrix);
8234 canvas.drawRect(left, top, right, top + length, p);
8235 }
8236
8237 if (drawBottom) {
8238 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8239 matrix.postRotate(180);
8240 matrix.postTranslate(left, bottom);
8241 fade.setLocalMatrix(matrix);
8242 canvas.drawRect(left, bottom - length, right, bottom, p);
8243 }
8244
8245 if (drawLeft) {
8246 matrix.setScale(1, fadeHeight * leftFadeStrength);
8247 matrix.postRotate(-90);
8248 matrix.postTranslate(left, top);
8249 fade.setLocalMatrix(matrix);
8250 canvas.drawRect(left, top, left + length, bottom, p);
8251 }
8252
8253 if (drawRight) {
8254 matrix.setScale(1, fadeHeight * rightFadeStrength);
8255 matrix.postRotate(90);
8256 matrix.postTranslate(right, top);
8257 fade.setLocalMatrix(matrix);
8258 canvas.drawRect(right - length, top, right, bottom, p);
8259 }
8260
8261 canvas.restoreToCount(saveCount);
8262
8263 // Step 6, draw decorations (scrollbars)
8264 onDrawScrollBars(canvas);
8265 }
8266
8267 /**
8268 * Override this if your view is known to always be drawn on top of a solid color background,
8269 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8270 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8271 * should be set to 0xFF.
8272 *
8273 * @see #setVerticalFadingEdgeEnabled
8274 * @see #setHorizontalFadingEdgeEnabled
8275 *
8276 * @return The known solid color background for this view, or 0 if the color may vary
8277 */
8278 public int getSolidColor() {
8279 return 0;
8280 }
8281
8282 /**
8283 * Build a human readable string representation of the specified view flags.
8284 *
8285 * @param flags the view flags to convert to a string
8286 * @return a String representing the supplied flags
8287 */
8288 private static String printFlags(int flags) {
8289 String output = "";
8290 int numFlags = 0;
8291 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8292 output += "TAKES_FOCUS";
8293 numFlags++;
8294 }
8295
8296 switch (flags & VISIBILITY_MASK) {
8297 case INVISIBLE:
8298 if (numFlags > 0) {
8299 output += " ";
8300 }
8301 output += "INVISIBLE";
8302 // USELESS HERE numFlags++;
8303 break;
8304 case GONE:
8305 if (numFlags > 0) {
8306 output += " ";
8307 }
8308 output += "GONE";
8309 // USELESS HERE numFlags++;
8310 break;
8311 default:
8312 break;
8313 }
8314 return output;
8315 }
8316
8317 /**
8318 * Build a human readable string representation of the specified private
8319 * view flags.
8320 *
8321 * @param privateFlags the private view flags to convert to a string
8322 * @return a String representing the supplied flags
8323 */
8324 private static String printPrivateFlags(int privateFlags) {
8325 String output = "";
8326 int numFlags = 0;
8327
8328 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8329 output += "WANTS_FOCUS";
8330 numFlags++;
8331 }
8332
8333 if ((privateFlags & FOCUSED) == FOCUSED) {
8334 if (numFlags > 0) {
8335 output += " ";
8336 }
8337 output += "FOCUSED";
8338 numFlags++;
8339 }
8340
8341 if ((privateFlags & SELECTED) == SELECTED) {
8342 if (numFlags > 0) {
8343 output += " ";
8344 }
8345 output += "SELECTED";
8346 numFlags++;
8347 }
8348
8349 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8350 if (numFlags > 0) {
8351 output += " ";
8352 }
8353 output += "IS_ROOT_NAMESPACE";
8354 numFlags++;
8355 }
8356
8357 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8358 if (numFlags > 0) {
8359 output += " ";
8360 }
8361 output += "HAS_BOUNDS";
8362 numFlags++;
8363 }
8364
8365 if ((privateFlags & DRAWN) == DRAWN) {
8366 if (numFlags > 0) {
8367 output += " ";
8368 }
8369 output += "DRAWN";
8370 // USELESS HERE numFlags++;
8371 }
8372 return output;
8373 }
8374
8375 /**
8376 * <p>Indicates whether or not this view's layout will be requested during
8377 * the next hierarchy layout pass.</p>
8378 *
8379 * @return true if the layout will be forced during next layout pass
8380 */
8381 public boolean isLayoutRequested() {
8382 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8383 }
8384
8385 /**
8386 * Assign a size and position to a view and all of its
8387 * descendants
8388 *
8389 * <p>This is the second phase of the layout mechanism.
8390 * (The first is measuring). In this phase, each parent calls
8391 * layout on all of its children to position them.
8392 * This is typically done using the child measurements
8393 * that were stored in the measure pass().
8394 *
8395 * Derived classes with children should override
8396 * onLayout. In that method, they should
Chet Haase21cd1382010-09-01 17:42:29 -07008397 * call layout on each of their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008398 *
8399 * @param l Left position, relative to parent
8400 * @param t Top position, relative to parent
8401 * @param r Right position, relative to parent
8402 * @param b Bottom position, relative to parent
8403 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008404 @SuppressWarnings({"unchecked"})
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008405 public final void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008406 int oldL = mLeft;
8407 int oldT = mTop;
8408 int oldB = mBottom;
8409 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008410 boolean changed = setFrame(l, t, r, b);
8411 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8412 if (ViewDebug.TRACE_HIERARCHY) {
8413 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8414 }
8415
8416 onLayout(changed, l, t, r, b);
8417 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008418
8419 if (mOnLayoutChangeListeners != null) {
8420 ArrayList<OnLayoutChangeListener> listenersCopy =
8421 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8422 int numListeners = listenersCopy.size();
8423 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07008424 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07008425 }
8426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008427 }
8428 mPrivateFlags &= ~FORCE_LAYOUT;
8429 }
8430
8431 /**
8432 * Called from layout when this view should
8433 * assign a size and position to each of its children.
8434 *
8435 * Derived classes with children should override
8436 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008437 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008438 * @param changed This is a new size or position for this view
8439 * @param left Left position, relative to parent
8440 * @param top Top position, relative to parent
8441 * @param right Right position, relative to parent
8442 * @param bottom Bottom position, relative to parent
8443 */
8444 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8445 }
8446
8447 /**
8448 * Assign a size and position to this view.
8449 *
8450 * This is called from layout.
8451 *
8452 * @param left Left position, relative to parent
8453 * @param top Top position, relative to parent
8454 * @param right Right position, relative to parent
8455 * @param bottom Bottom position, relative to parent
8456 * @return true if the new size and position are different than the
8457 * previous ones
8458 * {@hide}
8459 */
8460 protected boolean setFrame(int left, int top, int right, int bottom) {
8461 boolean changed = false;
8462
8463 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008464 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008465 + right + "," + bottom + ")");
8466 }
8467
8468 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8469 changed = true;
8470
8471 // Remember our drawn bit
8472 int drawn = mPrivateFlags & DRAWN;
8473
8474 // Invalidate our old position
8475 invalidate();
8476
8477
8478 int oldWidth = mRight - mLeft;
8479 int oldHeight = mBottom - mTop;
8480
8481 mLeft = left;
8482 mTop = top;
8483 mRight = right;
8484 mBottom = bottom;
8485
8486 mPrivateFlags |= HAS_BOUNDS;
8487
8488 int newWidth = right - left;
8489 int newHeight = bottom - top;
8490
8491 if (newWidth != oldWidth || newHeight != oldHeight) {
8492 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8493 }
8494
8495 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8496 // If we are visible, force the DRAWN bit to on so that
8497 // this invalidate will go through (at least to our parent).
8498 // This is because someone may have invalidated this view
8499 // before this call to setFrame came in, therby clearing
8500 // the DRAWN bit.
8501 mPrivateFlags |= DRAWN;
8502 invalidate();
8503 }
8504
8505 // Reset drawn bit to original value (invalidate turns it off)
8506 mPrivateFlags |= drawn;
8507
8508 mBackgroundSizeChanged = true;
8509 }
8510 return changed;
8511 }
8512
8513 /**
8514 * Finalize inflating a view from XML. This is called as the last phase
8515 * of inflation, after all child views have been added.
8516 *
8517 * <p>Even if the subclass overrides onFinishInflate, they should always be
8518 * sure to call the super method, so that we get called.
8519 */
8520 protected void onFinishInflate() {
8521 }
8522
8523 /**
8524 * Returns the resources associated with this view.
8525 *
8526 * @return Resources object.
8527 */
8528 public Resources getResources() {
8529 return mResources;
8530 }
8531
8532 /**
8533 * Invalidates the specified Drawable.
8534 *
8535 * @param drawable the drawable to invalidate
8536 */
8537 public void invalidateDrawable(Drawable drawable) {
8538 if (verifyDrawable(drawable)) {
8539 final Rect dirty = drawable.getBounds();
8540 final int scrollX = mScrollX;
8541 final int scrollY = mScrollY;
8542
8543 invalidate(dirty.left + scrollX, dirty.top + scrollY,
8544 dirty.right + scrollX, dirty.bottom + scrollY);
8545 }
8546 }
8547
8548 /**
8549 * Schedules an action on a drawable to occur at a specified time.
8550 *
8551 * @param who the recipient of the action
8552 * @param what the action to run on the drawable
8553 * @param when the time at which the action must occur. Uses the
8554 * {@link SystemClock#uptimeMillis} timebase.
8555 */
8556 public void scheduleDrawable(Drawable who, Runnable what, long when) {
8557 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8558 mAttachInfo.mHandler.postAtTime(what, who, when);
8559 }
8560 }
8561
8562 /**
8563 * Cancels a scheduled action on a drawable.
8564 *
8565 * @param who the recipient of the action
8566 * @param what the action to cancel
8567 */
8568 public void unscheduleDrawable(Drawable who, Runnable what) {
8569 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8570 mAttachInfo.mHandler.removeCallbacks(what, who);
8571 }
8572 }
8573
8574 /**
8575 * Unschedule any events associated with the given Drawable. This can be
8576 * used when selecting a new Drawable into a view, so that the previous
8577 * one is completely unscheduled.
8578 *
8579 * @param who The Drawable to unschedule.
8580 *
8581 * @see #drawableStateChanged
8582 */
8583 public void unscheduleDrawable(Drawable who) {
8584 if (mAttachInfo != null) {
8585 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
8586 }
8587 }
8588
8589 /**
8590 * If your view subclass is displaying its own Drawable objects, it should
8591 * override this function and return true for any Drawable it is
8592 * displaying. This allows animations for those drawables to be
8593 * scheduled.
8594 *
8595 * <p>Be sure to call through to the super class when overriding this
8596 * function.
8597 *
8598 * @param who The Drawable to verify. Return true if it is one you are
8599 * displaying, else return the result of calling through to the
8600 * super class.
8601 *
8602 * @return boolean If true than the Drawable is being displayed in the
8603 * view; else false and it is not allowed to animate.
8604 *
8605 * @see #unscheduleDrawable
8606 * @see #drawableStateChanged
8607 */
8608 protected boolean verifyDrawable(Drawable who) {
8609 return who == mBGDrawable;
8610 }
8611
8612 /**
8613 * This function is called whenever the state of the view changes in such
8614 * a way that it impacts the state of drawables being shown.
8615 *
8616 * <p>Be sure to call through to the superclass when overriding this
8617 * function.
8618 *
8619 * @see Drawable#setState
8620 */
8621 protected void drawableStateChanged() {
8622 Drawable d = mBGDrawable;
8623 if (d != null && d.isStateful()) {
8624 d.setState(getDrawableState());
8625 }
8626 }
8627
8628 /**
8629 * Call this to force a view to update its drawable state. This will cause
8630 * drawableStateChanged to be called on this view. Views that are interested
8631 * in the new state should call getDrawableState.
8632 *
8633 * @see #drawableStateChanged
8634 * @see #getDrawableState
8635 */
8636 public void refreshDrawableState() {
8637 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
8638 drawableStateChanged();
8639
8640 ViewParent parent = mParent;
8641 if (parent != null) {
8642 parent.childDrawableStateChanged(this);
8643 }
8644 }
8645
8646 /**
8647 * Return an array of resource IDs of the drawable states representing the
8648 * current state of the view.
8649 *
8650 * @return The current drawable state
8651 *
8652 * @see Drawable#setState
8653 * @see #drawableStateChanged
8654 * @see #onCreateDrawableState
8655 */
8656 public final int[] getDrawableState() {
8657 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
8658 return mDrawableState;
8659 } else {
8660 mDrawableState = onCreateDrawableState(0);
8661 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
8662 return mDrawableState;
8663 }
8664 }
8665
8666 /**
8667 * Generate the new {@link android.graphics.drawable.Drawable} state for
8668 * this view. This is called by the view
8669 * system when the cached Drawable state is determined to be invalid. To
8670 * retrieve the current state, you should use {@link #getDrawableState}.
8671 *
8672 * @param extraSpace if non-zero, this is the number of extra entries you
8673 * would like in the returned array in which you can place your own
8674 * states.
8675 *
8676 * @return Returns an array holding the current {@link Drawable} state of
8677 * the view.
8678 *
8679 * @see #mergeDrawableStates
8680 */
8681 protected int[] onCreateDrawableState(int extraSpace) {
8682 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
8683 mParent instanceof View) {
8684 return ((View) mParent).onCreateDrawableState(extraSpace);
8685 }
8686
8687 int[] drawableState;
8688
8689 int privateFlags = mPrivateFlags;
8690
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008691 int viewStateIndex = 0;
8692 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
8693 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
8694 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07008695 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008696 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
8697 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08008698 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
8699 // This is set if HW acceleration is requested, even if the current
8700 // process doesn't allow it. This is just to allow app preview
8701 // windows to better match their app.
8702 viewStateIndex |= VIEW_STATE_ACCELERATED;
8703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008704
8705 drawableState = VIEW_STATE_SETS[viewStateIndex];
8706
8707 //noinspection ConstantIfStatement
8708 if (false) {
8709 Log.i("View", "drawableStateIndex=" + viewStateIndex);
8710 Log.i("View", toString()
8711 + " pressed=" + ((privateFlags & PRESSED) != 0)
8712 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
8713 + " fo=" + hasFocus()
8714 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008715 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716 + ": " + Arrays.toString(drawableState));
8717 }
8718
8719 if (extraSpace == 0) {
8720 return drawableState;
8721 }
8722
8723 final int[] fullState;
8724 if (drawableState != null) {
8725 fullState = new int[drawableState.length + extraSpace];
8726 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
8727 } else {
8728 fullState = new int[extraSpace];
8729 }
8730
8731 return fullState;
8732 }
8733
8734 /**
8735 * Merge your own state values in <var>additionalState</var> into the base
8736 * state values <var>baseState</var> that were returned by
8737 * {@link #onCreateDrawableState}.
8738 *
8739 * @param baseState The base state values returned by
8740 * {@link #onCreateDrawableState}, which will be modified to also hold your
8741 * own additional state values.
8742 *
8743 * @param additionalState The additional state values you would like
8744 * added to <var>baseState</var>; this array is not modified.
8745 *
8746 * @return As a convenience, the <var>baseState</var> array you originally
8747 * passed into the function is returned.
8748 *
8749 * @see #onCreateDrawableState
8750 */
8751 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
8752 final int N = baseState.length;
8753 int i = N - 1;
8754 while (i >= 0 && baseState[i] == 0) {
8755 i--;
8756 }
8757 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
8758 return baseState;
8759 }
8760
8761 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07008762 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
8763 * on all Drawable objects associated with this view.
8764 */
8765 public void jumpDrawablesToCurrentState() {
8766 if (mBGDrawable != null) {
8767 mBGDrawable.jumpToCurrentState();
8768 }
8769 }
8770
8771 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008772 * Sets the background color for this view.
8773 * @param color the color of the background
8774 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008775 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07008777 if (mBGDrawable instanceof ColorDrawable) {
8778 ((ColorDrawable) mBGDrawable).setColor(color);
8779 } else {
8780 setBackgroundDrawable(new ColorDrawable(color));
8781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782 }
8783
8784 /**
8785 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07008786 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 * @param resid The identifier of the resource.
8788 * @attr ref android.R.styleable#View_background
8789 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008790 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008791 public void setBackgroundResource(int resid) {
8792 if (resid != 0 && resid == mBackgroundResource) {
8793 return;
8794 }
8795
8796 Drawable d= null;
8797 if (resid != 0) {
8798 d = mResources.getDrawable(resid);
8799 }
8800 setBackgroundDrawable(d);
8801
8802 mBackgroundResource = resid;
8803 }
8804
8805 /**
8806 * Set the background to a given Drawable, or remove the background. If the
8807 * background has padding, this View's padding is set to the background's
8808 * padding. However, when a background is removed, this View's padding isn't
8809 * touched. If setting the padding is desired, please use
8810 * {@link #setPadding(int, int, int, int)}.
8811 *
8812 * @param d The Drawable to use as the background, or null to remove the
8813 * background
8814 */
8815 public void setBackgroundDrawable(Drawable d) {
8816 boolean requestLayout = false;
8817
8818 mBackgroundResource = 0;
8819
8820 /*
8821 * Regardless of whether we're setting a new background or not, we want
8822 * to clear the previous drawable.
8823 */
8824 if (mBGDrawable != null) {
8825 mBGDrawable.setCallback(null);
8826 unscheduleDrawable(mBGDrawable);
8827 }
8828
8829 if (d != null) {
8830 Rect padding = sThreadLocal.get();
8831 if (padding == null) {
8832 padding = new Rect();
8833 sThreadLocal.set(padding);
8834 }
8835 if (d.getPadding(padding)) {
8836 setPadding(padding.left, padding.top, padding.right, padding.bottom);
8837 }
8838
8839 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
8840 // if it has a different minimum size, we should layout again
8841 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
8842 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
8843 requestLayout = true;
8844 }
8845
8846 d.setCallback(this);
8847 if (d.isStateful()) {
8848 d.setState(getDrawableState());
8849 }
8850 d.setVisible(getVisibility() == VISIBLE, false);
8851 mBGDrawable = d;
8852
8853 if ((mPrivateFlags & SKIP_DRAW) != 0) {
8854 mPrivateFlags &= ~SKIP_DRAW;
8855 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8856 requestLayout = true;
8857 }
8858 } else {
8859 /* Remove the background */
8860 mBGDrawable = null;
8861
8862 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
8863 /*
8864 * This view ONLY drew the background before and we're removing
8865 * the background, so now it won't draw anything
8866 * (hence we SKIP_DRAW)
8867 */
8868 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
8869 mPrivateFlags |= SKIP_DRAW;
8870 }
8871
8872 /*
8873 * When the background is set, we try to apply its padding to this
8874 * View. When the background is removed, we don't touch this View's
8875 * padding. This is noted in the Javadocs. Hence, we don't need to
8876 * requestLayout(), the invalidate() below is sufficient.
8877 */
8878
8879 // The old background's minimum size could have affected this
8880 // View's layout, so let's requestLayout
8881 requestLayout = true;
8882 }
8883
Romain Guy8f1344f52009-05-15 16:03:59 -07008884 computeOpaqueFlags();
8885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008886 if (requestLayout) {
8887 requestLayout();
8888 }
8889
8890 mBackgroundSizeChanged = true;
8891 invalidate();
8892 }
8893
8894 /**
8895 * Gets the background drawable
8896 * @return The drawable used as the background for this view, if any.
8897 */
8898 public Drawable getBackground() {
8899 return mBGDrawable;
8900 }
8901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008902 /**
8903 * Sets the padding. The view may add on the space required to display
8904 * the scrollbars, depending on the style and visibility of the scrollbars.
8905 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
8906 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
8907 * from the values set in this call.
8908 *
8909 * @attr ref android.R.styleable#View_padding
8910 * @attr ref android.R.styleable#View_paddingBottom
8911 * @attr ref android.R.styleable#View_paddingLeft
8912 * @attr ref android.R.styleable#View_paddingRight
8913 * @attr ref android.R.styleable#View_paddingTop
8914 * @param left the left padding in pixels
8915 * @param top the top padding in pixels
8916 * @param right the right padding in pixels
8917 * @param bottom the bottom padding in pixels
8918 */
8919 public void setPadding(int left, int top, int right, int bottom) {
8920 boolean changed = false;
8921
8922 mUserPaddingRight = right;
8923 mUserPaddingBottom = bottom;
8924
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008925 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07008926
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008927 // Common case is there are no scroll bars.
8928 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
8929 // TODO: Deal with RTL languages to adjust left padding instead of right.
8930 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
8931 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8932 ? 0 : getVerticalScrollbarWidth();
8933 }
8934 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
8935 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8936 ? 0 : getHorizontalScrollbarHeight();
8937 }
8938 }
Romain Guy8506ab42009-06-11 17:35:47 -07008939
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008940 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 changed = true;
8942 mPaddingLeft = left;
8943 }
8944 if (mPaddingTop != top) {
8945 changed = true;
8946 mPaddingTop = top;
8947 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008948 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008950 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008951 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008952 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008953 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008954 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 }
8956
8957 if (changed) {
8958 requestLayout();
8959 }
8960 }
8961
8962 /**
8963 * Returns the top padding of this view.
8964 *
8965 * @return the top padding in pixels
8966 */
8967 public int getPaddingTop() {
8968 return mPaddingTop;
8969 }
8970
8971 /**
8972 * Returns the bottom padding of this view. If there are inset and enabled
8973 * scrollbars, this value may include the space required to display the
8974 * scrollbars as well.
8975 *
8976 * @return the bottom padding in pixels
8977 */
8978 public int getPaddingBottom() {
8979 return mPaddingBottom;
8980 }
8981
8982 /**
8983 * Returns the left padding of this view. If there are inset and enabled
8984 * scrollbars, this value may include the space required to display the
8985 * scrollbars as well.
8986 *
8987 * @return the left padding in pixels
8988 */
8989 public int getPaddingLeft() {
8990 return mPaddingLeft;
8991 }
8992
8993 /**
8994 * Returns the right padding of this view. If there are inset and enabled
8995 * scrollbars, this value may include the space required to display the
8996 * scrollbars as well.
8997 *
8998 * @return the right padding in pixels
8999 */
9000 public int getPaddingRight() {
9001 return mPaddingRight;
9002 }
9003
9004 /**
9005 * Changes the selection state of this view. A view can be selected or not.
9006 * Note that selection is not the same as focus. Views are typically
9007 * selected in the context of an AdapterView like ListView or GridView;
9008 * the selected view is the view that is highlighted.
9009 *
9010 * @param selected true if the view must be selected, false otherwise
9011 */
9012 public void setSelected(boolean selected) {
9013 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9014 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009015 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016 invalidate();
9017 refreshDrawableState();
9018 dispatchSetSelected(selected);
9019 }
9020 }
9021
9022 /**
9023 * Dispatch setSelected to all of this View's children.
9024 *
9025 * @see #setSelected(boolean)
9026 *
9027 * @param selected The new selected state
9028 */
9029 protected void dispatchSetSelected(boolean selected) {
9030 }
9031
9032 /**
9033 * Indicates the selection state of this view.
9034 *
9035 * @return true if the view is selected, false otherwise
9036 */
9037 @ViewDebug.ExportedProperty
9038 public boolean isSelected() {
9039 return (mPrivateFlags & SELECTED) != 0;
9040 }
9041
9042 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009043 * Changes the activated state of this view. A view can be activated or not.
9044 * Note that activation is not the same as selection. Selection is
9045 * a transient property, representing the view (hierarchy) the user is
9046 * currently interacting with. Activation is a longer-term state that the
9047 * user can move views in and out of. For example, in a list view with
9048 * single or multiple selection enabled, the views in the current selection
9049 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9050 * here.) The activated state is propagated down to children of the view it
9051 * is set on.
9052 *
9053 * @param activated true if the view must be activated, false otherwise
9054 */
9055 public void setActivated(boolean activated) {
9056 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9057 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
9058 invalidate();
9059 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009060 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009061 }
9062 }
9063
9064 /**
9065 * Dispatch setActivated to all of this View's children.
9066 *
9067 * @see #setActivated(boolean)
9068 *
9069 * @param activated The new activated state
9070 */
9071 protected void dispatchSetActivated(boolean activated) {
9072 }
9073
9074 /**
9075 * Indicates the activation state of this view.
9076 *
9077 * @return true if the view is activated, false otherwise
9078 */
9079 @ViewDebug.ExportedProperty
9080 public boolean isActivated() {
9081 return (mPrivateFlags & ACTIVATED) != 0;
9082 }
9083
9084 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009085 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9086 * observer can be used to get notifications when global events, like
9087 * layout, happen.
9088 *
9089 * The returned ViewTreeObserver observer is not guaranteed to remain
9090 * valid for the lifetime of this View. If the caller of this method keeps
9091 * a long-lived reference to ViewTreeObserver, it should always check for
9092 * the return value of {@link ViewTreeObserver#isAlive()}.
9093 *
9094 * @return The ViewTreeObserver for this view's hierarchy.
9095 */
9096 public ViewTreeObserver getViewTreeObserver() {
9097 if (mAttachInfo != null) {
9098 return mAttachInfo.mTreeObserver;
9099 }
9100 if (mFloatingTreeObserver == null) {
9101 mFloatingTreeObserver = new ViewTreeObserver();
9102 }
9103 return mFloatingTreeObserver;
9104 }
9105
9106 /**
9107 * <p>Finds the topmost view in the current view hierarchy.</p>
9108 *
9109 * @return the topmost view containing this view
9110 */
9111 public View getRootView() {
9112 if (mAttachInfo != null) {
9113 final View v = mAttachInfo.mRootView;
9114 if (v != null) {
9115 return v;
9116 }
9117 }
Romain Guy8506ab42009-06-11 17:35:47 -07009118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009119 View parent = this;
9120
9121 while (parent.mParent != null && parent.mParent instanceof View) {
9122 parent = (View) parent.mParent;
9123 }
9124
9125 return parent;
9126 }
9127
9128 /**
9129 * <p>Computes the coordinates of this view on the screen. The argument
9130 * must be an array of two integers. After the method returns, the array
9131 * contains the x and y location in that order.</p>
9132 *
9133 * @param location an array of two integers in which to hold the coordinates
9134 */
9135 public void getLocationOnScreen(int[] location) {
9136 getLocationInWindow(location);
9137
9138 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009139 if (info != null) {
9140 location[0] += info.mWindowLeft;
9141 location[1] += info.mWindowTop;
9142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009143 }
9144
9145 /**
9146 * <p>Computes the coordinates of this view in its window. The argument
9147 * must be an array of two integers. After the method returns, the array
9148 * contains the x and y location in that order.</p>
9149 *
9150 * @param location an array of two integers in which to hold the coordinates
9151 */
9152 public void getLocationInWindow(int[] location) {
9153 if (location == null || location.length < 2) {
9154 throw new IllegalArgumentException("location must be an array of "
9155 + "two integers");
9156 }
9157
9158 location[0] = mLeft;
9159 location[1] = mTop;
9160
9161 ViewParent viewParent = mParent;
9162 while (viewParent instanceof View) {
9163 final View view = (View)viewParent;
9164 location[0] += view.mLeft - view.mScrollX;
9165 location[1] += view.mTop - view.mScrollY;
9166 viewParent = view.mParent;
9167 }
Romain Guy8506ab42009-06-11 17:35:47 -07009168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169 if (viewParent instanceof ViewRoot) {
9170 // *cough*
9171 final ViewRoot vr = (ViewRoot)viewParent;
9172 location[1] -= vr.mCurScrollY;
9173 }
9174 }
9175
9176 /**
9177 * {@hide}
9178 * @param id the id of the view to be found
9179 * @return the view of the specified id, null if cannot be found
9180 */
9181 protected View findViewTraversal(int id) {
9182 if (id == mID) {
9183 return this;
9184 }
9185 return null;
9186 }
9187
9188 /**
9189 * {@hide}
9190 * @param tag the tag of the view to be found
9191 * @return the view of specified tag, null if cannot be found
9192 */
9193 protected View findViewWithTagTraversal(Object tag) {
9194 if (tag != null && tag.equals(mTag)) {
9195 return this;
9196 }
9197 return null;
9198 }
9199
9200 /**
9201 * Look for a child view with the given id. If this view has the given
9202 * id, return this view.
9203 *
9204 * @param id The id to search for.
9205 * @return The view that has the given id in the hierarchy or null
9206 */
9207 public final View findViewById(int id) {
9208 if (id < 0) {
9209 return null;
9210 }
9211 return findViewTraversal(id);
9212 }
9213
9214 /**
9215 * Look for a child view with the given tag. If this view has the given
9216 * tag, return this view.
9217 *
9218 * @param tag The tag to search for, using "tag.equals(getTag())".
9219 * @return The View that has the given tag in the hierarchy or null
9220 */
9221 public final View findViewWithTag(Object tag) {
9222 if (tag == null) {
9223 return null;
9224 }
9225 return findViewWithTagTraversal(tag);
9226 }
9227
9228 /**
9229 * Sets the identifier for this view. The identifier does not have to be
9230 * unique in this view's hierarchy. The identifier should be a positive
9231 * number.
9232 *
9233 * @see #NO_ID
9234 * @see #getId
9235 * @see #findViewById
9236 *
9237 * @param id a number used to identify the view
9238 *
9239 * @attr ref android.R.styleable#View_id
9240 */
9241 public void setId(int id) {
9242 mID = id;
9243 }
9244
9245 /**
9246 * {@hide}
9247 *
9248 * @param isRoot true if the view belongs to the root namespace, false
9249 * otherwise
9250 */
9251 public void setIsRootNamespace(boolean isRoot) {
9252 if (isRoot) {
9253 mPrivateFlags |= IS_ROOT_NAMESPACE;
9254 } else {
9255 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9256 }
9257 }
9258
9259 /**
9260 * {@hide}
9261 *
9262 * @return true if the view belongs to the root namespace, false otherwise
9263 */
9264 public boolean isRootNamespace() {
9265 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9266 }
9267
9268 /**
9269 * Returns this view's identifier.
9270 *
9271 * @return a positive integer used to identify the view or {@link #NO_ID}
9272 * if the view has no ID
9273 *
9274 * @see #setId
9275 * @see #findViewById
9276 * @attr ref android.R.styleable#View_id
9277 */
9278 @ViewDebug.CapturedViewProperty
9279 public int getId() {
9280 return mID;
9281 }
9282
9283 /**
9284 * Returns this view's tag.
9285 *
9286 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07009287 *
9288 * @see #setTag(Object)
9289 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009290 */
9291 @ViewDebug.ExportedProperty
9292 public Object getTag() {
9293 return mTag;
9294 }
9295
9296 /**
9297 * Sets the tag associated with this view. A tag can be used to mark
9298 * a view in its hierarchy and does not have to be unique within the
9299 * hierarchy. Tags can also be used to store data within a view without
9300 * resorting to another data structure.
9301 *
9302 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07009303 *
9304 * @see #getTag()
9305 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009306 */
9307 public void setTag(final Object tag) {
9308 mTag = tag;
9309 }
9310
9311 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009312 * Returns the tag associated with this view and the specified key.
9313 *
9314 * @param key The key identifying the tag
9315 *
9316 * @return the Object stored in this view as a tag
9317 *
9318 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009319 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009320 */
9321 public Object getTag(int key) {
9322 SparseArray<Object> tags = null;
9323 synchronized (sTagsLock) {
9324 if (sTags != null) {
9325 tags = sTags.get(this);
9326 }
9327 }
9328
9329 if (tags != null) return tags.get(key);
9330 return null;
9331 }
9332
9333 /**
9334 * Sets a tag associated with this view and a key. A tag can be used
9335 * to mark a view in its hierarchy and does not have to be unique within
9336 * the hierarchy. Tags can also be used to store data within a view
9337 * without resorting to another data structure.
9338 *
9339 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009340 * application to ensure it is unique (see the <a
9341 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9342 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009343 * the Android framework or not associated with any package will cause
9344 * an {@link IllegalArgumentException} to be thrown.
9345 *
9346 * @param key The key identifying the tag
9347 * @param tag An Object to tag the view with
9348 *
9349 * @throws IllegalArgumentException If they specified key is not valid
9350 *
9351 * @see #setTag(Object)
9352 * @see #getTag(int)
9353 */
9354 public void setTag(int key, final Object tag) {
9355 // If the package id is 0x00 or 0x01, it's either an undefined package
9356 // or a framework id
9357 if ((key >>> 24) < 2) {
9358 throw new IllegalArgumentException("The key must be an application-specific "
9359 + "resource id.");
9360 }
9361
9362 setTagInternal(this, key, tag);
9363 }
9364
9365 /**
9366 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9367 * framework id.
9368 *
9369 * @hide
9370 */
9371 public void setTagInternal(int key, Object tag) {
9372 if ((key >>> 24) != 0x1) {
9373 throw new IllegalArgumentException("The key must be a framework-specific "
9374 + "resource id.");
9375 }
9376
Romain Guy8506ab42009-06-11 17:35:47 -07009377 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009378 }
9379
9380 private static void setTagInternal(View view, int key, Object tag) {
9381 SparseArray<Object> tags = null;
9382 synchronized (sTagsLock) {
9383 if (sTags == null) {
9384 sTags = new WeakHashMap<View, SparseArray<Object>>();
9385 } else {
9386 tags = sTags.get(view);
9387 }
9388 }
9389
9390 if (tags == null) {
9391 tags = new SparseArray<Object>(2);
9392 synchronized (sTagsLock) {
9393 sTags.put(view, tags);
9394 }
9395 }
9396
9397 tags.put(key, tag);
9398 }
9399
9400 /**
Romain Guy13922e02009-05-12 17:56:14 -07009401 * @param consistency The type of consistency. See ViewDebug for more information.
9402 *
9403 * @hide
9404 */
9405 protected boolean dispatchConsistencyCheck(int consistency) {
9406 return onConsistencyCheck(consistency);
9407 }
9408
9409 /**
9410 * Method that subclasses should implement to check their consistency. The type of
9411 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009412 *
Romain Guy13922e02009-05-12 17:56:14 -07009413 * @param consistency The type of consistency. See ViewDebug for more information.
9414 *
9415 * @throws IllegalStateException if the view is in an inconsistent state.
9416 *
9417 * @hide
9418 */
9419 protected boolean onConsistencyCheck(int consistency) {
9420 boolean result = true;
9421
9422 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9423 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9424
9425 if (checkLayout) {
9426 if (getParent() == null) {
9427 result = false;
9428 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9429 "View " + this + " does not have a parent.");
9430 }
9431
9432 if (mAttachInfo == null) {
9433 result = false;
9434 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9435 "View " + this + " is not attached to a window.");
9436 }
9437 }
9438
9439 if (checkDrawing) {
9440 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9441 // from their draw() method
9442
9443 if ((mPrivateFlags & DRAWN) != DRAWN &&
9444 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9445 result = false;
9446 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9447 "View " + this + " was invalidated but its drawing cache is valid.");
9448 }
9449 }
9450
9451 return result;
9452 }
9453
9454 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009455 * Prints information about this view in the log output, with the tag
9456 * {@link #VIEW_LOG_TAG}.
9457 *
9458 * @hide
9459 */
9460 public void debug() {
9461 debug(0);
9462 }
9463
9464 /**
9465 * Prints information about this view in the log output, with the tag
9466 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
9467 * indentation defined by the <code>depth</code>.
9468 *
9469 * @param depth the indentation level
9470 *
9471 * @hide
9472 */
9473 protected void debug(int depth) {
9474 String output = debugIndent(depth - 1);
9475
9476 output += "+ " + this;
9477 int id = getId();
9478 if (id != -1) {
9479 output += " (id=" + id + ")";
9480 }
9481 Object tag = getTag();
9482 if (tag != null) {
9483 output += " (tag=" + tag + ")";
9484 }
9485 Log.d(VIEW_LOG_TAG, output);
9486
9487 if ((mPrivateFlags & FOCUSED) != 0) {
9488 output = debugIndent(depth) + " FOCUSED";
9489 Log.d(VIEW_LOG_TAG, output);
9490 }
9491
9492 output = debugIndent(depth);
9493 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
9494 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
9495 + "} ";
9496 Log.d(VIEW_LOG_TAG, output);
9497
9498 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
9499 || mPaddingBottom != 0) {
9500 output = debugIndent(depth);
9501 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
9502 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
9503 Log.d(VIEW_LOG_TAG, output);
9504 }
9505
9506 output = debugIndent(depth);
9507 output += "mMeasureWidth=" + mMeasuredWidth +
9508 " mMeasureHeight=" + mMeasuredHeight;
9509 Log.d(VIEW_LOG_TAG, output);
9510
9511 output = debugIndent(depth);
9512 if (mLayoutParams == null) {
9513 output += "BAD! no layout params";
9514 } else {
9515 output = mLayoutParams.debug(output);
9516 }
9517 Log.d(VIEW_LOG_TAG, output);
9518
9519 output = debugIndent(depth);
9520 output += "flags={";
9521 output += View.printFlags(mViewFlags);
9522 output += "}";
9523 Log.d(VIEW_LOG_TAG, output);
9524
9525 output = debugIndent(depth);
9526 output += "privateFlags={";
9527 output += View.printPrivateFlags(mPrivateFlags);
9528 output += "}";
9529 Log.d(VIEW_LOG_TAG, output);
9530 }
9531
9532 /**
9533 * Creates an string of whitespaces used for indentation.
9534 *
9535 * @param depth the indentation level
9536 * @return a String containing (depth * 2 + 3) * 2 white spaces
9537 *
9538 * @hide
9539 */
9540 protected static String debugIndent(int depth) {
9541 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
9542 for (int i = 0; i < (depth * 2) + 3; i++) {
9543 spaces.append(' ').append(' ');
9544 }
9545 return spaces.toString();
9546 }
9547
9548 /**
9549 * <p>Return the offset of the widget's text baseline from the widget's top
9550 * boundary. If this widget does not support baseline alignment, this
9551 * method returns -1. </p>
9552 *
9553 * @return the offset of the baseline within the widget's bounds or -1
9554 * if baseline alignment is not supported
9555 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07009556 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009557 public int getBaseline() {
9558 return -1;
9559 }
9560
9561 /**
9562 * Call this when something has changed which has invalidated the
9563 * layout of this view. This will schedule a layout pass of the view
9564 * tree.
9565 */
9566 public void requestLayout() {
9567 if (ViewDebug.TRACE_HIERARCHY) {
9568 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
9569 }
9570
9571 mPrivateFlags |= FORCE_LAYOUT;
9572
9573 if (mParent != null && !mParent.isLayoutRequested()) {
9574 mParent.requestLayout();
9575 }
9576 }
9577
9578 /**
9579 * Forces this view to be laid out during the next layout pass.
9580 * This method does not call requestLayout() or forceLayout()
9581 * on the parent.
9582 */
9583 public void forceLayout() {
9584 mPrivateFlags |= FORCE_LAYOUT;
9585 }
9586
9587 /**
9588 * <p>
9589 * This is called to find out how big a view should be. The parent
9590 * supplies constraint information in the width and height parameters.
9591 * </p>
9592 *
9593 * <p>
9594 * The actual mesurement work of a view is performed in
9595 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
9596 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
9597 * </p>
9598 *
9599 *
9600 * @param widthMeasureSpec Horizontal space requirements as imposed by the
9601 * parent
9602 * @param heightMeasureSpec Vertical space requirements as imposed by the
9603 * parent
9604 *
9605 * @see #onMeasure(int, int)
9606 */
9607 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
9608 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
9609 widthMeasureSpec != mOldWidthMeasureSpec ||
9610 heightMeasureSpec != mOldHeightMeasureSpec) {
9611
9612 // first clears the measured dimension flag
9613 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9614
9615 if (ViewDebug.TRACE_HIERARCHY) {
9616 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
9617 }
9618
9619 // measure ourselves, this should set the measured dimension flag back
9620 onMeasure(widthMeasureSpec, heightMeasureSpec);
9621
9622 // flag not set, setMeasuredDimension() was not invoked, we raise
9623 // an exception to warn the developer
9624 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9625 throw new IllegalStateException("onMeasure() did not set the"
9626 + " measured dimension by calling"
9627 + " setMeasuredDimension()");
9628 }
9629
9630 mPrivateFlags |= LAYOUT_REQUIRED;
9631 }
9632
9633 mOldWidthMeasureSpec = widthMeasureSpec;
9634 mOldHeightMeasureSpec = heightMeasureSpec;
9635 }
9636
9637 /**
9638 * <p>
9639 * Measure the view and its content to determine the measured width and the
9640 * measured height. This method is invoked by {@link #measure(int, int)} and
9641 * should be overriden by subclasses to provide accurate and efficient
9642 * measurement of their contents.
9643 * </p>
9644 *
9645 * <p>
9646 * <strong>CONTRACT:</strong> When overriding this method, you
9647 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
9648 * measured width and height of this view. Failure to do so will trigger an
9649 * <code>IllegalStateException</code>, thrown by
9650 * {@link #measure(int, int)}. Calling the superclass'
9651 * {@link #onMeasure(int, int)} is a valid use.
9652 * </p>
9653 *
9654 * <p>
9655 * The base class implementation of measure defaults to the background size,
9656 * unless a larger size is allowed by the MeasureSpec. Subclasses should
9657 * override {@link #onMeasure(int, int)} to provide better measurements of
9658 * their content.
9659 * </p>
9660 *
9661 * <p>
9662 * If this method is overridden, it is the subclass's responsibility to make
9663 * sure the measured height and width are at least the view's minimum height
9664 * and width ({@link #getSuggestedMinimumHeight()} and
9665 * {@link #getSuggestedMinimumWidth()}).
9666 * </p>
9667 *
9668 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
9669 * The requirements are encoded with
9670 * {@link android.view.View.MeasureSpec}.
9671 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
9672 * The requirements are encoded with
9673 * {@link android.view.View.MeasureSpec}.
9674 *
9675 * @see #getMeasuredWidth()
9676 * @see #getMeasuredHeight()
9677 * @see #setMeasuredDimension(int, int)
9678 * @see #getSuggestedMinimumHeight()
9679 * @see #getSuggestedMinimumWidth()
9680 * @see android.view.View.MeasureSpec#getMode(int)
9681 * @see android.view.View.MeasureSpec#getSize(int)
9682 */
9683 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9684 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
9685 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
9686 }
9687
9688 /**
9689 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
9690 * measured width and measured height. Failing to do so will trigger an
9691 * exception at measurement time.</p>
9692 *
9693 * @param measuredWidth the measured width of this view
9694 * @param measuredHeight the measured height of this view
9695 */
9696 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
9697 mMeasuredWidth = measuredWidth;
9698 mMeasuredHeight = measuredHeight;
9699
9700 mPrivateFlags |= MEASURED_DIMENSION_SET;
9701 }
9702
9703 /**
9704 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
9705 * Will take the desired size, unless a different size is imposed by the constraints.
9706 *
9707 * @param size How big the view wants to be
9708 * @param measureSpec Constraints imposed by the parent
9709 * @return The size this view should be.
9710 */
9711 public static int resolveSize(int size, int measureSpec) {
9712 int result = size;
9713 int specMode = MeasureSpec.getMode(measureSpec);
9714 int specSize = MeasureSpec.getSize(measureSpec);
9715 switch (specMode) {
9716 case MeasureSpec.UNSPECIFIED:
9717 result = size;
9718 break;
9719 case MeasureSpec.AT_MOST:
9720 result = Math.min(size, specSize);
9721 break;
9722 case MeasureSpec.EXACTLY:
9723 result = specSize;
9724 break;
9725 }
9726 return result;
9727 }
9728
9729 /**
9730 * Utility to return a default size. Uses the supplied size if the
9731 * MeasureSpec imposed no contraints. Will get larger if allowed
9732 * by the MeasureSpec.
9733 *
9734 * @param size Default size for this view
9735 * @param measureSpec Constraints imposed by the parent
9736 * @return The size this view should be.
9737 */
9738 public static int getDefaultSize(int size, int measureSpec) {
9739 int result = size;
9740 int specMode = MeasureSpec.getMode(measureSpec);
9741 int specSize = MeasureSpec.getSize(measureSpec);
9742
9743 switch (specMode) {
9744 case MeasureSpec.UNSPECIFIED:
9745 result = size;
9746 break;
9747 case MeasureSpec.AT_MOST:
9748 case MeasureSpec.EXACTLY:
9749 result = specSize;
9750 break;
9751 }
9752 return result;
9753 }
9754
9755 /**
9756 * Returns the suggested minimum height that the view should use. This
9757 * returns the maximum of the view's minimum height
9758 * and the background's minimum height
9759 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
9760 * <p>
9761 * When being used in {@link #onMeasure(int, int)}, the caller should still
9762 * ensure the returned height is within the requirements of the parent.
9763 *
9764 * @return The suggested minimum height of the view.
9765 */
9766 protected int getSuggestedMinimumHeight() {
9767 int suggestedMinHeight = mMinHeight;
9768
9769 if (mBGDrawable != null) {
9770 final int bgMinHeight = mBGDrawable.getMinimumHeight();
9771 if (suggestedMinHeight < bgMinHeight) {
9772 suggestedMinHeight = bgMinHeight;
9773 }
9774 }
9775
9776 return suggestedMinHeight;
9777 }
9778
9779 /**
9780 * Returns the suggested minimum width that the view should use. This
9781 * returns the maximum of the view's minimum width)
9782 * and the background's minimum width
9783 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
9784 * <p>
9785 * When being used in {@link #onMeasure(int, int)}, the caller should still
9786 * ensure the returned width is within the requirements of the parent.
9787 *
9788 * @return The suggested minimum width of the view.
9789 */
9790 protected int getSuggestedMinimumWidth() {
9791 int suggestedMinWidth = mMinWidth;
9792
9793 if (mBGDrawable != null) {
9794 final int bgMinWidth = mBGDrawable.getMinimumWidth();
9795 if (suggestedMinWidth < bgMinWidth) {
9796 suggestedMinWidth = bgMinWidth;
9797 }
9798 }
9799
9800 return suggestedMinWidth;
9801 }
9802
9803 /**
9804 * Sets the minimum height of the view. It is not guaranteed the view will
9805 * be able to achieve this minimum height (for example, if its parent layout
9806 * constrains it with less available height).
9807 *
9808 * @param minHeight The minimum height the view will try to be.
9809 */
9810 public void setMinimumHeight(int minHeight) {
9811 mMinHeight = minHeight;
9812 }
9813
9814 /**
9815 * Sets the minimum width of the view. It is not guaranteed the view will
9816 * be able to achieve this minimum width (for example, if its parent layout
9817 * constrains it with less available width).
9818 *
9819 * @param minWidth The minimum width the view will try to be.
9820 */
9821 public void setMinimumWidth(int minWidth) {
9822 mMinWidth = minWidth;
9823 }
9824
9825 /**
9826 * Get the animation currently associated with this view.
9827 *
9828 * @return The animation that is currently playing or
9829 * scheduled to play for this view.
9830 */
9831 public Animation getAnimation() {
9832 return mCurrentAnimation;
9833 }
9834
9835 /**
9836 * Start the specified animation now.
9837 *
9838 * @param animation the animation to start now
9839 */
9840 public void startAnimation(Animation animation) {
9841 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
9842 setAnimation(animation);
9843 invalidate();
9844 }
9845
9846 /**
9847 * Cancels any animations for this view.
9848 */
9849 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08009850 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08009851 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08009852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009853 mCurrentAnimation = null;
9854 }
9855
9856 /**
9857 * Sets the next animation to play for this view.
9858 * If you want the animation to play immediately, use
9859 * startAnimation. This method provides allows fine-grained
9860 * control over the start time and invalidation, but you
9861 * must make sure that 1) the animation has a start time set, and
9862 * 2) the view will be invalidated when the animation is supposed to
9863 * start.
9864 *
9865 * @param animation The next animation, or null.
9866 */
9867 public void setAnimation(Animation animation) {
9868 mCurrentAnimation = animation;
9869 if (animation != null) {
9870 animation.reset();
9871 }
9872 }
9873
9874 /**
9875 * Invoked by a parent ViewGroup to notify the start of the animation
9876 * currently associated with this view. If you override this method,
9877 * always call super.onAnimationStart();
9878 *
9879 * @see #setAnimation(android.view.animation.Animation)
9880 * @see #getAnimation()
9881 */
9882 protected void onAnimationStart() {
9883 mPrivateFlags |= ANIMATION_STARTED;
9884 }
9885
9886 /**
9887 * Invoked by a parent ViewGroup to notify the end of the animation
9888 * currently associated with this view. If you override this method,
9889 * always call super.onAnimationEnd();
9890 *
9891 * @see #setAnimation(android.view.animation.Animation)
9892 * @see #getAnimation()
9893 */
9894 protected void onAnimationEnd() {
9895 mPrivateFlags &= ~ANIMATION_STARTED;
9896 }
9897
9898 /**
9899 * Invoked if there is a Transform that involves alpha. Subclass that can
9900 * draw themselves with the specified alpha should return true, and then
9901 * respect that alpha when their onDraw() is called. If this returns false
9902 * then the view may be redirected to draw into an offscreen buffer to
9903 * fulfill the request, which will look fine, but may be slower than if the
9904 * subclass handles it internally. The default implementation returns false.
9905 *
9906 * @param alpha The alpha (0..255) to apply to the view's drawing
9907 * @return true if the view can draw with the specified alpha.
9908 */
9909 protected boolean onSetAlpha(int alpha) {
9910 return false;
9911 }
9912
9913 /**
9914 * This is used by the RootView to perform an optimization when
9915 * the view hierarchy contains one or several SurfaceView.
9916 * SurfaceView is always considered transparent, but its children are not,
9917 * therefore all View objects remove themselves from the global transparent
9918 * region (passed as a parameter to this function).
9919 *
9920 * @param region The transparent region for this ViewRoot (window).
9921 *
9922 * @return Returns true if the effective visibility of the view at this
9923 * point is opaque, regardless of the transparent region; returns false
9924 * if it is possible for underlying windows to be seen behind the view.
9925 *
9926 * {@hide}
9927 */
9928 public boolean gatherTransparentRegion(Region region) {
9929 final AttachInfo attachInfo = mAttachInfo;
9930 if (region != null && attachInfo != null) {
9931 final int pflags = mPrivateFlags;
9932 if ((pflags & SKIP_DRAW) == 0) {
9933 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
9934 // remove it from the transparent region.
9935 final int[] location = attachInfo.mTransparentLocation;
9936 getLocationInWindow(location);
9937 region.op(location[0], location[1], location[0] + mRight - mLeft,
9938 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
9939 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
9940 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
9941 // exists, so we remove the background drawable's non-transparent
9942 // parts from this transparent region.
9943 applyDrawableToTransparentRegion(mBGDrawable, region);
9944 }
9945 }
9946 return true;
9947 }
9948
9949 /**
9950 * Play a sound effect for this view.
9951 *
9952 * <p>The framework will play sound effects for some built in actions, such as
9953 * clicking, but you may wish to play these effects in your widget,
9954 * for instance, for internal navigation.
9955 *
9956 * <p>The sound effect will only be played if sound effects are enabled by the user, and
9957 * {@link #isSoundEffectsEnabled()} is true.
9958 *
9959 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
9960 */
9961 public void playSoundEffect(int soundConstant) {
9962 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
9963 return;
9964 }
9965 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
9966 }
9967
9968 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009969 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009970 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009971 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009972 *
9973 * <p>The framework will provide haptic feedback for some built in actions,
9974 * such as long presses, but you may wish to provide feedback for your
9975 * own widget.
9976 *
9977 * <p>The feedback will only be performed if
9978 * {@link #isHapticFeedbackEnabled()} is true.
9979 *
9980 * @param feedbackConstant One of the constants defined in
9981 * {@link HapticFeedbackConstants}
9982 */
9983 public boolean performHapticFeedback(int feedbackConstant) {
9984 return performHapticFeedback(feedbackConstant, 0);
9985 }
9986
9987 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009988 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009989 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009990 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009991 *
9992 * @param feedbackConstant One of the constants defined in
9993 * {@link HapticFeedbackConstants}
9994 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
9995 */
9996 public boolean performHapticFeedback(int feedbackConstant, int flags) {
9997 if (mAttachInfo == null) {
9998 return false;
9999 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010000 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010001 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010002 && !isHapticFeedbackEnabled()) {
10003 return false;
10004 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010005 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10006 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010007 }
10008
10009 /**
Christopher Tate2c095f32010-10-04 14:13:40 -070010010 * !!! TODO: real docs
10011 *
10012 * The base class implementation makes the thumbnail the same size and appearance
10013 * as the view itself, and positions it with its center at the touch point.
10014 */
Christopher Tatea0374192010-10-05 13:06:41 -070010015 public static class DragThumbnailBuilder {
10016 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010017
10018 /**
10019 * Construct a thumbnail builder object for use with the given view.
10020 * @param view
10021 */
10022 public DragThumbnailBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010023 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010024 }
10025
Chris Tate6b391282010-10-14 15:48:59 -070010026 final public View getView() {
10027 return mView.get();
10028 }
10029
Christopher Tate2c095f32010-10-04 14:13:40 -070010030 /**
10031 * Provide the draggable-thumbnail metrics for the operation: the dimensions of
10032 * the thumbnail image itself, and the point within that thumbnail that should
10033 * be centered under the touch location while dragging.
10034 * <p>
10035 * The default implementation sets the dimensions of the thumbnail to be the
10036 * same as the dimensions of the View itself and centers the thumbnail under
10037 * the touch point.
10038 *
10039 * @param thumbnailSize The application should set the {@code x} member of this
10040 * parameter to the desired thumbnail width, and the {@code y} member to
10041 * the desired height.
10042 * @param thumbnailTouchPoint The application should set this point to be the
10043 * location within the thumbnail that should track directly underneath
10044 * the touch point on the screen during a drag.
10045 */
10046 public void onProvideThumbnailMetrics(Point thumbnailSize, Point thumbnailTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070010047 final View view = mView.get();
10048 if (view != null) {
10049 thumbnailSize.set(view.getWidth(), view.getHeight());
10050 thumbnailTouchPoint.set(thumbnailSize.x / 2, thumbnailSize.y / 2);
10051 } else {
10052 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10053 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010054 }
10055
10056 /**
10057 * Draw the thumbnail image for the upcoming drag. The thumbnail canvas was
10058 * created with the dimensions supplied by the onProvideThumbnailMetrics()
10059 * callback.
10060 *
10061 * @param canvas
10062 */
10063 public void onDrawThumbnail(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070010064 final View view = mView.get();
10065 if (view != null) {
10066 view.draw(canvas);
10067 } else {
10068 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag thumb but no view");
10069 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010070 }
10071 }
10072
10073 /**
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010074 * Drag and drop. App calls startDrag(), then callbacks to the thumbnail builder's
10075 * onProvideThumbnailMetrics() and onDrawThumbnail() methods happen, then the drag
10076 * operation is handed over to the OS.
Christopher Tatea53146c2010-09-07 11:57:52 -070010077 * !!! TODO: real docs
Christopher Tatea53146c2010-09-07 11:57:52 -070010078 */
Christopher Tate2c095f32010-10-04 14:13:40 -070010079 public final boolean startDrag(ClipData data, DragThumbnailBuilder thumbBuilder,
10080 boolean myWindowOnly) {
10081 if (ViewDebug.DEBUG_DRAG) {
10082 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " local=" + myWindowOnly);
Christopher Tatea53146c2010-09-07 11:57:52 -070010083 }
10084 boolean okay = false;
10085
Christopher Tate2c095f32010-10-04 14:13:40 -070010086 Point thumbSize = new Point();
10087 Point thumbTouchPoint = new Point();
10088 thumbBuilder.onProvideThumbnailMetrics(thumbSize, thumbTouchPoint);
10089
10090 if ((thumbSize.x < 0) || (thumbSize.y < 0) ||
10091 (thumbTouchPoint.x < 0) || (thumbTouchPoint.y < 0)) {
10092 throw new IllegalStateException("Drag thumb dimensions must not be negative");
10093 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010094
Chris Tatea32dcf72010-10-14 12:13:50 -070010095 if (ViewDebug.DEBUG_DRAG) {
10096 Log.d(VIEW_LOG_TAG, "drag thumb: width=" + thumbSize.x + " height=" + thumbSize.y
10097 + " thumbX=" + thumbTouchPoint.x + " thumbY=" + thumbTouchPoint.y);
10098 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010099 Surface surface = new Surface();
10100 try {
10101 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Chris Tatea32dcf72010-10-14 12:13:50 -070010102 myWindowOnly, thumbSize.x, thumbSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070010103 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070010104 + " surface=" + surface);
10105 if (token != null) {
10106 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070010107 try {
Chris Tate6b391282010-10-14 15:48:59 -070010108 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate2c095f32010-10-04 14:13:40 -070010109 thumbBuilder.onDrawThumbnail(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070010110 } finally {
10111 surface.unlockCanvasAndPost(canvas);
10112 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010113
Christopher Tate2c095f32010-10-04 14:13:40 -070010114 // repurpose 'thumbSize' for the last touch point
10115 getViewRoot().getLastTouchPoint(thumbSize);
10116
Christopher Tatea53146c2010-09-07 11:57:52 -070010117 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate2c095f32010-10-04 14:13:40 -070010118 (float) thumbSize.x, (float) thumbSize.y,
10119 (float) thumbTouchPoint.x, (float) thumbTouchPoint.y, data);
10120 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070010121 }
10122 } catch (Exception e) {
10123 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
10124 surface.destroy();
10125 }
10126
10127 return okay;
10128 }
10129
Christopher Tatea53146c2010-09-07 11:57:52 -070010130 /**
10131 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
10132 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
10133 *
10134 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
10135 * being dragged. onDragEvent() should return 'true' if the view can handle
10136 * a drop of that content. A view that returns 'false' here will receive no
10137 * further calls to onDragEvent() about the drag/drop operation.
10138 *
10139 * For DRAG_ENTERED, event.getClipDescription() describes the content being
10140 * dragged. This will be the same content description passed in the
10141 * DRAG_STARTED_EVENT invocation.
10142 *
10143 * For DRAG_EXITED, event.getClipDescription() describes the content being
10144 * dragged. This will be the same content description passed in the
10145 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
10146 * drag-acceptance visual state.
10147 *
10148 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10149 * coordinates of the current drag point. The view must return 'true' if it
10150 * can accept a drop of the current drag content, false otherwise.
10151 *
10152 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10153 * within the view; also, event.getClipData() returns the full data payload
10154 * being dropped. The view should return 'true' if it consumed the dropped
10155 * content, 'false' if it did not.
10156 *
10157 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
10158 * to its normal visual state.
10159 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010160 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070010161 return false;
10162 }
10163
10164 /**
10165 * Views typically don't need to override dispatchDragEvent(); it just calls
Chris Tate32affef2010-10-18 15:29:21 -070010166 * onDragEvent(event) and passes the result up appropriately.
Christopher Tatea53146c2010-09-07 11:57:52 -070010167 */
10168 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070010169 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10170 && mOnDragListener.onDrag(this, event)) {
10171 return true;
10172 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010173 return onDragEvent(event);
10174 }
10175
10176 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070010177 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
10178 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070010179 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070010180 */
10181 public void onCloseSystemDialogs(String reason) {
10182 }
10183
10184 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010185 * Given a Drawable whose bounds have been set to draw into this view,
10186 * update a Region being computed for {@link #gatherTransparentRegion} so
10187 * that any non-transparent parts of the Drawable are removed from the
10188 * given transparent region.
10189 *
10190 * @param dr The Drawable whose transparency is to be applied to the region.
10191 * @param region A Region holding the current transparency information,
10192 * where any parts of the region that are set are considered to be
10193 * transparent. On return, this region will be modified to have the
10194 * transparency information reduced by the corresponding parts of the
10195 * Drawable that are not transparent.
10196 * {@hide}
10197 */
10198 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
10199 if (DBG) {
10200 Log.i("View", "Getting transparent region for: " + this);
10201 }
10202 final Region r = dr.getTransparentRegion();
10203 final Rect db = dr.getBounds();
10204 final AttachInfo attachInfo = mAttachInfo;
10205 if (r != null && attachInfo != null) {
10206 final int w = getRight()-getLeft();
10207 final int h = getBottom()-getTop();
10208 if (db.left > 0) {
10209 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
10210 r.op(0, 0, db.left, h, Region.Op.UNION);
10211 }
10212 if (db.right < w) {
10213 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
10214 r.op(db.right, 0, w, h, Region.Op.UNION);
10215 }
10216 if (db.top > 0) {
10217 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
10218 r.op(0, 0, w, db.top, Region.Op.UNION);
10219 }
10220 if (db.bottom < h) {
10221 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
10222 r.op(0, db.bottom, w, h, Region.Op.UNION);
10223 }
10224 final int[] location = attachInfo.mTransparentLocation;
10225 getLocationInWindow(location);
10226 r.translate(location[0], location[1]);
10227 region.op(r, Region.Op.INTERSECT);
10228 } else {
10229 region.op(db, Region.Op.DIFFERENCE);
10230 }
10231 }
10232
Adam Powelle14579b2009-12-16 18:39:52 -080010233 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010234 mHasPerformedLongPress = false;
10235
10236 if (mPendingCheckForLongPress == null) {
10237 mPendingCheckForLongPress = new CheckForLongPress();
10238 }
10239 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080010240 postDelayed(mPendingCheckForLongPress,
10241 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010242 }
10243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010244 /**
10245 * Inflate a view from an XML resource. This convenience method wraps the {@link
10246 * LayoutInflater} class, which provides a full range of options for view inflation.
10247 *
10248 * @param context The Context object for your activity or application.
10249 * @param resource The resource ID to inflate
10250 * @param root A view group that will be the parent. Used to properly inflate the
10251 * layout_* parameters.
10252 * @see LayoutInflater
10253 */
10254 public static View inflate(Context context, int resource, ViewGroup root) {
10255 LayoutInflater factory = LayoutInflater.from(context);
10256 return factory.inflate(resource, root);
10257 }
Romain Guy33e72ae2010-07-17 12:40:29 -070010258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010259 /**
Adam Powell637d3372010-08-25 14:37:03 -070010260 * Scroll the view with standard behavior for scrolling beyond the normal
10261 * content boundaries. Views that call this method should override
10262 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
10263 * results of an over-scroll operation.
10264 *
10265 * Views can use this method to handle any touch or fling-based scrolling.
10266 *
10267 * @param deltaX Change in X in pixels
10268 * @param deltaY Change in Y in pixels
10269 * @param scrollX Current X scroll value in pixels before applying deltaX
10270 * @param scrollY Current Y scroll value in pixels before applying deltaY
10271 * @param scrollRangeX Maximum content scroll range along the X axis
10272 * @param scrollRangeY Maximum content scroll range along the Y axis
10273 * @param maxOverScrollX Number of pixels to overscroll by in either direction
10274 * along the X axis.
10275 * @param maxOverScrollY Number of pixels to overscroll by in either direction
10276 * along the Y axis.
10277 * @param isTouchEvent true if this scroll operation is the result of a touch event.
10278 * @return true if scrolling was clamped to an over-scroll boundary along either
10279 * axis, false otherwise.
10280 */
10281 protected boolean overScrollBy(int deltaX, int deltaY,
10282 int scrollX, int scrollY,
10283 int scrollRangeX, int scrollRangeY,
10284 int maxOverScrollX, int maxOverScrollY,
10285 boolean isTouchEvent) {
10286 final int overScrollMode = mOverScrollMode;
10287 final boolean canScrollHorizontal =
10288 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
10289 final boolean canScrollVertical =
10290 computeVerticalScrollRange() > computeVerticalScrollExtent();
10291 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
10292 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
10293 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
10294 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
10295
10296 int newScrollX = scrollX + deltaX;
10297 if (!overScrollHorizontal) {
10298 maxOverScrollX = 0;
10299 }
10300
10301 int newScrollY = scrollY + deltaY;
10302 if (!overScrollVertical) {
10303 maxOverScrollY = 0;
10304 }
10305
10306 // Clamp values if at the limits and record
10307 final int left = -maxOverScrollX;
10308 final int right = maxOverScrollX + scrollRangeX;
10309 final int top = -maxOverScrollY;
10310 final int bottom = maxOverScrollY + scrollRangeY;
10311
10312 boolean clampedX = false;
10313 if (newScrollX > right) {
10314 newScrollX = right;
10315 clampedX = true;
10316 } else if (newScrollX < left) {
10317 newScrollX = left;
10318 clampedX = true;
10319 }
10320
10321 boolean clampedY = false;
10322 if (newScrollY > bottom) {
10323 newScrollY = bottom;
10324 clampedY = true;
10325 } else if (newScrollY < top) {
10326 newScrollY = top;
10327 clampedY = true;
10328 }
10329
10330 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
10331
10332 return clampedX || clampedY;
10333 }
10334
10335 /**
10336 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
10337 * respond to the results of an over-scroll operation.
10338 *
10339 * @param scrollX New X scroll value in pixels
10340 * @param scrollY New Y scroll value in pixels
10341 * @param clampedX True if scrollX was clamped to an over-scroll boundary
10342 * @param clampedY True if scrollY was clamped to an over-scroll boundary
10343 */
10344 protected void onOverScrolled(int scrollX, int scrollY,
10345 boolean clampedX, boolean clampedY) {
10346 // Intentionally empty.
10347 }
10348
10349 /**
10350 * Returns the over-scroll mode for this view. The result will be
10351 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10352 * (allow over-scrolling only if the view content is larger than the container),
10353 * or {@link #OVER_SCROLL_NEVER}.
10354 *
10355 * @return This view's over-scroll mode.
10356 */
10357 public int getOverScrollMode() {
10358 return mOverScrollMode;
10359 }
10360
10361 /**
10362 * Set the over-scroll mode for this view. Valid over-scroll modes are
10363 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10364 * (allow over-scrolling only if the view content is larger than the container),
10365 * or {@link #OVER_SCROLL_NEVER}.
10366 *
10367 * Setting the over-scroll mode of a view will have an effect only if the
10368 * view is capable of scrolling.
10369 *
10370 * @param overScrollMode The new over-scroll mode for this view.
10371 */
10372 public void setOverScrollMode(int overScrollMode) {
10373 if (overScrollMode != OVER_SCROLL_ALWAYS &&
10374 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
10375 overScrollMode != OVER_SCROLL_NEVER) {
10376 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
10377 }
10378 mOverScrollMode = overScrollMode;
10379 }
10380
10381 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010382 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
10383 * Each MeasureSpec represents a requirement for either the width or the height.
10384 * A MeasureSpec is comprised of a size and a mode. There are three possible
10385 * modes:
10386 * <dl>
10387 * <dt>UNSPECIFIED</dt>
10388 * <dd>
10389 * The parent has not imposed any constraint on the child. It can be whatever size
10390 * it wants.
10391 * </dd>
10392 *
10393 * <dt>EXACTLY</dt>
10394 * <dd>
10395 * The parent has determined an exact size for the child. The child is going to be
10396 * given those bounds regardless of how big it wants to be.
10397 * </dd>
10398 *
10399 * <dt>AT_MOST</dt>
10400 * <dd>
10401 * The child can be as large as it wants up to the specified size.
10402 * </dd>
10403 * </dl>
10404 *
10405 * MeasureSpecs are implemented as ints to reduce object allocation. This class
10406 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
10407 */
10408 public static class MeasureSpec {
10409 private static final int MODE_SHIFT = 30;
10410 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
10411
10412 /**
10413 * Measure specification mode: The parent has not imposed any constraint
10414 * on the child. It can be whatever size it wants.
10415 */
10416 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
10417
10418 /**
10419 * Measure specification mode: The parent has determined an exact size
10420 * for the child. The child is going to be given those bounds regardless
10421 * of how big it wants to be.
10422 */
10423 public static final int EXACTLY = 1 << MODE_SHIFT;
10424
10425 /**
10426 * Measure specification mode: The child can be as large as it wants up
10427 * to the specified size.
10428 */
10429 public static final int AT_MOST = 2 << MODE_SHIFT;
10430
10431 /**
10432 * Creates a measure specification based on the supplied size and mode.
10433 *
10434 * The mode must always be one of the following:
10435 * <ul>
10436 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
10437 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
10438 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
10439 * </ul>
10440 *
10441 * @param size the size of the measure specification
10442 * @param mode the mode of the measure specification
10443 * @return the measure specification based on size and mode
10444 */
10445 public static int makeMeasureSpec(int size, int mode) {
10446 return size + mode;
10447 }
10448
10449 /**
10450 * Extracts the mode from the supplied measure specification.
10451 *
10452 * @param measureSpec the measure specification to extract the mode from
10453 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
10454 * {@link android.view.View.MeasureSpec#AT_MOST} or
10455 * {@link android.view.View.MeasureSpec#EXACTLY}
10456 */
10457 public static int getMode(int measureSpec) {
10458 return (measureSpec & MODE_MASK);
10459 }
10460
10461 /**
10462 * Extracts the size from the supplied measure specification.
10463 *
10464 * @param measureSpec the measure specification to extract the size from
10465 * @return the size in pixels defined in the supplied measure specification
10466 */
10467 public static int getSize(int measureSpec) {
10468 return (measureSpec & ~MODE_MASK);
10469 }
10470
10471 /**
10472 * Returns a String representation of the specified measure
10473 * specification.
10474 *
10475 * @param measureSpec the measure specification to convert to a String
10476 * @return a String with the following format: "MeasureSpec: MODE SIZE"
10477 */
10478 public static String toString(int measureSpec) {
10479 int mode = getMode(measureSpec);
10480 int size = getSize(measureSpec);
10481
10482 StringBuilder sb = new StringBuilder("MeasureSpec: ");
10483
10484 if (mode == UNSPECIFIED)
10485 sb.append("UNSPECIFIED ");
10486 else if (mode == EXACTLY)
10487 sb.append("EXACTLY ");
10488 else if (mode == AT_MOST)
10489 sb.append("AT_MOST ");
10490 else
10491 sb.append(mode).append(" ");
10492
10493 sb.append(size);
10494 return sb.toString();
10495 }
10496 }
10497
10498 class CheckForLongPress implements Runnable {
10499
10500 private int mOriginalWindowAttachCount;
10501
10502 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070010503 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010504 && mOriginalWindowAttachCount == mWindowAttachCount) {
10505 if (performLongClick()) {
10506 mHasPerformedLongPress = true;
10507 }
10508 }
10509 }
10510
10511 public void rememberWindowAttachCount() {
10512 mOriginalWindowAttachCount = mWindowAttachCount;
10513 }
10514 }
Adam Powelle14579b2009-12-16 18:39:52 -080010515
10516 private final class CheckForTap implements Runnable {
10517 public void run() {
10518 mPrivateFlags &= ~PREPRESSED;
10519 mPrivateFlags |= PRESSED;
10520 refreshDrawableState();
10521 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
10522 postCheckForLongClick(ViewConfiguration.getTapTimeout());
10523 }
10524 }
10525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010526
Adam Powella35d7682010-03-12 14:48:13 -080010527 private final class PerformClick implements Runnable {
10528 public void run() {
10529 performClick();
10530 }
10531 }
10532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010533 /**
10534 * Interface definition for a callback to be invoked when a key event is
10535 * dispatched to this view. The callback will be invoked before the key
10536 * event is given to the view.
10537 */
10538 public interface OnKeyListener {
10539 /**
10540 * Called when a key is dispatched to a view. This allows listeners to
10541 * get a chance to respond before the target view.
10542 *
10543 * @param v The view the key has been dispatched to.
10544 * @param keyCode The code for the physical key that was pressed
10545 * @param event The KeyEvent object containing full information about
10546 * the event.
10547 * @return True if the listener has consumed the event, false otherwise.
10548 */
10549 boolean onKey(View v, int keyCode, KeyEvent event);
10550 }
10551
10552 /**
10553 * Interface definition for a callback to be invoked when a touch event is
10554 * dispatched to this view. The callback will be invoked before the touch
10555 * event is given to the view.
10556 */
10557 public interface OnTouchListener {
10558 /**
10559 * Called when a touch event is dispatched to a view. This allows listeners to
10560 * get a chance to respond before the target view.
10561 *
10562 * @param v The view the touch event has been dispatched to.
10563 * @param event The MotionEvent object containing full information about
10564 * the event.
10565 * @return True if the listener has consumed the event, false otherwise.
10566 */
10567 boolean onTouch(View v, MotionEvent event);
10568 }
10569
10570 /**
10571 * Interface definition for a callback to be invoked when a view has been clicked and held.
10572 */
10573 public interface OnLongClickListener {
10574 /**
10575 * Called when a view has been clicked and held.
10576 *
10577 * @param v The view that was clicked and held.
10578 *
10579 * return True if the callback consumed the long click, false otherwise
10580 */
10581 boolean onLongClick(View v);
10582 }
10583
10584 /**
Chris Tate32affef2010-10-18 15:29:21 -070010585 * Interface definition for a callback to be invoked when a drag is being dispatched
10586 * to this view. The callback will be invoked before the hosting view's own
10587 * onDrag(event) method. If the listener wants to fall back to the hosting view's
10588 * onDrag(event) behavior, it should return 'false' from this callback.
10589 */
10590 public interface OnDragListener {
10591 /**
10592 * Called when a drag event is dispatched to a view. This allows listeners
10593 * to get a chance to override base View behavior.
10594 *
10595 * @param v The view the drag has been dispatched to.
10596 * @param event The DragEvent object containing full information
10597 * about the event.
10598 * @return true if the listener consumed the DragEvent, false in order to fall
10599 * back to the view's default handling.
10600 */
10601 boolean onDrag(View v, DragEvent event);
10602 }
10603
10604 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 * Interface definition for a callback to be invoked when the focus state of
10606 * a view changed.
10607 */
10608 public interface OnFocusChangeListener {
10609 /**
10610 * Called when the focus state of a view has changed.
10611 *
10612 * @param v The view whose state has changed.
10613 * @param hasFocus The new focus state of v.
10614 */
10615 void onFocusChange(View v, boolean hasFocus);
10616 }
10617
10618 /**
10619 * Interface definition for a callback to be invoked when a view is clicked.
10620 */
10621 public interface OnClickListener {
10622 /**
10623 * Called when a view has been clicked.
10624 *
10625 * @param v The view that was clicked.
10626 */
10627 void onClick(View v);
10628 }
10629
10630 /**
10631 * Interface definition for a callback to be invoked when the context menu
10632 * for this view is being built.
10633 */
10634 public interface OnCreateContextMenuListener {
10635 /**
10636 * Called when the context menu for this view is being built. It is not
10637 * safe to hold onto the menu after this method returns.
10638 *
10639 * @param menu The context menu that is being built
10640 * @param v The view for which the context menu is being built
10641 * @param menuInfo Extra information about the item for which the
10642 * context menu should be shown. This information will vary
10643 * depending on the class of v.
10644 */
10645 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
10646 }
10647
10648 private final class UnsetPressedState implements Runnable {
10649 public void run() {
10650 setPressed(false);
10651 }
10652 }
10653
10654 /**
10655 * Base class for derived classes that want to save and restore their own
10656 * state in {@link android.view.View#onSaveInstanceState()}.
10657 */
10658 public static class BaseSavedState extends AbsSavedState {
10659 /**
10660 * Constructor used when reading from a parcel. Reads the state of the superclass.
10661 *
10662 * @param source
10663 */
10664 public BaseSavedState(Parcel source) {
10665 super(source);
10666 }
10667
10668 /**
10669 * Constructor called by derived classes when creating their SavedState objects
10670 *
10671 * @param superState The state of the superclass of this view
10672 */
10673 public BaseSavedState(Parcelable superState) {
10674 super(superState);
10675 }
10676
10677 public static final Parcelable.Creator<BaseSavedState> CREATOR =
10678 new Parcelable.Creator<BaseSavedState>() {
10679 public BaseSavedState createFromParcel(Parcel in) {
10680 return new BaseSavedState(in);
10681 }
10682
10683 public BaseSavedState[] newArray(int size) {
10684 return new BaseSavedState[size];
10685 }
10686 };
10687 }
10688
10689 /**
10690 * A set of information given to a view when it is attached to its parent
10691 * window.
10692 */
10693 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010694 interface Callbacks {
10695 void playSoundEffect(int effectId);
10696 boolean performHapticFeedback(int effectId, boolean always);
10697 }
10698
10699 /**
10700 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
10701 * to a Handler. This class contains the target (View) to invalidate and
10702 * the coordinates of the dirty rectangle.
10703 *
10704 * For performance purposes, this class also implements a pool of up to
10705 * POOL_LIMIT objects that get reused. This reduces memory allocations
10706 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010707 */
Romain Guyd928d682009-03-31 17:52:16 -070010708 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010709 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070010710 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
10711 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070010712 public InvalidateInfo newInstance() {
10713 return new InvalidateInfo();
10714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010715
Romain Guyd928d682009-03-31 17:52:16 -070010716 public void onAcquired(InvalidateInfo element) {
10717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010718
Romain Guyd928d682009-03-31 17:52:16 -070010719 public void onReleased(InvalidateInfo element) {
10720 }
10721 }, POOL_LIMIT)
10722 );
10723
10724 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010725
10726 View target;
10727
10728 int left;
10729 int top;
10730 int right;
10731 int bottom;
10732
Romain Guyd928d682009-03-31 17:52:16 -070010733 public void setNextPoolable(InvalidateInfo element) {
10734 mNext = element;
10735 }
10736
10737 public InvalidateInfo getNextPoolable() {
10738 return mNext;
10739 }
10740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010741 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070010742 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010743 }
10744
10745 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070010746 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010747 }
10748 }
10749
10750 final IWindowSession mSession;
10751
10752 final IWindow mWindow;
10753
10754 final IBinder mWindowToken;
10755
10756 final Callbacks mRootCallbacks;
10757
10758 /**
10759 * The top view of the hierarchy.
10760 */
10761 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070010762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010763 IBinder mPanelParentWindowToken;
10764 Surface mSurface;
10765
Romain Guyb051e892010-09-28 19:09:36 -070010766 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080010767 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070010768 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070010769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010770 /**
Romain Guy8506ab42009-06-11 17:35:47 -070010771 * Scale factor used by the compatibility mode
10772 */
10773 float mApplicationScale;
10774
10775 /**
10776 * Indicates whether the application is in compatibility mode
10777 */
10778 boolean mScalingRequired;
10779
10780 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010781 * Left position of this view's window
10782 */
10783 int mWindowLeft;
10784
10785 /**
10786 * Top position of this view's window
10787 */
10788 int mWindowTop;
10789
10790 /**
Adam Powell26153a32010-11-08 15:22:27 -080010791 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070010792 */
Adam Powell26153a32010-11-08 15:22:27 -080010793 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070010794
10795 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010796 * For windows that are full-screen but using insets to layout inside
10797 * of the screen decorations, these are the current insets for the
10798 * content of the window.
10799 */
10800 final Rect mContentInsets = new Rect();
10801
10802 /**
10803 * For windows that are full-screen but using insets to layout inside
10804 * of the screen decorations, these are the current insets for the
10805 * actual visible parts of the window.
10806 */
10807 final Rect mVisibleInsets = new Rect();
10808
10809 /**
10810 * The internal insets given by this window. This value is
10811 * supplied by the client (through
10812 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
10813 * be given to the window manager when changed to be used in laying
10814 * out windows behind it.
10815 */
10816 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
10817 = new ViewTreeObserver.InternalInsetsInfo();
10818
10819 /**
10820 * All views in the window's hierarchy that serve as scroll containers,
10821 * used to determine if the window can be resized or must be panned
10822 * to adjust for a soft input area.
10823 */
10824 final ArrayList<View> mScrollContainers = new ArrayList<View>();
10825
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070010826 final KeyEvent.DispatcherState mKeyDispatchState
10827 = new KeyEvent.DispatcherState();
10828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010829 /**
10830 * Indicates whether the view's window currently has the focus.
10831 */
10832 boolean mHasWindowFocus;
10833
10834 /**
10835 * The current visibility of the window.
10836 */
10837 int mWindowVisibility;
10838
10839 /**
10840 * Indicates the time at which drawing started to occur.
10841 */
10842 long mDrawingTime;
10843
10844 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070010845 * Indicates whether or not ignoring the DIRTY_MASK flags.
10846 */
10847 boolean mIgnoreDirtyState;
10848
10849 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010850 * Indicates whether the view's window is currently in touch mode.
10851 */
10852 boolean mInTouchMode;
10853
10854 /**
10855 * Indicates that ViewRoot should trigger a global layout change
10856 * the next time it performs a traversal
10857 */
10858 boolean mRecomputeGlobalAttributes;
10859
10860 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010861 * Set during a traveral if any views want to keep the screen on.
10862 */
10863 boolean mKeepScreenOn;
10864
10865 /**
10866 * Set if the visibility of any views has changed.
10867 */
10868 boolean mViewVisibilityChanged;
10869
10870 /**
10871 * Set to true if a view has been scrolled.
10872 */
10873 boolean mViewScrollChanged;
10874
10875 /**
10876 * Global to the view hierarchy used as a temporary for dealing with
10877 * x/y points in the transparent region computations.
10878 */
10879 final int[] mTransparentLocation = new int[2];
10880
10881 /**
10882 * Global to the view hierarchy used as a temporary for dealing with
10883 * x/y points in the ViewGroup.invalidateChild implementation.
10884 */
10885 final int[] mInvalidateChildLocation = new int[2];
10886
Chet Haasec3aa3612010-06-17 08:50:37 -070010887
10888 /**
10889 * Global to the view hierarchy used as a temporary for dealing with
10890 * x/y location when view is transformed.
10891 */
10892 final float[] mTmpTransformLocation = new float[2];
10893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 /**
10895 * The view tree observer used to dispatch global events like
10896 * layout, pre-draw, touch mode change, etc.
10897 */
10898 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
10899
10900 /**
10901 * A Canvas used by the view hierarchy to perform bitmap caching.
10902 */
10903 Canvas mCanvas;
10904
10905 /**
10906 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
10907 * handler can be used to pump events in the UI events queue.
10908 */
10909 final Handler mHandler;
10910
10911 /**
10912 * Identifier for messages requesting the view to be invalidated.
10913 * Such messages should be sent to {@link #mHandler}.
10914 */
10915 static final int INVALIDATE_MSG = 0x1;
10916
10917 /**
10918 * Identifier for messages requesting the view to invalidate a region.
10919 * Such messages should be sent to {@link #mHandler}.
10920 */
10921 static final int INVALIDATE_RECT_MSG = 0x2;
10922
10923 /**
10924 * Temporary for use in computing invalidate rectangles while
10925 * calling up the hierarchy.
10926 */
10927 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070010928
10929 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070010930 * Temporary for use in computing hit areas with transformed views
10931 */
10932 final RectF mTmpTransformRect = new RectF();
10933
10934 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070010935 * Temporary list for use in collecting focusable descendents of a view.
10936 */
10937 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
10938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010939 /**
10940 * Creates a new set of attachment information with the specified
10941 * events handler and thread.
10942 *
10943 * @param handler the events handler the view must use
10944 */
10945 AttachInfo(IWindowSession session, IWindow window,
10946 Handler handler, Callbacks effectPlayer) {
10947 mSession = session;
10948 mWindow = window;
10949 mWindowToken = window.asBinder();
10950 mHandler = handler;
10951 mRootCallbacks = effectPlayer;
10952 }
10953 }
10954
10955 /**
10956 * <p>ScrollabilityCache holds various fields used by a View when scrolling
10957 * is supported. This avoids keeping too many unused fields in most
10958 * instances of View.</p>
10959 */
Mike Cleronf116bf82009-09-27 19:14:12 -070010960 private static class ScrollabilityCache implements Runnable {
10961
10962 /**
10963 * Scrollbars are not visible
10964 */
10965 public static final int OFF = 0;
10966
10967 /**
10968 * Scrollbars are visible
10969 */
10970 public static final int ON = 1;
10971
10972 /**
10973 * Scrollbars are fading away
10974 */
10975 public static final int FADING = 2;
10976
10977 public boolean fadeScrollBars;
10978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010979 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070010980 public int scrollBarDefaultDelayBeforeFade;
10981 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010982
10983 public int scrollBarSize;
10984 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070010985 public float[] interpolatorValues;
10986 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010987
10988 public final Paint paint;
10989 public final Matrix matrix;
10990 public Shader shader;
10991
Mike Cleronf116bf82009-09-27 19:14:12 -070010992 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
10993
Romain Guy8fb95422010-08-17 18:38:51 -070010994 private final float[] mOpaque = { 255.0f };
10995 private final float[] mTransparent = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070010996
10997 /**
10998 * When fading should start. This time moves into the future every time
10999 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11000 */
11001 public long fadeStartTime;
11002
11003
11004 /**
11005 * The current state of the scrollbars: ON, OFF, or FADING
11006 */
11007 public int state = OFF;
11008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011009 private int mLastColor;
11010
Mike Cleronf116bf82009-09-27 19:14:12 -070011011 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011012 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11013 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070011014 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11015 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011016
11017 paint = new Paint();
11018 matrix = new Matrix();
11019 // use use a height of 1, and then wack the matrix each time we
11020 // actually use it.
11021 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 paint.setShader(shader);
11024 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070011025 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011026 }
Romain Guy8506ab42009-06-11 17:35:47 -070011027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011028 public void setFadeColor(int color) {
11029 if (color != 0 && color != mLastColor) {
11030 mLastColor = color;
11031 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070011032
Romain Guye55e1a72009-08-27 10:42:26 -070011033 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11034 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011036 paint.setShader(shader);
11037 // Restore the default transfer mode (src_over)
11038 paint.setXfermode(null);
11039 }
11040 }
Mike Cleronf116bf82009-09-27 19:14:12 -070011041
11042 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070011043 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070011044 if (now >= fadeStartTime) {
11045
11046 // the animation fades the scrollbars out by changing
11047 // the opacity (alpha) from fully opaque to fully
11048 // transparent
11049 int nextFrame = (int) now;
11050 int framesCount = 0;
11051
11052 Interpolator interpolator = scrollBarInterpolator;
11053
11054 // Start opaque
11055 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
11056
11057 // End transparent
11058 nextFrame += scrollBarFadeDuration;
11059 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
11060
11061 state = FADING;
11062
11063 // Kick off the fade animation
11064 host.invalidate();
11065 }
11066 }
11067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011068 }
11069}