blob: b3e0f188977c6fdf9bf80140d0abba052c06043b [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;
Jeff Brown4e6319b2010-12-13 10:36:51 -080067import com.android.internal.util.Predicate;
Romain Guyf607bdc2010-09-10 19:20:06 -070068import com.android.internal.view.menu.MenuBuilder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
Christopher Tatea0374192010-10-05 13:06:41 -070070import java.lang.ref.WeakReference;
svetoslavganov75986cf2009-05-14 22:28:01 -070071import java.lang.reflect.InvocationTargetException;
72import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.util.ArrayList;
74import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070075import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070076import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077
78/**
79 * <p>
80 * This class represents the basic building block for user interface components. A View
81 * occupies a rectangular area on the screen and is responsible for drawing and
82 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070083 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
85 * are invisible containers that hold other Views (or other ViewGroups) and define
86 * their layout properties.
87 * </p>
88 *
89 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070090 * <p>For an introduction to using this class to develop your
91 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070093 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
95 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
102 * </p>
103 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700104 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 * <a name="Using"></a>
106 * <h3>Using Views</h3>
107 * <p>
108 * All of the views in a window are arranged in a single tree. You can add views
109 * either from code or by specifying a tree of views in one or more XML layout
110 * files. There are many specialized subclasses of views that act as controls or
111 * are capable of displaying text, images, or other content.
112 * </p>
113 * <p>
114 * Once you have created a tree of views, there are typically a few types of
115 * common operations you may wish to perform:
116 * <ul>
117 * <li><strong>Set properties:</strong> for example setting the text of a
118 * {@link android.widget.TextView}. The available properties and the methods
119 * that set them will vary among the different subclasses of views. Note that
120 * properties that are known at build time can be set in the XML layout
121 * files.</li>
122 * <li><strong>Set focus:</strong> The framework will handled moving focus in
123 * response to user input. To force focus to a specific view, call
124 * {@link #requestFocus}.</li>
125 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
126 * that will be notified when something interesting happens to the view. For
127 * example, all views will let you set a listener to be notified when the view
128 * gains or loses focus. You can register such a listener using
129 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
130 * specialized listeners. For example, a Button exposes a listener to notify
131 * clients when the button is clicked.</li>
132 * <li><strong>Set visibility:</strong> You can hide or show views using
133 * {@link #setVisibility}.</li>
134 * </ul>
135 * </p>
136 * <p><em>
137 * Note: The Android framework is responsible for measuring, laying out and
138 * drawing views. You should not call methods that perform these actions on
139 * views yourself unless you are actually implementing a
140 * {@link android.view.ViewGroup}.
141 * </em></p>
142 *
143 * <a name="Lifecycle"></a>
144 * <h3>Implementing a Custom View</h3>
145 *
146 * <p>
147 * To implement a custom view, you will usually begin by providing overrides for
148 * some of the standard methods that the framework calls on all views. You do
149 * not need to override all of these methods. In fact, you can start by just
150 * overriding {@link #onDraw(android.graphics.Canvas)}.
151 * <table border="2" width="85%" align="center" cellpadding="5">
152 * <thead>
153 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
154 * </thead>
155 *
156 * <tbody>
157 * <tr>
158 * <td rowspan="2">Creation</td>
159 * <td>Constructors</td>
160 * <td>There is a form of the constructor that are called when the view
161 * is created from code and a form that is called when the view is
162 * inflated from a layout file. The second form should parse and apply
163 * any attributes defined in the layout file.
164 * </td>
165 * </tr>
166 * <tr>
167 * <td><code>{@link #onFinishInflate()}</code></td>
168 * <td>Called after a view and all of its children has been inflated
169 * from XML.</td>
170 * </tr>
171 *
172 * <tr>
173 * <td rowspan="3">Layout</td>
174 * <td><code>{@link #onMeasure}</code></td>
175 * <td>Called to determine the size requirements for this view and all
176 * of its children.
177 * </td>
178 * </tr>
179 * <tr>
180 * <td><code>{@link #onLayout}</code></td>
181 * <td>Called when this view should assign a size and position to all
182 * of its children.
183 * </td>
184 * </tr>
185 * <tr>
186 * <td><code>{@link #onSizeChanged}</code></td>
187 * <td>Called when the size of this view has changed.
188 * </td>
189 * </tr>
190 *
191 * <tr>
192 * <td>Drawing</td>
193 * <td><code>{@link #onDraw}</code></td>
194 * <td>Called when the view should render its content.
195 * </td>
196 * </tr>
197 *
198 * <tr>
199 * <td rowspan="4">Event processing</td>
200 * <td><code>{@link #onKeyDown}</code></td>
201 * <td>Called when a new key event occurs.
202 * </td>
203 * </tr>
204 * <tr>
205 * <td><code>{@link #onKeyUp}</code></td>
206 * <td>Called when a key up event occurs.
207 * </td>
208 * </tr>
209 * <tr>
210 * <td><code>{@link #onTrackballEvent}</code></td>
211 * <td>Called when a trackball motion event occurs.
212 * </td>
213 * </tr>
214 * <tr>
215 * <td><code>{@link #onTouchEvent}</code></td>
216 * <td>Called when a touch screen motion event occurs.
217 * </td>
218 * </tr>
219 *
220 * <tr>
221 * <td rowspan="2">Focus</td>
222 * <td><code>{@link #onFocusChanged}</code></td>
223 * <td>Called when the view gains or loses focus.
224 * </td>
225 * </tr>
226 *
227 * <tr>
228 * <td><code>{@link #onWindowFocusChanged}</code></td>
229 * <td>Called when the window containing the view gains or loses focus.
230 * </td>
231 * </tr>
232 *
233 * <tr>
234 * <td rowspan="3">Attaching</td>
235 * <td><code>{@link #onAttachedToWindow()}</code></td>
236 * <td>Called when the view is attached to a window.
237 * </td>
238 * </tr>
239 *
240 * <tr>
241 * <td><code>{@link #onDetachedFromWindow}</code></td>
242 * <td>Called when the view is detached from its window.
243 * </td>
244 * </tr>
245 *
246 * <tr>
247 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
248 * <td>Called when the visibility of the window containing the view
249 * has changed.
250 * </td>
251 * </tr>
252 * </tbody>
253 *
254 * </table>
255 * </p>
256 *
257 * <a name="IDs"></a>
258 * <h3>IDs</h3>
259 * Views may have an integer id associated with them. These ids are typically
260 * assigned in the layout XML files, and are used to find specific views within
261 * the view tree. A common pattern is to:
262 * <ul>
263 * <li>Define a Button in the layout file and assign it a unique ID.
264 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700265 * &lt;Button
266 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 * android:layout_width="wrap_content"
268 * android:layout_height="wrap_content"
269 * android:text="@string/my_button_text"/&gt;
270 * </pre></li>
271 * <li>From the onCreate method of an Activity, find the Button
272 * <pre class="prettyprint">
273 * Button myButton = (Button) findViewById(R.id.my_button);
274 * </pre></li>
275 * </ul>
276 * <p>
277 * View IDs need not be unique throughout the tree, but it is good practice to
278 * ensure that they are at least unique within the part of the tree you are
279 * searching.
280 * </p>
281 *
282 * <a name="Position"></a>
283 * <h3>Position</h3>
284 * <p>
285 * The geometry of a view is that of a rectangle. A view has a location,
286 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
287 * two dimensions, expressed as a width and a height. The unit for location
288 * and dimensions is the pixel.
289 * </p>
290 *
291 * <p>
292 * It is possible to retrieve the location of a view by invoking the methods
293 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
294 * coordinate of the rectangle representing the view. The latter returns the
295 * top, or Y, coordinate of the rectangle representing the view. These methods
296 * both return the location of the view relative to its parent. For instance,
297 * when getLeft() returns 20, that means the view is located 20 pixels to the
298 * right of the left edge of its direct parent.
299 * </p>
300 *
301 * <p>
302 * In addition, several convenience methods are offered to avoid unnecessary
303 * computations, namely {@link #getRight()} and {@link #getBottom()}.
304 * These methods return the coordinates of the right and bottom edges of the
305 * rectangle representing the view. For instance, calling {@link #getRight()}
306 * is similar to the following computation: <code>getLeft() + getWidth()</code>
307 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
308 * </p>
309 *
310 * <a name="SizePaddingMargins"></a>
311 * <h3>Size, padding and margins</h3>
312 * <p>
313 * The size of a view is expressed with a width and a height. A view actually
314 * possess two pairs of width and height values.
315 * </p>
316 *
317 * <p>
318 * The first pair is known as <em>measured width</em> and
319 * <em>measured height</em>. These dimensions define how big a view wants to be
320 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
321 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
322 * and {@link #getMeasuredHeight()}.
323 * </p>
324 *
325 * <p>
326 * The second pair is simply known as <em>width</em> and <em>height</em>, or
327 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
328 * dimensions define the actual size of the view on screen, at drawing time and
329 * after layout. These values may, but do not have to, be different from the
330 * measured width and height. The width and height can be obtained by calling
331 * {@link #getWidth()} and {@link #getHeight()}.
332 * </p>
333 *
334 * <p>
335 * To measure its dimensions, a view takes into account its padding. The padding
336 * is expressed in pixels for the left, top, right and bottom parts of the view.
337 * Padding can be used to offset the content of the view by a specific amount of
338 * pixels. For instance, a left padding of 2 will push the view's content by
339 * 2 pixels to the right of the left edge. Padding can be set using the
340 * {@link #setPadding(int, int, int, int)} method and queried by calling
341 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
342 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
343 * </p>
344 *
345 * <p>
346 * Even though a view can define a padding, it does not provide any support for
347 * margins. However, view groups provide such a support. Refer to
348 * {@link android.view.ViewGroup} and
349 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
350 * </p>
351 *
352 * <a name="Layout"></a>
353 * <h3>Layout</h3>
354 * <p>
355 * Layout is a two pass process: a measure pass and a layout pass. The measuring
356 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
357 * of the view tree. Each view pushes dimension specifications down the tree
358 * during the recursion. At the end of the measure pass, every view has stored
359 * its measurements. The second pass happens in
360 * {@link #layout(int,int,int,int)} and is also top-down. During
361 * this pass each parent is responsible for positioning all of its children
362 * using the sizes computed in the measure pass.
363 * </p>
364 *
365 * <p>
366 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
367 * {@link #getMeasuredHeight()} values must be set, along with those for all of
368 * that view's descendants. A view's measured width and measured height values
369 * must respect the constraints imposed by the view's parents. This guarantees
370 * that at the end of the measure pass, all parents accept all of their
371 * children's measurements. A parent view may call measure() more than once on
372 * its children. For example, the parent may measure each child once with
373 * unspecified dimensions to find out how big they want to be, then call
374 * measure() on them again with actual numbers if the sum of all the children's
375 * unconstrained sizes is too big or too small.
376 * </p>
377 *
378 * <p>
379 * The measure pass uses two classes to communicate dimensions. The
380 * {@link MeasureSpec} class is used by views to tell their parents how they
381 * want to be measured and positioned. The base LayoutParams class just
382 * describes how big the view wants to be for both width and height. For each
383 * dimension, it can specify one of:
384 * <ul>
385 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800386 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 * (minus padding)
388 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
389 * enclose its content (plus padding).
390 * </ul>
391 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
392 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
393 * an X and Y value.
394 * </p>
395 *
396 * <p>
397 * MeasureSpecs are used to push requirements down the tree from parent to
398 * child. A MeasureSpec can be in one of three modes:
399 * <ul>
400 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
401 * of a child view. For example, a LinearLayout may call measure() on its child
402 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
403 * tall the child view wants to be given a width of 240 pixels.
404 * <li>EXACTLY: This is used by the parent to impose an exact size on the
405 * child. The child must use this size, and guarantee that all of its
406 * descendants will fit within this size.
407 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
408 * child. The child must gurantee that it and all of its descendants will fit
409 * within this size.
410 * </ul>
411 * </p>
412 *
413 * <p>
414 * To intiate a layout, call {@link #requestLayout}. This method is typically
415 * called by a view on itself when it believes that is can no longer fit within
416 * its current bounds.
417 * </p>
418 *
419 * <a name="Drawing"></a>
420 * <h3>Drawing</h3>
421 * <p>
422 * Drawing is handled by walking the tree and rendering each view that
423 * intersects the the invalid region. Because the tree is traversed in-order,
424 * this means that parents will draw before (i.e., behind) their children, with
425 * siblings drawn in the order they appear in the tree.
426 * If you set a background drawable for a View, then the View will draw it for you
427 * before calling back to its <code>onDraw()</code> method.
428 * </p>
429 *
430 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700431 * Note that the framework will not draw views that are not in the invalid region.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 * </p>
433 *
434 * <p>
435 * To force a view to draw, call {@link #invalidate()}.
436 * </p>
437 *
438 * <a name="EventHandlingThreading"></a>
439 * <h3>Event Handling and Threading</h3>
440 * <p>
441 * The basic cycle of a view is as follows:
442 * <ol>
443 * <li>An event comes in and is dispatched to the appropriate view. The view
444 * handles the event and notifies any listeners.</li>
445 * <li>If in the course of processing the event, the view's bounds may need
446 * to be changed, the view will call {@link #requestLayout()}.</li>
447 * <li>Similarly, if in the course of processing the event the view's appearance
448 * may need to be changed, the view will call {@link #invalidate()}.</li>
449 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
450 * the framework will take care of measuring, laying out, and drawing the tree
451 * as appropriate.</li>
452 * </ol>
453 * </p>
454 *
455 * <p><em>Note: The entire view tree is single threaded. You must always be on
456 * the UI thread when calling any method on any view.</em>
457 * If you are doing work on other threads and want to update the state of a view
458 * from that thread, you should use a {@link Handler}.
459 * </p>
460 *
461 * <a name="FocusHandling"></a>
462 * <h3>Focus Handling</h3>
463 * <p>
464 * The framework will handle routine focus movement in response to user input.
465 * This includes changing the focus as views are removed or hidden, or as new
466 * views become available. Views indicate their willingness to take focus
467 * through the {@link #isFocusable} method. To change whether a view can take
468 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
469 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
470 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
471 * </p>
472 * <p>
473 * Focus movement is based on an algorithm which finds the nearest neighbor in a
474 * given direction. In rare cases, the default algorithm may not match the
475 * intended behavior of the developer. In these situations, you can provide
476 * explicit overrides by using these XML attributes in the layout file:
477 * <pre>
478 * nextFocusDown
479 * nextFocusLeft
480 * nextFocusRight
481 * nextFocusUp
482 * </pre>
483 * </p>
484 *
485 *
486 * <p>
487 * To get a particular view to take focus, call {@link #requestFocus()}.
488 * </p>
489 *
490 * <a name="TouchMode"></a>
491 * <h3>Touch Mode</h3>
492 * <p>
493 * When a user is navigating a user interface via directional keys such as a D-pad, it is
494 * necessary to give focus to actionable items such as buttons so the user can see
495 * what will take input. If the device has touch capabilities, however, and the user
496 * begins interacting with the interface by touching it, it is no longer necessary to
497 * always highlight, or give focus to, a particular view. This motivates a mode
498 * for interaction named 'touch mode'.
499 * </p>
500 * <p>
501 * For a touch capable device, once the user touches the screen, the device
502 * will enter touch mode. From this point onward, only views for which
503 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
504 * Other views that are touchable, like buttons, will not take focus when touched; they will
505 * only fire the on click listeners.
506 * </p>
507 * <p>
508 * Any time a user hits a directional key, such as a D-pad direction, the view device will
509 * exit touch mode, and find a view to take focus, so that the user may resume interacting
510 * with the user interface without touching the screen again.
511 * </p>
512 * <p>
513 * The touch mode state is maintained across {@link android.app.Activity}s. Call
514 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
515 * </p>
516 *
517 * <a name="Scrolling"></a>
518 * <h3>Scrolling</h3>
519 * <p>
520 * The framework provides basic support for views that wish to internally
521 * scroll their content. This includes keeping track of the X and Y scroll
522 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700523 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
524 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 * </p>
526 *
527 * <a name="Tags"></a>
528 * <h3>Tags</h3>
529 * <p>
530 * Unlike IDs, tags are not used to identify views. Tags are essentially an
531 * extra piece of information that can be associated with a view. They are most
532 * often used as a convenience to store data related to views in the views
533 * themselves rather than by putting them in a separate structure.
534 * </p>
535 *
536 * <a name="Animation"></a>
537 * <h3>Animation</h3>
538 * <p>
539 * You can attach an {@link Animation} object to a view using
540 * {@link #setAnimation(Animation)} or
541 * {@link #startAnimation(Animation)}. The animation can alter the scale,
542 * rotation, translation and alpha of a view over time. If the animation is
543 * attached to a view that has children, the animation will affect the entire
544 * subtree rooted by that node. When an animation is started, the framework will
545 * take care of redrawing the appropriate views until the animation completes.
546 * </p>
547 *
Jeff Brown85a31762010-09-01 17:01:00 -0700548 * <a name="Security"></a>
549 * <h3>Security</h3>
550 * <p>
551 * Sometimes it is essential that an application be able to verify that an action
552 * is being performed with the full knowledge and consent of the user, such as
553 * granting a permission request, making a purchase or clicking on an advertisement.
554 * Unfortunately, a malicious application could try to spoof the user into
555 * performing these actions, unaware, by concealing the intended purpose of the view.
556 * As a remedy, the framework offers a touch filtering mechanism that can be used to
557 * improve the security of views that provide access to sensitive functionality.
558 * </p><p>
559 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
Jeff Brown49ed71d2010-12-06 17:13:33 -0800560 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework
Jeff Brown85a31762010-09-01 17:01:00 -0700561 * will discard touches that are received whenever the view's window is obscured by
562 * another visible window. As a result, the view will not receive touches whenever a
563 * toast, dialog or other window appears above the view's window.
564 * </p><p>
565 * For more fine-grained control over security, consider overriding the
566 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
567 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
568 * </p>
569 *
Romain Guyd6a463a2009-05-21 23:10:10 -0700570 * @attr ref android.R.styleable#View_background
571 * @attr ref android.R.styleable#View_clickable
572 * @attr ref android.R.styleable#View_contentDescription
573 * @attr ref android.R.styleable#View_drawingCacheQuality
574 * @attr ref android.R.styleable#View_duplicateParentState
575 * @attr ref android.R.styleable#View_id
576 * @attr ref android.R.styleable#View_fadingEdge
577 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700578 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700580 * @attr ref android.R.styleable#View_isScrollContainer
581 * @attr ref android.R.styleable#View_focusable
582 * @attr ref android.R.styleable#View_focusableInTouchMode
583 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
584 * @attr ref android.R.styleable#View_keepScreenOn
585 * @attr ref android.R.styleable#View_longClickable
586 * @attr ref android.R.styleable#View_minHeight
587 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 * @attr ref android.R.styleable#View_nextFocusDown
589 * @attr ref android.R.styleable#View_nextFocusLeft
590 * @attr ref android.R.styleable#View_nextFocusRight
591 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700592 * @attr ref android.R.styleable#View_onClick
593 * @attr ref android.R.styleable#View_padding
594 * @attr ref android.R.styleable#View_paddingBottom
595 * @attr ref android.R.styleable#View_paddingLeft
596 * @attr ref android.R.styleable#View_paddingRight
597 * @attr ref android.R.styleable#View_paddingTop
598 * @attr ref android.R.styleable#View_saveEnabled
Chet Haase73066682010-11-29 15:55:32 -0800599 * @attr ref android.R.styleable#View_rotation
600 * @attr ref android.R.styleable#View_rotationX
601 * @attr ref android.R.styleable#View_rotationY
602 * @attr ref android.R.styleable#View_scaleX
603 * @attr ref android.R.styleable#View_scaleY
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 * @attr ref android.R.styleable#View_scrollX
605 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700606 * @attr ref android.R.styleable#View_scrollbarSize
607 * @attr ref android.R.styleable#View_scrollbarStyle
608 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700609 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
610 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
612 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 * @attr ref android.R.styleable#View_scrollbarThumbVertical
614 * @attr ref android.R.styleable#View_scrollbarTrackVertical
615 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
616 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700617 * @attr ref android.R.styleable#View_soundEffectsEnabled
618 * @attr ref android.R.styleable#View_tag
Chet Haase73066682010-11-29 15:55:32 -0800619 * @attr ref android.R.styleable#View_transformPivotX
620 * @attr ref android.R.styleable#View_transformPivotY
621 * @attr ref android.R.styleable#View_translationX
622 * @attr ref android.R.styleable#View_translationY
Romain Guyd6a463a2009-05-21 23:10:10 -0700623 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 *
625 * @see android.view.ViewGroup
626 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700627public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 private static final boolean DBG = false;
629
630 /**
631 * The logging tag used by this class with android.util.Log.
632 */
633 protected static final String VIEW_LOG_TAG = "View";
634
635 /**
636 * Used to mark a View that has no ID.
637 */
638 public static final int NO_ID = -1;
639
640 /**
641 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
642 * calling setFlags.
643 */
644 private static final int NOT_FOCUSABLE = 0x00000000;
645
646 /**
647 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
648 * setFlags.
649 */
650 private static final int FOCUSABLE = 0x00000001;
651
652 /**
653 * Mask for use with setFlags indicating bits used for focus.
654 */
655 private static final int FOCUSABLE_MASK = 0x00000001;
656
657 /**
658 * This view will adjust its padding to fit sytem windows (e.g. status bar)
659 */
660 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
661
662 /**
663 * This view is visible. Use with {@link #setVisibility}.
664 */
665 public static final int VISIBLE = 0x00000000;
666
667 /**
668 * This view is invisible, but it still takes up space for layout purposes.
669 * Use with {@link #setVisibility}.
670 */
671 public static final int INVISIBLE = 0x00000004;
672
673 /**
674 * This view is invisible, and it doesn't take any space for layout
675 * purposes. Use with {@link #setVisibility}.
676 */
677 public static final int GONE = 0x00000008;
678
679 /**
680 * Mask for use with setFlags indicating bits used for visibility.
681 * {@hide}
682 */
683 static final int VISIBILITY_MASK = 0x0000000C;
684
685 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
686
687 /**
688 * This view is enabled. Intrepretation varies by subclass.
689 * Use with ENABLED_MASK when calling setFlags.
690 * {@hide}
691 */
692 static final int ENABLED = 0x00000000;
693
694 /**
695 * This view is disabled. Intrepretation varies by subclass.
696 * Use with ENABLED_MASK when calling setFlags.
697 * {@hide}
698 */
699 static final int DISABLED = 0x00000020;
700
701 /**
702 * Mask for use with setFlags indicating bits used for indicating whether
703 * this view is enabled
704 * {@hide}
705 */
706 static final int ENABLED_MASK = 0x00000020;
707
708 /**
709 * This view won't draw. {@link #onDraw} won't be called and further
710 * optimizations
711 * will be performed. It is okay to have this flag set and a background.
712 * Use with DRAW_MASK when calling setFlags.
713 * {@hide}
714 */
715 static final int WILL_NOT_DRAW = 0x00000080;
716
717 /**
718 * Mask for use with setFlags indicating bits used for indicating whether
719 * this view is will draw
720 * {@hide}
721 */
722 static final int DRAW_MASK = 0x00000080;
723
724 /**
725 * <p>This view doesn't show scrollbars.</p>
726 * {@hide}
727 */
728 static final int SCROLLBARS_NONE = 0x00000000;
729
730 /**
731 * <p>This view shows horizontal scrollbars.</p>
732 * {@hide}
733 */
734 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
735
736 /**
737 * <p>This view shows vertical scrollbars.</p>
738 * {@hide}
739 */
740 static final int SCROLLBARS_VERTICAL = 0x00000200;
741
742 /**
743 * <p>Mask for use with setFlags indicating bits used for indicating which
744 * scrollbars are enabled.</p>
745 * {@hide}
746 */
747 static final int SCROLLBARS_MASK = 0x00000300;
748
Jeff Brown85a31762010-09-01 17:01:00 -0700749 /**
750 * Indicates that the view should filter touches when its window is obscured.
751 * Refer to the class comments for more information about this security feature.
752 * {@hide}
753 */
754 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
755
756 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757
758 /**
759 * <p>This view doesn't show fading edges.</p>
760 * {@hide}
761 */
762 static final int FADING_EDGE_NONE = 0x00000000;
763
764 /**
765 * <p>This view shows horizontal fading edges.</p>
766 * {@hide}
767 */
768 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
769
770 /**
771 * <p>This view shows vertical fading edges.</p>
772 * {@hide}
773 */
774 static final int FADING_EDGE_VERTICAL = 0x00002000;
775
776 /**
777 * <p>Mask for use with setFlags indicating bits used for indicating which
778 * fading edges are enabled.</p>
779 * {@hide}
780 */
781 static final int FADING_EDGE_MASK = 0x00003000;
782
783 /**
784 * <p>Indicates this view can be clicked. When clickable, a View reacts
785 * to clicks by notifying the OnClickListener.<p>
786 * {@hide}
787 */
788 static final int CLICKABLE = 0x00004000;
789
790 /**
791 * <p>Indicates this view is caching its drawing into a bitmap.</p>
792 * {@hide}
793 */
794 static final int DRAWING_CACHE_ENABLED = 0x00008000;
795
796 /**
797 * <p>Indicates that no icicle should be saved for this view.<p>
798 * {@hide}
799 */
800 static final int SAVE_DISABLED = 0x000010000;
801
802 /**
803 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
804 * property.</p>
805 * {@hide}
806 */
807 static final int SAVE_DISABLED_MASK = 0x000010000;
808
809 /**
810 * <p>Indicates that no drawing cache should ever be created for this view.<p>
811 * {@hide}
812 */
813 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
814
815 /**
816 * <p>Indicates this view can take / keep focus when int touch mode.</p>
817 * {@hide}
818 */
819 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
820
821 /**
822 * <p>Enables low quality mode for the drawing cache.</p>
823 */
824 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
825
826 /**
827 * <p>Enables high quality mode for the drawing cache.</p>
828 */
829 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
830
831 /**
832 * <p>Enables automatic quality mode for the drawing cache.</p>
833 */
834 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
835
836 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
837 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
838 };
839
840 /**
841 * <p>Mask for use with setFlags indicating bits used for the cache
842 * quality property.</p>
843 * {@hide}
844 */
845 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
846
847 /**
848 * <p>
849 * Indicates this view can be long clicked. When long clickable, a View
850 * reacts to long clicks by notifying the OnLongClickListener or showing a
851 * context menu.
852 * </p>
853 * {@hide}
854 */
855 static final int LONG_CLICKABLE = 0x00200000;
856
857 /**
858 * <p>Indicates that this view gets its drawable states from its direct parent
859 * and ignores its original internal states.</p>
860 *
861 * @hide
862 */
863 static final int DUPLICATE_PARENT_STATE = 0x00400000;
864
865 /**
866 * The scrollbar style to display the scrollbars inside the content area,
867 * without increasing the padding. The scrollbars will be overlaid with
868 * translucency on the view's content.
869 */
870 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
871
872 /**
873 * The scrollbar style to display the scrollbars inside the padded area,
874 * increasing the padding of the view. The scrollbars will not overlap the
875 * content area of the view.
876 */
877 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
878
879 /**
880 * The scrollbar style to display the scrollbars at the edge of the view,
881 * without increasing the padding. The scrollbars will be overlaid with
882 * translucency.
883 */
884 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
885
886 /**
887 * The scrollbar style to display the scrollbars at the edge of the view,
888 * increasing the padding of the view. The scrollbars will only overlap the
889 * background, if any.
890 */
891 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
892
893 /**
894 * Mask to check if the scrollbar style is overlay or inset.
895 * {@hide}
896 */
897 static final int SCROLLBARS_INSET_MASK = 0x01000000;
898
899 /**
900 * Mask to check if the scrollbar style is inside or outside.
901 * {@hide}
902 */
903 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
904
905 /**
906 * Mask for scrollbar style.
907 * {@hide}
908 */
909 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
910
911 /**
912 * View flag indicating that the screen should remain on while the
913 * window containing this view is visible to the user. This effectively
914 * takes care of automatically setting the WindowManager's
915 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
916 */
917 public static final int KEEP_SCREEN_ON = 0x04000000;
918
919 /**
920 * View flag indicating whether this view should have sound effects enabled
921 * for events such as clicking and touching.
922 */
923 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
924
925 /**
926 * View flag indicating whether this view should have haptic feedback
927 * enabled for events such as long presses.
928 */
929 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
930
931 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700932 * <p>Indicates that the view hierarchy should stop saving state when
933 * it reaches this view. If state saving is initiated immediately at
934 * the view, it will be allowed.
935 * {@hide}
936 */
937 static final int PARENT_SAVE_DISABLED = 0x20000000;
938
939 /**
940 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
941 * {@hide}
942 */
943 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
944
945 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700946 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
947 * should add all focusable Views regardless if they are focusable in touch mode.
948 */
949 public static final int FOCUSABLES_ALL = 0x00000000;
950
951 /**
952 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
953 * should add only Views focusable in touch mode.
954 */
955 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
956
957 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 * Use with {@link #focusSearch}. Move focus to the previous selectable
959 * item.
960 */
961 public static final int FOCUS_BACKWARD = 0x00000001;
962
963 /**
964 * Use with {@link #focusSearch}. Move focus to the next selectable
965 * item.
966 */
967 public static final int FOCUS_FORWARD = 0x00000002;
968
969 /**
970 * Use with {@link #focusSearch}. Move focus to the left.
971 */
972 public static final int FOCUS_LEFT = 0x00000011;
973
974 /**
975 * Use with {@link #focusSearch}. Move focus up.
976 */
977 public static final int FOCUS_UP = 0x00000021;
978
979 /**
980 * Use with {@link #focusSearch}. Move focus to the right.
981 */
982 public static final int FOCUS_RIGHT = 0x00000042;
983
984 /**
985 * Use with {@link #focusSearch}. Move focus down.
986 */
987 public static final int FOCUS_DOWN = 0x00000082;
988
989 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -0800990 * Bits of {@link #getMeasuredWidthAndState()} and
991 * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
992 */
993 public static final int MEASURED_SIZE_MASK = 0x00ffffff;
994
995 /**
996 * Bits of {@link #getMeasuredWidthAndState()} and
997 * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
998 */
999 public static final int MEASURED_STATE_MASK = 0xff000000;
1000
1001 /**
1002 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1003 * for functions that combine both width and height into a single int,
1004 * such as {@link #getMeasuredState()} and the childState argument of
1005 * {@link #resolveSizeAndState(int, int, int)}.
1006 */
1007 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1008
1009 /**
1010 * Bit of {@link #getMeasuredWidthAndState()} and
1011 * {@link #getMeasuredWidthAndState()} that indicates the measured size
1012 * is smaller that the space the view would like to have.
1013 */
1014 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1015
1016 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 * Base View state sets
1018 */
1019 // Singles
1020 /**
1021 * Indicates the view has no states set. States are used with
1022 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1023 * view depending on its state.
1024 *
1025 * @see android.graphics.drawable.Drawable
1026 * @see #getDrawableState()
1027 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001028 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 /**
1030 * Indicates the view is enabled. States are used with
1031 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1032 * view depending on its state.
1033 *
1034 * @see android.graphics.drawable.Drawable
1035 * @see #getDrawableState()
1036 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001037 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 /**
1039 * Indicates the view is focused. 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[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 /**
1048 * Indicates the view is selected. States are used with
1049 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1050 * view depending on its state.
1051 *
1052 * @see android.graphics.drawable.Drawable
1053 * @see #getDrawableState()
1054 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001055 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 /**
1057 * Indicates the view is pressed. States are used with
1058 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1059 * view depending on its state.
1060 *
1061 * @see android.graphics.drawable.Drawable
1062 * @see #getDrawableState()
1063 * @hide
1064 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001065 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 /**
1067 * Indicates the view's window has focus. States are used with
1068 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1069 * view depending on its state.
1070 *
1071 * @see android.graphics.drawable.Drawable
1072 * @see #getDrawableState()
1073 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001074 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 // Doubles
1076 /**
1077 * Indicates the view is enabled and has the focus.
1078 *
1079 * @see #ENABLED_STATE_SET
1080 * @see #FOCUSED_STATE_SET
1081 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001082 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 /**
1084 * Indicates the view is enabled and selected.
1085 *
1086 * @see #ENABLED_STATE_SET
1087 * @see #SELECTED_STATE_SET
1088 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001089 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 /**
1091 * Indicates the view is enabled and that its window has focus.
1092 *
1093 * @see #ENABLED_STATE_SET
1094 * @see #WINDOW_FOCUSED_STATE_SET
1095 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001096 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 /**
1098 * Indicates the view is focused and selected.
1099 *
1100 * @see #FOCUSED_STATE_SET
1101 * @see #SELECTED_STATE_SET
1102 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001103 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 /**
1105 * Indicates the view has the focus and that its window has the focus.
1106 *
1107 * @see #FOCUSED_STATE_SET
1108 * @see #WINDOW_FOCUSED_STATE_SET
1109 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001110 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 /**
1112 * Indicates the view is selected and that its window has the focus.
1113 *
1114 * @see #SELECTED_STATE_SET
1115 * @see #WINDOW_FOCUSED_STATE_SET
1116 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001117 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 // Triples
1119 /**
1120 * Indicates the view is enabled, focused and selected.
1121 *
1122 * @see #ENABLED_STATE_SET
1123 * @see #FOCUSED_STATE_SET
1124 * @see #SELECTED_STATE_SET
1125 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001126 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 /**
1128 * Indicates the view is enabled, focused and its window has the focus.
1129 *
1130 * @see #ENABLED_STATE_SET
1131 * @see #FOCUSED_STATE_SET
1132 * @see #WINDOW_FOCUSED_STATE_SET
1133 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001134 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 /**
1136 * Indicates the view is enabled, selected and its window has the focus.
1137 *
1138 * @see #ENABLED_STATE_SET
1139 * @see #SELECTED_STATE_SET
1140 * @see #WINDOW_FOCUSED_STATE_SET
1141 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001142 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 /**
1144 * Indicates the view is focused, selected and its window has the focus.
1145 *
1146 * @see #FOCUSED_STATE_SET
1147 * @see #SELECTED_STATE_SET
1148 * @see #WINDOW_FOCUSED_STATE_SET
1149 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001150 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 /**
1152 * Indicates the view is enabled, focused, selected and its window
1153 * has the focus.
1154 *
1155 * @see #ENABLED_STATE_SET
1156 * @see #FOCUSED_STATE_SET
1157 * @see #SELECTED_STATE_SET
1158 * @see #WINDOW_FOCUSED_STATE_SET
1159 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001160 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 /**
1162 * Indicates the view is pressed and its window has the focus.
1163 *
1164 * @see #PRESSED_STATE_SET
1165 * @see #WINDOW_FOCUSED_STATE_SET
1166 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001167 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 /**
1169 * Indicates the view is pressed and selected.
1170 *
1171 * @see #PRESSED_STATE_SET
1172 * @see #SELECTED_STATE_SET
1173 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001174 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 /**
1176 * Indicates the view is pressed, selected and its window has the focus.
1177 *
1178 * @see #PRESSED_STATE_SET
1179 * @see #SELECTED_STATE_SET
1180 * @see #WINDOW_FOCUSED_STATE_SET
1181 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001182 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 /**
1184 * Indicates the view is pressed and focused.
1185 *
1186 * @see #PRESSED_STATE_SET
1187 * @see #FOCUSED_STATE_SET
1188 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001189 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 /**
1191 * Indicates the view is pressed, focused and its window has the focus.
1192 *
1193 * @see #PRESSED_STATE_SET
1194 * @see #FOCUSED_STATE_SET
1195 * @see #WINDOW_FOCUSED_STATE_SET
1196 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001197 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 /**
1199 * Indicates the view is pressed, focused and selected.
1200 *
1201 * @see #PRESSED_STATE_SET
1202 * @see #SELECTED_STATE_SET
1203 * @see #FOCUSED_STATE_SET
1204 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001205 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 /**
1207 * Indicates the view is pressed, focused, selected and its window has the focus.
1208 *
1209 * @see #PRESSED_STATE_SET
1210 * @see #FOCUSED_STATE_SET
1211 * @see #SELECTED_STATE_SET
1212 * @see #WINDOW_FOCUSED_STATE_SET
1213 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001214 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 /**
1216 * Indicates the view is pressed and enabled.
1217 *
1218 * @see #PRESSED_STATE_SET
1219 * @see #ENABLED_STATE_SET
1220 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001221 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 /**
1223 * Indicates the view is pressed, enabled and its window has the focus.
1224 *
1225 * @see #PRESSED_STATE_SET
1226 * @see #ENABLED_STATE_SET
1227 * @see #WINDOW_FOCUSED_STATE_SET
1228 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001229 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 /**
1231 * Indicates the view is pressed, enabled and selected.
1232 *
1233 * @see #PRESSED_STATE_SET
1234 * @see #ENABLED_STATE_SET
1235 * @see #SELECTED_STATE_SET
1236 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001237 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 /**
1239 * Indicates the view is pressed, enabled, selected and its window has the
1240 * focus.
1241 *
1242 * @see #PRESSED_STATE_SET
1243 * @see #ENABLED_STATE_SET
1244 * @see #SELECTED_STATE_SET
1245 * @see #WINDOW_FOCUSED_STATE_SET
1246 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001247 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 /**
1249 * Indicates the view is pressed, enabled and focused.
1250 *
1251 * @see #PRESSED_STATE_SET
1252 * @see #ENABLED_STATE_SET
1253 * @see #FOCUSED_STATE_SET
1254 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001255 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 /**
1257 * Indicates the view is pressed, enabled, focused and its window has the
1258 * focus.
1259 *
1260 * @see #PRESSED_STATE_SET
1261 * @see #ENABLED_STATE_SET
1262 * @see #FOCUSED_STATE_SET
1263 * @see #WINDOW_FOCUSED_STATE_SET
1264 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001265 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 /**
1267 * Indicates the view is pressed, enabled, focused and selected.
1268 *
1269 * @see #PRESSED_STATE_SET
1270 * @see #ENABLED_STATE_SET
1271 * @see #SELECTED_STATE_SET
1272 * @see #FOCUSED_STATE_SET
1273 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001274 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 /**
1276 * Indicates the view is pressed, enabled, focused, selected and its window
1277 * has the focus.
1278 *
1279 * @see #PRESSED_STATE_SET
1280 * @see #ENABLED_STATE_SET
1281 * @see #SELECTED_STATE_SET
1282 * @see #FOCUSED_STATE_SET
1283 * @see #WINDOW_FOCUSED_STATE_SET
1284 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001285 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286
1287 /**
1288 * The order here is very important to {@link #getDrawableState()}
1289 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001290 private static final int[][] VIEW_STATE_SETS;
1291
Romain Guyb051e892010-09-28 19:09:36 -07001292 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1293 static final int VIEW_STATE_SELECTED = 1 << 1;
1294 static final int VIEW_STATE_FOCUSED = 1 << 2;
1295 static final int VIEW_STATE_ENABLED = 1 << 3;
1296 static final int VIEW_STATE_PRESSED = 1 << 4;
1297 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001298 static final int VIEW_STATE_ACCELERATED = 1 << 6;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001299
1300 static final int[] VIEW_STATE_IDS = new int[] {
1301 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1302 R.attr.state_selected, VIEW_STATE_SELECTED,
1303 R.attr.state_focused, VIEW_STATE_FOCUSED,
1304 R.attr.state_enabled, VIEW_STATE_ENABLED,
1305 R.attr.state_pressed, VIEW_STATE_PRESSED,
1306 R.attr.state_activated, VIEW_STATE_ACTIVATED,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001307 R.attr.state_accelerated, VIEW_STATE_ACCELERATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 };
1309
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001310 static {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001311 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1312 throw new IllegalStateException(
1313 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1314 }
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001315 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001316 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001317 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001318 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001319 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001320 orderedIds[i * 2] = viewState;
1321 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001322 }
1323 }
1324 }
Romain Guyb051e892010-09-28 19:09:36 -07001325 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1326 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1327 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001328 int numBits = Integer.bitCount(i);
1329 int[] set = new int[numBits];
1330 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001331 for (int j = 0; j < orderedIds.length; j += 2) {
1332 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001333 set[pos++] = orderedIds[j];
1334 }
1335 }
1336 VIEW_STATE_SETS[i] = set;
1337 }
1338
1339 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1340 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1341 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1342 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1343 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1344 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1345 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1346 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1347 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1348 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1349 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1350 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1351 | VIEW_STATE_FOCUSED];
1352 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1353 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1354 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1355 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1356 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1357 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1358 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1359 | VIEW_STATE_ENABLED];
1360 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1361 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1362 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1363 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1364 | VIEW_STATE_ENABLED];
1365 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1366 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1367 | VIEW_STATE_ENABLED];
1368 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1369 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1370 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1371
1372 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1373 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1374 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1375 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1376 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1377 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1378 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1379 | VIEW_STATE_PRESSED];
1380 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1381 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1382 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1383 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1384 | VIEW_STATE_PRESSED];
1385 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1386 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1387 | VIEW_STATE_PRESSED];
1388 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1389 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1390 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1391 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1392 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1393 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1394 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1395 | VIEW_STATE_PRESSED];
1396 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1397 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1398 | VIEW_STATE_PRESSED];
1399 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1400 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1401 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1402 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1403 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1404 | VIEW_STATE_PRESSED];
1405 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1406 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1407 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1408 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1409 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1410 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1411 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1413 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1414 | VIEW_STATE_PRESSED];
1415 }
1416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 /**
1418 * Used by views that contain lists of items. This state indicates that
1419 * the view is showing the last item.
1420 * @hide
1421 */
1422 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1423 /**
1424 * Used by views that contain lists of items. This state indicates that
1425 * the view is showing the first item.
1426 * @hide
1427 */
1428 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1429 /**
1430 * Used by views that contain lists of items. This state indicates that
1431 * the view is showing the middle item.
1432 * @hide
1433 */
1434 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1435 /**
1436 * Used by views that contain lists of items. This state indicates that
1437 * the view is showing only one item.
1438 * @hide
1439 */
1440 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1441 /**
1442 * Used by views that contain lists of items. This state indicates that
1443 * the view is pressed and showing the last item.
1444 * @hide
1445 */
1446 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1447 /**
1448 * Used by views that contain lists of items. This state indicates that
1449 * the view is pressed and showing the first item.
1450 * @hide
1451 */
1452 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1453 /**
1454 * Used by views that contain lists of items. This state indicates that
1455 * the view is pressed and showing the middle item.
1456 * @hide
1457 */
1458 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1459 /**
1460 * Used by views that contain lists of items. This state indicates that
1461 * the view is pressed and showing only one item.
1462 * @hide
1463 */
1464 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1465
1466 /**
1467 * Temporary Rect currently for use in setBackground(). This will probably
1468 * be extended in the future to hold our own class with more than just
1469 * a Rect. :)
1470 */
1471 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001472
1473 /**
1474 * Map used to store views' tags.
1475 */
1476 private static WeakHashMap<View, SparseArray<Object>> sTags;
1477
1478 /**
1479 * Lock used to access sTags.
1480 */
1481 private static final Object sTagsLock = new Object();
1482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 /**
1484 * The animation currently associated with this view.
1485 * @hide
1486 */
1487 protected Animation mCurrentAnimation = null;
1488
1489 /**
1490 * Width as measured during measure pass.
1491 * {@hide}
1492 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001493 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001494 /*package*/ int mMeasuredWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495
1496 /**
1497 * Height as measured during measure pass.
1498 * {@hide}
1499 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001500 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001501 /*package*/ int mMeasuredHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502
1503 /**
1504 * The view's identifier.
1505 * {@hide}
1506 *
1507 * @see #setId(int)
1508 * @see #getId()
1509 */
1510 @ViewDebug.ExportedProperty(resolveId = true)
1511 int mID = NO_ID;
1512
1513 /**
1514 * The view's tag.
1515 * {@hide}
1516 *
1517 * @see #setTag(Object)
1518 * @see #getTag()
1519 */
1520 protected Object mTag;
1521
1522 // for mPrivateFlags:
1523 /** {@hide} */
1524 static final int WANTS_FOCUS = 0x00000001;
1525 /** {@hide} */
1526 static final int FOCUSED = 0x00000002;
1527 /** {@hide} */
1528 static final int SELECTED = 0x00000004;
1529 /** {@hide} */
1530 static final int IS_ROOT_NAMESPACE = 0x00000008;
1531 /** {@hide} */
1532 static final int HAS_BOUNDS = 0x00000010;
1533 /** {@hide} */
1534 static final int DRAWN = 0x00000020;
1535 /**
1536 * When this flag is set, this view is running an animation on behalf of its
1537 * children and should therefore not cancel invalidate requests, even if they
1538 * lie outside of this view's bounds.
1539 *
1540 * {@hide}
1541 */
1542 static final int DRAW_ANIMATION = 0x00000040;
1543 /** {@hide} */
1544 static final int SKIP_DRAW = 0x00000080;
1545 /** {@hide} */
1546 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1547 /** {@hide} */
1548 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1549 /** {@hide} */
1550 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1551 /** {@hide} */
1552 static final int MEASURED_DIMENSION_SET = 0x00000800;
1553 /** {@hide} */
1554 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001555 /** {@hide} */
1556 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557
1558 private static final int PRESSED = 0x00004000;
1559
1560 /** {@hide} */
1561 static final int DRAWING_CACHE_VALID = 0x00008000;
1562 /**
1563 * Flag used to indicate that this view should be drawn once more (and only once
1564 * more) after its animation has completed.
1565 * {@hide}
1566 */
1567 static final int ANIMATION_STARTED = 0x00010000;
1568
1569 private static final int SAVE_STATE_CALLED = 0x00020000;
1570
1571 /**
1572 * Indicates that the View returned true when onSetAlpha() was called and that
1573 * the alpha must be restored.
1574 * {@hide}
1575 */
1576 static final int ALPHA_SET = 0x00040000;
1577
1578 /**
1579 * Set by {@link #setScrollContainer(boolean)}.
1580 */
1581 static final int SCROLL_CONTAINER = 0x00080000;
1582
1583 /**
1584 * Set by {@link #setScrollContainer(boolean)}.
1585 */
1586 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1587
1588 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001589 * View flag indicating whether this view was invalidated (fully or partially.)
1590 *
1591 * @hide
1592 */
1593 static final int DIRTY = 0x00200000;
1594
1595 /**
1596 * View flag indicating whether this view was invalidated by an opaque
1597 * invalidate request.
1598 *
1599 * @hide
1600 */
1601 static final int DIRTY_OPAQUE = 0x00400000;
1602
1603 /**
1604 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1605 *
1606 * @hide
1607 */
1608 static final int DIRTY_MASK = 0x00600000;
1609
1610 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001611 * Indicates whether the background is opaque.
1612 *
1613 * @hide
1614 */
1615 static final int OPAQUE_BACKGROUND = 0x00800000;
1616
1617 /**
1618 * Indicates whether the scrollbars are opaque.
1619 *
1620 * @hide
1621 */
1622 static final int OPAQUE_SCROLLBARS = 0x01000000;
1623
1624 /**
1625 * Indicates whether the view is opaque.
1626 *
1627 * @hide
1628 */
1629 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001630
1631 /**
1632 * Indicates a prepressed state;
1633 * the short time between ACTION_DOWN and recognizing
1634 * a 'real' press. Prepressed is used to recognize quick taps
1635 * even when they are shorter than ViewConfiguration.getTapTimeout().
1636 *
1637 * @hide
1638 */
1639 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001640
1641 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001642 * Indicates whether the view is temporarily detached.
1643 *
1644 * @hide
1645 */
1646 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001647
1648 /**
1649 * Indicates that we should awaken scroll bars once attached
1650 *
1651 * @hide
1652 */
1653 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001654
1655 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001656 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1657 * for transform operations
1658 *
1659 * @hide
1660 */
Adam Powellf37df072010-09-17 16:22:49 -07001661 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001662
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001663 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001664 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001665
Chet Haasefd2b0022010-08-06 13:08:56 -07001666 /**
Adam Powell637d3372010-08-25 14:37:03 -07001667 * Always allow a user to over-scroll this view, provided it is a
1668 * view that can scroll.
1669 *
1670 * @see #getOverScrollMode()
1671 * @see #setOverScrollMode(int)
1672 */
1673 public static final int OVER_SCROLL_ALWAYS = 0;
1674
1675 /**
1676 * Allow a user to over-scroll this view only if the content is large
1677 * enough to meaningfully scroll, provided it is a view that can scroll.
1678 *
1679 * @see #getOverScrollMode()
1680 * @see #setOverScrollMode(int)
1681 */
1682 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1683
1684 /**
1685 * Never allow a user to over-scroll this view.
1686 *
1687 * @see #getOverScrollMode()
1688 * @see #setOverScrollMode(int)
1689 */
1690 public static final int OVER_SCROLL_NEVER = 2;
1691
1692 /**
1693 * Controls the over-scroll mode for this view.
1694 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1695 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1696 * and {@link #OVER_SCROLL_NEVER}.
1697 */
1698 private int mOverScrollMode;
1699
1700 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 * The parent this view is attached to.
1702 * {@hide}
1703 *
1704 * @see #getParent()
1705 */
1706 protected ViewParent mParent;
1707
1708 /**
1709 * {@hide}
1710 */
1711 AttachInfo mAttachInfo;
1712
1713 /**
1714 * {@hide}
1715 */
Romain Guy809a7f62009-05-14 15:44:42 -07001716 @ViewDebug.ExportedProperty(flagMapping = {
1717 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1718 name = "FORCE_LAYOUT"),
1719 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1720 name = "LAYOUT_REQUIRED"),
1721 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001722 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001723 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1724 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1725 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1726 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1727 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 int mPrivateFlags;
1729
1730 /**
1731 * Count of how many windows this view has been attached to.
1732 */
1733 int mWindowAttachCount;
1734
1735 /**
1736 * The layout parameters associated with this view and used by the parent
1737 * {@link android.view.ViewGroup} to determine how this view should be
1738 * laid out.
1739 * {@hide}
1740 */
1741 protected ViewGroup.LayoutParams mLayoutParams;
1742
1743 /**
1744 * The view flags hold various views states.
1745 * {@hide}
1746 */
1747 @ViewDebug.ExportedProperty
1748 int mViewFlags;
1749
1750 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001751 * The transform matrix for the View. This transform is calculated internally
1752 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1753 * is used by default. Do *not* use this variable directly; instead call
1754 * getMatrix(), which will automatically recalculate the matrix if necessary
1755 * to get the correct matrix based on the latest rotation and scale properties.
1756 */
1757 private final Matrix mMatrix = new Matrix();
1758
1759 /**
1760 * The transform matrix for the View. This transform is calculated internally
1761 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1762 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001763 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001764 * to get the correct matrix based on the latest rotation and scale properties.
1765 */
1766 private Matrix mInverseMatrix;
1767
1768 /**
1769 * An internal variable that tracks whether we need to recalculate the
1770 * transform matrix, based on whether the rotation or scaleX/Y properties
1771 * have changed since the matrix was last calculated.
1772 */
1773 private boolean mMatrixDirty = false;
1774
1775 /**
1776 * An internal variable that tracks whether we need to recalculate the
1777 * transform matrix, based on whether the rotation or scaleX/Y properties
1778 * have changed since the matrix was last calculated.
1779 */
1780 private boolean mInverseMatrixDirty = true;
1781
1782 /**
1783 * A variable that tracks whether we need to recalculate the
1784 * transform matrix, based on whether the rotation or scaleX/Y properties
1785 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001786 * is only valid after a call to updateMatrix() or to a function that
1787 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001788 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001789 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001790
1791 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001792 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1793 */
1794 private Camera mCamera = null;
1795
1796 /**
1797 * This matrix is used when computing the matrix for 3D rotations.
1798 */
1799 private Matrix matrix3D = null;
1800
1801 /**
1802 * These prev values are used to recalculate a centered pivot point when necessary. The
1803 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1804 * set), so thes values are only used then as well.
1805 */
1806 private int mPrevWidth = -1;
1807 private int mPrevHeight = -1;
1808
1809 /**
1810 * Convenience value to check for float values that are close enough to zero to be considered
1811 * zero.
1812 */
Romain Guy2542d192010-08-18 11:47:12 -07001813 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001814
1815 /**
1816 * The degrees rotation around the vertical axis through the pivot point.
1817 */
1818 @ViewDebug.ExportedProperty
1819 private float mRotationY = 0f;
1820
1821 /**
1822 * The degrees rotation around the horizontal axis through the pivot point.
1823 */
1824 @ViewDebug.ExportedProperty
1825 private float mRotationX = 0f;
1826
1827 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001828 * The degrees rotation around the pivot point.
1829 */
1830 @ViewDebug.ExportedProperty
1831 private float mRotation = 0f;
1832
1833 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001834 * The amount of translation of the object away from its left property (post-layout).
1835 */
1836 @ViewDebug.ExportedProperty
1837 private float mTranslationX = 0f;
1838
1839 /**
1840 * The amount of translation of the object away from its top property (post-layout).
1841 */
1842 @ViewDebug.ExportedProperty
1843 private float mTranslationY = 0f;
1844
1845 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001846 * The amount of scale in the x direction around the pivot point. A
1847 * value of 1 means no scaling is applied.
1848 */
1849 @ViewDebug.ExportedProperty
1850 private float mScaleX = 1f;
1851
1852 /**
1853 * The amount of scale in the y direction around the pivot point. A
1854 * value of 1 means no scaling is applied.
1855 */
1856 @ViewDebug.ExportedProperty
1857 private float mScaleY = 1f;
1858
1859 /**
1860 * The amount of scale in the x direction around the pivot point. A
1861 * value of 1 means no scaling is applied.
1862 */
1863 @ViewDebug.ExportedProperty
1864 private float mPivotX = 0f;
1865
1866 /**
1867 * The amount of scale in the y direction around the pivot point. A
1868 * value of 1 means no scaling is applied.
1869 */
1870 @ViewDebug.ExportedProperty
1871 private float mPivotY = 0f;
1872
1873 /**
1874 * The opacity of the View. This is a value from 0 to 1, where 0 means
1875 * completely transparent and 1 means completely opaque.
1876 */
1877 @ViewDebug.ExportedProperty
1878 private float mAlpha = 1f;
1879
1880 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 * The distance in pixels from the left edge of this view's parent
1882 * to the left edge of this view.
1883 * {@hide}
1884 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001885 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 protected int mLeft;
1887 /**
1888 * The distance in pixels from the left edge of this view's parent
1889 * to the right edge of this view.
1890 * {@hide}
1891 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001892 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 protected int mRight;
1894 /**
1895 * The distance in pixels from the top edge of this view's parent
1896 * to the top edge of this view.
1897 * {@hide}
1898 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001899 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 protected int mTop;
1901 /**
1902 * The distance in pixels from the top edge of this view's parent
1903 * to the bottom edge of this view.
1904 * {@hide}
1905 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001906 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 protected int mBottom;
1908
1909 /**
1910 * The offset, in pixels, by which the content of this view is scrolled
1911 * horizontally.
1912 * {@hide}
1913 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001914 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 protected int mScrollX;
1916 /**
1917 * The offset, in pixels, by which the content of this view is scrolled
1918 * vertically.
1919 * {@hide}
1920 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001921 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 protected int mScrollY;
1923
1924 /**
1925 * The left padding in pixels, that is the distance in pixels between the
1926 * left edge of this view and the left edge of its content.
1927 * {@hide}
1928 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001929 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 protected int mPaddingLeft;
1931 /**
1932 * The right padding in pixels, that is the distance in pixels between the
1933 * right edge of this view and the right edge of its content.
1934 * {@hide}
1935 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001936 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 protected int mPaddingRight;
1938 /**
1939 * The top padding in pixels, that is the distance in pixels between the
1940 * top edge of this view and the top edge of its content.
1941 * {@hide}
1942 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001943 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 protected int mPaddingTop;
1945 /**
1946 * The bottom padding in pixels, that is the distance in pixels between the
1947 * bottom edge of this view and the bottom edge of its content.
1948 * {@hide}
1949 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001950 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 protected int mPaddingBottom;
1952
1953 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001954 * Briefly describes the view and is primarily used for accessibility support.
1955 */
1956 private CharSequence mContentDescription;
1957
1958 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 * Cache the paddingRight set by the user to append to the scrollbar's size.
1960 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001961 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 int mUserPaddingRight;
1963
1964 /**
1965 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1966 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001967 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 int mUserPaddingBottom;
1969
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001970 /**
Adam Powell20232d02010-12-08 21:08:53 -08001971 * Cache the paddingLeft set by the user to append to the scrollbar's size.
1972 */
1973 @ViewDebug.ExportedProperty(category = "padding")
1974 int mUserPaddingLeft;
1975
1976 /**
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001977 * @hide
1978 */
1979 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1980 /**
1981 * @hide
1982 */
1983 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984
1985 private Resources mResources = null;
1986
1987 private Drawable mBGDrawable;
1988
1989 private int mBackgroundResource;
1990 private boolean mBackgroundSizeChanged;
1991
1992 /**
1993 * Listener used to dispatch focus change events.
1994 * This field should be made private, so it is hidden from the SDK.
1995 * {@hide}
1996 */
1997 protected OnFocusChangeListener mOnFocusChangeListener;
1998
1999 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002000 * Listeners for layout change events.
2001 */
2002 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2003
2004 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 * Listener used to dispatch click events.
2006 * This field should be made private, so it is hidden from the SDK.
2007 * {@hide}
2008 */
2009 protected OnClickListener mOnClickListener;
2010
2011 /**
2012 * Listener used to dispatch long click events.
2013 * This field should be made private, so it is hidden from the SDK.
2014 * {@hide}
2015 */
2016 protected OnLongClickListener mOnLongClickListener;
2017
2018 /**
2019 * Listener used to build the context menu.
2020 * This field should be made private, so it is hidden from the SDK.
2021 * {@hide}
2022 */
2023 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2024
2025 private OnKeyListener mOnKeyListener;
2026
2027 private OnTouchListener mOnTouchListener;
2028
Chris Tate32affef2010-10-18 15:29:21 -07002029 private OnDragListener mOnDragListener;
2030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 /**
2032 * The application environment this view lives in.
2033 * This field should be made private, so it is hidden from the SDK.
2034 * {@hide}
2035 */
2036 protected Context mContext;
2037
2038 private ScrollabilityCache mScrollCache;
2039
2040 private int[] mDrawableState = null;
2041
Romain Guy02890fd2010-08-06 17:58:44 -07002042 private Bitmap mDrawingCache;
2043 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07002044 private DisplayList mDisplayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045
2046 /**
2047 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2048 * the user may specify which view to go to next.
2049 */
2050 private int mNextFocusLeftId = View.NO_ID;
2051
2052 /**
2053 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2054 * the user may specify which view to go to next.
2055 */
2056 private int mNextFocusRightId = View.NO_ID;
2057
2058 /**
2059 * When this view has focus and the next focus is {@link #FOCUS_UP},
2060 * the user may specify which view to go to next.
2061 */
2062 private int mNextFocusUpId = View.NO_ID;
2063
2064 /**
2065 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2066 * the user may specify which view to go to next.
2067 */
2068 private int mNextFocusDownId = View.NO_ID;
2069
Jeff Brown4e6319b2010-12-13 10:36:51 -08002070 /**
2071 * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2072 * the user may specify which view to go to next.
2073 */
2074 int mNextFocusForwardId = View.NO_ID;
2075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08002077 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08002078 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08002079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 private UnsetPressedState mUnsetPressedState;
2081
2082 /**
2083 * Whether the long press's action has been invoked. The tap's action is invoked on the
2084 * up event while a long press is invoked as soon as the long press duration is reached, so
2085 * a long press could be performed before the tap is checked, in which case the tap's action
2086 * should not be invoked.
2087 */
2088 private boolean mHasPerformedLongPress;
2089
2090 /**
2091 * The minimum height of the view. We'll try our best to have the height
2092 * of this view to at least this amount.
2093 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002094 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 private int mMinHeight;
2096
2097 /**
2098 * The minimum width of the view. We'll try our best to have the width
2099 * of this view to at least this amount.
2100 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002101 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 private int mMinWidth;
2103
2104 /**
2105 * The delegate to handle touch events that are physically in this view
2106 * but should be handled by another view.
2107 */
2108 private TouchDelegate mTouchDelegate = null;
2109
2110 /**
2111 * Solid color to use as a background when creating the drawing cache. Enables
2112 * the cache to use 16 bit bitmaps instead of 32 bit.
2113 */
2114 private int mDrawingCacheBackgroundColor = 0;
2115
2116 /**
2117 * Special tree observer used when mAttachInfo is null.
2118 */
2119 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002120
2121 /**
2122 * Cache the touch slop from the context that created the view.
2123 */
2124 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002127 * Cache drag/drop state
2128 *
2129 */
2130 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002131
2132 /**
Adam Powell20232d02010-12-08 21:08:53 -08002133 * Position of the vertical scroll bar.
2134 */
2135 private int mVerticalScrollbarPosition;
2136
2137 /**
2138 * Position the scroll bar at the default position as determined by the system.
2139 */
2140 public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2141
2142 /**
2143 * Position the scroll bar along the left edge.
2144 */
2145 public static final int SCROLLBAR_POSITION_LEFT = 1;
2146
2147 /**
2148 * Position the scroll bar along the right edge.
2149 */
2150 public static final int SCROLLBAR_POSITION_RIGHT = 2;
2151
2152 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 * Simple constructor to use when creating a view from code.
2154 *
2155 * @param context The Context the view is running in, through which it can
2156 * access the current theme, resources, etc.
2157 */
2158 public View(Context context) {
2159 mContext = context;
2160 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002161 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002162 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Adam Powell637d3372010-08-25 14:37:03 -07002163 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 }
2165
2166 /**
2167 * Constructor that is called when inflating a view from XML. This is called
2168 * when a view is being constructed from an XML file, supplying attributes
2169 * that were specified in the XML file. This version uses a default style of
2170 * 0, so the only attribute values applied are those in the Context's Theme
2171 * and the given AttributeSet.
2172 *
2173 * <p>
2174 * The method onFinishInflate() will be called after all children have been
2175 * added.
2176 *
2177 * @param context The Context the view is running in, through which it can
2178 * access the current theme, resources, etc.
2179 * @param attrs The attributes of the XML tag that is inflating the view.
2180 * @see #View(Context, AttributeSet, int)
2181 */
2182 public View(Context context, AttributeSet attrs) {
2183 this(context, attrs, 0);
2184 }
2185
2186 /**
2187 * Perform inflation from XML and apply a class-specific base style. This
2188 * constructor of View allows subclasses to use their own base style when
2189 * they are inflating. For example, a Button class's constructor would call
2190 * this version of the super class constructor and supply
2191 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2192 * the theme's button style to modify all of the base view attributes (in
2193 * particular its background) as well as the Button class's attributes.
2194 *
2195 * @param context The Context the view is running in, through which it can
2196 * access the current theme, resources, etc.
2197 * @param attrs The attributes of the XML tag that is inflating the view.
2198 * @param defStyle The default style to apply to this view. If 0, no style
2199 * will be applied (beyond what is included in the theme). This may
2200 * either be an attribute resource, whose value will be retrieved
2201 * from the current theme, or an explicit style resource.
2202 * @see #View(Context, AttributeSet)
2203 */
2204 public View(Context context, AttributeSet attrs, int defStyle) {
2205 this(context);
2206
2207 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2208 defStyle, 0);
2209
2210 Drawable background = null;
2211
2212 int leftPadding = -1;
2213 int topPadding = -1;
2214 int rightPadding = -1;
2215 int bottomPadding = -1;
2216
2217 int padding = -1;
2218
2219 int viewFlagValues = 0;
2220 int viewFlagMasks = 0;
2221
2222 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 int x = 0;
2225 int y = 0;
2226
Chet Haase73066682010-11-29 15:55:32 -08002227 float tx = 0;
2228 float ty = 0;
2229 float rotation = 0;
2230 float rotationX = 0;
2231 float rotationY = 0;
2232 float sx = 1f;
2233 float sy = 1f;
2234 boolean transformSet = false;
2235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2237
Adam Powell637d3372010-08-25 14:37:03 -07002238 int overScrollMode = mOverScrollMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 final int N = a.getIndexCount();
2240 for (int i = 0; i < N; i++) {
2241 int attr = a.getIndex(i);
2242 switch (attr) {
2243 case com.android.internal.R.styleable.View_background:
2244 background = a.getDrawable(attr);
2245 break;
2246 case com.android.internal.R.styleable.View_padding:
2247 padding = a.getDimensionPixelSize(attr, -1);
2248 break;
2249 case com.android.internal.R.styleable.View_paddingLeft:
2250 leftPadding = a.getDimensionPixelSize(attr, -1);
2251 break;
2252 case com.android.internal.R.styleable.View_paddingTop:
2253 topPadding = a.getDimensionPixelSize(attr, -1);
2254 break;
2255 case com.android.internal.R.styleable.View_paddingRight:
2256 rightPadding = a.getDimensionPixelSize(attr, -1);
2257 break;
2258 case com.android.internal.R.styleable.View_paddingBottom:
2259 bottomPadding = a.getDimensionPixelSize(attr, -1);
2260 break;
2261 case com.android.internal.R.styleable.View_scrollX:
2262 x = a.getDimensionPixelOffset(attr, 0);
2263 break;
2264 case com.android.internal.R.styleable.View_scrollY:
2265 y = a.getDimensionPixelOffset(attr, 0);
2266 break;
Chet Haase73066682010-11-29 15:55:32 -08002267 case com.android.internal.R.styleable.View_alpha:
2268 setAlpha(a.getFloat(attr, 1f));
2269 break;
2270 case com.android.internal.R.styleable.View_transformPivotX:
2271 setPivotX(a.getDimensionPixelOffset(attr, 0));
2272 break;
2273 case com.android.internal.R.styleable.View_transformPivotY:
2274 setPivotY(a.getDimensionPixelOffset(attr, 0));
2275 break;
2276 case com.android.internal.R.styleable.View_translationX:
2277 tx = a.getDimensionPixelOffset(attr, 0);
2278 transformSet = true;
2279 break;
2280 case com.android.internal.R.styleable.View_translationY:
2281 ty = a.getDimensionPixelOffset(attr, 0);
2282 transformSet = true;
2283 break;
2284 case com.android.internal.R.styleable.View_rotation:
2285 rotation = a.getFloat(attr, 0);
2286 transformSet = true;
2287 break;
2288 case com.android.internal.R.styleable.View_rotationX:
2289 rotationX = a.getFloat(attr, 0);
2290 transformSet = true;
2291 break;
2292 case com.android.internal.R.styleable.View_rotationY:
2293 rotationY = a.getFloat(attr, 0);
2294 transformSet = true;
2295 break;
2296 case com.android.internal.R.styleable.View_scaleX:
2297 sx = a.getFloat(attr, 1f);
2298 transformSet = true;
2299 break;
2300 case com.android.internal.R.styleable.View_scaleY:
2301 sy = a.getFloat(attr, 1f);
2302 transformSet = true;
2303 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 case com.android.internal.R.styleable.View_id:
2305 mID = a.getResourceId(attr, NO_ID);
2306 break;
2307 case com.android.internal.R.styleable.View_tag:
2308 mTag = a.getText(attr);
2309 break;
2310 case com.android.internal.R.styleable.View_fitsSystemWindows:
2311 if (a.getBoolean(attr, false)) {
2312 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2313 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2314 }
2315 break;
2316 case com.android.internal.R.styleable.View_focusable:
2317 if (a.getBoolean(attr, false)) {
2318 viewFlagValues |= FOCUSABLE;
2319 viewFlagMasks |= FOCUSABLE_MASK;
2320 }
2321 break;
2322 case com.android.internal.R.styleable.View_focusableInTouchMode:
2323 if (a.getBoolean(attr, false)) {
2324 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2325 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2326 }
2327 break;
2328 case com.android.internal.R.styleable.View_clickable:
2329 if (a.getBoolean(attr, false)) {
2330 viewFlagValues |= CLICKABLE;
2331 viewFlagMasks |= CLICKABLE;
2332 }
2333 break;
2334 case com.android.internal.R.styleable.View_longClickable:
2335 if (a.getBoolean(attr, false)) {
2336 viewFlagValues |= LONG_CLICKABLE;
2337 viewFlagMasks |= LONG_CLICKABLE;
2338 }
2339 break;
2340 case com.android.internal.R.styleable.View_saveEnabled:
2341 if (!a.getBoolean(attr, true)) {
2342 viewFlagValues |= SAVE_DISABLED;
2343 viewFlagMasks |= SAVE_DISABLED_MASK;
2344 }
2345 break;
2346 case com.android.internal.R.styleable.View_duplicateParentState:
2347 if (a.getBoolean(attr, false)) {
2348 viewFlagValues |= DUPLICATE_PARENT_STATE;
2349 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2350 }
2351 break;
2352 case com.android.internal.R.styleable.View_visibility:
2353 final int visibility = a.getInt(attr, 0);
2354 if (visibility != 0) {
2355 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2356 viewFlagMasks |= VISIBILITY_MASK;
2357 }
2358 break;
2359 case com.android.internal.R.styleable.View_drawingCacheQuality:
2360 final int cacheQuality = a.getInt(attr, 0);
2361 if (cacheQuality != 0) {
2362 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2363 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2364 }
2365 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002366 case com.android.internal.R.styleable.View_contentDescription:
2367 mContentDescription = a.getString(attr);
2368 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2370 if (!a.getBoolean(attr, true)) {
2371 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2372 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2373 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002374 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2376 if (!a.getBoolean(attr, true)) {
2377 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2378 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2379 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002380 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 case R.styleable.View_scrollbars:
2382 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2383 if (scrollbars != SCROLLBARS_NONE) {
2384 viewFlagValues |= scrollbars;
2385 viewFlagMasks |= SCROLLBARS_MASK;
2386 initializeScrollbars(a);
2387 }
2388 break;
2389 case R.styleable.View_fadingEdge:
2390 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2391 if (fadingEdge != FADING_EDGE_NONE) {
2392 viewFlagValues |= fadingEdge;
2393 viewFlagMasks |= FADING_EDGE_MASK;
2394 initializeFadingEdge(a);
2395 }
2396 break;
2397 case R.styleable.View_scrollbarStyle:
2398 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2399 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2400 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2401 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2402 }
2403 break;
2404 case R.styleable.View_isScrollContainer:
2405 setScrollContainer = true;
2406 if (a.getBoolean(attr, false)) {
2407 setScrollContainer(true);
2408 }
2409 break;
2410 case com.android.internal.R.styleable.View_keepScreenOn:
2411 if (a.getBoolean(attr, false)) {
2412 viewFlagValues |= KEEP_SCREEN_ON;
2413 viewFlagMasks |= KEEP_SCREEN_ON;
2414 }
2415 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002416 case R.styleable.View_filterTouchesWhenObscured:
2417 if (a.getBoolean(attr, false)) {
2418 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2419 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2420 }
2421 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 case R.styleable.View_nextFocusLeft:
2423 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2424 break;
2425 case R.styleable.View_nextFocusRight:
2426 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2427 break;
2428 case R.styleable.View_nextFocusUp:
2429 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2430 break;
2431 case R.styleable.View_nextFocusDown:
2432 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2433 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002434 case R.styleable.View_nextFocusForward:
2435 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2436 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 case R.styleable.View_minWidth:
2438 mMinWidth = a.getDimensionPixelSize(attr, 0);
2439 break;
2440 case R.styleable.View_minHeight:
2441 mMinHeight = a.getDimensionPixelSize(attr, 0);
2442 break;
Romain Guy9a817362009-05-01 10:57:14 -07002443 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002444 if (context.isRestricted()) {
2445 throw new IllegalStateException("The android:onClick attribute cannot "
2446 + "be used within a restricted context");
2447 }
2448
Romain Guy9a817362009-05-01 10:57:14 -07002449 final String handlerName = a.getString(attr);
2450 if (handlerName != null) {
2451 setOnClickListener(new OnClickListener() {
2452 private Method mHandler;
2453
2454 public void onClick(View v) {
2455 if (mHandler == null) {
2456 try {
2457 mHandler = getContext().getClass().getMethod(handlerName,
2458 View.class);
2459 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002460 int id = getId();
2461 String idText = id == NO_ID ? "" : " with id '"
2462 + getContext().getResources().getResourceEntryName(
2463 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002464 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002465 handlerName + "(View) in the activity "
2466 + getContext().getClass() + " for onClick handler"
2467 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002468 }
2469 }
2470
2471 try {
2472 mHandler.invoke(getContext(), View.this);
2473 } catch (IllegalAccessException e) {
2474 throw new IllegalStateException("Could not execute non "
2475 + "public method of the activity", e);
2476 } catch (InvocationTargetException e) {
2477 throw new IllegalStateException("Could not execute "
2478 + "method of the activity", e);
2479 }
2480 }
2481 });
2482 }
2483 break;
Adam Powell637d3372010-08-25 14:37:03 -07002484 case R.styleable.View_overScrollMode:
2485 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2486 break;
Adam Powell20232d02010-12-08 21:08:53 -08002487 case R.styleable.View_verticalScrollbarPosition:
2488 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2489 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 }
2491 }
2492
Adam Powell637d3372010-08-25 14:37:03 -07002493 setOverScrollMode(overScrollMode);
2494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 if (background != null) {
2496 setBackgroundDrawable(background);
2497 }
2498
2499 if (padding >= 0) {
2500 leftPadding = padding;
2501 topPadding = padding;
2502 rightPadding = padding;
2503 bottomPadding = padding;
2504 }
2505
2506 // If the user specified the padding (either with android:padding or
2507 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2508 // use the default padding or the padding from the background drawable
2509 // (stored at this point in mPadding*)
2510 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2511 topPadding >= 0 ? topPadding : mPaddingTop,
2512 rightPadding >= 0 ? rightPadding : mPaddingRight,
2513 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2514
2515 if (viewFlagMasks != 0) {
2516 setFlags(viewFlagValues, viewFlagMasks);
2517 }
2518
2519 // Needs to be called after mViewFlags is set
2520 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2521 recomputePadding();
2522 }
2523
2524 if (x != 0 || y != 0) {
2525 scrollTo(x, y);
2526 }
2527
Chet Haase73066682010-11-29 15:55:32 -08002528 if (transformSet) {
2529 setTranslationX(tx);
2530 setTranslationY(ty);
2531 setRotation(rotation);
2532 setRotationX(rotationX);
2533 setRotationY(rotationY);
2534 setScaleX(sx);
2535 setScaleY(sy);
2536 }
2537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2539 setScrollContainer(true);
2540 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002541
2542 computeOpaqueFlags();
2543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 a.recycle();
2545 }
2546
2547 /**
2548 * Non-public constructor for use in testing
2549 */
2550 View() {
2551 }
2552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 /**
2554 * <p>
2555 * Initializes the fading edges from a given set of styled attributes. This
2556 * method should be called by subclasses that need fading edges and when an
2557 * instance of these subclasses is created programmatically rather than
2558 * being inflated from XML. This method is automatically called when the XML
2559 * is inflated.
2560 * </p>
2561 *
2562 * @param a the styled attributes set to initialize the fading edges from
2563 */
2564 protected void initializeFadingEdge(TypedArray a) {
2565 initScrollCache();
2566
2567 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2568 R.styleable.View_fadingEdgeLength,
2569 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2570 }
2571
2572 /**
2573 * Returns the size of the vertical faded edges used to indicate that more
2574 * content in this view is visible.
2575 *
2576 * @return The size in pixels of the vertical faded edge or 0 if vertical
2577 * faded edges are not enabled for this view.
2578 * @attr ref android.R.styleable#View_fadingEdgeLength
2579 */
2580 public int getVerticalFadingEdgeLength() {
2581 if (isVerticalFadingEdgeEnabled()) {
2582 ScrollabilityCache cache = mScrollCache;
2583 if (cache != null) {
2584 return cache.fadingEdgeLength;
2585 }
2586 }
2587 return 0;
2588 }
2589
2590 /**
2591 * Set the size of the faded edge used to indicate that more content in this
2592 * view is available. Will not change whether the fading edge is enabled; use
2593 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2594 * to enable the fading edge for the vertical or horizontal fading edges.
2595 *
2596 * @param length The size in pixels of the faded edge used to indicate that more
2597 * content in this view is visible.
2598 */
2599 public void setFadingEdgeLength(int length) {
2600 initScrollCache();
2601 mScrollCache.fadingEdgeLength = length;
2602 }
2603
2604 /**
2605 * Returns the size of the horizontal faded edges used to indicate that more
2606 * content in this view is visible.
2607 *
2608 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2609 * faded edges are not enabled for this view.
2610 * @attr ref android.R.styleable#View_fadingEdgeLength
2611 */
2612 public int getHorizontalFadingEdgeLength() {
2613 if (isHorizontalFadingEdgeEnabled()) {
2614 ScrollabilityCache cache = mScrollCache;
2615 if (cache != null) {
2616 return cache.fadingEdgeLength;
2617 }
2618 }
2619 return 0;
2620 }
2621
2622 /**
2623 * Returns the width of the vertical scrollbar.
2624 *
2625 * @return The width in pixels of the vertical scrollbar or 0 if there
2626 * is no vertical scrollbar.
2627 */
2628 public int getVerticalScrollbarWidth() {
2629 ScrollabilityCache cache = mScrollCache;
2630 if (cache != null) {
2631 ScrollBarDrawable scrollBar = cache.scrollBar;
2632 if (scrollBar != null) {
2633 int size = scrollBar.getSize(true);
2634 if (size <= 0) {
2635 size = cache.scrollBarSize;
2636 }
2637 return size;
2638 }
2639 return 0;
2640 }
2641 return 0;
2642 }
2643
2644 /**
2645 * Returns the height of the horizontal scrollbar.
2646 *
2647 * @return The height in pixels of the horizontal scrollbar or 0 if
2648 * there is no horizontal scrollbar.
2649 */
2650 protected int getHorizontalScrollbarHeight() {
2651 ScrollabilityCache cache = mScrollCache;
2652 if (cache != null) {
2653 ScrollBarDrawable scrollBar = cache.scrollBar;
2654 if (scrollBar != null) {
2655 int size = scrollBar.getSize(false);
2656 if (size <= 0) {
2657 size = cache.scrollBarSize;
2658 }
2659 return size;
2660 }
2661 return 0;
2662 }
2663 return 0;
2664 }
2665
2666 /**
2667 * <p>
2668 * Initializes the scrollbars from a given set of styled attributes. This
2669 * method should be called by subclasses that need scrollbars and when an
2670 * instance of these subclasses is created programmatically rather than
2671 * being inflated from XML. This method is automatically called when the XML
2672 * is inflated.
2673 * </p>
2674 *
2675 * @param a the styled attributes set to initialize the scrollbars from
2676 */
2677 protected void initializeScrollbars(TypedArray a) {
2678 initScrollCache();
2679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002681
2682 if (scrollabilityCache.scrollBar == null) {
2683 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2684 }
2685
Romain Guy8bda2482010-03-02 11:42:11 -08002686 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687
Mike Cleronf116bf82009-09-27 19:14:12 -07002688 if (!fadeScrollbars) {
2689 scrollabilityCache.state = ScrollabilityCache.ON;
2690 }
2691 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2692
2693
2694 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2695 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2696 .getScrollBarFadeDuration());
2697 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2698 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2699 ViewConfiguration.getScrollDefaultDelay());
2700
2701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2703 com.android.internal.R.styleable.View_scrollbarSize,
2704 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2705
2706 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2707 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2708
2709 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2710 if (thumb != null) {
2711 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2712 }
2713
2714 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2715 false);
2716 if (alwaysDraw) {
2717 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2718 }
2719
2720 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2721 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2722
2723 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2724 if (thumb != null) {
2725 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2726 }
2727
2728 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2729 false);
2730 if (alwaysDraw) {
2731 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2732 }
2733
2734 // Re-apply user/background padding so that scrollbar(s) get added
2735 recomputePadding();
2736 }
2737
2738 /**
2739 * <p>
2740 * Initalizes the scrollability cache if necessary.
2741 * </p>
2742 */
2743 private void initScrollCache() {
2744 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002745 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 }
2747 }
2748
2749 /**
Adam Powell20232d02010-12-08 21:08:53 -08002750 * Set the position of the vertical scroll bar. Should be one of
2751 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
2752 * {@link #SCROLLBAR_POSITION_RIGHT}.
2753 *
2754 * @param position Where the vertical scroll bar should be positioned.
2755 */
2756 public void setVerticalScrollbarPosition(int position) {
2757 if (mVerticalScrollbarPosition != position) {
2758 mVerticalScrollbarPosition = position;
2759 computeOpaqueFlags();
2760 recomputePadding();
2761 }
2762 }
2763
2764 /**
2765 * @return The position where the vertical scroll bar will show, if applicable.
2766 * @see #setVerticalScrollbarPosition(int)
2767 */
2768 public int getVerticalScrollbarPosition() {
2769 return mVerticalScrollbarPosition;
2770 }
2771
2772 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 * Register a callback to be invoked when focus of this view changed.
2774 *
2775 * @param l The callback that will run.
2776 */
2777 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2778 mOnFocusChangeListener = l;
2779 }
2780
2781 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002782 * Add a listener that will be called when the bounds of the view change due to
2783 * layout processing.
2784 *
2785 * @param listener The listener that will be called when layout bounds change.
2786 */
2787 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2788 if (mOnLayoutChangeListeners == null) {
2789 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2790 }
2791 mOnLayoutChangeListeners.add(listener);
2792 }
2793
2794 /**
2795 * Remove a listener for layout changes.
2796 *
2797 * @param listener The listener for layout bounds change.
2798 */
2799 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2800 if (mOnLayoutChangeListeners == null) {
2801 return;
2802 }
2803 mOnLayoutChangeListeners.remove(listener);
2804 }
2805
2806 /**
2807 * Gets the current list of listeners for layout changes.
2808 * @return
2809 */
2810 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2811 return mOnLayoutChangeListeners;
2812 }
2813
2814 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 * Returns the focus-change callback registered for this view.
2816 *
2817 * @return The callback, or null if one is not registered.
2818 */
2819 public OnFocusChangeListener getOnFocusChangeListener() {
2820 return mOnFocusChangeListener;
2821 }
2822
2823 /**
2824 * Register a callback to be invoked when this view is clicked. If this view is not
2825 * clickable, it becomes clickable.
2826 *
2827 * @param l The callback that will run
2828 *
2829 * @see #setClickable(boolean)
2830 */
2831 public void setOnClickListener(OnClickListener l) {
2832 if (!isClickable()) {
2833 setClickable(true);
2834 }
2835 mOnClickListener = l;
2836 }
2837
2838 /**
2839 * Register a callback to be invoked when this view is clicked and held. If this view is not
2840 * long clickable, it becomes long clickable.
2841 *
2842 * @param l The callback that will run
2843 *
2844 * @see #setLongClickable(boolean)
2845 */
2846 public void setOnLongClickListener(OnLongClickListener l) {
2847 if (!isLongClickable()) {
2848 setLongClickable(true);
2849 }
2850 mOnLongClickListener = l;
2851 }
2852
2853 /**
2854 * Register a callback to be invoked when the context menu for this view is
2855 * being built. If this view is not long clickable, it becomes long clickable.
2856 *
2857 * @param l The callback that will run
2858 *
2859 */
2860 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2861 if (!isLongClickable()) {
2862 setLongClickable(true);
2863 }
2864 mOnCreateContextMenuListener = l;
2865 }
2866
2867 /**
2868 * Call this view's OnClickListener, if it is defined.
2869 *
2870 * @return True there was an assigned OnClickListener that was called, false
2871 * otherwise is returned.
2872 */
2873 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002874 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 if (mOnClickListener != null) {
2877 playSoundEffect(SoundEffectConstants.CLICK);
2878 mOnClickListener.onClick(this);
2879 return true;
2880 }
2881
2882 return false;
2883 }
2884
2885 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002886 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2887 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002889 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 */
2891 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002892 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 boolean handled = false;
2895 if (mOnLongClickListener != null) {
2896 handled = mOnLongClickListener.onLongClick(View.this);
2897 }
2898 if (!handled) {
2899 handled = showContextMenu();
2900 }
2901 if (handled) {
2902 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2903 }
2904 return handled;
2905 }
2906
2907 /**
2908 * Bring up the context menu for this view.
2909 *
2910 * @return Whether a context menu was displayed.
2911 */
2912 public boolean showContextMenu() {
2913 return getParent().showContextMenuForChild(this);
2914 }
2915
2916 /**
Adam Powell6e346362010-07-23 10:18:23 -07002917 * Start an action mode.
2918 *
2919 * @param callback Callback that will control the lifecycle of the action mode
2920 * @return The new action mode if it is started, null otherwise
2921 *
2922 * @see ActionMode
2923 */
2924 public ActionMode startActionMode(ActionMode.Callback callback) {
2925 return getParent().startActionModeForChild(this, callback);
2926 }
2927
2928 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 * Register a callback to be invoked when a key is pressed in this view.
2930 * @param l the key listener to attach to this view
2931 */
2932 public void setOnKeyListener(OnKeyListener l) {
2933 mOnKeyListener = l;
2934 }
2935
2936 /**
2937 * Register a callback to be invoked when a touch event is sent to this view.
2938 * @param l the touch listener to attach to this view
2939 */
2940 public void setOnTouchListener(OnTouchListener l) {
2941 mOnTouchListener = l;
2942 }
2943
2944 /**
Chris Tate32affef2010-10-18 15:29:21 -07002945 * Register a callback to be invoked when a drag event is sent to this view.
2946 * @param l The drag listener to attach to this view
2947 */
2948 public void setOnDragListener(OnDragListener l) {
2949 mOnDragListener = l;
2950 }
2951
2952 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2954 *
2955 * Note: this does not check whether this {@link View} should get focus, it just
2956 * gives it focus no matter what. It should only be called internally by framework
2957 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2958 *
2959 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2960 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2961 * focus moved when requestFocus() is called. It may not always
2962 * apply, in which case use the default View.FOCUS_DOWN.
2963 * @param previouslyFocusedRect The rectangle of the view that had focus
2964 * prior in this View's coordinate system.
2965 */
2966 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2967 if (DBG) {
2968 System.out.println(this + " requestFocus()");
2969 }
2970
2971 if ((mPrivateFlags & FOCUSED) == 0) {
2972 mPrivateFlags |= FOCUSED;
2973
2974 if (mParent != null) {
2975 mParent.requestChildFocus(this, this);
2976 }
2977
2978 onFocusChanged(true, direction, previouslyFocusedRect);
2979 refreshDrawableState();
2980 }
2981 }
2982
2983 /**
2984 * Request that a rectangle of this view be visible on the screen,
2985 * scrolling if necessary just enough.
2986 *
2987 * <p>A View should call this if it maintains some notion of which part
2988 * of its content is interesting. For example, a text editing view
2989 * should call this when its cursor moves.
2990 *
2991 * @param rectangle The rectangle.
2992 * @return Whether any parent scrolled.
2993 */
2994 public boolean requestRectangleOnScreen(Rect rectangle) {
2995 return requestRectangleOnScreen(rectangle, false);
2996 }
2997
2998 /**
2999 * Request that a rectangle of this view be visible on the screen,
3000 * scrolling if necessary just enough.
3001 *
3002 * <p>A View should call this if it maintains some notion of which part
3003 * of its content is interesting. For example, a text editing view
3004 * should call this when its cursor moves.
3005 *
3006 * <p>When <code>immediate</code> is set to true, scrolling will not be
3007 * animated.
3008 *
3009 * @param rectangle The rectangle.
3010 * @param immediate True to forbid animated scrolling, false otherwise
3011 * @return Whether any parent scrolled.
3012 */
3013 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3014 View child = this;
3015 ViewParent parent = mParent;
3016 boolean scrolled = false;
3017 while (parent != null) {
3018 scrolled |= parent.requestChildRectangleOnScreen(child,
3019 rectangle, immediate);
3020
3021 // offset rect so next call has the rectangle in the
3022 // coordinate system of its direct child.
3023 rectangle.offset(child.getLeft(), child.getTop());
3024 rectangle.offset(-child.getScrollX(), -child.getScrollY());
3025
3026 if (!(parent instanceof View)) {
3027 break;
3028 }
Romain Guy8506ab42009-06-11 17:35:47 -07003029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 child = (View) parent;
3031 parent = child.getParent();
3032 }
3033 return scrolled;
3034 }
3035
3036 /**
3037 * Called when this view wants to give up focus. This will cause
3038 * {@link #onFocusChanged} to be called.
3039 */
3040 public void clearFocus() {
3041 if (DBG) {
3042 System.out.println(this + " clearFocus()");
3043 }
3044
3045 if ((mPrivateFlags & FOCUSED) != 0) {
3046 mPrivateFlags &= ~FOCUSED;
3047
3048 if (mParent != null) {
3049 mParent.clearChildFocus(this);
3050 }
3051
3052 onFocusChanged(false, 0, null);
3053 refreshDrawableState();
3054 }
3055 }
3056
3057 /**
3058 * Called to clear the focus of a view that is about to be removed.
3059 * Doesn't call clearChildFocus, which prevents this view from taking
3060 * focus again before it has been removed from the parent
3061 */
3062 void clearFocusForRemoval() {
3063 if ((mPrivateFlags & FOCUSED) != 0) {
3064 mPrivateFlags &= ~FOCUSED;
3065
3066 onFocusChanged(false, 0, null);
3067 refreshDrawableState();
3068 }
3069 }
3070
3071 /**
3072 * Called internally by the view system when a new view is getting focus.
3073 * This is what clears the old focus.
3074 */
3075 void unFocus() {
3076 if (DBG) {
3077 System.out.println(this + " unFocus()");
3078 }
3079
3080 if ((mPrivateFlags & FOCUSED) != 0) {
3081 mPrivateFlags &= ~FOCUSED;
3082
3083 onFocusChanged(false, 0, null);
3084 refreshDrawableState();
3085 }
3086 }
3087
3088 /**
3089 * Returns true if this view has focus iteself, or is the ancestor of the
3090 * view that has focus.
3091 *
3092 * @return True if this view has or contains focus, false otherwise.
3093 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003094 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 public boolean hasFocus() {
3096 return (mPrivateFlags & FOCUSED) != 0;
3097 }
3098
3099 /**
3100 * Returns true if this view is focusable or if it contains a reachable View
3101 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3102 * is a View whose parents do not block descendants focus.
3103 *
3104 * Only {@link #VISIBLE} views are considered focusable.
3105 *
3106 * @return True if the view is focusable or if the view contains a focusable
3107 * View, false otherwise.
3108 *
3109 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3110 */
3111 public boolean hasFocusable() {
3112 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3113 }
3114
3115 /**
3116 * Called by the view system when the focus state of this view changes.
3117 * When the focus change event is caused by directional navigation, direction
3118 * and previouslyFocusedRect provide insight into where the focus is coming from.
3119 * When overriding, be sure to call up through to the super class so that
3120 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07003121 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 * @param gainFocus True if the View has focus; false otherwise.
3123 * @param direction The direction focus has moved when requestFocus()
3124 * is called to give this view focus. Values are
Jeff Brown4e6319b2010-12-13 10:36:51 -08003125 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3126 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3127 * It may not always apply, in which case use the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003128 * @param previouslyFocusedRect The rectangle, in this view's coordinate
3129 * system, of the previously focused view. If applicable, this will be
3130 * passed in as finer grained information about where the focus is coming
3131 * from (in addition to direction). Will be <code>null</code> otherwise.
3132 */
3133 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003134 if (gainFocus) {
3135 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3136 }
3137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 InputMethodManager imm = InputMethodManager.peekInstance();
3139 if (!gainFocus) {
3140 if (isPressed()) {
3141 setPressed(false);
3142 }
3143 if (imm != null && mAttachInfo != null
3144 && mAttachInfo.mHasWindowFocus) {
3145 imm.focusOut(this);
3146 }
Romain Guya2431d02009-04-30 16:30:00 -07003147 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 } else if (imm != null && mAttachInfo != null
3149 && mAttachInfo.mHasWindowFocus) {
3150 imm.focusIn(this);
3151 }
Romain Guy8506ab42009-06-11 17:35:47 -07003152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153 invalidate();
3154 if (mOnFocusChangeListener != null) {
3155 mOnFocusChangeListener.onFocusChange(this, gainFocus);
3156 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003157
3158 if (mAttachInfo != null) {
3159 mAttachInfo.mKeyDispatchState.reset(this);
3160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 }
3162
3163 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07003164 * {@inheritDoc}
3165 */
3166 public void sendAccessibilityEvent(int eventType) {
3167 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3168 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3169 }
3170 }
3171
3172 /**
3173 * {@inheritDoc}
3174 */
3175 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3176 event.setClassName(getClass().getName());
3177 event.setPackageName(getContext().getPackageName());
3178 event.setEnabled(isEnabled());
3179 event.setContentDescription(mContentDescription);
3180
3181 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3182 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3183 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3184 event.setItemCount(focusablesTempList.size());
3185 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3186 focusablesTempList.clear();
3187 }
3188
3189 dispatchPopulateAccessibilityEvent(event);
3190
3191 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3192 }
3193
3194 /**
3195 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3196 * to be populated.
3197 *
3198 * @param event The event.
3199 *
3200 * @return True if the event population was completed.
3201 */
3202 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3203 return false;
3204 }
3205
3206 /**
3207 * Gets the {@link View} description. It briefly describes the view and is
3208 * primarily used for accessibility support. Set this property to enable
3209 * better accessibility support for your application. This is especially
3210 * true for views that do not have textual representation (For example,
3211 * ImageButton).
3212 *
3213 * @return The content descriptiopn.
3214 *
3215 * @attr ref android.R.styleable#View_contentDescription
3216 */
3217 public CharSequence getContentDescription() {
3218 return mContentDescription;
3219 }
3220
3221 /**
3222 * Sets the {@link View} description. It briefly describes the view and is
3223 * primarily used for accessibility support. Set this property to enable
3224 * better accessibility support for your application. This is especially
3225 * true for views that do not have textual representation (For example,
3226 * ImageButton).
3227 *
3228 * @param contentDescription The content description.
3229 *
3230 * @attr ref android.R.styleable#View_contentDescription
3231 */
3232 public void setContentDescription(CharSequence contentDescription) {
3233 mContentDescription = contentDescription;
3234 }
3235
3236 /**
Romain Guya2431d02009-04-30 16:30:00 -07003237 * Invoked whenever this view loses focus, either by losing window focus or by losing
3238 * focus within its window. This method can be used to clear any state tied to the
3239 * focus. For instance, if a button is held pressed with the trackball and the window
3240 * loses focus, this method can be used to cancel the press.
3241 *
3242 * Subclasses of View overriding this method should always call super.onFocusLost().
3243 *
3244 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003245 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003246 *
3247 * @hide pending API council approval
3248 */
3249 protected void onFocusLost() {
3250 resetPressedState();
3251 }
3252
3253 private void resetPressedState() {
3254 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3255 return;
3256 }
3257
3258 if (isPressed()) {
3259 setPressed(false);
3260
3261 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003262 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003263 }
3264 }
3265 }
3266
3267 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 * Returns true if this view has focus
3269 *
3270 * @return True if this view has focus, false otherwise.
3271 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003272 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 public boolean isFocused() {
3274 return (mPrivateFlags & FOCUSED) != 0;
3275 }
3276
3277 /**
3278 * Find the view in the hierarchy rooted at this view that currently has
3279 * focus.
3280 *
3281 * @return The view that currently has focus, or null if no focused view can
3282 * be found.
3283 */
3284 public View findFocus() {
3285 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3286 }
3287
3288 /**
3289 * Change whether this view is one of the set of scrollable containers in
3290 * its window. This will be used to determine whether the window can
3291 * resize or must pan when a soft input area is open -- scrollable
3292 * containers allow the window to use resize mode since the container
3293 * will appropriately shrink.
3294 */
3295 public void setScrollContainer(boolean isScrollContainer) {
3296 if (isScrollContainer) {
3297 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3298 mAttachInfo.mScrollContainers.add(this);
3299 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3300 }
3301 mPrivateFlags |= SCROLL_CONTAINER;
3302 } else {
3303 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3304 mAttachInfo.mScrollContainers.remove(this);
3305 }
3306 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3307 }
3308 }
3309
3310 /**
3311 * Returns the quality of the drawing cache.
3312 *
3313 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3314 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3315 *
3316 * @see #setDrawingCacheQuality(int)
3317 * @see #setDrawingCacheEnabled(boolean)
3318 * @see #isDrawingCacheEnabled()
3319 *
3320 * @attr ref android.R.styleable#View_drawingCacheQuality
3321 */
3322 public int getDrawingCacheQuality() {
3323 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3324 }
3325
3326 /**
3327 * Set the drawing cache quality of this view. This value is used only when the
3328 * drawing cache is enabled
3329 *
3330 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3331 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3332 *
3333 * @see #getDrawingCacheQuality()
3334 * @see #setDrawingCacheEnabled(boolean)
3335 * @see #isDrawingCacheEnabled()
3336 *
3337 * @attr ref android.R.styleable#View_drawingCacheQuality
3338 */
3339 public void setDrawingCacheQuality(int quality) {
3340 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3341 }
3342
3343 /**
3344 * Returns whether the screen should remain on, corresponding to the current
3345 * value of {@link #KEEP_SCREEN_ON}.
3346 *
3347 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3348 *
3349 * @see #setKeepScreenOn(boolean)
3350 *
3351 * @attr ref android.R.styleable#View_keepScreenOn
3352 */
3353 public boolean getKeepScreenOn() {
3354 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3355 }
3356
3357 /**
3358 * Controls whether the screen should remain on, modifying the
3359 * value of {@link #KEEP_SCREEN_ON}.
3360 *
3361 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3362 *
3363 * @see #getKeepScreenOn()
3364 *
3365 * @attr ref android.R.styleable#View_keepScreenOn
3366 */
3367 public void setKeepScreenOn(boolean keepScreenOn) {
3368 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3369 }
3370
3371 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003372 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3373 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 *
3375 * @attr ref android.R.styleable#View_nextFocusLeft
3376 */
3377 public int getNextFocusLeftId() {
3378 return mNextFocusLeftId;
3379 }
3380
3381 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003382 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3383 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
3384 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 *
3386 * @attr ref android.R.styleable#View_nextFocusLeft
3387 */
3388 public void setNextFocusLeftId(int nextFocusLeftId) {
3389 mNextFocusLeftId = nextFocusLeftId;
3390 }
3391
3392 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003393 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3394 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 *
3396 * @attr ref android.R.styleable#View_nextFocusRight
3397 */
3398 public int getNextFocusRightId() {
3399 return mNextFocusRightId;
3400 }
3401
3402 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003403 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3404 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
3405 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 *
3407 * @attr ref android.R.styleable#View_nextFocusRight
3408 */
3409 public void setNextFocusRightId(int nextFocusRightId) {
3410 mNextFocusRightId = nextFocusRightId;
3411 }
3412
3413 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003414 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3415 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 *
3417 * @attr ref android.R.styleable#View_nextFocusUp
3418 */
3419 public int getNextFocusUpId() {
3420 return mNextFocusUpId;
3421 }
3422
3423 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003424 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3425 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
3426 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 *
3428 * @attr ref android.R.styleable#View_nextFocusUp
3429 */
3430 public void setNextFocusUpId(int nextFocusUpId) {
3431 mNextFocusUpId = nextFocusUpId;
3432 }
3433
3434 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003435 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3436 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 *
3438 * @attr ref android.R.styleable#View_nextFocusDown
3439 */
3440 public int getNextFocusDownId() {
3441 return mNextFocusDownId;
3442 }
3443
3444 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003445 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3446 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
3447 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 *
3449 * @attr ref android.R.styleable#View_nextFocusDown
3450 */
3451 public void setNextFocusDownId(int nextFocusDownId) {
3452 mNextFocusDownId = nextFocusDownId;
3453 }
3454
3455 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003456 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3457 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3458 *
3459 * @attr ref android.R.styleable#View_nextFocusForward
3460 */
3461 public int getNextFocusForwardId() {
3462 return mNextFocusForwardId;
3463 }
3464
3465 /**
3466 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3467 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
3468 * decide automatically.
3469 *
3470 * @attr ref android.R.styleable#View_nextFocusForward
3471 */
3472 public void setNextFocusForwardId(int nextFocusForwardId) {
3473 mNextFocusForwardId = nextFocusForwardId;
3474 }
3475
3476 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 * Returns the visibility of this view and all of its ancestors
3478 *
3479 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3480 */
3481 public boolean isShown() {
3482 View current = this;
3483 //noinspection ConstantConditions
3484 do {
3485 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3486 return false;
3487 }
3488 ViewParent parent = current.mParent;
3489 if (parent == null) {
3490 return false; // We are not attached to the view root
3491 }
3492 if (!(parent instanceof View)) {
3493 return true;
3494 }
3495 current = (View) parent;
3496 } while (current != null);
3497
3498 return false;
3499 }
3500
3501 /**
3502 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3503 * is set
3504 *
3505 * @param insets Insets for system windows
3506 *
3507 * @return True if this view applied the insets, false otherwise
3508 */
3509 protected boolean fitSystemWindows(Rect insets) {
3510 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3511 mPaddingLeft = insets.left;
3512 mPaddingTop = insets.top;
3513 mPaddingRight = insets.right;
3514 mPaddingBottom = insets.bottom;
3515 requestLayout();
3516 return true;
3517 }
3518 return false;
3519 }
3520
3521 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003522 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3523 * @return True if window has FITS_SYSTEM_WINDOWS set
3524 *
3525 * @hide
3526 */
3527 public boolean isFitsSystemWindowsFlagSet() {
3528 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3529 }
3530
3531 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 * Returns the visibility status for this view.
3533 *
3534 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3535 * @attr ref android.R.styleable#View_visibility
3536 */
3537 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003538 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3539 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3540 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 })
3542 public int getVisibility() {
3543 return mViewFlags & VISIBILITY_MASK;
3544 }
3545
3546 /**
3547 * Set the enabled state of this view.
3548 *
3549 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3550 * @attr ref android.R.styleable#View_visibility
3551 */
3552 @RemotableViewMethod
3553 public void setVisibility(int visibility) {
3554 setFlags(visibility, VISIBILITY_MASK);
3555 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3556 }
3557
3558 /**
3559 * Returns the enabled status for this view. The interpretation of the
3560 * enabled state varies by subclass.
3561 *
3562 * @return True if this view is enabled, false otherwise.
3563 */
3564 @ViewDebug.ExportedProperty
3565 public boolean isEnabled() {
3566 return (mViewFlags & ENABLED_MASK) == ENABLED;
3567 }
3568
3569 /**
3570 * Set the enabled state of this view. The interpretation of the enabled
3571 * state varies by subclass.
3572 *
3573 * @param enabled True if this view is enabled, false otherwise.
3574 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003575 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003577 if (enabled == isEnabled()) return;
3578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3580
3581 /*
3582 * The View most likely has to change its appearance, so refresh
3583 * the drawable state.
3584 */
3585 refreshDrawableState();
3586
3587 // Invalidate too, since the default behavior for views is to be
3588 // be drawn at 50% alpha rather than to change the drawable.
3589 invalidate();
3590 }
3591
3592 /**
3593 * Set whether this view can receive the focus.
3594 *
3595 * Setting this to false will also ensure that this view is not focusable
3596 * in touch mode.
3597 *
3598 * @param focusable If true, this view can receive the focus.
3599 *
3600 * @see #setFocusableInTouchMode(boolean)
3601 * @attr ref android.R.styleable#View_focusable
3602 */
3603 public void setFocusable(boolean focusable) {
3604 if (!focusable) {
3605 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3606 }
3607 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3608 }
3609
3610 /**
3611 * Set whether this view can receive focus while in touch mode.
3612 *
3613 * Setting this to true will also ensure that this view is focusable.
3614 *
3615 * @param focusableInTouchMode If true, this view can receive the focus while
3616 * in touch mode.
3617 *
3618 * @see #setFocusable(boolean)
3619 * @attr ref android.R.styleable#View_focusableInTouchMode
3620 */
3621 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3622 // Focusable in touch mode should always be set before the focusable flag
3623 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3624 // which, in touch mode, will not successfully request focus on this view
3625 // because the focusable in touch mode flag is not set
3626 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3627 if (focusableInTouchMode) {
3628 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3629 }
3630 }
3631
3632 /**
3633 * Set whether this view should have sound effects enabled for events such as
3634 * clicking and touching.
3635 *
3636 * <p>You may wish to disable sound effects for a view if you already play sounds,
3637 * for instance, a dial key that plays dtmf tones.
3638 *
3639 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3640 * @see #isSoundEffectsEnabled()
3641 * @see #playSoundEffect(int)
3642 * @attr ref android.R.styleable#View_soundEffectsEnabled
3643 */
3644 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3645 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3646 }
3647
3648 /**
3649 * @return whether this view should have sound effects enabled for events such as
3650 * clicking and touching.
3651 *
3652 * @see #setSoundEffectsEnabled(boolean)
3653 * @see #playSoundEffect(int)
3654 * @attr ref android.R.styleable#View_soundEffectsEnabled
3655 */
3656 @ViewDebug.ExportedProperty
3657 public boolean isSoundEffectsEnabled() {
3658 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3659 }
3660
3661 /**
3662 * Set whether this view should have haptic feedback for events such as
3663 * long presses.
3664 *
3665 * <p>You may wish to disable haptic feedback if your view already controls
3666 * its own haptic feedback.
3667 *
3668 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3669 * @see #isHapticFeedbackEnabled()
3670 * @see #performHapticFeedback(int)
3671 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3672 */
3673 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3674 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3675 }
3676
3677 /**
3678 * @return whether this view should have haptic feedback enabled for events
3679 * long presses.
3680 *
3681 * @see #setHapticFeedbackEnabled(boolean)
3682 * @see #performHapticFeedback(int)
3683 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3684 */
3685 @ViewDebug.ExportedProperty
3686 public boolean isHapticFeedbackEnabled() {
3687 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3688 }
3689
3690 /**
3691 * If this view doesn't do any drawing on its own, set this flag to
3692 * allow further optimizations. By default, this flag is not set on
3693 * View, but could be set on some View subclasses such as ViewGroup.
3694 *
3695 * Typically, if you override {@link #onDraw} you should clear this flag.
3696 *
3697 * @param willNotDraw whether or not this View draw on its own
3698 */
3699 public void setWillNotDraw(boolean willNotDraw) {
3700 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3701 }
3702
3703 /**
3704 * Returns whether or not this View draws on its own.
3705 *
3706 * @return true if this view has nothing to draw, false otherwise
3707 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003708 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 public boolean willNotDraw() {
3710 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3711 }
3712
3713 /**
3714 * When a View's drawing cache is enabled, drawing is redirected to an
3715 * offscreen bitmap. Some views, like an ImageView, must be able to
3716 * bypass this mechanism if they already draw a single bitmap, to avoid
3717 * unnecessary usage of the memory.
3718 *
3719 * @param willNotCacheDrawing true if this view does not cache its
3720 * drawing, false otherwise
3721 */
3722 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3723 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3724 }
3725
3726 /**
3727 * Returns whether or not this View can cache its drawing or not.
3728 *
3729 * @return true if this view does not cache its drawing, false otherwise
3730 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003731 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 public boolean willNotCacheDrawing() {
3733 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3734 }
3735
3736 /**
3737 * Indicates whether this view reacts to click events or not.
3738 *
3739 * @return true if the view is clickable, false otherwise
3740 *
3741 * @see #setClickable(boolean)
3742 * @attr ref android.R.styleable#View_clickable
3743 */
3744 @ViewDebug.ExportedProperty
3745 public boolean isClickable() {
3746 return (mViewFlags & CLICKABLE) == CLICKABLE;
3747 }
3748
3749 /**
3750 * Enables or disables click events for this view. When a view
3751 * is clickable it will change its state to "pressed" on every click.
3752 * Subclasses should set the view clickable to visually react to
3753 * user's clicks.
3754 *
3755 * @param clickable true to make the view clickable, false otherwise
3756 *
3757 * @see #isClickable()
3758 * @attr ref android.R.styleable#View_clickable
3759 */
3760 public void setClickable(boolean clickable) {
3761 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3762 }
3763
3764 /**
3765 * Indicates whether this view reacts to long click events or not.
3766 *
3767 * @return true if the view is long clickable, false otherwise
3768 *
3769 * @see #setLongClickable(boolean)
3770 * @attr ref android.R.styleable#View_longClickable
3771 */
3772 public boolean isLongClickable() {
3773 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3774 }
3775
3776 /**
3777 * Enables or disables long click events for this view. When a view is long
3778 * clickable it reacts to the user holding down the button for a longer
3779 * duration than a tap. This event can either launch the listener or a
3780 * context menu.
3781 *
3782 * @param longClickable true to make the view long clickable, false otherwise
3783 * @see #isLongClickable()
3784 * @attr ref android.R.styleable#View_longClickable
3785 */
3786 public void setLongClickable(boolean longClickable) {
3787 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3788 }
3789
3790 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003791 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 *
3793 * @see #isClickable()
3794 * @see #setClickable(boolean)
3795 *
3796 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3797 * the View's internal state from a previously set "pressed" state.
3798 */
3799 public void setPressed(boolean pressed) {
3800 if (pressed) {
3801 mPrivateFlags |= PRESSED;
3802 } else {
3803 mPrivateFlags &= ~PRESSED;
3804 }
3805 refreshDrawableState();
3806 dispatchSetPressed(pressed);
3807 }
3808
3809 /**
3810 * Dispatch setPressed to all of this View's children.
3811 *
3812 * @see #setPressed(boolean)
3813 *
3814 * @param pressed The new pressed state
3815 */
3816 protected void dispatchSetPressed(boolean pressed) {
3817 }
3818
3819 /**
3820 * Indicates whether the view is currently in pressed state. Unless
3821 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3822 * the pressed state.
3823 *
3824 * @see #setPressed
3825 * @see #isClickable()
3826 * @see #setClickable(boolean)
3827 *
3828 * @return true if the view is currently pressed, false otherwise
3829 */
3830 public boolean isPressed() {
3831 return (mPrivateFlags & PRESSED) == PRESSED;
3832 }
3833
3834 /**
3835 * Indicates whether this view will save its state (that is,
3836 * whether its {@link #onSaveInstanceState} method will be called).
3837 *
3838 * @return Returns true if the view state saving is enabled, else false.
3839 *
3840 * @see #setSaveEnabled(boolean)
3841 * @attr ref android.R.styleable#View_saveEnabled
3842 */
3843 public boolean isSaveEnabled() {
3844 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3845 }
3846
3847 /**
3848 * Controls whether the saving of this view's state is
3849 * enabled (that is, whether its {@link #onSaveInstanceState} method
3850 * will be called). Note that even if freezing is enabled, the
3851 * view still must have an id assigned to it (via {@link #setId setId()})
3852 * for its state to be saved. This flag can only disable the
3853 * saving of this view; any child views may still have their state saved.
3854 *
3855 * @param enabled Set to false to <em>disable</em> state saving, or true
3856 * (the default) to allow it.
3857 *
3858 * @see #isSaveEnabled()
3859 * @see #setId(int)
3860 * @see #onSaveInstanceState()
3861 * @attr ref android.R.styleable#View_saveEnabled
3862 */
3863 public void setSaveEnabled(boolean enabled) {
3864 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3865 }
3866
Jeff Brown85a31762010-09-01 17:01:00 -07003867 /**
3868 * Gets whether the framework should discard touches when the view's
3869 * window is obscured by another visible window.
3870 * Refer to the {@link View} security documentation for more details.
3871 *
3872 * @return True if touch filtering is enabled.
3873 *
3874 * @see #setFilterTouchesWhenObscured(boolean)
3875 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3876 */
3877 @ViewDebug.ExportedProperty
3878 public boolean getFilterTouchesWhenObscured() {
3879 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3880 }
3881
3882 /**
3883 * Sets whether the framework should discard touches when the view's
3884 * window is obscured by another visible window.
3885 * Refer to the {@link View} security documentation for more details.
3886 *
3887 * @param enabled True if touch filtering should be enabled.
3888 *
3889 * @see #getFilterTouchesWhenObscured
3890 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3891 */
3892 public void setFilterTouchesWhenObscured(boolean enabled) {
3893 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3894 FILTER_TOUCHES_WHEN_OBSCURED);
3895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896
3897 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003898 * Indicates whether the entire hierarchy under this view will save its
3899 * state when a state saving traversal occurs from its parent. The default
3900 * is true; if false, these views will not be saved unless
3901 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3902 *
3903 * @return Returns true if the view state saving from parent is enabled, else false.
3904 *
3905 * @see #setSaveFromParentEnabled(boolean)
3906 */
3907 public boolean isSaveFromParentEnabled() {
3908 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3909 }
3910
3911 /**
3912 * Controls whether the entire hierarchy under this view will save its
3913 * state when a state saving traversal occurs from its parent. The default
3914 * is true; if false, these views will not be saved unless
3915 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3916 *
3917 * @param enabled Set to false to <em>disable</em> state saving, or true
3918 * (the default) to allow it.
3919 *
3920 * @see #isSaveFromParentEnabled()
3921 * @see #setId(int)
3922 * @see #onSaveInstanceState()
3923 */
3924 public void setSaveFromParentEnabled(boolean enabled) {
3925 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
3926 }
3927
3928
3929 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 * Returns whether this View is able to take focus.
3931 *
3932 * @return True if this view can take focus, or false otherwise.
3933 * @attr ref android.R.styleable#View_focusable
3934 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003935 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 public final boolean isFocusable() {
3937 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3938 }
3939
3940 /**
3941 * When a view is focusable, it may not want to take focus when in touch mode.
3942 * For example, a button would like focus when the user is navigating via a D-pad
3943 * so that the user can click on it, but once the user starts touching the screen,
3944 * the button shouldn't take focus
3945 * @return Whether the view is focusable in touch mode.
3946 * @attr ref android.R.styleable#View_focusableInTouchMode
3947 */
3948 @ViewDebug.ExportedProperty
3949 public final boolean isFocusableInTouchMode() {
3950 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3951 }
3952
3953 /**
3954 * Find the nearest view in the specified direction that can take focus.
3955 * This does not actually give focus to that view.
3956 *
3957 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3958 *
3959 * @return The nearest focusable in the specified direction, or null if none
3960 * can be found.
3961 */
3962 public View focusSearch(int direction) {
3963 if (mParent != null) {
3964 return mParent.focusSearch(this, direction);
3965 } else {
3966 return null;
3967 }
3968 }
3969
3970 /**
3971 * This method is the last chance for the focused view and its ancestors to
3972 * respond to an arrow key. This is called when the focused view did not
3973 * consume the key internally, nor could the view system find a new view in
3974 * the requested direction to give focus to.
3975 *
3976 * @param focused The currently focused view.
3977 * @param direction The direction focus wants to move. One of FOCUS_UP,
3978 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3979 * @return True if the this view consumed this unhandled move.
3980 */
3981 public boolean dispatchUnhandledMove(View focused, int direction) {
3982 return false;
3983 }
3984
3985 /**
3986 * If a user manually specified the next view id for a particular direction,
Jeff Brown4e6319b2010-12-13 10:36:51 -08003987 * use the root to look up the view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 * @param root The root view of the hierarchy containing this view.
Jeff Brown4e6319b2010-12-13 10:36:51 -08003989 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
3990 * or FOCUS_BACKWARD.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 * @return The user specified next view, or null if there is none.
3992 */
3993 View findUserSetNextFocus(View root, int direction) {
3994 switch (direction) {
3995 case FOCUS_LEFT:
3996 if (mNextFocusLeftId == View.NO_ID) return null;
3997 return findViewShouldExist(root, mNextFocusLeftId);
3998 case FOCUS_RIGHT:
3999 if (mNextFocusRightId == View.NO_ID) return null;
4000 return findViewShouldExist(root, mNextFocusRightId);
4001 case FOCUS_UP:
4002 if (mNextFocusUpId == View.NO_ID) return null;
4003 return findViewShouldExist(root, mNextFocusUpId);
4004 case FOCUS_DOWN:
4005 if (mNextFocusDownId == View.NO_ID) return null;
4006 return findViewShouldExist(root, mNextFocusDownId);
Jeff Brown4e6319b2010-12-13 10:36:51 -08004007 case FOCUS_FORWARD:
4008 if (mNextFocusForwardId == View.NO_ID) return null;
4009 return findViewShouldExist(root, mNextFocusForwardId);
4010 case FOCUS_BACKWARD: {
4011 final int id = mID;
4012 return root.findViewByPredicate(new Predicate<View>() {
4013 @Override
4014 public boolean apply(View t) {
4015 return t.mNextFocusForwardId == id;
4016 }
4017 });
4018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 }
4020 return null;
4021 }
4022
4023 private static View findViewShouldExist(View root, int childViewId) {
4024 View result = root.findViewById(childViewId);
4025 if (result == null) {
4026 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4027 + "by user for id " + childViewId);
4028 }
4029 return result;
4030 }
4031
4032 /**
4033 * Find and return all focusable views that are descendants of this view,
4034 * possibly including this view if it is focusable itself.
4035 *
4036 * @param direction The direction of the focus
4037 * @return A list of focusable views
4038 */
4039 public ArrayList<View> getFocusables(int direction) {
4040 ArrayList<View> result = new ArrayList<View>(24);
4041 addFocusables(result, direction);
4042 return result;
4043 }
4044
4045 /**
4046 * Add any focusable views that are descendants of this view (possibly
4047 * including this view if it is focusable itself) to views. If we are in touch mode,
4048 * only add views that are also focusable in touch mode.
4049 *
4050 * @param views Focusable views found so far
4051 * @param direction The direction of the focus
4052 */
4053 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07004054 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056
svetoslavganov75986cf2009-05-14 22:28:01 -07004057 /**
4058 * Adds any focusable views that are descendants of this view (possibly
4059 * including this view if it is focusable itself) to views. This method
4060 * adds all focusable views regardless if we are in touch mode or
4061 * only views focusable in touch mode if we are in touch mode depending on
4062 * the focusable mode paramater.
4063 *
4064 * @param views Focusable views found so far or null if all we are interested is
4065 * the number of focusables.
4066 * @param direction The direction of the focus.
4067 * @param focusableMode The type of focusables to be added.
4068 *
4069 * @see #FOCUSABLES_ALL
4070 * @see #FOCUSABLES_TOUCH_MODE
4071 */
4072 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4073 if (!isFocusable()) {
4074 return;
4075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004076
svetoslavganov75986cf2009-05-14 22:28:01 -07004077 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4078 isInTouchMode() && !isFocusableInTouchMode()) {
4079 return;
4080 }
4081
4082 if (views != null) {
4083 views.add(this);
4084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 }
4086
4087 /**
4088 * Find and return all touchable views that are descendants of this view,
4089 * possibly including this view if it is touchable itself.
4090 *
4091 * @return A list of touchable views
4092 */
4093 public ArrayList<View> getTouchables() {
4094 ArrayList<View> result = new ArrayList<View>();
4095 addTouchables(result);
4096 return result;
4097 }
4098
4099 /**
4100 * Add any touchable views that are descendants of this view (possibly
4101 * including this view if it is touchable itself) to views.
4102 *
4103 * @param views Touchable views found so far
4104 */
4105 public void addTouchables(ArrayList<View> views) {
4106 final int viewFlags = mViewFlags;
4107
4108 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4109 && (viewFlags & ENABLED_MASK) == ENABLED) {
4110 views.add(this);
4111 }
4112 }
4113
4114 /**
4115 * Call this to try to give focus to a specific view or to one of its
4116 * descendants.
4117 *
4118 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4119 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4120 * while the device is in touch mode.
4121 *
4122 * See also {@link #focusSearch}, which is what you call to say that you
4123 * have focus, and you want your parent to look for the next one.
4124 *
4125 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4126 * {@link #FOCUS_DOWN} and <code>null</code>.
4127 *
4128 * @return Whether this view or one of its descendants actually took focus.
4129 */
4130 public final boolean requestFocus() {
4131 return requestFocus(View.FOCUS_DOWN);
4132 }
4133
4134
4135 /**
4136 * Call this to try to give focus to a specific view or to one of its
4137 * descendants and give it a hint about what direction focus is heading.
4138 *
4139 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4140 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4141 * while the device is in touch mode.
4142 *
4143 * See also {@link #focusSearch}, which is what you call to say that you
4144 * have focus, and you want your parent to look for the next one.
4145 *
4146 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4147 * <code>null</code> set for the previously focused rectangle.
4148 *
4149 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4150 * @return Whether this view or one of its descendants actually took focus.
4151 */
4152 public final boolean requestFocus(int direction) {
4153 return requestFocus(direction, null);
4154 }
4155
4156 /**
4157 * Call this to try to give focus to a specific view or to one of its descendants
4158 * and give it hints about the direction and a specific rectangle that the focus
4159 * is coming from. The rectangle can help give larger views a finer grained hint
4160 * about where focus is coming from, and therefore, where to show selection, or
4161 * forward focus change internally.
4162 *
4163 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4164 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4165 * while the device is in touch mode.
4166 *
4167 * A View will not take focus if it is not visible.
4168 *
4169 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4170 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4171 *
4172 * See also {@link #focusSearch}, which is what you call to say that you
4173 * have focus, and you want your parent to look for the next one.
4174 *
4175 * You may wish to override this method if your custom {@link View} has an internal
4176 * {@link View} that it wishes to forward the request to.
4177 *
4178 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4179 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4180 * to give a finer grained hint about where focus is coming from. May be null
4181 * if there is no hint.
4182 * @return Whether this view or one of its descendants actually took focus.
4183 */
4184 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4185 // need to be focusable
4186 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4187 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4188 return false;
4189 }
4190
4191 // need to be focusable in touch mode if in touch mode
4192 if (isInTouchMode() &&
4193 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4194 return false;
4195 }
4196
4197 // need to not have any parents blocking us
4198 if (hasAncestorThatBlocksDescendantFocus()) {
4199 return false;
4200 }
4201
4202 handleFocusGainInternal(direction, previouslyFocusedRect);
4203 return true;
4204 }
4205
Christopher Tate2c095f32010-10-04 14:13:40 -07004206 /** Gets the ViewRoot, or null if not attached. */
4207 /*package*/ ViewRoot getViewRoot() {
4208 View root = getRootView();
4209 return root != null ? (ViewRoot)root.getParent() : null;
4210 }
4211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 /**
4213 * Call this to try to give focus to a specific view or to one of its descendants. This is a
4214 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4215 * touch mode to request focus when they are touched.
4216 *
4217 * @return Whether this view or one of its descendants actually took focus.
4218 *
4219 * @see #isInTouchMode()
4220 *
4221 */
4222 public final boolean requestFocusFromTouch() {
4223 // Leave touch mode if we need to
4224 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07004225 ViewRoot viewRoot = getViewRoot();
4226 if (viewRoot != null) {
4227 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 }
4229 }
4230 return requestFocus(View.FOCUS_DOWN);
4231 }
4232
4233 /**
4234 * @return Whether any ancestor of this view blocks descendant focus.
4235 */
4236 private boolean hasAncestorThatBlocksDescendantFocus() {
4237 ViewParent ancestor = mParent;
4238 while (ancestor instanceof ViewGroup) {
4239 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4240 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4241 return true;
4242 } else {
4243 ancestor = vgAncestor.getParent();
4244 }
4245 }
4246 return false;
4247 }
4248
4249 /**
Romain Guya440b002010-02-24 15:57:54 -08004250 * @hide
4251 */
4252 public void dispatchStartTemporaryDetach() {
4253 onStartTemporaryDetach();
4254 }
4255
4256 /**
4257 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4259 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004260 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 */
4262 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004263 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004264 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004265 }
4266
4267 /**
4268 * @hide
4269 */
4270 public void dispatchFinishTemporaryDetach() {
4271 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 }
Romain Guy8506ab42009-06-11 17:35:47 -07004273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004274 /**
4275 * Called after {@link #onStartTemporaryDetach} when the container is done
4276 * changing the view.
4277 */
4278 public void onFinishTemporaryDetach() {
4279 }
Romain Guy8506ab42009-06-11 17:35:47 -07004280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 /**
4282 * capture information of this view for later analysis: developement only
4283 * check dynamic switch to make sure we only dump view
4284 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4285 */
4286 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004287 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 return;
4289 }
4290 ViewDebug.dumpCapturedView(subTag, v);
4291 }
4292
4293 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004294 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4295 * for this view's window. Returns null if the view is not currently attached
4296 * to the window. Normally you will not need to use this directly, but
4297 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4298 */
4299 public KeyEvent.DispatcherState getKeyDispatcherState() {
4300 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4301 }
4302
4303 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 * Dispatch a key event before it is processed by any input method
4305 * associated with the view hierarchy. This can be used to intercept
4306 * key events in special situations before the IME consumes them; a
4307 * typical example would be handling the BACK key to update the application's
4308 * UI instead of allowing the IME to see it and close itself.
4309 *
4310 * @param event The key event to be dispatched.
4311 * @return True if the event was handled, false otherwise.
4312 */
4313 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4314 return onKeyPreIme(event.getKeyCode(), event);
4315 }
4316
4317 /**
4318 * Dispatch a key event to the next view on the focus path. This path runs
4319 * from the top of the view tree down to the currently focused view. If this
4320 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4321 * the next node down the focus path. This method also fires any key
4322 * listeners.
4323 *
4324 * @param event The key event to be dispatched.
4325 * @return True if the event was handled, false otherwise.
4326 */
4327 public boolean dispatchKeyEvent(KeyEvent event) {
4328 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004329
Romain Guyf607bdc2010-09-10 19:20:06 -07004330 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004331 if (android.util.Config.LOGV) {
4332 captureViewInfo("captureViewKeyEvent", this);
4333 }
4334
Romain Guyf607bdc2010-09-10 19:20:06 -07004335 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4337 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4338 return true;
4339 }
4340
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004341 return event.dispatch(this, mAttachInfo != null
4342 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 }
4344
4345 /**
4346 * Dispatches a key shortcut event.
4347 *
4348 * @param event The key event to be dispatched.
4349 * @return True if the event was handled by the view, false otherwise.
4350 */
4351 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4352 return onKeyShortcut(event.getKeyCode(), event);
4353 }
4354
4355 /**
4356 * Pass the touch screen motion event down to the target view, or this
4357 * view if it is the target.
4358 *
4359 * @param event The motion event to be dispatched.
4360 * @return True if the event was handled by the view, false otherwise.
4361 */
4362 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004363 if (!onFilterTouchEventForSecurity(event)) {
4364 return false;
4365 }
4366
Romain Guyf607bdc2010-09-10 19:20:06 -07004367 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4369 mOnTouchListener.onTouch(this, event)) {
4370 return true;
4371 }
4372 return onTouchEvent(event);
4373 }
4374
4375 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004376 * Filter the touch event to apply security policies.
4377 *
4378 * @param event The motion event to be filtered.
4379 * @return True if the event should be dispatched, false if the event should be dropped.
4380 *
4381 * @see #getFilterTouchesWhenObscured
4382 */
4383 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004384 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004385 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4386 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4387 // Window is obscured, drop this touch.
4388 return false;
4389 }
4390 return true;
4391 }
4392
4393 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 * Pass a trackball motion event down to the focused view.
4395 *
4396 * @param event The motion event to be dispatched.
4397 * @return True if the event was handled by the view, false otherwise.
4398 */
4399 public boolean dispatchTrackballEvent(MotionEvent event) {
4400 //Log.i("view", "view=" + this + ", " + event.toString());
4401 return onTrackballEvent(event);
4402 }
4403
4404 /**
4405 * Called when the window containing this view gains or loses window focus.
4406 * ViewGroups should override to route to their children.
4407 *
4408 * @param hasFocus True if the window containing this view now has focus,
4409 * false otherwise.
4410 */
4411 public void dispatchWindowFocusChanged(boolean hasFocus) {
4412 onWindowFocusChanged(hasFocus);
4413 }
4414
4415 /**
4416 * Called when the window containing this view gains or loses focus. Note
4417 * that this is separate from view focus: to receive key events, both
4418 * your view and its window must have focus. If a window is displayed
4419 * on top of yours that takes input focus, then your own window will lose
4420 * focus but the view focus will remain unchanged.
4421 *
4422 * @param hasWindowFocus True if the window containing this view now has
4423 * focus, false otherwise.
4424 */
4425 public void onWindowFocusChanged(boolean hasWindowFocus) {
4426 InputMethodManager imm = InputMethodManager.peekInstance();
4427 if (!hasWindowFocus) {
4428 if (isPressed()) {
4429 setPressed(false);
4430 }
4431 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4432 imm.focusOut(this);
4433 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004434 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004435 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004436 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004437 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4438 imm.focusIn(this);
4439 }
4440 refreshDrawableState();
4441 }
4442
4443 /**
4444 * Returns true if this view is in a window that currently has window focus.
4445 * Note that this is not the same as the view itself having focus.
4446 *
4447 * @return True if this view is in a window that currently has window focus.
4448 */
4449 public boolean hasWindowFocus() {
4450 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4451 }
4452
4453 /**
Adam Powell326d8082009-12-09 15:10:07 -08004454 * Dispatch a view visibility change down the view hierarchy.
4455 * ViewGroups should override to route to their children.
4456 * @param changedView The view whose visibility changed. Could be 'this' or
4457 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004458 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4459 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004460 */
4461 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4462 onVisibilityChanged(changedView, visibility);
4463 }
4464
4465 /**
4466 * Called when the visibility of the view or an ancestor of the view is changed.
4467 * @param changedView The view whose visibility changed. Could be 'this' or
4468 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004469 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4470 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004471 */
4472 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004473 if (visibility == VISIBLE) {
4474 if (mAttachInfo != null) {
4475 initialAwakenScrollBars();
4476 } else {
4477 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4478 }
4479 }
Adam Powell326d8082009-12-09 15:10:07 -08004480 }
4481
4482 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004483 * Dispatch a hint about whether this view is displayed. For instance, when
4484 * a View moves out of the screen, it might receives a display hint indicating
4485 * the view is not displayed. Applications should not <em>rely</em> on this hint
4486 * as there is no guarantee that they will receive one.
4487 *
4488 * @param hint A hint about whether or not this view is displayed:
4489 * {@link #VISIBLE} or {@link #INVISIBLE}.
4490 */
4491 public void dispatchDisplayHint(int hint) {
4492 onDisplayHint(hint);
4493 }
4494
4495 /**
4496 * Gives this view a hint about whether is displayed or not. For instance, when
4497 * a View moves out of the screen, it might receives a display hint indicating
4498 * the view is not displayed. Applications should not <em>rely</em> on this hint
4499 * as there is no guarantee that they will receive one.
4500 *
4501 * @param hint A hint about whether or not this view is displayed:
4502 * {@link #VISIBLE} or {@link #INVISIBLE}.
4503 */
4504 protected void onDisplayHint(int hint) {
4505 }
4506
4507 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004508 * Dispatch a window visibility change down the view hierarchy.
4509 * ViewGroups should override to route to their children.
4510 *
4511 * @param visibility The new visibility of the window.
4512 *
4513 * @see #onWindowVisibilityChanged
4514 */
4515 public void dispatchWindowVisibilityChanged(int visibility) {
4516 onWindowVisibilityChanged(visibility);
4517 }
4518
4519 /**
4520 * Called when the window containing has change its visibility
4521 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4522 * that this tells you whether or not your window is being made visible
4523 * to the window manager; this does <em>not</em> tell you whether or not
4524 * your window is obscured by other windows on the screen, even if it
4525 * is itself visible.
4526 *
4527 * @param visibility The new visibility of the window.
4528 */
4529 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004530 if (visibility == VISIBLE) {
4531 initialAwakenScrollBars();
4532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533 }
4534
4535 /**
4536 * Returns the current visibility of the window this view is attached to
4537 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4538 *
4539 * @return Returns the current visibility of the view's window.
4540 */
4541 public int getWindowVisibility() {
4542 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4543 }
4544
4545 /**
4546 * Retrieve the overall visible display size in which the window this view is
4547 * attached to has been positioned in. This takes into account screen
4548 * decorations above the window, for both cases where the window itself
4549 * is being position inside of them or the window is being placed under
4550 * then and covered insets are used for the window to position its content
4551 * inside. In effect, this tells you the available area where content can
4552 * be placed and remain visible to users.
4553 *
4554 * <p>This function requires an IPC back to the window manager to retrieve
4555 * the requested information, so should not be used in performance critical
4556 * code like drawing.
4557 *
4558 * @param outRect Filled in with the visible display frame. If the view
4559 * is not attached to a window, this is simply the raw display size.
4560 */
4561 public void getWindowVisibleDisplayFrame(Rect outRect) {
4562 if (mAttachInfo != null) {
4563 try {
4564 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4565 } catch (RemoteException e) {
4566 return;
4567 }
4568 // XXX This is really broken, and probably all needs to be done
4569 // in the window manager, and we need to know more about whether
4570 // we want the area behind or in front of the IME.
4571 final Rect insets = mAttachInfo.mVisibleInsets;
4572 outRect.left += insets.left;
4573 outRect.top += insets.top;
4574 outRect.right -= insets.right;
4575 outRect.bottom -= insets.bottom;
4576 return;
4577 }
4578 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4579 outRect.set(0, 0, d.getWidth(), d.getHeight());
4580 }
4581
4582 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004583 * Dispatch a notification about a resource configuration change down
4584 * the view hierarchy.
4585 * ViewGroups should override to route to their children.
4586 *
4587 * @param newConfig The new resource configuration.
4588 *
4589 * @see #onConfigurationChanged
4590 */
4591 public void dispatchConfigurationChanged(Configuration newConfig) {
4592 onConfigurationChanged(newConfig);
4593 }
4594
4595 /**
4596 * Called when the current configuration of the resources being used
4597 * by the application have changed. You can use this to decide when
4598 * to reload resources that can changed based on orientation and other
4599 * configuration characterstics. You only need to use this if you are
4600 * not relying on the normal {@link android.app.Activity} mechanism of
4601 * recreating the activity instance upon a configuration change.
4602 *
4603 * @param newConfig The new resource configuration.
4604 */
4605 protected void onConfigurationChanged(Configuration newConfig) {
4606 }
4607
4608 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 * Private function to aggregate all per-view attributes in to the view
4610 * root.
4611 */
4612 void dispatchCollectViewAttributes(int visibility) {
4613 performCollectViewAttributes(visibility);
4614 }
4615
4616 void performCollectViewAttributes(int visibility) {
4617 //noinspection PointlessBitwiseExpression
4618 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4619 == (VISIBLE | KEEP_SCREEN_ON)) {
4620 mAttachInfo.mKeepScreenOn = true;
4621 }
4622 }
4623
4624 void needGlobalAttributesUpdate(boolean force) {
4625 AttachInfo ai = mAttachInfo;
4626 if (ai != null) {
4627 if (ai.mKeepScreenOn || force) {
4628 ai.mRecomputeGlobalAttributes = true;
4629 }
4630 }
4631 }
4632
4633 /**
4634 * Returns whether the device is currently in touch mode. Touch mode is entered
4635 * once the user begins interacting with the device by touch, and affects various
4636 * things like whether focus is always visible to the user.
4637 *
4638 * @return Whether the device is in touch mode.
4639 */
4640 @ViewDebug.ExportedProperty
4641 public boolean isInTouchMode() {
4642 if (mAttachInfo != null) {
4643 return mAttachInfo.mInTouchMode;
4644 } else {
4645 return ViewRoot.isInTouchMode();
4646 }
4647 }
4648
4649 /**
4650 * Returns the context the view is running in, through which it can
4651 * access the current theme, resources, etc.
4652 *
4653 * @return The view's Context.
4654 */
4655 @ViewDebug.CapturedViewProperty
4656 public final Context getContext() {
4657 return mContext;
4658 }
4659
4660 /**
4661 * Handle a key event before it is processed by any input method
4662 * associated with the view hierarchy. This can be used to intercept
4663 * key events in special situations before the IME consumes them; a
4664 * typical example would be handling the BACK key to update the application's
4665 * UI instead of allowing the IME to see it and close itself.
4666 *
4667 * @param keyCode The value in event.getKeyCode().
4668 * @param event Description of the key event.
4669 * @return If you handled the event, return true. If you want to allow the
4670 * event to be handled by the next receiver, return false.
4671 */
4672 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4673 return false;
4674 }
4675
4676 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004677 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
4678 * KeyEvent.Callback.onKeyDown()}: perform press of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004679 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4680 * is released, if the view is enabled and clickable.
4681 *
4682 * @param keyCode A key code that represents the button pressed, from
4683 * {@link android.view.KeyEvent}.
4684 * @param event The KeyEvent object that defines the button action.
4685 */
4686 public boolean onKeyDown(int keyCode, KeyEvent event) {
4687 boolean result = false;
4688
4689 switch (keyCode) {
4690 case KeyEvent.KEYCODE_DPAD_CENTER:
4691 case KeyEvent.KEYCODE_ENTER: {
4692 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4693 return true;
4694 }
4695 // Long clickable items don't necessarily have to be clickable
4696 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4697 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4698 (event.getRepeatCount() == 0)) {
4699 setPressed(true);
4700 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004701 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004702 }
4703 return true;
4704 }
4705 break;
4706 }
4707 }
4708 return result;
4709 }
4710
4711 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004712 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4713 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4714 * the event).
4715 */
4716 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4717 return false;
4718 }
4719
4720 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004721 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
4722 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004723 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4724 * {@link KeyEvent#KEYCODE_ENTER} is released.
4725 *
4726 * @param keyCode A key code that represents the button pressed, from
4727 * {@link android.view.KeyEvent}.
4728 * @param event The KeyEvent object that defines the button action.
4729 */
4730 public boolean onKeyUp(int keyCode, KeyEvent event) {
4731 boolean result = false;
4732
4733 switch (keyCode) {
4734 case KeyEvent.KEYCODE_DPAD_CENTER:
4735 case KeyEvent.KEYCODE_ENTER: {
4736 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4737 return true;
4738 }
4739 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4740 setPressed(false);
4741
4742 if (!mHasPerformedLongPress) {
4743 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004744 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745
4746 result = performClick();
4747 }
4748 }
4749 break;
4750 }
4751 }
4752 return result;
4753 }
4754
4755 /**
4756 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4757 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4758 * the event).
4759 *
4760 * @param keyCode A key code that represents the button pressed, from
4761 * {@link android.view.KeyEvent}.
4762 * @param repeatCount The number of times the action was made.
4763 * @param event The KeyEvent object that defines the button action.
4764 */
4765 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4766 return false;
4767 }
4768
4769 /**
4770 * Called when an unhandled key shortcut event occurs.
4771 *
4772 * @param keyCode The value in event.getKeyCode().
4773 * @param event Description of the key event.
4774 * @return If you handled the event, return true. If you want to allow the
4775 * event to be handled by the next receiver, return false.
4776 */
4777 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4778 return false;
4779 }
4780
4781 /**
4782 * Check whether the called view is a text editor, in which case it
4783 * would make sense to automatically display a soft input window for
4784 * it. Subclasses should override this if they implement
4785 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004786 * a call on that method would return a non-null InputConnection, and
4787 * they are really a first-class editor that the user would normally
4788 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004789 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004790 * <p>The default implementation always returns false. This does
4791 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4792 * will not be called or the user can not otherwise perform edits on your
4793 * view; it is just a hint to the system that this is not the primary
4794 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004795 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004796 * @return Returns true if this view is a text editor, else false.
4797 */
4798 public boolean onCheckIsTextEditor() {
4799 return false;
4800 }
Romain Guy8506ab42009-06-11 17:35:47 -07004801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004802 /**
4803 * Create a new InputConnection for an InputMethod to interact
4804 * with the view. The default implementation returns null, since it doesn't
4805 * support input methods. You can override this to implement such support.
4806 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004807 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004808 * <p>When implementing this, you probably also want to implement
4809 * {@link #onCheckIsTextEditor()} to indicate you will return a
4810 * non-null InputConnection.
4811 *
4812 * @param outAttrs Fill in with attribute information about the connection.
4813 */
4814 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4815 return null;
4816 }
4817
4818 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004819 * Called by the {@link android.view.inputmethod.InputMethodManager}
4820 * when a view who is not the current
4821 * input connection target is trying to make a call on the manager. The
4822 * default implementation returns false; you can override this to return
4823 * true for certain views if you are performing InputConnection proxying
4824 * to them.
4825 * @param view The View that is making the InputMethodManager call.
4826 * @return Return true to allow the call, false to reject.
4827 */
4828 public boolean checkInputConnectionProxy(View view) {
4829 return false;
4830 }
Romain Guy8506ab42009-06-11 17:35:47 -07004831
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004832 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004833 * Show the context menu for this view. It is not safe to hold on to the
4834 * menu after returning from this method.
4835 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004836 * You should normally not overload this method. Overload
4837 * {@link #onCreateContextMenu(ContextMenu)} or define an
4838 * {@link OnCreateContextMenuListener} to add items to the context menu.
4839 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840 * @param menu The context menu to populate
4841 */
4842 public void createContextMenu(ContextMenu menu) {
4843 ContextMenuInfo menuInfo = getContextMenuInfo();
4844
4845 // Sets the current menu info so all items added to menu will have
4846 // my extra info set.
4847 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4848
4849 onCreateContextMenu(menu);
4850 if (mOnCreateContextMenuListener != null) {
4851 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4852 }
4853
4854 // Clear the extra information so subsequent items that aren't mine don't
4855 // have my extra info.
4856 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4857
4858 if (mParent != null) {
4859 mParent.createContextMenu(menu);
4860 }
4861 }
4862
4863 /**
4864 * Views should implement this if they have extra information to associate
4865 * with the context menu. The return result is supplied as a parameter to
4866 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4867 * callback.
4868 *
4869 * @return Extra information about the item for which the context menu
4870 * should be shown. This information will vary across different
4871 * subclasses of View.
4872 */
4873 protected ContextMenuInfo getContextMenuInfo() {
4874 return null;
4875 }
4876
4877 /**
4878 * Views should implement this if the view itself is going to add items to
4879 * the context menu.
4880 *
4881 * @param menu the context menu to populate
4882 */
4883 protected void onCreateContextMenu(ContextMenu menu) {
4884 }
4885
4886 /**
4887 * Implement this method to handle trackball motion events. The
4888 * <em>relative</em> movement of the trackball since the last event
4889 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4890 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4891 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4892 * they will often be fractional values, representing the more fine-grained
4893 * movement information available from a trackball).
4894 *
4895 * @param event The motion event.
4896 * @return True if the event was handled, false otherwise.
4897 */
4898 public boolean onTrackballEvent(MotionEvent event) {
4899 return false;
4900 }
4901
4902 /**
4903 * Implement this method to handle touch screen motion events.
4904 *
4905 * @param event The motion event.
4906 * @return True if the event was handled, false otherwise.
4907 */
4908 public boolean onTouchEvent(MotionEvent event) {
4909 final int viewFlags = mViewFlags;
4910
4911 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4912 // A disabled view that is clickable still consumes the touch
4913 // events, it just doesn't respond to them.
4914 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4915 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4916 }
4917
4918 if (mTouchDelegate != null) {
4919 if (mTouchDelegate.onTouchEvent(event)) {
4920 return true;
4921 }
4922 }
4923
4924 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4925 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4926 switch (event.getAction()) {
4927 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004928 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4929 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004930 // take focus if we don't have it already and we should in
4931 // touch mode.
4932 boolean focusTaken = false;
4933 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4934 focusTaken = requestFocus();
4935 }
4936
4937 if (!mHasPerformedLongPress) {
4938 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004939 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004940
4941 // Only perform take click actions if we were in the pressed state
4942 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004943 // Use a Runnable and post this rather than calling
4944 // performClick directly. This lets other visual state
4945 // of the view update before click actions start.
4946 if (mPerformClick == null) {
4947 mPerformClick = new PerformClick();
4948 }
4949 if (!post(mPerformClick)) {
4950 performClick();
4951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004952 }
4953 }
4954
4955 if (mUnsetPressedState == null) {
4956 mUnsetPressedState = new UnsetPressedState();
4957 }
4958
Adam Powelle14579b2009-12-16 18:39:52 -08004959 if (prepressed) {
4960 mPrivateFlags |= PRESSED;
4961 refreshDrawableState();
4962 postDelayed(mUnsetPressedState,
4963 ViewConfiguration.getPressedStateDuration());
4964 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 // If the post failed, unpress right now
4966 mUnsetPressedState.run();
4967 }
Adam Powelle14579b2009-12-16 18:39:52 -08004968 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969 }
4970 break;
4971
4972 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004973 if (mPendingCheckForTap == null) {
4974 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004975 }
Adam Powelle14579b2009-12-16 18:39:52 -08004976 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004977 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004978 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004979 break;
4980
4981 case MotionEvent.ACTION_CANCEL:
4982 mPrivateFlags &= ~PRESSED;
4983 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004984 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004985 break;
4986
4987 case MotionEvent.ACTION_MOVE:
4988 final int x = (int) event.getX();
4989 final int y = (int) event.getY();
4990
4991 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004992 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004993 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004994 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004995 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004996 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004997 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998
4999 // Need to switch from pressed to not pressed
5000 mPrivateFlags &= ~PRESSED;
5001 refreshDrawableState();
5002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005003 }
5004 break;
5005 }
5006 return true;
5007 }
5008
5009 return false;
5010 }
5011
5012 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05005013 * Remove the longpress detection timer.
5014 */
5015 private void removeLongPressCallback() {
5016 if (mPendingCheckForLongPress != null) {
5017 removeCallbacks(mPendingCheckForLongPress);
5018 }
5019 }
Adam Powelle14579b2009-12-16 18:39:52 -08005020
5021 /**
Romain Guya440b002010-02-24 15:57:54 -08005022 * Remove the prepress detection timer.
5023 */
5024 private void removeUnsetPressCallback() {
5025 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
5026 setPressed(false);
5027 removeCallbacks(mUnsetPressedState);
5028 }
5029 }
5030
5031 /**
Adam Powelle14579b2009-12-16 18:39:52 -08005032 * Remove the tap detection timer.
5033 */
5034 private void removeTapCallback() {
5035 if (mPendingCheckForTap != null) {
5036 mPrivateFlags &= ~PREPRESSED;
5037 removeCallbacks(mPendingCheckForTap);
5038 }
5039 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05005040
5041 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005042 * Cancels a pending long press. Your subclass can use this if you
5043 * want the context menu to come up if the user presses and holds
5044 * at the same place, but you don't want it to come up if they press
5045 * and then move around enough to cause scrolling.
5046 */
5047 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05005048 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08005049
5050 /*
5051 * The prepressed state handled by the tap callback is a display
5052 * construct, but the tap callback will post a long press callback
5053 * less its own timeout. Remove it here.
5054 */
5055 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005056 }
5057
5058 /**
5059 * Sets the TouchDelegate for this View.
5060 */
5061 public void setTouchDelegate(TouchDelegate delegate) {
5062 mTouchDelegate = delegate;
5063 }
5064
5065 /**
5066 * Gets the TouchDelegate for this View.
5067 */
5068 public TouchDelegate getTouchDelegate() {
5069 return mTouchDelegate;
5070 }
5071
5072 /**
5073 * Set flags controlling behavior of this view.
5074 *
5075 * @param flags Constant indicating the value which should be set
5076 * @param mask Constant indicating the bit range that should be changed
5077 */
5078 void setFlags(int flags, int mask) {
5079 int old = mViewFlags;
5080 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
5081
5082 int changed = mViewFlags ^ old;
5083 if (changed == 0) {
5084 return;
5085 }
5086 int privateFlags = mPrivateFlags;
5087
5088 /* Check if the FOCUSABLE bit has changed */
5089 if (((changed & FOCUSABLE_MASK) != 0) &&
5090 ((privateFlags & HAS_BOUNDS) !=0)) {
5091 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
5092 && ((privateFlags & FOCUSED) != 0)) {
5093 /* Give up focus if we are no longer focusable */
5094 clearFocus();
5095 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
5096 && ((privateFlags & FOCUSED) == 0)) {
5097 /*
5098 * Tell the view system that we are now available to take focus
5099 * if no one else already has it.
5100 */
5101 if (mParent != null) mParent.focusableViewAvailable(this);
5102 }
5103 }
5104
5105 if ((flags & VISIBILITY_MASK) == VISIBLE) {
5106 if ((changed & VISIBILITY_MASK) != 0) {
5107 /*
5108 * If this view is becoming visible, set the DRAWN flag so that
5109 * the next invalidate() will not be skipped.
5110 */
5111 mPrivateFlags |= DRAWN;
5112
5113 needGlobalAttributesUpdate(true);
5114
5115 // a view becoming visible is worth notifying the parent
5116 // about in case nothing has focus. even if this specific view
5117 // isn't focusable, it may contain something that is, so let
5118 // the root view try to give this focus if nothing else does.
5119 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
5120 mParent.focusableViewAvailable(this);
5121 }
5122 }
5123 }
5124
5125 /* Check if the GONE bit has changed */
5126 if ((changed & GONE) != 0) {
5127 needGlobalAttributesUpdate(false);
5128 requestLayout();
5129 invalidate();
5130
Romain Guyecd80ee2009-12-03 17:13:02 -08005131 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5132 if (hasFocus()) clearFocus();
5133 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005134 }
5135 if (mAttachInfo != null) {
5136 mAttachInfo.mViewVisibilityChanged = true;
5137 }
5138 }
5139
5140 /* Check if the VISIBLE bit has changed */
5141 if ((changed & INVISIBLE) != 0) {
5142 needGlobalAttributesUpdate(false);
5143 invalidate();
5144
5145 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5146 // root view becoming invisible shouldn't clear focus
5147 if (getRootView() != this) {
5148 clearFocus();
5149 }
5150 }
5151 if (mAttachInfo != null) {
5152 mAttachInfo.mViewVisibilityChanged = true;
5153 }
5154 }
5155
Adam Powell326d8082009-12-09 15:10:07 -08005156 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07005157 if (mParent instanceof ViewGroup) {
5158 ((ViewGroup)mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
5159 }
Adam Powell326d8082009-12-09 15:10:07 -08005160 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5161 }
5162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005163 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5164 destroyDrawingCache();
5165 }
5166
5167 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5168 destroyDrawingCache();
5169 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5170 }
5171
5172 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5173 destroyDrawingCache();
5174 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5175 }
5176
5177 if ((changed & DRAW_MASK) != 0) {
5178 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5179 if (mBGDrawable != null) {
5180 mPrivateFlags &= ~SKIP_DRAW;
5181 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5182 } else {
5183 mPrivateFlags |= SKIP_DRAW;
5184 }
5185 } else {
5186 mPrivateFlags &= ~SKIP_DRAW;
5187 }
5188 requestLayout();
5189 invalidate();
5190 }
5191
5192 if ((changed & KEEP_SCREEN_ON) != 0) {
5193 if (mParent != null) {
5194 mParent.recomputeViewAttributes(this);
5195 }
5196 }
5197 }
5198
5199 /**
5200 * Change the view's z order in the tree, so it's on top of other sibling
5201 * views
5202 */
5203 public void bringToFront() {
5204 if (mParent != null) {
5205 mParent.bringChildToFront(this);
5206 }
5207 }
5208
5209 /**
5210 * This is called in response to an internal scroll in this view (i.e., the
5211 * view scrolled its own contents). This is typically as a result of
5212 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5213 * called.
5214 *
5215 * @param l Current horizontal scroll origin.
5216 * @param t Current vertical scroll origin.
5217 * @param oldl Previous horizontal scroll origin.
5218 * @param oldt Previous vertical scroll origin.
5219 */
5220 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5221 mBackgroundSizeChanged = true;
5222
5223 final AttachInfo ai = mAttachInfo;
5224 if (ai != null) {
5225 ai.mViewScrollChanged = true;
5226 }
5227 }
5228
5229 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005230 * Interface definition for a callback to be invoked when the layout bounds of a view
5231 * changes due to layout processing.
5232 */
5233 public interface OnLayoutChangeListener {
5234 /**
5235 * Called when the focus state of a view has changed.
5236 *
5237 * @param v The view whose state has changed.
5238 * @param left The new value of the view's left property.
5239 * @param top The new value of the view's top property.
5240 * @param right The new value of the view's right property.
5241 * @param bottom The new value of the view's bottom property.
5242 * @param oldLeft The previous value of the view's left property.
5243 * @param oldTop The previous value of the view's top property.
5244 * @param oldRight The previous value of the view's right property.
5245 * @param oldBottom The previous value of the view's bottom property.
5246 */
5247 void onLayoutChange(View v, int left, int top, int right, int bottom,
5248 int oldLeft, int oldTop, int oldRight, int oldBottom);
5249 }
5250
5251 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005252 * This is called during layout when the size of this view has changed. If
5253 * you were just added to the view hierarchy, you're called with the old
5254 * values of 0.
5255 *
5256 * @param w Current width of this view.
5257 * @param h Current height of this view.
5258 * @param oldw Old width of this view.
5259 * @param oldh Old height of this view.
5260 */
5261 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5262 }
5263
5264 /**
5265 * Called by draw to draw the child views. This may be overridden
5266 * by derived classes to gain control just before its children are drawn
5267 * (but after its own view has been drawn).
5268 * @param canvas the canvas on which to draw the view
5269 */
5270 protected void dispatchDraw(Canvas canvas) {
5271 }
5272
5273 /**
5274 * Gets the parent of this view. Note that the parent is a
5275 * ViewParent and not necessarily a View.
5276 *
5277 * @return Parent of this view.
5278 */
5279 public final ViewParent getParent() {
5280 return mParent;
5281 }
5282
5283 /**
5284 * Return the scrolled left position of this view. This is the left edge of
5285 * the displayed part of your view. You do not need to draw any pixels
5286 * farther left, since those are outside of the frame of your view on
5287 * screen.
5288 *
5289 * @return The left edge of the displayed part of your view, in pixels.
5290 */
5291 public final int getScrollX() {
5292 return mScrollX;
5293 }
5294
5295 /**
5296 * Return the scrolled top position of this view. This is the top edge of
5297 * the displayed part of your view. You do not need to draw any pixels above
5298 * it, since those are outside of the frame of your view on screen.
5299 *
5300 * @return The top edge of the displayed part of your view, in pixels.
5301 */
5302 public final int getScrollY() {
5303 return mScrollY;
5304 }
5305
5306 /**
5307 * Return the width of the your view.
5308 *
5309 * @return The width of your view, in pixels.
5310 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005311 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 public final int getWidth() {
5313 return mRight - mLeft;
5314 }
5315
5316 /**
5317 * Return the height of your view.
5318 *
5319 * @return The height of your view, in pixels.
5320 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005321 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005322 public final int getHeight() {
5323 return mBottom - mTop;
5324 }
5325
5326 /**
5327 * Return the visible drawing bounds of your view. Fills in the output
5328 * rectangle with the values from getScrollX(), getScrollY(),
5329 * getWidth(), and getHeight().
5330 *
5331 * @param outRect The (scrolled) drawing bounds of the view.
5332 */
5333 public void getDrawingRect(Rect outRect) {
5334 outRect.left = mScrollX;
5335 outRect.top = mScrollY;
5336 outRect.right = mScrollX + (mRight - mLeft);
5337 outRect.bottom = mScrollY + (mBottom - mTop);
5338 }
5339
5340 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005341 * Like {@link #getMeasuredWidthAndState()}, but only returns the
5342 * raw width component (that is the result is masked by
5343 * {@link #MEASURED_SIZE_MASK}).
5344 *
5345 * @return The raw measured width of this view.
5346 */
5347 public final int getMeasuredWidth() {
5348 return mMeasuredWidth & MEASURED_SIZE_MASK;
5349 }
5350
5351 /**
5352 * Return the full width measurement information for this view as computed
5353 * by the most recent call to {@link #measure}. This result is a bit mask
5354 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005355 * This should be used during measurement and layout calculations only. Use
5356 * {@link #getWidth()} to see how wide a view is after layout.
5357 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005358 * @return The measured width of this view as a bit mask.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005359 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08005360 public final int getMeasuredWidthAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 return mMeasuredWidth;
5362 }
5363
5364 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005365 * Like {@link #getMeasuredHeightAndState()}, but only returns the
5366 * raw width component (that is the result is masked by
5367 * {@link #MEASURED_SIZE_MASK}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005368 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005369 * @return The raw measured height of this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005370 */
5371 public final int getMeasuredHeight() {
Dianne Hackborn189ee182010-12-02 21:48:53 -08005372 return mMeasuredHeight & MEASURED_SIZE_MASK;
5373 }
5374
5375 /**
5376 * Return the full height measurement information for this view as computed
5377 * by the most recent call to {@link #measure}. This result is a bit mask
5378 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5379 * This should be used during measurement and layout calculations only. Use
5380 * {@link #getHeight()} to see how wide a view is after layout.
5381 *
5382 * @return The measured width of this view as a bit mask.
5383 */
5384 public final int getMeasuredHeightAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005385 return mMeasuredHeight;
5386 }
5387
5388 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005389 * Return only the state bits of {@link #getMeasuredWidthAndState()}
5390 * and {@link #getMeasuredHeightAndState()}, combined into one integer.
5391 * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
5392 * and the height component is at the shifted bits
5393 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
5394 */
5395 public final int getMeasuredState() {
5396 return (mMeasuredWidth&MEASURED_STATE_MASK)
5397 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
5398 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
5399 }
5400
5401 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005402 * The transform matrix of this view, which is calculated based on the current
5403 * roation, scale, and pivot properties.
5404 *
5405 * @see #getRotation()
5406 * @see #getScaleX()
5407 * @see #getScaleY()
5408 * @see #getPivotX()
5409 * @see #getPivotY()
5410 * @return The current transform matrix for the view
5411 */
5412 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005413 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005414 return mMatrix;
5415 }
5416
5417 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005418 * Utility function to determine if the value is far enough away from zero to be
5419 * considered non-zero.
5420 * @param value A floating point value to check for zero-ness
5421 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5422 */
5423 private static boolean nonzero(float value) {
5424 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5425 }
5426
5427 /**
Jeff Brown86671742010-09-30 20:00:15 -07005428 * Returns true if the transform matrix is the identity matrix.
5429 * Recomputes the matrix if necessary.
Romain Guy33e72ae2010-07-17 12:40:29 -07005430 *
5431 * @return True if the transform matrix is the identity matrix, false otherwise.
5432 */
Jeff Brown86671742010-09-30 20:00:15 -07005433 final boolean hasIdentityMatrix() {
5434 updateMatrix();
5435 return mMatrixIsIdentity;
5436 }
5437
5438 /**
5439 * Recomputes the transform matrix if necessary.
5440 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005441 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005442 if (mMatrixDirty) {
5443 // transform-related properties have changed since the last time someone
5444 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005445
5446 // Figure out if we need to update the pivot point
5447 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005448 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005449 mPrevWidth = mRight - mLeft;
5450 mPrevHeight = mBottom - mTop;
5451 mPivotX = (float) mPrevWidth / 2f;
5452 mPivotY = (float) mPrevHeight / 2f;
5453 }
5454 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005455 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005456 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5457 mMatrix.setTranslate(mTranslationX, mTranslationY);
5458 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5459 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5460 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005461 if (mCamera == null) {
5462 mCamera = new Camera();
5463 matrix3D = new Matrix();
5464 }
5465 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005466 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005467 mCamera.rotateX(mRotationX);
5468 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005469 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005470 mCamera.getMatrix(matrix3D);
5471 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005472 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005473 mMatrix.postConcat(matrix3D);
5474 mCamera.restore();
5475 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005476 mMatrixDirty = false;
5477 mMatrixIsIdentity = mMatrix.isIdentity();
5478 mInverseMatrixDirty = true;
5479 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005480 }
5481
5482 /**
5483 * Utility method to retrieve the inverse of the current mMatrix property.
5484 * We cache the matrix to avoid recalculating it when transform properties
5485 * have not changed.
5486 *
5487 * @return The inverse of the current matrix of this view.
5488 */
Jeff Brown86671742010-09-30 20:00:15 -07005489 final Matrix getInverseMatrix() {
5490 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005491 if (mInverseMatrixDirty) {
5492 if (mInverseMatrix == null) {
5493 mInverseMatrix = new Matrix();
5494 }
5495 mMatrix.invert(mInverseMatrix);
5496 mInverseMatrixDirty = false;
5497 }
5498 return mInverseMatrix;
5499 }
5500
5501 /**
5502 * The degrees that the view is rotated around the pivot point.
5503 *
5504 * @see #getPivotX()
5505 * @see #getPivotY()
5506 * @return The degrees of rotation.
5507 */
5508 public float getRotation() {
5509 return mRotation;
5510 }
5511
5512 /**
Chet Haase897247b2010-09-09 14:54:47 -07005513 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5514 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005515 *
5516 * @param rotation The degrees of rotation.
5517 * @see #getPivotX()
5518 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005519 *
5520 * @attr ref android.R.styleable#View_rotation
Chet Haasec3aa3612010-06-17 08:50:37 -07005521 */
5522 public void setRotation(float rotation) {
5523 if (mRotation != rotation) {
5524 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005525 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005526 mRotation = rotation;
5527 mMatrixDirty = true;
5528 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005529 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005530 }
5531 }
5532
5533 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005534 * The degrees that the view is rotated around the vertical axis through the pivot point.
5535 *
5536 * @see #getPivotX()
5537 * @see #getPivotY()
5538 * @return The degrees of Y rotation.
5539 */
5540 public float getRotationY() {
5541 return mRotationY;
5542 }
5543
5544 /**
Chet Haase897247b2010-09-09 14:54:47 -07005545 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5546 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5547 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005548 *
5549 * @param rotationY The degrees of Y rotation.
5550 * @see #getPivotX()
5551 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005552 *
5553 * @attr ref android.R.styleable#View_rotationY
Chet Haasefd2b0022010-08-06 13:08:56 -07005554 */
5555 public void setRotationY(float rotationY) {
5556 if (mRotationY != rotationY) {
5557 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005558 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005559 mRotationY = rotationY;
5560 mMatrixDirty = true;
5561 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005562 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005563 }
5564 }
5565
5566 /**
5567 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5568 *
5569 * @see #getPivotX()
5570 * @see #getPivotY()
5571 * @return The degrees of X rotation.
5572 */
5573 public float getRotationX() {
5574 return mRotationX;
5575 }
5576
5577 /**
Chet Haase897247b2010-09-09 14:54:47 -07005578 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5579 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5580 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005581 *
5582 * @param rotationX The degrees of X rotation.
5583 * @see #getPivotX()
5584 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005585 *
5586 * @attr ref android.R.styleable#View_rotationX
Chet Haasefd2b0022010-08-06 13:08:56 -07005587 */
5588 public void setRotationX(float rotationX) {
5589 if (mRotationX != rotationX) {
5590 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005591 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005592 mRotationX = rotationX;
5593 mMatrixDirty = true;
5594 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005595 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005596 }
5597 }
5598
5599 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005600 * The amount that the view is scaled in x around the pivot point, as a proportion of
5601 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5602 *
Joe Onorato93162322010-09-16 15:42:01 -04005603 * <p>By default, this is 1.0f.
5604 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005605 * @see #getPivotX()
5606 * @see #getPivotY()
5607 * @return The scaling factor.
5608 */
5609 public float getScaleX() {
5610 return mScaleX;
5611 }
5612
5613 /**
5614 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5615 * the view's unscaled width. A value of 1 means that no scaling is applied.
5616 *
5617 * @param scaleX The scaling factor.
5618 * @see #getPivotX()
5619 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005620 *
5621 * @attr ref android.R.styleable#View_scaleX
Chet Haasec3aa3612010-06-17 08:50:37 -07005622 */
5623 public void setScaleX(float scaleX) {
5624 if (mScaleX != scaleX) {
5625 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005626 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005627 mScaleX = scaleX;
5628 mMatrixDirty = true;
5629 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005630 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005631 }
5632 }
5633
5634 /**
5635 * The amount that the view is scaled in y around the pivot point, as a proportion of
5636 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5637 *
Joe Onorato93162322010-09-16 15:42:01 -04005638 * <p>By default, this is 1.0f.
5639 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005640 * @see #getPivotX()
5641 * @see #getPivotY()
5642 * @return The scaling factor.
5643 */
5644 public float getScaleY() {
5645 return mScaleY;
5646 }
5647
5648 /**
5649 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5650 * the view's unscaled width. A value of 1 means that no scaling is applied.
5651 *
5652 * @param scaleY The scaling factor.
5653 * @see #getPivotX()
5654 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005655 *
5656 * @attr ref android.R.styleable#View_scaleY
Chet Haasec3aa3612010-06-17 08:50:37 -07005657 */
5658 public void setScaleY(float scaleY) {
5659 if (mScaleY != scaleY) {
5660 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005661 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005662 mScaleY = scaleY;
5663 mMatrixDirty = true;
5664 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005665 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005666 }
5667 }
5668
5669 /**
5670 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5671 * and {@link #setScaleX(float) scaled}.
5672 *
5673 * @see #getRotation()
5674 * @see #getScaleX()
5675 * @see #getScaleY()
5676 * @see #getPivotY()
5677 * @return The x location of the pivot point.
5678 */
5679 public float getPivotX() {
5680 return mPivotX;
5681 }
5682
5683 /**
5684 * Sets the x location of the point around which the view is
5685 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005686 * By default, the pivot point is centered on the object.
5687 * Setting this property disables this behavior and causes the view to use only the
5688 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005689 *
5690 * @param pivotX The x location of the pivot point.
5691 * @see #getRotation()
5692 * @see #getScaleX()
5693 * @see #getScaleY()
5694 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005695 *
5696 * @attr ref android.R.styleable#View_transformPivotX
Chet Haasec3aa3612010-06-17 08:50:37 -07005697 */
5698 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005699 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005700 if (mPivotX != pivotX) {
5701 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005702 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005703 mPivotX = pivotX;
5704 mMatrixDirty = true;
5705 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005706 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005707 }
5708 }
5709
5710 /**
5711 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5712 * and {@link #setScaleY(float) scaled}.
5713 *
5714 * @see #getRotation()
5715 * @see #getScaleX()
5716 * @see #getScaleY()
5717 * @see #getPivotY()
5718 * @return The y location of the pivot point.
5719 */
5720 public float getPivotY() {
5721 return mPivotY;
5722 }
5723
5724 /**
5725 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005726 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5727 * Setting this property disables this behavior and causes the view to use only the
5728 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005729 *
5730 * @param pivotY The y location of the pivot point.
5731 * @see #getRotation()
5732 * @see #getScaleX()
5733 * @see #getScaleY()
5734 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005735 *
5736 * @attr ref android.R.styleable#View_transformPivotY
Chet Haasec3aa3612010-06-17 08:50:37 -07005737 */
5738 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005739 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005740 if (mPivotY != pivotY) {
5741 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005742 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005743 mPivotY = pivotY;
5744 mMatrixDirty = true;
5745 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005746 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005747 }
5748 }
5749
5750 /**
5751 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5752 * completely transparent and 1 means the view is completely opaque.
5753 *
Joe Onorato93162322010-09-16 15:42:01 -04005754 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005755 * @return The opacity of the view.
5756 */
5757 public float getAlpha() {
5758 return mAlpha;
5759 }
5760
5761 /**
5762 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5763 * completely transparent and 1 means the view is completely opaque.
5764 *
5765 * @param alpha The opacity of the view.
Chet Haase73066682010-11-29 15:55:32 -08005766 *
5767 * @attr ref android.R.styleable#View_alpha
Chet Haasec3aa3612010-06-17 08:50:37 -07005768 */
5769 public void setAlpha(float alpha) {
5770 mAlpha = alpha;
Chet Haaseed032702010-10-01 14:05:54 -07005771 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07005772 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005773 // subclass is handling alpha - don't optimize rendering cache invalidation
5774 invalidate();
5775 } else {
Romain Guya3496a92010-10-12 11:53:24 -07005776 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005777 invalidate(false);
5778 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005779 }
5780
5781 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 * Top position of this view relative to its parent.
5783 *
5784 * @return The top of this view, in pixels.
5785 */
5786 @ViewDebug.CapturedViewProperty
5787 public final int getTop() {
5788 return mTop;
5789 }
5790
5791 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005792 * Sets the top position of this view relative to its parent. This method is meant to be called
5793 * by the layout system and should not generally be called otherwise, because the property
5794 * may be changed at any time by the layout.
5795 *
5796 * @param top The top of this view, in pixels.
5797 */
5798 public final void setTop(int top) {
5799 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07005800 updateMatrix();
5801 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005802 final ViewParent p = mParent;
5803 if (p != null && mAttachInfo != null) {
5804 final Rect r = mAttachInfo.mTmpInvalRect;
5805 int minTop;
5806 int yLoc;
5807 if (top < mTop) {
5808 minTop = top;
5809 yLoc = top - mTop;
5810 } else {
5811 minTop = mTop;
5812 yLoc = 0;
5813 }
5814 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5815 p.invalidateChild(this, r);
5816 }
5817 } else {
5818 // Double-invalidation is necessary to capture view's old and new areas
5819 invalidate();
5820 }
5821
Chet Haaseed032702010-10-01 14:05:54 -07005822 int width = mRight - mLeft;
5823 int oldHeight = mBottom - mTop;
5824
Chet Haase21cd1382010-09-01 17:42:29 -07005825 mTop = top;
5826
Chet Haaseed032702010-10-01 14:05:54 -07005827 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5828
Chet Haase21cd1382010-09-01 17:42:29 -07005829 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005830 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5831 // A change in dimension means an auto-centered pivot point changes, too
5832 mMatrixDirty = true;
5833 }
Chet Haase21cd1382010-09-01 17:42:29 -07005834 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5835 invalidate();
5836 }
Chet Haase55dbb652010-12-21 20:15:08 -08005837 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07005838 }
5839 }
5840
5841 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005842 * Bottom position of this view relative to its parent.
5843 *
5844 * @return The bottom of this view, in pixels.
5845 */
5846 @ViewDebug.CapturedViewProperty
5847 public final int getBottom() {
5848 return mBottom;
5849 }
5850
5851 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005852 * Sets the bottom position of this view relative to its parent. This method is meant to be
5853 * called by the layout system and should not generally be called otherwise, because the
5854 * property may be changed at any time by the layout.
5855 *
5856 * @param bottom The bottom of this view, in pixels.
5857 */
5858 public final void setBottom(int bottom) {
5859 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07005860 updateMatrix();
5861 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005862 final ViewParent p = mParent;
5863 if (p != null && mAttachInfo != null) {
5864 final Rect r = mAttachInfo.mTmpInvalRect;
5865 int maxBottom;
5866 if (bottom < mBottom) {
5867 maxBottom = mBottom;
5868 } else {
5869 maxBottom = bottom;
5870 }
5871 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5872 p.invalidateChild(this, r);
5873 }
5874 } else {
5875 // Double-invalidation is necessary to capture view's old and new areas
5876 invalidate();
5877 }
5878
Chet Haaseed032702010-10-01 14:05:54 -07005879 int width = mRight - mLeft;
5880 int oldHeight = mBottom - mTop;
5881
Chet Haase21cd1382010-09-01 17:42:29 -07005882 mBottom = bottom;
5883
Chet Haaseed032702010-10-01 14:05:54 -07005884 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5885
Chet Haase21cd1382010-09-01 17:42:29 -07005886 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005887 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5888 // A change in dimension means an auto-centered pivot point changes, too
5889 mMatrixDirty = true;
5890 }
Chet Haase21cd1382010-09-01 17:42:29 -07005891 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5892 invalidate();
5893 }
Chet Haase55dbb652010-12-21 20:15:08 -08005894 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07005895 }
5896 }
5897
5898 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 * Left position of this view relative to its parent.
5900 *
5901 * @return The left edge of this view, in pixels.
5902 */
5903 @ViewDebug.CapturedViewProperty
5904 public final int getLeft() {
5905 return mLeft;
5906 }
5907
5908 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005909 * Sets the left position of this view relative to its parent. This method is meant to be called
5910 * by the layout system and should not generally be called otherwise, because the property
5911 * may be changed at any time by the layout.
5912 *
5913 * @param left The bottom of this view, in pixels.
5914 */
5915 public final void setLeft(int left) {
5916 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07005917 updateMatrix();
5918 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005919 final ViewParent p = mParent;
5920 if (p != null && mAttachInfo != null) {
5921 final Rect r = mAttachInfo.mTmpInvalRect;
5922 int minLeft;
5923 int xLoc;
5924 if (left < mLeft) {
5925 minLeft = left;
5926 xLoc = left - mLeft;
5927 } else {
5928 minLeft = mLeft;
5929 xLoc = 0;
5930 }
5931 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
5932 p.invalidateChild(this, r);
5933 }
5934 } else {
5935 // Double-invalidation is necessary to capture view's old and new areas
5936 invalidate();
5937 }
5938
Chet Haaseed032702010-10-01 14:05:54 -07005939 int oldWidth = mRight - mLeft;
5940 int height = mBottom - mTop;
5941
Chet Haase21cd1382010-09-01 17:42:29 -07005942 mLeft = left;
5943
Chet Haaseed032702010-10-01 14:05:54 -07005944 onSizeChanged(mRight - mLeft, height, oldWidth, height);
5945
Chet Haase21cd1382010-09-01 17:42:29 -07005946 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005947 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5948 // A change in dimension means an auto-centered pivot point changes, too
5949 mMatrixDirty = true;
5950 }
Chet Haase21cd1382010-09-01 17:42:29 -07005951 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5952 invalidate();
5953 }
Chet Haase55dbb652010-12-21 20:15:08 -08005954 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07005955 }
5956 }
5957
5958 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 * Right position of this view relative to its parent.
5960 *
5961 * @return The right edge of this view, in pixels.
5962 */
5963 @ViewDebug.CapturedViewProperty
5964 public final int getRight() {
5965 return mRight;
5966 }
5967
5968 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005969 * Sets the right position of this view relative to its parent. This method is meant to be called
5970 * by the layout system and should not generally be called otherwise, because the property
5971 * may be changed at any time by the layout.
5972 *
5973 * @param right The bottom of this view, in pixels.
5974 */
5975 public final void setRight(int right) {
5976 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07005977 updateMatrix();
5978 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005979 final ViewParent p = mParent;
5980 if (p != null && mAttachInfo != null) {
5981 final Rect r = mAttachInfo.mTmpInvalRect;
5982 int maxRight;
5983 if (right < mRight) {
5984 maxRight = mRight;
5985 } else {
5986 maxRight = right;
5987 }
5988 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
5989 p.invalidateChild(this, r);
5990 }
5991 } else {
5992 // Double-invalidation is necessary to capture view's old and new areas
5993 invalidate();
5994 }
5995
Chet Haaseed032702010-10-01 14:05:54 -07005996 int oldWidth = mRight - mLeft;
5997 int height = mBottom - mTop;
5998
Chet Haase21cd1382010-09-01 17:42:29 -07005999 mRight = right;
6000
Chet Haaseed032702010-10-01 14:05:54 -07006001 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6002
Chet Haase21cd1382010-09-01 17:42:29 -07006003 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006004 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6005 // A change in dimension means an auto-centered pivot point changes, too
6006 mMatrixDirty = true;
6007 }
Chet Haase21cd1382010-09-01 17:42:29 -07006008 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6009 invalidate();
6010 }
Chet Haase55dbb652010-12-21 20:15:08 -08006011 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006012 }
6013 }
6014
6015 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006016 * The visual x position of this view, in pixels. This is equivalent to the
6017 * {@link #setTranslationX(float) translationX} property plus the current
6018 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07006019 *
Chet Haasedf030d22010-07-30 17:22:38 -07006020 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006021 */
Chet Haasedf030d22010-07-30 17:22:38 -07006022 public float getX() {
6023 return mLeft + mTranslationX;
6024 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006025
Chet Haasedf030d22010-07-30 17:22:38 -07006026 /**
6027 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
6028 * {@link #setTranslationX(float) translationX} property to be the difference between
6029 * the x value passed in and the current {@link #getLeft() left} property.
6030 *
6031 * @param x The visual x position of this view, in pixels.
6032 */
6033 public void setX(float x) {
6034 setTranslationX(x - mLeft);
6035 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006036
Chet Haasedf030d22010-07-30 17:22:38 -07006037 /**
6038 * The visual y position of this view, in pixels. This is equivalent to the
6039 * {@link #setTranslationY(float) translationY} property plus the current
6040 * {@link #getTop() top} property.
6041 *
6042 * @return The visual y position of this view, in pixels.
6043 */
6044 public float getY() {
6045 return mTop + mTranslationY;
6046 }
6047
6048 /**
6049 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
6050 * {@link #setTranslationY(float) translationY} property to be the difference between
6051 * the y value passed in and the current {@link #getTop() top} property.
6052 *
6053 * @param y The visual y position of this view, in pixels.
6054 */
6055 public void setY(float y) {
6056 setTranslationY(y - mTop);
6057 }
6058
6059
6060 /**
6061 * The horizontal location of this view relative to its {@link #getLeft() left} position.
6062 * This position is post-layout, in addition to wherever the object's
6063 * layout placed it.
6064 *
6065 * @return The horizontal position of this view relative to its left position, in pixels.
6066 */
6067 public float getTranslationX() {
6068 return mTranslationX;
6069 }
6070
6071 /**
6072 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
6073 * This effectively positions the object post-layout, in addition to wherever the object's
6074 * layout placed it.
6075 *
6076 * @param translationX The horizontal position of this view relative to its left position,
6077 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006078 *
6079 * @attr ref android.R.styleable#View_translationX
Chet Haasedf030d22010-07-30 17:22:38 -07006080 */
6081 public void setTranslationX(float translationX) {
6082 if (mTranslationX != translationX) {
6083 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006084 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006085 mTranslationX = translationX;
6086 mMatrixDirty = true;
6087 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006088 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006089 }
6090 }
6091
6092 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006093 * The horizontal location of this view relative to its {@link #getTop() top} position.
6094 * This position is post-layout, in addition to wherever the object's
6095 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006096 *
Chet Haasedf030d22010-07-30 17:22:38 -07006097 * @return The vertical position of this view relative to its top position,
6098 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006099 */
Chet Haasedf030d22010-07-30 17:22:38 -07006100 public float getTranslationY() {
6101 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07006102 }
6103
6104 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006105 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
6106 * This effectively positions the object post-layout, in addition to wherever the object's
6107 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006108 *
Chet Haasedf030d22010-07-30 17:22:38 -07006109 * @param translationY The vertical position of this view relative to its top position,
6110 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006111 *
6112 * @attr ref android.R.styleable#View_translationY
Chet Haasec3aa3612010-06-17 08:50:37 -07006113 */
Chet Haasedf030d22010-07-30 17:22:38 -07006114 public void setTranslationY(float translationY) {
6115 if (mTranslationY != translationY) {
6116 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006117 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006118 mTranslationY = translationY;
6119 mMatrixDirty = true;
6120 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006121 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006122 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006123 }
6124
6125 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 * Hit rectangle in parent's coordinates
6127 *
6128 * @param outRect The hit rectangle of the view.
6129 */
6130 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07006131 updateMatrix();
6132 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006133 outRect.set(mLeft, mTop, mRight, mBottom);
6134 } else {
6135 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07006136 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07006137 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07006138 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
6139 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07006140 }
6141 }
6142
6143 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07006144 * Determines whether the given point, in local coordinates is inside the view.
6145 */
6146 /*package*/ final boolean pointInView(float localX, float localY) {
6147 return localX >= 0 && localX < (mRight - mLeft)
6148 && localY >= 0 && localY < (mBottom - mTop);
6149 }
6150
6151 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07006152 * Utility method to determine whether the given point, in local coordinates,
6153 * is inside the view, where the area of the view is expanded by the slop factor.
6154 * This method is called while processing touch-move events to determine if the event
6155 * is still within the view.
6156 */
6157 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07006158 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07006159 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 }
6161
6162 /**
6163 * When a view has focus and the user navigates away from it, the next view is searched for
6164 * starting from the rectangle filled in by this method.
6165 *
6166 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
6167 * view maintains some idea of internal selection, such as a cursor, or a selected row
6168 * or column, you should override this method and fill in a more specific rectangle.
6169 *
6170 * @param r The rectangle to fill in, in this view's coordinates.
6171 */
6172 public void getFocusedRect(Rect r) {
6173 getDrawingRect(r);
6174 }
6175
6176 /**
6177 * If some part of this view is not clipped by any of its parents, then
6178 * return that area in r in global (root) coordinates. To convert r to local
6179 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
6180 * -globalOffset.y)) If the view is completely clipped or translated out,
6181 * return false.
6182 *
6183 * @param r If true is returned, r holds the global coordinates of the
6184 * visible portion of this view.
6185 * @param globalOffset If true is returned, globalOffset holds the dx,dy
6186 * between this view and its root. globalOffet may be null.
6187 * @return true if r is non-empty (i.e. part of the view is visible at the
6188 * root level.
6189 */
6190 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6191 int width = mRight - mLeft;
6192 int height = mBottom - mTop;
6193 if (width > 0 && height > 0) {
6194 r.set(0, 0, width, height);
6195 if (globalOffset != null) {
6196 globalOffset.set(-mScrollX, -mScrollY);
6197 }
6198 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6199 }
6200 return false;
6201 }
6202
6203 public final boolean getGlobalVisibleRect(Rect r) {
6204 return getGlobalVisibleRect(r, null);
6205 }
6206
6207 public final boolean getLocalVisibleRect(Rect r) {
6208 Point offset = new Point();
6209 if (getGlobalVisibleRect(r, offset)) {
6210 r.offset(-offset.x, -offset.y); // make r local
6211 return true;
6212 }
6213 return false;
6214 }
6215
6216 /**
6217 * Offset this view's vertical location by the specified number of pixels.
6218 *
6219 * @param offset the number of pixels to offset the view by
6220 */
6221 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006222 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006223 updateMatrix();
6224 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006225 final ViewParent p = mParent;
6226 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006227 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006228 int minTop;
6229 int maxBottom;
6230 int yLoc;
6231 if (offset < 0) {
6232 minTop = mTop + offset;
6233 maxBottom = mBottom;
6234 yLoc = offset;
6235 } else {
6236 minTop = mTop;
6237 maxBottom = mBottom + offset;
6238 yLoc = 0;
6239 }
6240 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6241 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006242 }
6243 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006244 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006245 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006246
Chet Haasec3aa3612010-06-17 08:50:37 -07006247 mTop += offset;
6248 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006249
Chet Haasec3aa3612010-06-17 08:50:37 -07006250 if (!mMatrixIsIdentity) {
6251 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006252 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006253 }
6254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 }
6256
6257 /**
6258 * Offset this view's horizontal location by the specified amount of pixels.
6259 *
6260 * @param offset the numer of pixels to offset the view by
6261 */
6262 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006263 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006264 updateMatrix();
6265 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006266 final ViewParent p = mParent;
6267 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006268 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006269 int minLeft;
6270 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006271 if (offset < 0) {
6272 minLeft = mLeft + offset;
6273 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006274 } else {
6275 minLeft = mLeft;
6276 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006277 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006278 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07006279 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006280 }
6281 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006282 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006283 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006284
Chet Haasec3aa3612010-06-17 08:50:37 -07006285 mLeft += offset;
6286 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006287
Chet Haasec3aa3612010-06-17 08:50:37 -07006288 if (!mMatrixIsIdentity) {
6289 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006290 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006291 }
6292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006293 }
6294
6295 /**
6296 * Get the LayoutParams associated with this view. All views should have
6297 * layout parameters. These supply parameters to the <i>parent</i> of this
6298 * view specifying how it should be arranged. There are many subclasses of
6299 * ViewGroup.LayoutParams, and these correspond to the different subclasses
6300 * of ViewGroup that are responsible for arranging their children.
6301 * @return The LayoutParams associated with this view
6302 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07006303 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 public ViewGroup.LayoutParams getLayoutParams() {
6305 return mLayoutParams;
6306 }
6307
6308 /**
6309 * Set the layout parameters associated with this view. These supply
6310 * parameters to the <i>parent</i> of this view specifying how it should be
6311 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6312 * correspond to the different subclasses of ViewGroup that are responsible
6313 * for arranging their children.
6314 *
6315 * @param params the layout parameters for this view
6316 */
6317 public void setLayoutParams(ViewGroup.LayoutParams params) {
6318 if (params == null) {
6319 throw new NullPointerException("params == null");
6320 }
6321 mLayoutParams = params;
6322 requestLayout();
6323 }
6324
6325 /**
6326 * Set the scrolled position of your view. This will cause a call to
6327 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6328 * invalidated.
6329 * @param x the x position to scroll to
6330 * @param y the y position to scroll to
6331 */
6332 public void scrollTo(int x, int y) {
6333 if (mScrollX != x || mScrollY != y) {
6334 int oldX = mScrollX;
6335 int oldY = mScrollY;
6336 mScrollX = x;
6337 mScrollY = y;
6338 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006339 if (!awakenScrollBars()) {
6340 invalidate();
6341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 }
6343 }
6344
6345 /**
6346 * Move the scrolled position of your view. This will cause a call to
6347 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6348 * invalidated.
6349 * @param x the amount of pixels to scroll by horizontally
6350 * @param y the amount of pixels to scroll by vertically
6351 */
6352 public void scrollBy(int x, int y) {
6353 scrollTo(mScrollX + x, mScrollY + y);
6354 }
6355
6356 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006357 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6358 * animation to fade the scrollbars out after a default delay. If a subclass
6359 * provides animated scrolling, the start delay should equal the duration
6360 * of the scrolling animation.</p>
6361 *
6362 * <p>The animation starts only if at least one of the scrollbars is
6363 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6364 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6365 * this method returns true, and false otherwise. If the animation is
6366 * started, this method calls {@link #invalidate()}; in that case the
6367 * caller should not call {@link #invalidate()}.</p>
6368 *
6369 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006370 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006371 *
6372 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6373 * and {@link #scrollTo(int, int)}.</p>
6374 *
6375 * @return true if the animation is played, false otherwise
6376 *
6377 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006378 * @see #scrollBy(int, int)
6379 * @see #scrollTo(int, int)
6380 * @see #isHorizontalScrollBarEnabled()
6381 * @see #isVerticalScrollBarEnabled()
6382 * @see #setHorizontalScrollBarEnabled(boolean)
6383 * @see #setVerticalScrollBarEnabled(boolean)
6384 */
6385 protected boolean awakenScrollBars() {
6386 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006387 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006388 }
6389
6390 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006391 * Trigger the scrollbars to draw.
6392 * This method differs from awakenScrollBars() only in its default duration.
6393 * initialAwakenScrollBars() will show the scroll bars for longer than
6394 * usual to give the user more of a chance to notice them.
6395 *
6396 * @return true if the animation is played, false otherwise.
6397 */
6398 private boolean initialAwakenScrollBars() {
6399 return mScrollCache != null &&
6400 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6401 }
6402
6403 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006404 * <p>
6405 * Trigger the scrollbars to draw. When invoked this method starts an
6406 * animation to fade the scrollbars out after a fixed delay. If a subclass
6407 * provides animated scrolling, the start delay should equal the duration of
6408 * the scrolling animation.
6409 * </p>
6410 *
6411 * <p>
6412 * The animation starts only if at least one of the scrollbars is enabled,
6413 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6414 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6415 * this method returns true, and false otherwise. If the animation is
6416 * started, this method calls {@link #invalidate()}; in that case the caller
6417 * should not call {@link #invalidate()}.
6418 * </p>
6419 *
6420 * <p>
6421 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006422 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006423 * </p>
6424 *
6425 * @param startDelay the delay, in milliseconds, after which the animation
6426 * should start; when the delay is 0, the animation starts
6427 * immediately
6428 * @return true if the animation is played, false otherwise
6429 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006430 * @see #scrollBy(int, int)
6431 * @see #scrollTo(int, int)
6432 * @see #isHorizontalScrollBarEnabled()
6433 * @see #isVerticalScrollBarEnabled()
6434 * @see #setHorizontalScrollBarEnabled(boolean)
6435 * @see #setVerticalScrollBarEnabled(boolean)
6436 */
6437 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006438 return awakenScrollBars(startDelay, true);
6439 }
6440
6441 /**
6442 * <p>
6443 * Trigger the scrollbars to draw. When invoked this method starts an
6444 * animation to fade the scrollbars out after a fixed delay. If a subclass
6445 * provides animated scrolling, the start delay should equal the duration of
6446 * the scrolling animation.
6447 * </p>
6448 *
6449 * <p>
6450 * The animation starts only if at least one of the scrollbars is enabled,
6451 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6452 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6453 * this method returns true, and false otherwise. If the animation is
6454 * started, this method calls {@link #invalidate()} if the invalidate parameter
6455 * is set to true; in that case the caller
6456 * should not call {@link #invalidate()}.
6457 * </p>
6458 *
6459 * <p>
6460 * This method should be invoked everytime a subclass directly updates the
6461 * scroll parameters.
6462 * </p>
6463 *
6464 * @param startDelay the delay, in milliseconds, after which the animation
6465 * should start; when the delay is 0, the animation starts
6466 * immediately
6467 *
6468 * @param invalidate Wheter this method should call invalidate
6469 *
6470 * @return true if the animation is played, false otherwise
6471 *
6472 * @see #scrollBy(int, int)
6473 * @see #scrollTo(int, int)
6474 * @see #isHorizontalScrollBarEnabled()
6475 * @see #isVerticalScrollBarEnabled()
6476 * @see #setHorizontalScrollBarEnabled(boolean)
6477 * @see #setVerticalScrollBarEnabled(boolean)
6478 */
6479 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006480 final ScrollabilityCache scrollCache = mScrollCache;
6481
6482 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6483 return false;
6484 }
6485
6486 if (scrollCache.scrollBar == null) {
6487 scrollCache.scrollBar = new ScrollBarDrawable();
6488 }
6489
6490 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6491
Mike Cleron290947b2009-09-29 18:34:32 -07006492 if (invalidate) {
6493 // Invalidate to show the scrollbars
6494 invalidate();
6495 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006496
6497 if (scrollCache.state == ScrollabilityCache.OFF) {
6498 // FIXME: this is copied from WindowManagerService.
6499 // We should get this value from the system when it
6500 // is possible to do so.
6501 final int KEY_REPEAT_FIRST_DELAY = 750;
6502 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6503 }
6504
6505 // Tell mScrollCache when we should start fading. This may
6506 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006507 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006508 scrollCache.fadeStartTime = fadeStartTime;
6509 scrollCache.state = ScrollabilityCache.ON;
6510
6511 // Schedule our fader to run, unscheduling any old ones first
6512 if (mAttachInfo != null) {
6513 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6514 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6515 }
6516
6517 return true;
6518 }
6519
6520 return false;
6521 }
6522
6523 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 * Mark the the area defined by dirty as needing to be drawn. If the view is
6525 * visible, {@link #onDraw} will be called at some point in the future.
6526 * This must be called from a UI thread. To call from a non-UI thread, call
6527 * {@link #postInvalidate()}.
6528 *
6529 * WARNING: This method is destructive to dirty.
6530 * @param dirty the rectangle representing the bounds of the dirty region
6531 */
6532 public void invalidate(Rect dirty) {
6533 if (ViewDebug.TRACE_HIERARCHY) {
6534 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6535 }
6536
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006537 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6538 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6540 final ViewParent p = mParent;
6541 final AttachInfo ai = mAttachInfo;
Romain Guyaf636eb2010-12-09 17:47:21 -08006542 if (p != null && ai != null && ai.mHardwareAccelerated) {
6543 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6544 // with a null dirty rect, which tells the ViewRoot to redraw everything
6545 p.invalidateChild(this, null);
6546 return;
6547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 if (p != null && ai != null) {
6549 final int scrollX = mScrollX;
6550 final int scrollY = mScrollY;
6551 final Rect r = ai.mTmpInvalRect;
6552 r.set(dirty.left - scrollX, dirty.top - scrollY,
6553 dirty.right - scrollX, dirty.bottom - scrollY);
6554 mParent.invalidateChild(this, r);
6555 }
6556 }
6557 }
6558
6559 /**
6560 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6561 * The coordinates of the dirty rect are relative to the view.
6562 * If the view is visible, {@link #onDraw} will be called at some point
6563 * in the future. This must be called from a UI thread. To call
6564 * from a non-UI thread, call {@link #postInvalidate()}.
6565 * @param l the left position of the dirty region
6566 * @param t the top position of the dirty region
6567 * @param r the right position of the dirty region
6568 * @param b the bottom position of the dirty region
6569 */
6570 public void invalidate(int l, int t, int r, int b) {
6571 if (ViewDebug.TRACE_HIERARCHY) {
6572 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6573 }
6574
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006575 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6576 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6578 final ViewParent p = mParent;
6579 final AttachInfo ai = mAttachInfo;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006580 if (p != null && ai != null && ai.mHardwareAccelerated) {
6581 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6582 // with a null dirty rect, which tells the ViewRoot to redraw everything
6583 p.invalidateChild(this, null);
6584 return;
6585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 if (p != null && ai != null && l < r && t < b) {
6587 final int scrollX = mScrollX;
6588 final int scrollY = mScrollY;
6589 final Rect tmpr = ai.mTmpInvalRect;
6590 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6591 p.invalidateChild(this, tmpr);
6592 }
6593 }
6594 }
6595
6596 /**
6597 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6598 * be called at some point in the future. This must be called from a
6599 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6600 */
6601 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006602 invalidate(true);
6603 }
6604
6605 /**
6606 * This is where the invalidate() work actually happens. A full invalidate()
6607 * causes the drawing cache to be invalidated, but this function can be called with
6608 * invalidateCache set to false to skip that invalidation step for cases that do not
6609 * need it (for example, a component that remains at the same dimensions with the same
6610 * content).
6611 *
6612 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6613 * well. This is usually true for a full invalidate, but may be set to false if the
6614 * View's contents or dimensions have not changed.
6615 */
6616 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 if (ViewDebug.TRACE_HIERARCHY) {
6618 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6619 }
6620
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006621 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6622 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID)) {
Chet Haaseed032702010-10-01 14:05:54 -07006623 mPrivateFlags &= ~DRAWN;
6624 if (invalidateCache) {
6625 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006628 final ViewParent p = mParent;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006629 if (p != null && ai != null && ai.mHardwareAccelerated) {
6630 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6631 // with a null dirty rect, which tells the ViewRoot to redraw everything
6632 p.invalidateChild(this, null);
6633 return;
6634 }
Michael Jurkaebefea42010-11-15 16:04:01 -08006635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 if (p != null && ai != null) {
6637 final Rect r = ai.mTmpInvalRect;
6638 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6639 // Don't call invalidate -- we don't want to internally scroll
6640 // our own bounds
6641 p.invalidateChild(this, r);
6642 }
6643 }
6644 }
6645
6646 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006647 * Indicates whether this View is opaque. An opaque View guarantees that it will
6648 * draw all the pixels overlapping its bounds using a fully opaque color.
6649 *
6650 * Subclasses of View should override this method whenever possible to indicate
6651 * whether an instance is opaque. Opaque Views are treated in a special way by
6652 * the View hierarchy, possibly allowing it to perform optimizations during
6653 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006654 *
Romain Guy24443ea2009-05-11 11:56:30 -07006655 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006656 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006657 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006658 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006659 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6660 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006661 }
6662
Adam Powell20232d02010-12-08 21:08:53 -08006663 /**
6664 * @hide
6665 */
6666 protected void computeOpaqueFlags() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006667 // Opaque if:
6668 // - Has a background
6669 // - Background is opaque
6670 // - Doesn't have scrollbars or scrollbars are inside overlay
6671
6672 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6673 mPrivateFlags |= OPAQUE_BACKGROUND;
6674 } else {
6675 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6676 }
6677
6678 final int flags = mViewFlags;
6679 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6680 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6681 mPrivateFlags |= OPAQUE_SCROLLBARS;
6682 } else {
6683 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6684 }
6685 }
6686
6687 /**
6688 * @hide
6689 */
6690 protected boolean hasOpaqueScrollbars() {
6691 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006692 }
6693
6694 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 * @return A handler associated with the thread running the View. This
6696 * handler can be used to pump events in the UI events queue.
6697 */
6698 public Handler getHandler() {
6699 if (mAttachInfo != null) {
6700 return mAttachInfo.mHandler;
6701 }
6702 return null;
6703 }
6704
6705 /**
6706 * Causes the Runnable to be added to the message queue.
6707 * The runnable will be run on the user interface thread.
6708 *
6709 * @param action The Runnable that will be executed.
6710 *
6711 * @return Returns true if the Runnable was successfully placed in to the
6712 * message queue. Returns false on failure, usually because the
6713 * looper processing the message queue is exiting.
6714 */
6715 public boolean post(Runnable action) {
6716 Handler handler;
6717 if (mAttachInfo != null) {
6718 handler = mAttachInfo.mHandler;
6719 } else {
6720 // Assume that post will succeed later
6721 ViewRoot.getRunQueue().post(action);
6722 return true;
6723 }
6724
6725 return handler.post(action);
6726 }
6727
6728 /**
6729 * Causes the Runnable to be added to the message queue, to be run
6730 * after the specified amount of time elapses.
6731 * The runnable will be run on the user interface thread.
6732 *
6733 * @param action The Runnable that will be executed.
6734 * @param delayMillis The delay (in milliseconds) until the Runnable
6735 * will be executed.
6736 *
6737 * @return true if the Runnable was successfully placed in to the
6738 * message queue. Returns false on failure, usually because the
6739 * looper processing the message queue is exiting. Note that a
6740 * result of true does not mean the Runnable will be processed --
6741 * if the looper is quit before the delivery time of the message
6742 * occurs then the message will be dropped.
6743 */
6744 public boolean postDelayed(Runnable action, long delayMillis) {
6745 Handler handler;
6746 if (mAttachInfo != null) {
6747 handler = mAttachInfo.mHandler;
6748 } else {
6749 // Assume that post will succeed later
6750 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6751 return true;
6752 }
6753
6754 return handler.postDelayed(action, delayMillis);
6755 }
6756
6757 /**
6758 * Removes the specified Runnable from the message queue.
6759 *
6760 * @param action The Runnable to remove from the message handling queue
6761 *
6762 * @return true if this view could ask the Handler to remove the Runnable,
6763 * false otherwise. When the returned value is true, the Runnable
6764 * may or may not have been actually removed from the message queue
6765 * (for instance, if the Runnable was not in the queue already.)
6766 */
6767 public boolean removeCallbacks(Runnable action) {
6768 Handler handler;
6769 if (mAttachInfo != null) {
6770 handler = mAttachInfo.mHandler;
6771 } else {
6772 // Assume that post will succeed later
6773 ViewRoot.getRunQueue().removeCallbacks(action);
6774 return true;
6775 }
6776
6777 handler.removeCallbacks(action);
6778 return true;
6779 }
6780
6781 /**
6782 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6783 * Use this to invalidate the View from a non-UI thread.
6784 *
6785 * @see #invalidate()
6786 */
6787 public void postInvalidate() {
6788 postInvalidateDelayed(0);
6789 }
6790
6791 /**
6792 * Cause an invalidate of the specified area to happen on a subsequent cycle
6793 * through the event loop. Use this to invalidate the View from a non-UI thread.
6794 *
6795 * @param left The left coordinate of the rectangle to invalidate.
6796 * @param top The top coordinate of the rectangle to invalidate.
6797 * @param right The right coordinate of the rectangle to invalidate.
6798 * @param bottom The bottom coordinate of the rectangle to invalidate.
6799 *
6800 * @see #invalidate(int, int, int, int)
6801 * @see #invalidate(Rect)
6802 */
6803 public void postInvalidate(int left, int top, int right, int bottom) {
6804 postInvalidateDelayed(0, left, top, right, bottom);
6805 }
6806
6807 /**
6808 * Cause an invalidate to happen on a subsequent cycle through the event
6809 * loop. Waits for the specified amount of time.
6810 *
6811 * @param delayMilliseconds the duration in milliseconds to delay the
6812 * invalidation by
6813 */
6814 public void postInvalidateDelayed(long delayMilliseconds) {
6815 // We try only with the AttachInfo because there's no point in invalidating
6816 // if we are not attached to our window
6817 if (mAttachInfo != null) {
6818 Message msg = Message.obtain();
6819 msg.what = AttachInfo.INVALIDATE_MSG;
6820 msg.obj = this;
6821 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6822 }
6823 }
6824
6825 /**
6826 * Cause an invalidate of the specified area to happen on a subsequent cycle
6827 * through the event loop. Waits for the specified amount of time.
6828 *
6829 * @param delayMilliseconds the duration in milliseconds to delay the
6830 * invalidation by
6831 * @param left The left coordinate of the rectangle to invalidate.
6832 * @param top The top coordinate of the rectangle to invalidate.
6833 * @param right The right coordinate of the rectangle to invalidate.
6834 * @param bottom The bottom coordinate of the rectangle to invalidate.
6835 */
6836 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6837 int right, int bottom) {
6838
6839 // We try only with the AttachInfo because there's no point in invalidating
6840 // if we are not attached to our window
6841 if (mAttachInfo != null) {
6842 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6843 info.target = this;
6844 info.left = left;
6845 info.top = top;
6846 info.right = right;
6847 info.bottom = bottom;
6848
6849 final Message msg = Message.obtain();
6850 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6851 msg.obj = info;
6852 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6853 }
6854 }
6855
6856 /**
6857 * Called by a parent to request that a child update its values for mScrollX
6858 * and mScrollY if necessary. This will typically be done if the child is
6859 * animating a scroll using a {@link android.widget.Scroller Scroller}
6860 * object.
6861 */
6862 public void computeScroll() {
6863 }
6864
6865 /**
6866 * <p>Indicate whether the horizontal edges are faded when the view is
6867 * scrolled horizontally.</p>
6868 *
6869 * @return true if the horizontal edges should are faded on scroll, false
6870 * otherwise
6871 *
6872 * @see #setHorizontalFadingEdgeEnabled(boolean)
6873 * @attr ref android.R.styleable#View_fadingEdge
6874 */
6875 public boolean isHorizontalFadingEdgeEnabled() {
6876 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6877 }
6878
6879 /**
6880 * <p>Define whether the horizontal edges should be faded when this view
6881 * is scrolled horizontally.</p>
6882 *
6883 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6884 * be faded when the view is scrolled
6885 * horizontally
6886 *
6887 * @see #isHorizontalFadingEdgeEnabled()
6888 * @attr ref android.R.styleable#View_fadingEdge
6889 */
6890 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6891 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6892 if (horizontalFadingEdgeEnabled) {
6893 initScrollCache();
6894 }
6895
6896 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6897 }
6898 }
6899
6900 /**
6901 * <p>Indicate whether the vertical edges are faded when the view is
6902 * scrolled horizontally.</p>
6903 *
6904 * @return true if the vertical edges should are faded on scroll, false
6905 * otherwise
6906 *
6907 * @see #setVerticalFadingEdgeEnabled(boolean)
6908 * @attr ref android.R.styleable#View_fadingEdge
6909 */
6910 public boolean isVerticalFadingEdgeEnabled() {
6911 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6912 }
6913
6914 /**
6915 * <p>Define whether the vertical edges should be faded when this view
6916 * is scrolled vertically.</p>
6917 *
6918 * @param verticalFadingEdgeEnabled true if the vertical edges should
6919 * be faded when the view is scrolled
6920 * vertically
6921 *
6922 * @see #isVerticalFadingEdgeEnabled()
6923 * @attr ref android.R.styleable#View_fadingEdge
6924 */
6925 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6926 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6927 if (verticalFadingEdgeEnabled) {
6928 initScrollCache();
6929 }
6930
6931 mViewFlags ^= FADING_EDGE_VERTICAL;
6932 }
6933 }
6934
6935 /**
6936 * Returns the strength, or intensity, of the top faded edge. The strength is
6937 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6938 * returns 0.0 or 1.0 but no value in between.
6939 *
6940 * Subclasses should override this method to provide a smoother fade transition
6941 * when scrolling occurs.
6942 *
6943 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6944 */
6945 protected float getTopFadingEdgeStrength() {
6946 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6947 }
6948
6949 /**
6950 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6951 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6952 * returns 0.0 or 1.0 but no value in between.
6953 *
6954 * Subclasses should override this method to provide a smoother fade transition
6955 * when scrolling occurs.
6956 *
6957 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6958 */
6959 protected float getBottomFadingEdgeStrength() {
6960 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6961 computeVerticalScrollRange() ? 1.0f : 0.0f;
6962 }
6963
6964 /**
6965 * Returns the strength, or intensity, of the left faded edge. The strength is
6966 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6967 * returns 0.0 or 1.0 but no value in between.
6968 *
6969 * Subclasses should override this method to provide a smoother fade transition
6970 * when scrolling occurs.
6971 *
6972 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6973 */
6974 protected float getLeftFadingEdgeStrength() {
6975 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6976 }
6977
6978 /**
6979 * Returns the strength, or intensity, of the right faded edge. The strength is
6980 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6981 * returns 0.0 or 1.0 but no value in between.
6982 *
6983 * Subclasses should override this method to provide a smoother fade transition
6984 * when scrolling occurs.
6985 *
6986 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6987 */
6988 protected float getRightFadingEdgeStrength() {
6989 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6990 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6991 }
6992
6993 /**
6994 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6995 * scrollbar is not drawn by default.</p>
6996 *
6997 * @return true if the horizontal scrollbar should be painted, false
6998 * otherwise
6999 *
7000 * @see #setHorizontalScrollBarEnabled(boolean)
7001 */
7002 public boolean isHorizontalScrollBarEnabled() {
7003 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7004 }
7005
7006 /**
7007 * <p>Define whether the horizontal scrollbar should be drawn or not. The
7008 * scrollbar is not drawn by default.</p>
7009 *
7010 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
7011 * be painted
7012 *
7013 * @see #isHorizontalScrollBarEnabled()
7014 */
7015 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
7016 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
7017 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007018 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007019 recomputePadding();
7020 }
7021 }
7022
7023 /**
7024 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
7025 * scrollbar is not drawn by default.</p>
7026 *
7027 * @return true if the vertical scrollbar should be painted, false
7028 * otherwise
7029 *
7030 * @see #setVerticalScrollBarEnabled(boolean)
7031 */
7032 public boolean isVerticalScrollBarEnabled() {
7033 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
7034 }
7035
7036 /**
7037 * <p>Define whether the vertical scrollbar should be drawn or not. The
7038 * scrollbar is not drawn by default.</p>
7039 *
7040 * @param verticalScrollBarEnabled true if the vertical scrollbar should
7041 * be painted
7042 *
7043 * @see #isVerticalScrollBarEnabled()
7044 */
7045 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
7046 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
7047 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007048 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007049 recomputePadding();
7050 }
7051 }
7052
Adam Powell20232d02010-12-08 21:08:53 -08007053 /**
7054 * @hide
7055 */
7056 protected void recomputePadding() {
7057 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007058 }
Mike Cleronfe81d382009-09-28 14:22:16 -07007059
7060 /**
7061 * Define whether scrollbars will fade when the view is not scrolling.
7062 *
7063 * @param fadeScrollbars wheter to enable fading
7064 *
7065 */
7066 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
7067 initScrollCache();
7068 final ScrollabilityCache scrollabilityCache = mScrollCache;
7069 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07007070 if (fadeScrollbars) {
7071 scrollabilityCache.state = ScrollabilityCache.OFF;
7072 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07007073 scrollabilityCache.state = ScrollabilityCache.ON;
7074 }
7075 }
7076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007077 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07007078 *
7079 * Returns true if scrollbars will fade when this view is not scrolling
7080 *
7081 * @return true if scrollbar fading is enabled
7082 */
7083 public boolean isScrollbarFadingEnabled() {
7084 return mScrollCache != null && mScrollCache.fadeScrollBars;
7085 }
7086
7087 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007088 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
7089 * inset. When inset, they add to the padding of the view. And the scrollbars
7090 * can be drawn inside the padding area or on the edge of the view. For example,
7091 * if a view has a background drawable and you want to draw the scrollbars
7092 * inside the padding specified by the drawable, you can use
7093 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
7094 * appear at the edge of the view, ignoring the padding, then you can use
7095 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
7096 * @param style the style of the scrollbars. Should be one of
7097 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
7098 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
7099 * @see #SCROLLBARS_INSIDE_OVERLAY
7100 * @see #SCROLLBARS_INSIDE_INSET
7101 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7102 * @see #SCROLLBARS_OUTSIDE_INSET
7103 */
7104 public void setScrollBarStyle(int style) {
7105 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
7106 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07007107 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007108 recomputePadding();
7109 }
7110 }
7111
7112 /**
7113 * <p>Returns the current scrollbar style.</p>
7114 * @return the current scrollbar style
7115 * @see #SCROLLBARS_INSIDE_OVERLAY
7116 * @see #SCROLLBARS_INSIDE_INSET
7117 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7118 * @see #SCROLLBARS_OUTSIDE_INSET
7119 */
7120 public int getScrollBarStyle() {
7121 return mViewFlags & SCROLLBARS_STYLE_MASK;
7122 }
7123
7124 /**
7125 * <p>Compute the horizontal range that the horizontal scrollbar
7126 * represents.</p>
7127 *
7128 * <p>The range is expressed in arbitrary units that must be the same as the
7129 * units used by {@link #computeHorizontalScrollExtent()} and
7130 * {@link #computeHorizontalScrollOffset()}.</p>
7131 *
7132 * <p>The default range is the drawing width of this view.</p>
7133 *
7134 * @return the total horizontal range represented by the horizontal
7135 * scrollbar
7136 *
7137 * @see #computeHorizontalScrollExtent()
7138 * @see #computeHorizontalScrollOffset()
7139 * @see android.widget.ScrollBarDrawable
7140 */
7141 protected int computeHorizontalScrollRange() {
7142 return getWidth();
7143 }
7144
7145 /**
7146 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7147 * within the horizontal range. This value is used to compute the position
7148 * of the thumb within the scrollbar's track.</p>
7149 *
7150 * <p>The range is expressed in arbitrary units that must be the same as the
7151 * units used by {@link #computeHorizontalScrollRange()} and
7152 * {@link #computeHorizontalScrollExtent()}.</p>
7153 *
7154 * <p>The default offset is the scroll offset of this view.</p>
7155 *
7156 * @return the horizontal offset of the scrollbar's thumb
7157 *
7158 * @see #computeHorizontalScrollRange()
7159 * @see #computeHorizontalScrollExtent()
7160 * @see android.widget.ScrollBarDrawable
7161 */
7162 protected int computeHorizontalScrollOffset() {
7163 return mScrollX;
7164 }
7165
7166 /**
7167 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7168 * within the horizontal range. This value is used to compute the length
7169 * of the thumb within the scrollbar's track.</p>
7170 *
7171 * <p>The range is expressed in arbitrary units that must be the same as the
7172 * units used by {@link #computeHorizontalScrollRange()} and
7173 * {@link #computeHorizontalScrollOffset()}.</p>
7174 *
7175 * <p>The default extent is the drawing width of this view.</p>
7176 *
7177 * @return the horizontal extent of the scrollbar's thumb
7178 *
7179 * @see #computeHorizontalScrollRange()
7180 * @see #computeHorizontalScrollOffset()
7181 * @see android.widget.ScrollBarDrawable
7182 */
7183 protected int computeHorizontalScrollExtent() {
7184 return getWidth();
7185 }
7186
7187 /**
7188 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7189 *
7190 * <p>The range is expressed in arbitrary units that must be the same as the
7191 * units used by {@link #computeVerticalScrollExtent()} and
7192 * {@link #computeVerticalScrollOffset()}.</p>
7193 *
7194 * @return the total vertical range represented by the vertical scrollbar
7195 *
7196 * <p>The default range is the drawing height of this view.</p>
7197 *
7198 * @see #computeVerticalScrollExtent()
7199 * @see #computeVerticalScrollOffset()
7200 * @see android.widget.ScrollBarDrawable
7201 */
7202 protected int computeVerticalScrollRange() {
7203 return getHeight();
7204 }
7205
7206 /**
7207 * <p>Compute the vertical offset of the vertical scrollbar's thumb
7208 * within the horizontal range. This value is used to compute the position
7209 * of the thumb within the scrollbar's track.</p>
7210 *
7211 * <p>The range is expressed in arbitrary units that must be the same as the
7212 * units used by {@link #computeVerticalScrollRange()} and
7213 * {@link #computeVerticalScrollExtent()}.</p>
7214 *
7215 * <p>The default offset is the scroll offset of this view.</p>
7216 *
7217 * @return the vertical offset of the scrollbar's thumb
7218 *
7219 * @see #computeVerticalScrollRange()
7220 * @see #computeVerticalScrollExtent()
7221 * @see android.widget.ScrollBarDrawable
7222 */
7223 protected int computeVerticalScrollOffset() {
7224 return mScrollY;
7225 }
7226
7227 /**
7228 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7229 * within the vertical range. This value is used to compute the length
7230 * of the thumb within the scrollbar's track.</p>
7231 *
7232 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08007233 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 * {@link #computeVerticalScrollOffset()}.</p>
7235 *
7236 * <p>The default extent is the drawing height of this view.</p>
7237 *
7238 * @return the vertical extent of the scrollbar's thumb
7239 *
7240 * @see #computeVerticalScrollRange()
7241 * @see #computeVerticalScrollOffset()
7242 * @see android.widget.ScrollBarDrawable
7243 */
7244 protected int computeVerticalScrollExtent() {
7245 return getHeight();
7246 }
7247
7248 /**
7249 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7250 * scrollbars are painted only if they have been awakened first.</p>
7251 *
7252 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07007253 *
7254 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08007256 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007257 // scrollbars are drawn only when the animation is running
7258 final ScrollabilityCache cache = mScrollCache;
7259 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007260
7261 int state = cache.state;
7262
7263 if (state == ScrollabilityCache.OFF) {
7264 return;
7265 }
7266
7267 boolean invalidate = false;
7268
7269 if (state == ScrollabilityCache.FADING) {
7270 // We're fading -- get our fade interpolation
7271 if (cache.interpolatorValues == null) {
7272 cache.interpolatorValues = new float[1];
7273 }
7274
7275 float[] values = cache.interpolatorValues;
7276
7277 // Stops the animation if we're done
7278 if (cache.scrollBarInterpolator.timeToValues(values) ==
7279 Interpolator.Result.FREEZE_END) {
7280 cache.state = ScrollabilityCache.OFF;
7281 } else {
7282 cache.scrollBar.setAlpha(Math.round(values[0]));
7283 }
7284
7285 // This will make the scroll bars inval themselves after
7286 // drawing. We only want this when we're fading so that
7287 // we prevent excessive redraws
7288 invalidate = true;
7289 } else {
7290 // We're just on -- but we may have been fading before so
7291 // reset alpha
7292 cache.scrollBar.setAlpha(255);
7293 }
7294
7295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 final int viewFlags = mViewFlags;
7297
7298 final boolean drawHorizontalScrollBar =
7299 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7300 final boolean drawVerticalScrollBar =
7301 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7302 && !isVerticalScrollBarHidden();
7303
7304 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7305 final int width = mRight - mLeft;
7306 final int height = mBottom - mTop;
7307
7308 final ScrollBarDrawable scrollBar = cache.scrollBar;
7309 int size = scrollBar.getSize(false);
7310 if (size <= 0) {
7311 size = cache.scrollBarSize;
7312 }
7313
Mike Reede8853fc2009-09-04 14:01:48 -04007314 final int scrollX = mScrollX;
7315 final int scrollY = mScrollY;
7316 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7317
Mike Cleronf116bf82009-09-27 19:14:12 -07007318 int left, top, right, bottom;
7319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007320 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007321 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04007322 computeHorizontalScrollOffset(),
7323 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04007324 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07007325 getVerticalScrollbarWidth() : 0;
7326 top = scrollY + height - size - (mUserPaddingBottom & inside);
7327 left = scrollX + (mPaddingLeft & inside);
7328 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7329 bottom = top + size;
7330 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7331 if (invalidate) {
7332 invalidate(left, top, right, bottom);
7333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 }
7335
7336 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04007337 scrollBar.setParameters(computeVerticalScrollRange(),
7338 computeVerticalScrollOffset(),
7339 computeVerticalScrollExtent(), true);
Adam Powell20232d02010-12-08 21:08:53 -08007340 switch (mVerticalScrollbarPosition) {
7341 default:
7342 case SCROLLBAR_POSITION_DEFAULT:
7343 case SCROLLBAR_POSITION_RIGHT:
7344 left = scrollX + width - size - (mUserPaddingRight & inside);
7345 break;
7346 case SCROLLBAR_POSITION_LEFT:
7347 left = scrollX + (mUserPaddingLeft & inside);
7348 break;
7349 }
Mike Cleronf116bf82009-09-27 19:14:12 -07007350 top = scrollY + (mPaddingTop & inside);
7351 right = left + size;
7352 bottom = scrollY + height - (mUserPaddingBottom & inside);
7353 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7354 if (invalidate) {
7355 invalidate(left, top, right, bottom);
7356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007357 }
7358 }
7359 }
7360 }
Romain Guy8506ab42009-06-11 17:35:47 -07007361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007362 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007363 * 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 -08007364 * FastScroller is visible.
7365 * @return whether to temporarily hide the vertical scrollbar
7366 * @hide
7367 */
7368 protected boolean isVerticalScrollBarHidden() {
7369 return false;
7370 }
7371
7372 /**
7373 * <p>Draw the horizontal scrollbar if
7374 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7375 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007376 * @param canvas the canvas on which to draw the scrollbar
7377 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007378 *
7379 * @see #isHorizontalScrollBarEnabled()
7380 * @see #computeHorizontalScrollRange()
7381 * @see #computeHorizontalScrollExtent()
7382 * @see #computeHorizontalScrollOffset()
7383 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007384 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007385 */
Romain Guy8fb95422010-08-17 18:38:51 -07007386 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7387 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007388 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007389 scrollBar.draw(canvas);
7390 }
Mike Reede8853fc2009-09-04 14:01:48 -04007391
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007392 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007393 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7394 * returns true.</p>
7395 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 * @param canvas the canvas on which to draw the scrollbar
7397 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007398 *
7399 * @see #isVerticalScrollBarEnabled()
7400 * @see #computeVerticalScrollRange()
7401 * @see #computeVerticalScrollExtent()
7402 * @see #computeVerticalScrollOffset()
7403 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007404 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007405 */
Romain Guy8fb95422010-08-17 18:38:51 -07007406 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7407 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007408 scrollBar.setBounds(l, t, r, b);
7409 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007410 }
7411
7412 /**
7413 * Implement this to do your drawing.
7414 *
7415 * @param canvas the canvas on which the background will be drawn
7416 */
7417 protected void onDraw(Canvas canvas) {
7418 }
7419
7420 /*
7421 * Caller is responsible for calling requestLayout if necessary.
7422 * (This allows addViewInLayout to not request a new layout.)
7423 */
7424 void assignParent(ViewParent parent) {
7425 if (mParent == null) {
7426 mParent = parent;
7427 } else if (parent == null) {
7428 mParent = null;
7429 } else {
7430 throw new RuntimeException("view " + this + " being added, but"
7431 + " it already has a parent");
7432 }
7433 }
7434
7435 /**
7436 * This is called when the view is attached to a window. At this point it
7437 * has a Surface and will start drawing. Note that this function is
7438 * guaranteed to be called before {@link #onDraw}, however it may be called
7439 * any time before the first onDraw -- including before or after
7440 * {@link #onMeasure}.
7441 *
7442 * @see #onDetachedFromWindow()
7443 */
7444 protected void onAttachedToWindow() {
7445 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7446 mParent.requestTransparentRegion(this);
7447 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007448 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7449 initialAwakenScrollBars();
7450 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7451 }
Chet Haasea9b61ac2010-12-20 07:40:25 -08007452 jumpDrawablesToCurrentState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007453 }
7454
7455 /**
7456 * This is called when the view is detached from a window. At this point it
7457 * no longer has a surface for drawing.
7458 *
7459 * @see #onAttachedToWindow()
7460 */
7461 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007462 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08007463 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007464 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007465 destroyDrawingCache();
7466 }
7467
7468 /**
7469 * @return The number of times this view has been attached to a window
7470 */
7471 protected int getWindowAttachCount() {
7472 return mWindowAttachCount;
7473 }
7474
7475 /**
7476 * Retrieve a unique token identifying the window this view is attached to.
7477 * @return Return the window's token for use in
7478 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7479 */
7480 public IBinder getWindowToken() {
7481 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7482 }
7483
7484 /**
7485 * Retrieve a unique token identifying the top-level "real" window of
7486 * the window that this view is attached to. That is, this is like
7487 * {@link #getWindowToken}, except if the window this view in is a panel
7488 * window (attached to another containing window), then the token of
7489 * the containing window is returned instead.
7490 *
7491 * @return Returns the associated window token, either
7492 * {@link #getWindowToken()} or the containing window's token.
7493 */
7494 public IBinder getApplicationWindowToken() {
7495 AttachInfo ai = mAttachInfo;
7496 if (ai != null) {
7497 IBinder appWindowToken = ai.mPanelParentWindowToken;
7498 if (appWindowToken == null) {
7499 appWindowToken = ai.mWindowToken;
7500 }
7501 return appWindowToken;
7502 }
7503 return null;
7504 }
7505
7506 /**
7507 * Retrieve private session object this view hierarchy is using to
7508 * communicate with the window manager.
7509 * @return the session object to communicate with the window manager
7510 */
7511 /*package*/ IWindowSession getWindowSession() {
7512 return mAttachInfo != null ? mAttachInfo.mSession : null;
7513 }
7514
7515 /**
7516 * @param info the {@link android.view.View.AttachInfo} to associated with
7517 * this view
7518 */
7519 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7520 //System.out.println("Attached! " + this);
7521 mAttachInfo = info;
7522 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007523 // We will need to evaluate the drawable state at least once.
7524 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007525 if (mFloatingTreeObserver != null) {
7526 info.mTreeObserver.merge(mFloatingTreeObserver);
7527 mFloatingTreeObserver = null;
7528 }
7529 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7530 mAttachInfo.mScrollContainers.add(this);
7531 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7532 }
7533 performCollectViewAttributes(visibility);
7534 onAttachedToWindow();
7535 int vis = info.mWindowVisibility;
7536 if (vis != GONE) {
7537 onWindowVisibilityChanged(vis);
7538 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007539 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7540 // If nobody has evaluated the drawable state yet, then do it now.
7541 refreshDrawableState();
7542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007543 }
7544
7545 void dispatchDetachedFromWindow() {
7546 //System.out.println("Detached! " + this);
7547 AttachInfo info = mAttachInfo;
7548 if (info != null) {
7549 int vis = info.mWindowVisibility;
7550 if (vis != GONE) {
7551 onWindowVisibilityChanged(GONE);
7552 }
7553 }
7554
7555 onDetachedFromWindow();
7556 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7557 mAttachInfo.mScrollContainers.remove(this);
7558 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7559 }
7560 mAttachInfo = null;
7561 }
7562
7563 /**
7564 * Store this view hierarchy's frozen state into the given container.
7565 *
7566 * @param container The SparseArray in which to save the view's state.
7567 *
7568 * @see #restoreHierarchyState
7569 * @see #dispatchSaveInstanceState
7570 * @see #onSaveInstanceState
7571 */
7572 public void saveHierarchyState(SparseArray<Parcelable> container) {
7573 dispatchSaveInstanceState(container);
7574 }
7575
7576 /**
7577 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7578 * May be overridden to modify how freezing happens to a view's children; for example, some
7579 * views may want to not store state for their children.
7580 *
7581 * @param container The SparseArray in which to save the view's state.
7582 *
7583 * @see #dispatchRestoreInstanceState
7584 * @see #saveHierarchyState
7585 * @see #onSaveInstanceState
7586 */
7587 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7588 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7589 mPrivateFlags &= ~SAVE_STATE_CALLED;
7590 Parcelable state = onSaveInstanceState();
7591 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7592 throw new IllegalStateException(
7593 "Derived class did not call super.onSaveInstanceState()");
7594 }
7595 if (state != null) {
7596 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7597 // + ": " + state);
7598 container.put(mID, state);
7599 }
7600 }
7601 }
7602
7603 /**
7604 * Hook allowing a view to generate a representation of its internal state
7605 * that can later be used to create a new instance with that same state.
7606 * This state should only contain information that is not persistent or can
7607 * not be reconstructed later. For example, you will never store your
7608 * current position on screen because that will be computed again when a
7609 * new instance of the view is placed in its view hierarchy.
7610 * <p>
7611 * Some examples of things you may store here: the current cursor position
7612 * in a text view (but usually not the text itself since that is stored in a
7613 * content provider or other persistent storage), the currently selected
7614 * item in a list view.
7615 *
7616 * @return Returns a Parcelable object containing the view's current dynamic
7617 * state, or null if there is nothing interesting to save. The
7618 * default implementation returns null.
7619 * @see #onRestoreInstanceState
7620 * @see #saveHierarchyState
7621 * @see #dispatchSaveInstanceState
7622 * @see #setSaveEnabled(boolean)
7623 */
7624 protected Parcelable onSaveInstanceState() {
7625 mPrivateFlags |= SAVE_STATE_CALLED;
7626 return BaseSavedState.EMPTY_STATE;
7627 }
7628
7629 /**
7630 * Restore this view hierarchy's frozen state from the given container.
7631 *
7632 * @param container The SparseArray which holds previously frozen states.
7633 *
7634 * @see #saveHierarchyState
7635 * @see #dispatchRestoreInstanceState
7636 * @see #onRestoreInstanceState
7637 */
7638 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7639 dispatchRestoreInstanceState(container);
7640 }
7641
7642 /**
7643 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7644 * children. May be overridden to modify how restoreing happens to a view's children; for
7645 * example, some views may want to not store state for their children.
7646 *
7647 * @param container The SparseArray which holds previously saved state.
7648 *
7649 * @see #dispatchSaveInstanceState
7650 * @see #restoreHierarchyState
7651 * @see #onRestoreInstanceState
7652 */
7653 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7654 if (mID != NO_ID) {
7655 Parcelable state = container.get(mID);
7656 if (state != null) {
7657 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7658 // + ": " + state);
7659 mPrivateFlags &= ~SAVE_STATE_CALLED;
7660 onRestoreInstanceState(state);
7661 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7662 throw new IllegalStateException(
7663 "Derived class did not call super.onRestoreInstanceState()");
7664 }
7665 }
7666 }
7667 }
7668
7669 /**
7670 * Hook allowing a view to re-apply a representation of its internal state that had previously
7671 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7672 * null state.
7673 *
7674 * @param state The frozen state that had previously been returned by
7675 * {@link #onSaveInstanceState}.
7676 *
7677 * @see #onSaveInstanceState
7678 * @see #restoreHierarchyState
7679 * @see #dispatchRestoreInstanceState
7680 */
7681 protected void onRestoreInstanceState(Parcelable state) {
7682 mPrivateFlags |= SAVE_STATE_CALLED;
7683 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007684 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7685 + "received " + state.getClass().toString() + " instead. This usually happens "
7686 + "when two views of different type have the same id in the same hierarchy. "
7687 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7688 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689 }
7690 }
7691
7692 /**
7693 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7694 *
7695 * @return the drawing start time in milliseconds
7696 */
7697 public long getDrawingTime() {
7698 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7699 }
7700
7701 /**
7702 * <p>Enables or disables the duplication of the parent's state into this view. When
7703 * duplication is enabled, this view gets its drawable state from its parent rather
7704 * than from its own internal properties.</p>
7705 *
7706 * <p>Note: in the current implementation, setting this property to true after the
7707 * view was added to a ViewGroup might have no effect at all. This property should
7708 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7709 *
7710 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7711 * property is enabled, an exception will be thrown.</p>
7712 *
7713 * @param enabled True to enable duplication of the parent's drawable state, false
7714 * to disable it.
7715 *
7716 * @see #getDrawableState()
7717 * @see #isDuplicateParentStateEnabled()
7718 */
7719 public void setDuplicateParentStateEnabled(boolean enabled) {
7720 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7721 }
7722
7723 /**
7724 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7725 *
7726 * @return True if this view's drawable state is duplicated from the parent,
7727 * false otherwise
7728 *
7729 * @see #getDrawableState()
7730 * @see #setDuplicateParentStateEnabled(boolean)
7731 */
7732 public boolean isDuplicateParentStateEnabled() {
7733 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7734 }
7735
7736 /**
7737 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
7738 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
7739 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
7740 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
7741 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
7742 * null.</p>
7743 *
7744 * @param enabled true to enable the drawing cache, false otherwise
7745 *
7746 * @see #isDrawingCacheEnabled()
7747 * @see #getDrawingCache()
7748 * @see #buildDrawingCache()
7749 */
7750 public void setDrawingCacheEnabled(boolean enabled) {
7751 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
7752 }
7753
7754 /**
7755 * <p>Indicates whether the drawing cache is enabled for this view.</p>
7756 *
7757 * @return true if the drawing cache is enabled
7758 *
7759 * @see #setDrawingCacheEnabled(boolean)
7760 * @see #getDrawingCache()
7761 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07007762 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 public boolean isDrawingCacheEnabled() {
7764 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
7765 }
7766
7767 /**
Romain Guyb051e892010-09-28 19:09:36 -07007768 * <p>Returns a display list that can be used to draw this view again
7769 * without executing its draw method.</p>
7770 *
7771 * @return A DisplayList ready to replay, or null if caching is not enabled.
7772 */
7773 DisplayList getDisplayList() {
7774 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7775 return null;
7776 }
Romain Guyb051e892010-09-28 19:09:36 -07007777 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
7778 return null;
7779 }
7780
7781 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
7782 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mDisplayList == null)) {
7783
Romain Guyb051e892010-09-28 19:09:36 -07007784 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
7785
7786 final HardwareCanvas canvas = mDisplayList.start();
7787 try {
7788 int width = mRight - mLeft;
7789 int height = mBottom - mTop;
7790
7791 canvas.setViewport(width, height);
7792 canvas.onPreDraw();
7793
7794 final int restoreCount = canvas.save();
7795
Romain Guy2fe9a8f2010-10-04 20:17:01 -07007796 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07007797
7798 // Fast path for layouts with no backgrounds
7799 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7800 mPrivateFlags &= ~DIRTY_MASK;
7801 dispatchDraw(canvas);
7802 } else {
7803 draw(canvas);
7804 }
7805
7806 canvas.restoreToCount(restoreCount);
7807 } finally {
7808 canvas.onPostDraw();
7809
7810 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07007811 }
7812 }
7813
7814 return mDisplayList;
7815 }
7816
7817 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007818 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
7819 *
7820 * @return A non-scaled bitmap representing this view or null if cache is disabled.
7821 *
7822 * @see #getDrawingCache(boolean)
7823 */
7824 public Bitmap getDrawingCache() {
7825 return getDrawingCache(false);
7826 }
7827
7828 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007829 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
7830 * is null when caching is disabled. If caching is enabled and the cache is not ready,
7831 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
7832 * draw from the cache when the cache is enabled. To benefit from the cache, you must
7833 * request the drawing cache by calling this method and draw it on screen if the
7834 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007835 *
7836 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7837 * this method will create a bitmap of the same size as this view. Because this bitmap
7838 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7839 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7840 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7841 * size than the view. This implies that your application must be able to handle this
7842 * size.</p>
7843 *
7844 * @param autoScale Indicates whether the generated bitmap should be scaled based on
7845 * the current density of the screen when the application is in compatibility
7846 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 *
Romain Guyfbd8f692009-06-26 14:51:58 -07007848 * @return A bitmap representing this view or null if cache is disabled.
7849 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007850 * @see #setDrawingCacheEnabled(boolean)
7851 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07007852 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007853 * @see #destroyDrawingCache()
7854 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007855 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7857 return null;
7858 }
7859 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007860 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 }
Romain Guy02890fd2010-08-06 17:58:44 -07007862 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007863 }
7864
7865 /**
7866 * <p>Frees the resources used by the drawing cache. If you call
7867 * {@link #buildDrawingCache()} manually without calling
7868 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7869 * should cleanup the cache with this method afterwards.</p>
7870 *
7871 * @see #setDrawingCacheEnabled(boolean)
7872 * @see #buildDrawingCache()
7873 * @see #getDrawingCache()
7874 */
7875 public void destroyDrawingCache() {
7876 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007877 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007878 mDrawingCache = null;
7879 }
Romain Guyfbd8f692009-06-26 14:51:58 -07007880 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007881 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07007882 mUnscaledDrawingCache = null;
7883 }
Romain Guyb051e892010-09-28 19:09:36 -07007884 if (mDisplayList != null) {
Romain Guyb051e892010-09-28 19:09:36 -07007885 mDisplayList = null;
7886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 }
7888
7889 /**
7890 * Setting a solid background color for the drawing cache's bitmaps will improve
7891 * perfromance and memory usage. Note, though that this should only be used if this
7892 * view will always be drawn on top of a solid color.
7893 *
7894 * @param color The background color to use for the drawing cache's bitmap
7895 *
7896 * @see #setDrawingCacheEnabled(boolean)
7897 * @see #buildDrawingCache()
7898 * @see #getDrawingCache()
7899 */
7900 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08007901 if (color != mDrawingCacheBackgroundColor) {
7902 mDrawingCacheBackgroundColor = color;
7903 mPrivateFlags &= ~DRAWING_CACHE_VALID;
7904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 }
7906
7907 /**
7908 * @see #setDrawingCacheBackgroundColor(int)
7909 *
7910 * @return The background color to used for the drawing cache's bitmap
7911 */
7912 public int getDrawingCacheBackgroundColor() {
7913 return mDrawingCacheBackgroundColor;
7914 }
7915
7916 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007917 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
7918 *
7919 * @see #buildDrawingCache(boolean)
7920 */
7921 public void buildDrawingCache() {
7922 buildDrawingCache(false);
7923 }
7924
7925 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007926 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
7927 *
7928 * <p>If you call {@link #buildDrawingCache()} manually without calling
7929 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7930 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007931 *
7932 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7933 * this method will create a bitmap of the same size as this view. Because this bitmap
7934 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7935 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7936 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7937 * size than the view. This implies that your application must be able to handle this
7938 * size.</p>
Romain Guy0d9275e2010-10-26 14:22:30 -07007939 *
7940 * <p>You should avoid calling this method when hardware acceleration is enabled. If
7941 * you do not need the drawing cache bitmap, calling this method will increase memory
7942 * usage and cause the view to be rendered in software once, thus negatively impacting
7943 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944 *
7945 * @see #getDrawingCache()
7946 * @see #destroyDrawingCache()
7947 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007948 public void buildDrawingCache(boolean autoScale) {
7949 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07007950 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007951
7952 if (ViewDebug.TRACE_HIERARCHY) {
7953 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955
Romain Guy8506ab42009-06-11 17:35:47 -07007956 int width = mRight - mLeft;
7957 int height = mBottom - mTop;
7958
7959 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007960 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007961
Romain Guye1123222009-06-29 14:24:56 -07007962 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007963 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7964 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966
7967 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007968 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08007969 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970
7971 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007972 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08007973 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7975 destroyDrawingCache();
7976 return;
7977 }
7978
7979 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07007980 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981
7982 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 Bitmap.Config quality;
7984 if (!opaque) {
7985 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7986 case DRAWING_CACHE_QUALITY_AUTO:
7987 quality = Bitmap.Config.ARGB_8888;
7988 break;
7989 case DRAWING_CACHE_QUALITY_LOW:
7990 quality = Bitmap.Config.ARGB_4444;
7991 break;
7992 case DRAWING_CACHE_QUALITY_HIGH:
7993 quality = Bitmap.Config.ARGB_8888;
7994 break;
7995 default:
7996 quality = Bitmap.Config.ARGB_8888;
7997 break;
7998 }
7999 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07008000 // Optimization for translucent windows
8001 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08008002 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008003 }
8004
8005 // Try to cleanup memory
8006 if (bitmap != null) bitmap.recycle();
8007
8008 try {
8009 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07008010 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07008011 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07008012 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008013 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07008014 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008015 }
Adam Powell26153a32010-11-08 15:22:27 -08008016 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 } catch (OutOfMemoryError e) {
8018 // If there is not enough memory to create the bitmap cache, just
8019 // ignore the issue as bitmap caches are not required to draw the
8020 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07008021 if (autoScale) {
8022 mDrawingCache = null;
8023 } else {
8024 mUnscaledDrawingCache = null;
8025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 return;
8027 }
8028
8029 clear = drawingCacheBackgroundColor != 0;
8030 }
8031
8032 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 if (attachInfo != null) {
8034 canvas = attachInfo.mCanvas;
8035 if (canvas == null) {
8036 canvas = new Canvas();
8037 }
8038 canvas.setBitmap(bitmap);
8039 // Temporarily clobber the cached Canvas in case one of our children
8040 // is also using a drawing cache. Without this, the children would
8041 // steal the canvas by attaching their own bitmap to it and bad, bad
8042 // thing would happen (invisible views, corrupted drawings, etc.)
8043 attachInfo.mCanvas = null;
8044 } else {
8045 // This case should hopefully never or seldom happen
8046 canvas = new Canvas(bitmap);
8047 }
8048
8049 if (clear) {
8050 bitmap.eraseColor(drawingCacheBackgroundColor);
8051 }
8052
8053 computeScroll();
8054 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07008055
Romain Guye1123222009-06-29 14:24:56 -07008056 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008057 final float scale = attachInfo.mApplicationScale;
8058 canvas.scale(scale, scale);
8059 }
8060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008061 canvas.translate(-mScrollX, -mScrollY);
8062
Romain Guy5bcdff42009-05-14 21:27:18 -07008063 mPrivateFlags |= DRAWN;
Romain Guy0d9275e2010-10-26 14:22:30 -07008064 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated) {
8065 mPrivateFlags |= DRAWING_CACHE_VALID;
8066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008067
8068 // Fast path for layouts with no backgrounds
8069 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8070 if (ViewDebug.TRACE_HIERARCHY) {
8071 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8072 }
Romain Guy5bcdff42009-05-14 21:27:18 -07008073 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 dispatchDraw(canvas);
8075 } else {
8076 draw(canvas);
8077 }
8078
8079 canvas.restoreToCount(restoreCount);
8080
8081 if (attachInfo != null) {
8082 // Restore the cached Canvas for our siblings
8083 attachInfo.mCanvas = canvas;
8084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 }
8086 }
8087
8088 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008089 * Create a snapshot of the view into a bitmap. We should probably make
8090 * some form of this public, but should think about the API.
8091 */
Romain Guy223ff5c2010-03-02 17:07:47 -08008092 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008093 int width = mRight - mLeft;
8094 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008095
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008096 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07008097 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008098 width = (int) ((width * scale) + 0.5f);
8099 height = (int) ((height * scale) + 0.5f);
8100
Romain Guy8c11e312009-09-14 15:15:30 -07008101 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008102 if (bitmap == null) {
8103 throw new OutOfMemoryError();
8104 }
8105
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008106 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8107
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008108 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008109 if (attachInfo != null) {
8110 canvas = attachInfo.mCanvas;
8111 if (canvas == null) {
8112 canvas = new Canvas();
8113 }
8114 canvas.setBitmap(bitmap);
8115 // Temporarily clobber the cached Canvas in case one of our children
8116 // is also using a drawing cache. Without this, the children would
8117 // steal the canvas by attaching their own bitmap to it and bad, bad
8118 // things would happen (invisible views, corrupted drawings, etc.)
8119 attachInfo.mCanvas = null;
8120 } else {
8121 // This case should hopefully never or seldom happen
8122 canvas = new Canvas(bitmap);
8123 }
8124
Romain Guy5bcdff42009-05-14 21:27:18 -07008125 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008126 bitmap.eraseColor(backgroundColor);
8127 }
8128
8129 computeScroll();
8130 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008131 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008132 canvas.translate(-mScrollX, -mScrollY);
8133
Romain Guy5bcdff42009-05-14 21:27:18 -07008134 // Temporarily remove the dirty mask
8135 int flags = mPrivateFlags;
8136 mPrivateFlags &= ~DIRTY_MASK;
8137
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008138 // Fast path for layouts with no backgrounds
8139 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8140 dispatchDraw(canvas);
8141 } else {
8142 draw(canvas);
8143 }
8144
Romain Guy5bcdff42009-05-14 21:27:18 -07008145 mPrivateFlags = flags;
8146
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008147 canvas.restoreToCount(restoreCount);
8148
8149 if (attachInfo != null) {
8150 // Restore the cached Canvas for our siblings
8151 attachInfo.mCanvas = canvas;
8152 }
Romain Guy8506ab42009-06-11 17:35:47 -07008153
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008154 return bitmap;
8155 }
8156
8157 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 * Indicates whether this View is currently in edit mode. A View is usually
8159 * in edit mode when displayed within a developer tool. For instance, if
8160 * this View is being drawn by a visual user interface builder, this method
8161 * should return true.
8162 *
8163 * Subclasses should check the return value of this method to provide
8164 * different behaviors if their normal behavior might interfere with the
8165 * host environment. For instance: the class spawns a thread in its
8166 * constructor, the drawing code relies on device-specific features, etc.
8167 *
8168 * This method is usually checked in the drawing code of custom widgets.
8169 *
8170 * @return True if this View is in edit mode, false otherwise.
8171 */
8172 public boolean isInEditMode() {
8173 return false;
8174 }
8175
8176 /**
8177 * If the View draws content inside its padding and enables fading edges,
8178 * it needs to support padding offsets. Padding offsets are added to the
8179 * fading edges to extend the length of the fade so that it covers pixels
8180 * drawn inside the padding.
8181 *
8182 * Subclasses of this class should override this method if they need
8183 * to draw content inside the padding.
8184 *
8185 * @return True if padding offset must be applied, false otherwise.
8186 *
8187 * @see #getLeftPaddingOffset()
8188 * @see #getRightPaddingOffset()
8189 * @see #getTopPaddingOffset()
8190 * @see #getBottomPaddingOffset()
8191 *
8192 * @since CURRENT
8193 */
8194 protected boolean isPaddingOffsetRequired() {
8195 return false;
8196 }
8197
8198 /**
8199 * Amount by which to extend the left fading region. Called only when
8200 * {@link #isPaddingOffsetRequired()} returns true.
8201 *
8202 * @return The left padding offset in pixels.
8203 *
8204 * @see #isPaddingOffsetRequired()
8205 *
8206 * @since CURRENT
8207 */
8208 protected int getLeftPaddingOffset() {
8209 return 0;
8210 }
8211
8212 /**
8213 * Amount by which to extend the right fading region. Called only when
8214 * {@link #isPaddingOffsetRequired()} returns true.
8215 *
8216 * @return The right padding offset in pixels.
8217 *
8218 * @see #isPaddingOffsetRequired()
8219 *
8220 * @since CURRENT
8221 */
8222 protected int getRightPaddingOffset() {
8223 return 0;
8224 }
8225
8226 /**
8227 * Amount by which to extend the top fading region. Called only when
8228 * {@link #isPaddingOffsetRequired()} returns true.
8229 *
8230 * @return The top padding offset in pixels.
8231 *
8232 * @see #isPaddingOffsetRequired()
8233 *
8234 * @since CURRENT
8235 */
8236 protected int getTopPaddingOffset() {
8237 return 0;
8238 }
8239
8240 /**
8241 * Amount by which to extend the bottom fading region. Called only when
8242 * {@link #isPaddingOffsetRequired()} returns true.
8243 *
8244 * @return The bottom padding offset in pixels.
8245 *
8246 * @see #isPaddingOffsetRequired()
8247 *
8248 * @since CURRENT
8249 */
8250 protected int getBottomPaddingOffset() {
8251 return 0;
8252 }
8253
8254 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008255 * <p>Indicates whether this view is attached to an hardware accelerated
8256 * window or not.</p>
8257 *
8258 * <p>Even if this method returns true, it does not mean that every call
8259 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8260 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8261 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8262 * window is hardware accelerated,
8263 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8264 * return false, and this method will return true.</p>
8265 *
8266 * @return True if the view is attached to a window and the window is
8267 * hardware accelerated; false in any other case.
8268 */
8269 public boolean isHardwareAccelerated() {
8270 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8271 }
8272
8273 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008274 * Manually render this view (and all of its children) to the given Canvas.
8275 * The view must have already done a full layout before this function is
Chet Haasec75ec332010-12-17 07:44:30 -08008276 * called. When implementing a view, implement {@link #onDraw} instead of
8277 * overriding this method. If you do need to override this method, call
8278 * the superclass version.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008279 *
8280 * @param canvas The Canvas to which the View is rendered.
8281 */
8282 public void draw(Canvas canvas) {
8283 if (ViewDebug.TRACE_HIERARCHY) {
8284 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8285 }
8286
Romain Guy5bcdff42009-05-14 21:27:18 -07008287 final int privateFlags = mPrivateFlags;
8288 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8289 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8290 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008292 /*
8293 * Draw traversal performs several drawing steps which must be executed
8294 * in the appropriate order:
8295 *
8296 * 1. Draw the background
8297 * 2. If necessary, save the canvas' layers to prepare for fading
8298 * 3. Draw view's content
8299 * 4. Draw children
8300 * 5. If necessary, draw the fading edges and restore layers
8301 * 6. Draw decorations (scrollbars for instance)
8302 */
8303
8304 // Step 1, draw the background, if needed
8305 int saveCount;
8306
Romain Guy24443ea2009-05-11 11:56:30 -07008307 if (!dirtyOpaque) {
8308 final Drawable background = mBGDrawable;
8309 if (background != null) {
8310 final int scrollX = mScrollX;
8311 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312
Romain Guy24443ea2009-05-11 11:56:30 -07008313 if (mBackgroundSizeChanged) {
8314 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8315 mBackgroundSizeChanged = false;
8316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008317
Romain Guy24443ea2009-05-11 11:56:30 -07008318 if ((scrollX | scrollY) == 0) {
8319 background.draw(canvas);
8320 } else {
8321 canvas.translate(scrollX, scrollY);
8322 background.draw(canvas);
8323 canvas.translate(-scrollX, -scrollY);
8324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008325 }
8326 }
8327
8328 // skip step 2 & 5 if possible (common case)
8329 final int viewFlags = mViewFlags;
8330 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8331 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8332 if (!verticalEdges && !horizontalEdges) {
8333 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008334 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008335
8336 // Step 4, draw the children
8337 dispatchDraw(canvas);
8338
8339 // Step 6, draw decorations (scrollbars)
8340 onDrawScrollBars(canvas);
8341
8342 // we're done...
8343 return;
8344 }
8345
8346 /*
8347 * Here we do the full fledged routine...
8348 * (this is an uncommon case where speed matters less,
8349 * this is why we repeat some of the tests that have been
8350 * done above)
8351 */
8352
8353 boolean drawTop = false;
8354 boolean drawBottom = false;
8355 boolean drawLeft = false;
8356 boolean drawRight = false;
8357
8358 float topFadeStrength = 0.0f;
8359 float bottomFadeStrength = 0.0f;
8360 float leftFadeStrength = 0.0f;
8361 float rightFadeStrength = 0.0f;
8362
8363 // Step 2, save the canvas' layers
8364 int paddingLeft = mPaddingLeft;
8365 int paddingTop = mPaddingTop;
8366
8367 final boolean offsetRequired = isPaddingOffsetRequired();
8368 if (offsetRequired) {
8369 paddingLeft += getLeftPaddingOffset();
8370 paddingTop += getTopPaddingOffset();
8371 }
8372
8373 int left = mScrollX + paddingLeft;
8374 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8375 int top = mScrollY + paddingTop;
8376 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8377
8378 if (offsetRequired) {
8379 right += getRightPaddingOffset();
8380 bottom += getBottomPaddingOffset();
8381 }
8382
8383 final ScrollabilityCache scrollabilityCache = mScrollCache;
8384 int length = scrollabilityCache.fadingEdgeLength;
8385
8386 // clip the fade length if top and bottom fades overlap
8387 // overlapping fades produce odd-looking artifacts
8388 if (verticalEdges && (top + length > bottom - length)) {
8389 length = (bottom - top) / 2;
8390 }
8391
8392 // also clip horizontal fades if necessary
8393 if (horizontalEdges && (left + length > right - length)) {
8394 length = (right - left) / 2;
8395 }
8396
8397 if (verticalEdges) {
8398 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008399 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008400 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008401 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008402 }
8403
8404 if (horizontalEdges) {
8405 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008406 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008407 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008408 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 }
8410
8411 saveCount = canvas.getSaveCount();
8412
8413 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008414 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008415 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8416
8417 if (drawTop) {
8418 canvas.saveLayer(left, top, right, top + length, null, flags);
8419 }
8420
8421 if (drawBottom) {
8422 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8423 }
8424
8425 if (drawLeft) {
8426 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8427 }
8428
8429 if (drawRight) {
8430 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8431 }
8432 } else {
8433 scrollabilityCache.setFadeColor(solidColor);
8434 }
8435
8436 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008437 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008438
8439 // Step 4, draw the children
8440 dispatchDraw(canvas);
8441
8442 // Step 5, draw the fade effect and restore layers
8443 final Paint p = scrollabilityCache.paint;
8444 final Matrix matrix = scrollabilityCache.matrix;
8445 final Shader fade = scrollabilityCache.shader;
8446 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8447
8448 if (drawTop) {
8449 matrix.setScale(1, fadeHeight * topFadeStrength);
8450 matrix.postTranslate(left, top);
8451 fade.setLocalMatrix(matrix);
8452 canvas.drawRect(left, top, right, top + length, p);
8453 }
8454
8455 if (drawBottom) {
8456 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8457 matrix.postRotate(180);
8458 matrix.postTranslate(left, bottom);
8459 fade.setLocalMatrix(matrix);
8460 canvas.drawRect(left, bottom - length, right, bottom, p);
8461 }
8462
8463 if (drawLeft) {
8464 matrix.setScale(1, fadeHeight * leftFadeStrength);
8465 matrix.postRotate(-90);
8466 matrix.postTranslate(left, top);
8467 fade.setLocalMatrix(matrix);
8468 canvas.drawRect(left, top, left + length, bottom, p);
8469 }
8470
8471 if (drawRight) {
8472 matrix.setScale(1, fadeHeight * rightFadeStrength);
8473 matrix.postRotate(90);
8474 matrix.postTranslate(right, top);
8475 fade.setLocalMatrix(matrix);
8476 canvas.drawRect(right - length, top, right, bottom, p);
8477 }
8478
8479 canvas.restoreToCount(saveCount);
8480
8481 // Step 6, draw decorations (scrollbars)
8482 onDrawScrollBars(canvas);
8483 }
8484
8485 /**
8486 * Override this if your view is known to always be drawn on top of a solid color background,
8487 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8488 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8489 * should be set to 0xFF.
8490 *
8491 * @see #setVerticalFadingEdgeEnabled
8492 * @see #setHorizontalFadingEdgeEnabled
8493 *
8494 * @return The known solid color background for this view, or 0 if the color may vary
8495 */
8496 public int getSolidColor() {
8497 return 0;
8498 }
8499
8500 /**
8501 * Build a human readable string representation of the specified view flags.
8502 *
8503 * @param flags the view flags to convert to a string
8504 * @return a String representing the supplied flags
8505 */
8506 private static String printFlags(int flags) {
8507 String output = "";
8508 int numFlags = 0;
8509 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8510 output += "TAKES_FOCUS";
8511 numFlags++;
8512 }
8513
8514 switch (flags & VISIBILITY_MASK) {
8515 case INVISIBLE:
8516 if (numFlags > 0) {
8517 output += " ";
8518 }
8519 output += "INVISIBLE";
8520 // USELESS HERE numFlags++;
8521 break;
8522 case GONE:
8523 if (numFlags > 0) {
8524 output += " ";
8525 }
8526 output += "GONE";
8527 // USELESS HERE numFlags++;
8528 break;
8529 default:
8530 break;
8531 }
8532 return output;
8533 }
8534
8535 /**
8536 * Build a human readable string representation of the specified private
8537 * view flags.
8538 *
8539 * @param privateFlags the private view flags to convert to a string
8540 * @return a String representing the supplied flags
8541 */
8542 private static String printPrivateFlags(int privateFlags) {
8543 String output = "";
8544 int numFlags = 0;
8545
8546 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8547 output += "WANTS_FOCUS";
8548 numFlags++;
8549 }
8550
8551 if ((privateFlags & FOCUSED) == FOCUSED) {
8552 if (numFlags > 0) {
8553 output += " ";
8554 }
8555 output += "FOCUSED";
8556 numFlags++;
8557 }
8558
8559 if ((privateFlags & SELECTED) == SELECTED) {
8560 if (numFlags > 0) {
8561 output += " ";
8562 }
8563 output += "SELECTED";
8564 numFlags++;
8565 }
8566
8567 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8568 if (numFlags > 0) {
8569 output += " ";
8570 }
8571 output += "IS_ROOT_NAMESPACE";
8572 numFlags++;
8573 }
8574
8575 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8576 if (numFlags > 0) {
8577 output += " ";
8578 }
8579 output += "HAS_BOUNDS";
8580 numFlags++;
8581 }
8582
8583 if ((privateFlags & DRAWN) == DRAWN) {
8584 if (numFlags > 0) {
8585 output += " ";
8586 }
8587 output += "DRAWN";
8588 // USELESS HERE numFlags++;
8589 }
8590 return output;
8591 }
8592
8593 /**
8594 * <p>Indicates whether or not this view's layout will be requested during
8595 * the next hierarchy layout pass.</p>
8596 *
8597 * @return true if the layout will be forced during next layout pass
8598 */
8599 public boolean isLayoutRequested() {
8600 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8601 }
8602
8603 /**
8604 * Assign a size and position to a view and all of its
8605 * descendants
8606 *
8607 * <p>This is the second phase of the layout mechanism.
8608 * (The first is measuring). In this phase, each parent calls
8609 * layout on all of its children to position them.
8610 * This is typically done using the child measurements
8611 * that were stored in the measure pass().
8612 *
8613 * Derived classes with children should override
8614 * onLayout. In that method, they should
Chet Haase21cd1382010-09-01 17:42:29 -07008615 * call layout on each of their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008616 *
8617 * @param l Left position, relative to parent
8618 * @param t Top position, relative to parent
8619 * @param r Right position, relative to parent
8620 * @param b Bottom position, relative to parent
8621 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008622 @SuppressWarnings({"unchecked"})
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008623 public final void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008624 int oldL = mLeft;
8625 int oldT = mTop;
8626 int oldB = mBottom;
8627 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628 boolean changed = setFrame(l, t, r, b);
8629 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8630 if (ViewDebug.TRACE_HIERARCHY) {
8631 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8632 }
8633
8634 onLayout(changed, l, t, r, b);
8635 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008636
8637 if (mOnLayoutChangeListeners != null) {
8638 ArrayList<OnLayoutChangeListener> listenersCopy =
8639 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8640 int numListeners = listenersCopy.size();
8641 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07008642 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07008643 }
8644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008645 }
8646 mPrivateFlags &= ~FORCE_LAYOUT;
8647 }
8648
8649 /**
8650 * Called from layout when this view should
8651 * assign a size and position to each of its children.
8652 *
8653 * Derived classes with children should override
8654 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008655 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 * @param changed This is a new size or position for this view
8657 * @param left Left position, relative to parent
8658 * @param top Top position, relative to parent
8659 * @param right Right position, relative to parent
8660 * @param bottom Bottom position, relative to parent
8661 */
8662 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8663 }
8664
8665 /**
8666 * Assign a size and position to this view.
8667 *
8668 * This is called from layout.
8669 *
8670 * @param left Left position, relative to parent
8671 * @param top Top position, relative to parent
8672 * @param right Right position, relative to parent
8673 * @param bottom Bottom position, relative to parent
8674 * @return true if the new size and position are different than the
8675 * previous ones
8676 * {@hide}
8677 */
8678 protected boolean setFrame(int left, int top, int right, int bottom) {
8679 boolean changed = false;
8680
8681 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008682 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008683 + right + "," + bottom + ")");
8684 }
8685
8686 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8687 changed = true;
8688
8689 // Remember our drawn bit
8690 int drawn = mPrivateFlags & DRAWN;
8691
8692 // Invalidate our old position
8693 invalidate();
8694
8695
8696 int oldWidth = mRight - mLeft;
8697 int oldHeight = mBottom - mTop;
8698
8699 mLeft = left;
8700 mTop = top;
8701 mRight = right;
8702 mBottom = bottom;
8703
8704 mPrivateFlags |= HAS_BOUNDS;
8705
8706 int newWidth = right - left;
8707 int newHeight = bottom - top;
8708
8709 if (newWidth != oldWidth || newHeight != oldHeight) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08008710 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8711 // A change in dimension means an auto-centered pivot point changes, too
8712 mMatrixDirty = true;
8713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8715 }
8716
8717 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8718 // If we are visible, force the DRAWN bit to on so that
8719 // this invalidate will go through (at least to our parent).
8720 // This is because someone may have invalidated this view
Chet Haase6c7ad5d2010-12-28 08:40:00 -08008721 // before this call to setFrame came in, thereby clearing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008722 // the DRAWN bit.
8723 mPrivateFlags |= DRAWN;
8724 invalidate();
8725 }
8726
8727 // Reset drawn bit to original value (invalidate turns it off)
8728 mPrivateFlags |= drawn;
8729
8730 mBackgroundSizeChanged = true;
8731 }
8732 return changed;
8733 }
8734
8735 /**
8736 * Finalize inflating a view from XML. This is called as the last phase
8737 * of inflation, after all child views have been added.
8738 *
8739 * <p>Even if the subclass overrides onFinishInflate, they should always be
8740 * sure to call the super method, so that we get called.
8741 */
8742 protected void onFinishInflate() {
8743 }
8744
8745 /**
8746 * Returns the resources associated with this view.
8747 *
8748 * @return Resources object.
8749 */
8750 public Resources getResources() {
8751 return mResources;
8752 }
8753
8754 /**
8755 * Invalidates the specified Drawable.
8756 *
8757 * @param drawable the drawable to invalidate
8758 */
8759 public void invalidateDrawable(Drawable drawable) {
8760 if (verifyDrawable(drawable)) {
8761 final Rect dirty = drawable.getBounds();
8762 final int scrollX = mScrollX;
8763 final int scrollY = mScrollY;
8764
8765 invalidate(dirty.left + scrollX, dirty.top + scrollY,
8766 dirty.right + scrollX, dirty.bottom + scrollY);
8767 }
8768 }
8769
8770 /**
8771 * Schedules an action on a drawable to occur at a specified time.
8772 *
8773 * @param who the recipient of the action
8774 * @param what the action to run on the drawable
8775 * @param when the time at which the action must occur. Uses the
8776 * {@link SystemClock#uptimeMillis} timebase.
8777 */
8778 public void scheduleDrawable(Drawable who, Runnable what, long when) {
8779 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8780 mAttachInfo.mHandler.postAtTime(what, who, when);
8781 }
8782 }
8783
8784 /**
8785 * Cancels a scheduled action on a drawable.
8786 *
8787 * @param who the recipient of the action
8788 * @param what the action to cancel
8789 */
8790 public void unscheduleDrawable(Drawable who, Runnable what) {
8791 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8792 mAttachInfo.mHandler.removeCallbacks(what, who);
8793 }
8794 }
8795
8796 /**
8797 * Unschedule any events associated with the given Drawable. This can be
8798 * used when selecting a new Drawable into a view, so that the previous
8799 * one is completely unscheduled.
8800 *
8801 * @param who The Drawable to unschedule.
8802 *
8803 * @see #drawableStateChanged
8804 */
8805 public void unscheduleDrawable(Drawable who) {
8806 if (mAttachInfo != null) {
8807 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
8808 }
8809 }
8810
8811 /**
8812 * If your view subclass is displaying its own Drawable objects, it should
8813 * override this function and return true for any Drawable it is
8814 * displaying. This allows animations for those drawables to be
8815 * scheduled.
8816 *
8817 * <p>Be sure to call through to the super class when overriding this
8818 * function.
8819 *
8820 * @param who The Drawable to verify. Return true if it is one you are
8821 * displaying, else return the result of calling through to the
8822 * super class.
8823 *
8824 * @return boolean If true than the Drawable is being displayed in the
8825 * view; else false and it is not allowed to animate.
8826 *
8827 * @see #unscheduleDrawable
8828 * @see #drawableStateChanged
8829 */
8830 protected boolean verifyDrawable(Drawable who) {
8831 return who == mBGDrawable;
8832 }
8833
8834 /**
8835 * This function is called whenever the state of the view changes in such
8836 * a way that it impacts the state of drawables being shown.
8837 *
8838 * <p>Be sure to call through to the superclass when overriding this
8839 * function.
8840 *
8841 * @see Drawable#setState
8842 */
8843 protected void drawableStateChanged() {
8844 Drawable d = mBGDrawable;
8845 if (d != null && d.isStateful()) {
8846 d.setState(getDrawableState());
8847 }
8848 }
8849
8850 /**
8851 * Call this to force a view to update its drawable state. This will cause
8852 * drawableStateChanged to be called on this view. Views that are interested
8853 * in the new state should call getDrawableState.
8854 *
8855 * @see #drawableStateChanged
8856 * @see #getDrawableState
8857 */
8858 public void refreshDrawableState() {
8859 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
8860 drawableStateChanged();
8861
8862 ViewParent parent = mParent;
8863 if (parent != null) {
8864 parent.childDrawableStateChanged(this);
8865 }
8866 }
8867
8868 /**
8869 * Return an array of resource IDs of the drawable states representing the
8870 * current state of the view.
8871 *
8872 * @return The current drawable state
8873 *
8874 * @see Drawable#setState
8875 * @see #drawableStateChanged
8876 * @see #onCreateDrawableState
8877 */
8878 public final int[] getDrawableState() {
8879 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
8880 return mDrawableState;
8881 } else {
8882 mDrawableState = onCreateDrawableState(0);
8883 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
8884 return mDrawableState;
8885 }
8886 }
8887
8888 /**
8889 * Generate the new {@link android.graphics.drawable.Drawable} state for
8890 * this view. This is called by the view
8891 * system when the cached Drawable state is determined to be invalid. To
8892 * retrieve the current state, you should use {@link #getDrawableState}.
8893 *
8894 * @param extraSpace if non-zero, this is the number of extra entries you
8895 * would like in the returned array in which you can place your own
8896 * states.
8897 *
8898 * @return Returns an array holding the current {@link Drawable} state of
8899 * the view.
8900 *
8901 * @see #mergeDrawableStates
8902 */
8903 protected int[] onCreateDrawableState(int extraSpace) {
8904 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
8905 mParent instanceof View) {
8906 return ((View) mParent).onCreateDrawableState(extraSpace);
8907 }
8908
8909 int[] drawableState;
8910
8911 int privateFlags = mPrivateFlags;
8912
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008913 int viewStateIndex = 0;
8914 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
8915 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
8916 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07008917 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008918 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
8919 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08008920 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
8921 // This is set if HW acceleration is requested, even if the current
8922 // process doesn't allow it. This is just to allow app preview
8923 // windows to better match their app.
8924 viewStateIndex |= VIEW_STATE_ACCELERATED;
8925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926
8927 drawableState = VIEW_STATE_SETS[viewStateIndex];
8928
8929 //noinspection ConstantIfStatement
8930 if (false) {
8931 Log.i("View", "drawableStateIndex=" + viewStateIndex);
8932 Log.i("View", toString()
8933 + " pressed=" + ((privateFlags & PRESSED) != 0)
8934 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
8935 + " fo=" + hasFocus()
8936 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008937 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008938 + ": " + Arrays.toString(drawableState));
8939 }
8940
8941 if (extraSpace == 0) {
8942 return drawableState;
8943 }
8944
8945 final int[] fullState;
8946 if (drawableState != null) {
8947 fullState = new int[drawableState.length + extraSpace];
8948 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
8949 } else {
8950 fullState = new int[extraSpace];
8951 }
8952
8953 return fullState;
8954 }
8955
8956 /**
8957 * Merge your own state values in <var>additionalState</var> into the base
8958 * state values <var>baseState</var> that were returned by
8959 * {@link #onCreateDrawableState}.
8960 *
8961 * @param baseState The base state values returned by
8962 * {@link #onCreateDrawableState}, which will be modified to also hold your
8963 * own additional state values.
8964 *
8965 * @param additionalState The additional state values you would like
8966 * added to <var>baseState</var>; this array is not modified.
8967 *
8968 * @return As a convenience, the <var>baseState</var> array you originally
8969 * passed into the function is returned.
8970 *
8971 * @see #onCreateDrawableState
8972 */
8973 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
8974 final int N = baseState.length;
8975 int i = N - 1;
8976 while (i >= 0 && baseState[i] == 0) {
8977 i--;
8978 }
8979 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
8980 return baseState;
8981 }
8982
8983 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07008984 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
8985 * on all Drawable objects associated with this view.
8986 */
8987 public void jumpDrawablesToCurrentState() {
8988 if (mBGDrawable != null) {
8989 mBGDrawable.jumpToCurrentState();
8990 }
8991 }
8992
8993 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008994 * Sets the background color for this view.
8995 * @param color the color of the background
8996 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008997 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07008999 if (mBGDrawable instanceof ColorDrawable) {
9000 ((ColorDrawable) mBGDrawable).setColor(color);
9001 } else {
9002 setBackgroundDrawable(new ColorDrawable(color));
9003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009004 }
9005
9006 /**
9007 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07009008 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009009 * @param resid The identifier of the resource.
9010 * @attr ref android.R.styleable#View_background
9011 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009012 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009013 public void setBackgroundResource(int resid) {
9014 if (resid != 0 && resid == mBackgroundResource) {
9015 return;
9016 }
9017
9018 Drawable d= null;
9019 if (resid != 0) {
9020 d = mResources.getDrawable(resid);
9021 }
9022 setBackgroundDrawable(d);
9023
9024 mBackgroundResource = resid;
9025 }
9026
9027 /**
9028 * Set the background to a given Drawable, or remove the background. If the
9029 * background has padding, this View's padding is set to the background's
9030 * padding. However, when a background is removed, this View's padding isn't
9031 * touched. If setting the padding is desired, please use
9032 * {@link #setPadding(int, int, int, int)}.
9033 *
9034 * @param d The Drawable to use as the background, or null to remove the
9035 * background
9036 */
9037 public void setBackgroundDrawable(Drawable d) {
9038 boolean requestLayout = false;
9039
9040 mBackgroundResource = 0;
9041
9042 /*
9043 * Regardless of whether we're setting a new background or not, we want
9044 * to clear the previous drawable.
9045 */
9046 if (mBGDrawable != null) {
9047 mBGDrawable.setCallback(null);
9048 unscheduleDrawable(mBGDrawable);
9049 }
9050
9051 if (d != null) {
9052 Rect padding = sThreadLocal.get();
9053 if (padding == null) {
9054 padding = new Rect();
9055 sThreadLocal.set(padding);
9056 }
9057 if (d.getPadding(padding)) {
9058 setPadding(padding.left, padding.top, padding.right, padding.bottom);
9059 }
9060
9061 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
9062 // if it has a different minimum size, we should layout again
9063 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9064 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9065 requestLayout = true;
9066 }
9067
9068 d.setCallback(this);
9069 if (d.isStateful()) {
9070 d.setState(getDrawableState());
9071 }
9072 d.setVisible(getVisibility() == VISIBLE, false);
9073 mBGDrawable = d;
9074
9075 if ((mPrivateFlags & SKIP_DRAW) != 0) {
9076 mPrivateFlags &= ~SKIP_DRAW;
9077 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9078 requestLayout = true;
9079 }
9080 } else {
9081 /* Remove the background */
9082 mBGDrawable = null;
9083
9084 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9085 /*
9086 * This view ONLY drew the background before and we're removing
9087 * the background, so now it won't draw anything
9088 * (hence we SKIP_DRAW)
9089 */
9090 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9091 mPrivateFlags |= SKIP_DRAW;
9092 }
9093
9094 /*
9095 * When the background is set, we try to apply its padding to this
9096 * View. When the background is removed, we don't touch this View's
9097 * padding. This is noted in the Javadocs. Hence, we don't need to
9098 * requestLayout(), the invalidate() below is sufficient.
9099 */
9100
9101 // The old background's minimum size could have affected this
9102 // View's layout, so let's requestLayout
9103 requestLayout = true;
9104 }
9105
Romain Guy8f1344f52009-05-15 16:03:59 -07009106 computeOpaqueFlags();
9107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108 if (requestLayout) {
9109 requestLayout();
9110 }
9111
9112 mBackgroundSizeChanged = true;
9113 invalidate();
9114 }
9115
9116 /**
9117 * Gets the background drawable
9118 * @return The drawable used as the background for this view, if any.
9119 */
9120 public Drawable getBackground() {
9121 return mBGDrawable;
9122 }
9123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009124 /**
9125 * Sets the padding. The view may add on the space required to display
9126 * the scrollbars, depending on the style and visibility of the scrollbars.
9127 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9128 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9129 * from the values set in this call.
9130 *
9131 * @attr ref android.R.styleable#View_padding
9132 * @attr ref android.R.styleable#View_paddingBottom
9133 * @attr ref android.R.styleable#View_paddingLeft
9134 * @attr ref android.R.styleable#View_paddingRight
9135 * @attr ref android.R.styleable#View_paddingTop
9136 * @param left the left padding in pixels
9137 * @param top the top padding in pixels
9138 * @param right the right padding in pixels
9139 * @param bottom the bottom padding in pixels
9140 */
9141 public void setPadding(int left, int top, int right, int bottom) {
9142 boolean changed = false;
9143
Adam Powell20232d02010-12-08 21:08:53 -08009144 mUserPaddingLeft = left;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009145 mUserPaddingRight = right;
9146 mUserPaddingBottom = bottom;
9147
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009148 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07009149
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009150 // Common case is there are no scroll bars.
9151 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009152 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
Adam Powell20232d02010-12-08 21:08:53 -08009153 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9154 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009155 ? 0 : getVerticalScrollbarWidth();
Adam Powell20232d02010-12-08 21:08:53 -08009156 switch (mVerticalScrollbarPosition) {
9157 case SCROLLBAR_POSITION_DEFAULT:
9158 case SCROLLBAR_POSITION_RIGHT:
9159 right += offset;
9160 break;
9161 case SCROLLBAR_POSITION_LEFT:
9162 left += offset;
9163 break;
9164 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009165 }
Adam Powell20232d02010-12-08 21:08:53 -08009166 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009167 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9168 ? 0 : getHorizontalScrollbarHeight();
9169 }
9170 }
Romain Guy8506ab42009-06-11 17:35:47 -07009171
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009172 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009173 changed = true;
9174 mPaddingLeft = left;
9175 }
9176 if (mPaddingTop != top) {
9177 changed = true;
9178 mPaddingTop = top;
9179 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009180 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009182 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009183 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009184 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009185 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009186 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009187 }
9188
9189 if (changed) {
9190 requestLayout();
9191 }
9192 }
9193
9194 /**
9195 * Returns the top padding of this view.
9196 *
9197 * @return the top padding in pixels
9198 */
9199 public int getPaddingTop() {
9200 return mPaddingTop;
9201 }
9202
9203 /**
9204 * Returns the bottom padding of this view. If there are inset and enabled
9205 * scrollbars, this value may include the space required to display the
9206 * scrollbars as well.
9207 *
9208 * @return the bottom padding in pixels
9209 */
9210 public int getPaddingBottom() {
9211 return mPaddingBottom;
9212 }
9213
9214 /**
9215 * Returns the left padding of this view. If there are inset and enabled
9216 * scrollbars, this value may include the space required to display the
9217 * scrollbars as well.
9218 *
9219 * @return the left padding in pixels
9220 */
9221 public int getPaddingLeft() {
9222 return mPaddingLeft;
9223 }
9224
9225 /**
9226 * Returns the right padding of this view. If there are inset and enabled
9227 * scrollbars, this value may include the space required to display the
9228 * scrollbars as well.
9229 *
9230 * @return the right padding in pixels
9231 */
9232 public int getPaddingRight() {
9233 return mPaddingRight;
9234 }
9235
9236 /**
9237 * Changes the selection state of this view. A view can be selected or not.
9238 * Note that selection is not the same as focus. Views are typically
9239 * selected in the context of an AdapterView like ListView or GridView;
9240 * the selected view is the view that is highlighted.
9241 *
9242 * @param selected true if the view must be selected, false otherwise
9243 */
9244 public void setSelected(boolean selected) {
9245 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9246 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009247 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009248 invalidate();
9249 refreshDrawableState();
9250 dispatchSetSelected(selected);
9251 }
9252 }
9253
9254 /**
9255 * Dispatch setSelected to all of this View's children.
9256 *
9257 * @see #setSelected(boolean)
9258 *
9259 * @param selected The new selected state
9260 */
9261 protected void dispatchSetSelected(boolean selected) {
9262 }
9263
9264 /**
9265 * Indicates the selection state of this view.
9266 *
9267 * @return true if the view is selected, false otherwise
9268 */
9269 @ViewDebug.ExportedProperty
9270 public boolean isSelected() {
9271 return (mPrivateFlags & SELECTED) != 0;
9272 }
9273
9274 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009275 * Changes the activated state of this view. A view can be activated or not.
9276 * Note that activation is not the same as selection. Selection is
9277 * a transient property, representing the view (hierarchy) the user is
9278 * currently interacting with. Activation is a longer-term state that the
9279 * user can move views in and out of. For example, in a list view with
9280 * single or multiple selection enabled, the views in the current selection
9281 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9282 * here.) The activated state is propagated down to children of the view it
9283 * is set on.
9284 *
9285 * @param activated true if the view must be activated, false otherwise
9286 */
9287 public void setActivated(boolean activated) {
9288 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9289 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
9290 invalidate();
9291 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009292 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009293 }
9294 }
9295
9296 /**
9297 * Dispatch setActivated to all of this View's children.
9298 *
9299 * @see #setActivated(boolean)
9300 *
9301 * @param activated The new activated state
9302 */
9303 protected void dispatchSetActivated(boolean activated) {
9304 }
9305
9306 /**
9307 * Indicates the activation state of this view.
9308 *
9309 * @return true if the view is activated, false otherwise
9310 */
9311 @ViewDebug.ExportedProperty
9312 public boolean isActivated() {
9313 return (mPrivateFlags & ACTIVATED) != 0;
9314 }
9315
9316 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9318 * observer can be used to get notifications when global events, like
9319 * layout, happen.
9320 *
9321 * The returned ViewTreeObserver observer is not guaranteed to remain
9322 * valid for the lifetime of this View. If the caller of this method keeps
9323 * a long-lived reference to ViewTreeObserver, it should always check for
9324 * the return value of {@link ViewTreeObserver#isAlive()}.
9325 *
9326 * @return The ViewTreeObserver for this view's hierarchy.
9327 */
9328 public ViewTreeObserver getViewTreeObserver() {
9329 if (mAttachInfo != null) {
9330 return mAttachInfo.mTreeObserver;
9331 }
9332 if (mFloatingTreeObserver == null) {
9333 mFloatingTreeObserver = new ViewTreeObserver();
9334 }
9335 return mFloatingTreeObserver;
9336 }
9337
9338 /**
9339 * <p>Finds the topmost view in the current view hierarchy.</p>
9340 *
9341 * @return the topmost view containing this view
9342 */
9343 public View getRootView() {
9344 if (mAttachInfo != null) {
9345 final View v = mAttachInfo.mRootView;
9346 if (v != null) {
9347 return v;
9348 }
9349 }
Romain Guy8506ab42009-06-11 17:35:47 -07009350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009351 View parent = this;
9352
9353 while (parent.mParent != null && parent.mParent instanceof View) {
9354 parent = (View) parent.mParent;
9355 }
9356
9357 return parent;
9358 }
9359
9360 /**
9361 * <p>Computes the coordinates of this view on the screen. The argument
9362 * must be an array of two integers. After the method returns, the array
9363 * contains the x and y location in that order.</p>
9364 *
9365 * @param location an array of two integers in which to hold the coordinates
9366 */
9367 public void getLocationOnScreen(int[] location) {
9368 getLocationInWindow(location);
9369
9370 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009371 if (info != null) {
9372 location[0] += info.mWindowLeft;
9373 location[1] += info.mWindowTop;
9374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009375 }
9376
9377 /**
9378 * <p>Computes the coordinates of this view in its window. The argument
9379 * must be an array of two integers. After the method returns, the array
9380 * contains the x and y location in that order.</p>
9381 *
9382 * @param location an array of two integers in which to hold the coordinates
9383 */
9384 public void getLocationInWindow(int[] location) {
9385 if (location == null || location.length < 2) {
9386 throw new IllegalArgumentException("location must be an array of "
9387 + "two integers");
9388 }
9389
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009390 location[0] = mLeft + (int) (mTranslationX + 0.5f);
9391 location[1] = mTop + (int) (mTranslationY + 0.5f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009392
9393 ViewParent viewParent = mParent;
9394 while (viewParent instanceof View) {
9395 final View view = (View)viewParent;
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009396 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
9397 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009398 viewParent = view.mParent;
9399 }
Romain Guy8506ab42009-06-11 17:35:47 -07009400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 if (viewParent instanceof ViewRoot) {
9402 // *cough*
9403 final ViewRoot vr = (ViewRoot)viewParent;
9404 location[1] -= vr.mCurScrollY;
9405 }
9406 }
9407
9408 /**
9409 * {@hide}
9410 * @param id the id of the view to be found
9411 * @return the view of the specified id, null if cannot be found
9412 */
9413 protected View findViewTraversal(int id) {
9414 if (id == mID) {
9415 return this;
9416 }
9417 return null;
9418 }
9419
9420 /**
9421 * {@hide}
9422 * @param tag the tag of the view to be found
9423 * @return the view of specified tag, null if cannot be found
9424 */
9425 protected View findViewWithTagTraversal(Object tag) {
9426 if (tag != null && tag.equals(mTag)) {
9427 return this;
9428 }
9429 return null;
9430 }
9431
9432 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009433 * {@hide}
9434 * @param predicate The predicate to evaluate.
9435 * @return The first view that matches the predicate or null.
9436 */
9437 protected View findViewByPredicateTraversal(Predicate<View> predicate) {
9438 if (predicate.apply(this)) {
9439 return this;
9440 }
9441 return null;
9442 }
9443
9444 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009445 * Look for a child view with the given id. If this view has the given
9446 * id, return this view.
9447 *
9448 * @param id The id to search for.
9449 * @return The view that has the given id in the hierarchy or null
9450 */
9451 public final View findViewById(int id) {
9452 if (id < 0) {
9453 return null;
9454 }
9455 return findViewTraversal(id);
9456 }
9457
9458 /**
9459 * Look for a child view with the given tag. If this view has the given
9460 * tag, return this view.
9461 *
9462 * @param tag The tag to search for, using "tag.equals(getTag())".
9463 * @return The View that has the given tag in the hierarchy or null
9464 */
9465 public final View findViewWithTag(Object tag) {
9466 if (tag == null) {
9467 return null;
9468 }
9469 return findViewWithTagTraversal(tag);
9470 }
9471
9472 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009473 * {@hide}
9474 * Look for a child view that matches the specified predicate.
9475 * If this view matches the predicate, return this view.
9476 *
9477 * @param predicate The predicate to evaluate.
9478 * @return The first view that matches the predicate or null.
9479 */
9480 public final View findViewByPredicate(Predicate<View> predicate) {
9481 return findViewByPredicateTraversal(predicate);
9482 }
9483
9484 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009485 * Sets the identifier for this view. The identifier does not have to be
9486 * unique in this view's hierarchy. The identifier should be a positive
9487 * number.
9488 *
9489 * @see #NO_ID
9490 * @see #getId
9491 * @see #findViewById
9492 *
9493 * @param id a number used to identify the view
9494 *
9495 * @attr ref android.R.styleable#View_id
9496 */
9497 public void setId(int id) {
9498 mID = id;
9499 }
9500
9501 /**
9502 * {@hide}
9503 *
9504 * @param isRoot true if the view belongs to the root namespace, false
9505 * otherwise
9506 */
9507 public void setIsRootNamespace(boolean isRoot) {
9508 if (isRoot) {
9509 mPrivateFlags |= IS_ROOT_NAMESPACE;
9510 } else {
9511 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9512 }
9513 }
9514
9515 /**
9516 * {@hide}
9517 *
9518 * @return true if the view belongs to the root namespace, false otherwise
9519 */
9520 public boolean isRootNamespace() {
9521 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9522 }
9523
9524 /**
9525 * Returns this view's identifier.
9526 *
9527 * @return a positive integer used to identify the view or {@link #NO_ID}
9528 * if the view has no ID
9529 *
9530 * @see #setId
9531 * @see #findViewById
9532 * @attr ref android.R.styleable#View_id
9533 */
9534 @ViewDebug.CapturedViewProperty
9535 public int getId() {
9536 return mID;
9537 }
9538
9539 /**
9540 * Returns this view's tag.
9541 *
9542 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07009543 *
9544 * @see #setTag(Object)
9545 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009546 */
9547 @ViewDebug.ExportedProperty
9548 public Object getTag() {
9549 return mTag;
9550 }
9551
9552 /**
9553 * Sets the tag associated with this view. A tag can be used to mark
9554 * a view in its hierarchy and does not have to be unique within the
9555 * hierarchy. Tags can also be used to store data within a view without
9556 * resorting to another data structure.
9557 *
9558 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07009559 *
9560 * @see #getTag()
9561 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009562 */
9563 public void setTag(final Object tag) {
9564 mTag = tag;
9565 }
9566
9567 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009568 * Returns the tag associated with this view and the specified key.
9569 *
9570 * @param key The key identifying the tag
9571 *
9572 * @return the Object stored in this view as a tag
9573 *
9574 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009575 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009576 */
9577 public Object getTag(int key) {
9578 SparseArray<Object> tags = null;
9579 synchronized (sTagsLock) {
9580 if (sTags != null) {
9581 tags = sTags.get(this);
9582 }
9583 }
9584
9585 if (tags != null) return tags.get(key);
9586 return null;
9587 }
9588
9589 /**
9590 * Sets a tag associated with this view and a key. A tag can be used
9591 * to mark a view in its hierarchy and does not have to be unique within
9592 * the hierarchy. Tags can also be used to store data within a view
9593 * without resorting to another data structure.
9594 *
9595 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009596 * application to ensure it is unique (see the <a
9597 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9598 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009599 * the Android framework or not associated with any package will cause
9600 * an {@link IllegalArgumentException} to be thrown.
9601 *
9602 * @param key The key identifying the tag
9603 * @param tag An Object to tag the view with
9604 *
9605 * @throws IllegalArgumentException If they specified key is not valid
9606 *
9607 * @see #setTag(Object)
9608 * @see #getTag(int)
9609 */
9610 public void setTag(int key, final Object tag) {
9611 // If the package id is 0x00 or 0x01, it's either an undefined package
9612 // or a framework id
9613 if ((key >>> 24) < 2) {
9614 throw new IllegalArgumentException("The key must be an application-specific "
9615 + "resource id.");
9616 }
9617
9618 setTagInternal(this, key, tag);
9619 }
9620
9621 /**
9622 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9623 * framework id.
9624 *
9625 * @hide
9626 */
9627 public void setTagInternal(int key, Object tag) {
9628 if ((key >>> 24) != 0x1) {
9629 throw new IllegalArgumentException("The key must be a framework-specific "
9630 + "resource id.");
9631 }
9632
Romain Guy8506ab42009-06-11 17:35:47 -07009633 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009634 }
9635
9636 private static void setTagInternal(View view, int key, Object tag) {
9637 SparseArray<Object> tags = null;
9638 synchronized (sTagsLock) {
9639 if (sTags == null) {
9640 sTags = new WeakHashMap<View, SparseArray<Object>>();
9641 } else {
9642 tags = sTags.get(view);
9643 }
9644 }
9645
9646 if (tags == null) {
9647 tags = new SparseArray<Object>(2);
9648 synchronized (sTagsLock) {
9649 sTags.put(view, tags);
9650 }
9651 }
9652
9653 tags.put(key, tag);
9654 }
9655
9656 /**
Romain Guy13922e02009-05-12 17:56:14 -07009657 * @param consistency The type of consistency. See ViewDebug for more information.
9658 *
9659 * @hide
9660 */
9661 protected boolean dispatchConsistencyCheck(int consistency) {
9662 return onConsistencyCheck(consistency);
9663 }
9664
9665 /**
9666 * Method that subclasses should implement to check their consistency. The type of
9667 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009668 *
Romain Guy13922e02009-05-12 17:56:14 -07009669 * @param consistency The type of consistency. See ViewDebug for more information.
9670 *
9671 * @throws IllegalStateException if the view is in an inconsistent state.
9672 *
9673 * @hide
9674 */
9675 protected boolean onConsistencyCheck(int consistency) {
9676 boolean result = true;
9677
9678 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9679 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9680
9681 if (checkLayout) {
9682 if (getParent() == null) {
9683 result = false;
9684 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9685 "View " + this + " does not have a parent.");
9686 }
9687
9688 if (mAttachInfo == null) {
9689 result = false;
9690 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9691 "View " + this + " is not attached to a window.");
9692 }
9693 }
9694
9695 if (checkDrawing) {
9696 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9697 // from their draw() method
9698
9699 if ((mPrivateFlags & DRAWN) != DRAWN &&
9700 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9701 result = false;
9702 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9703 "View " + this + " was invalidated but its drawing cache is valid.");
9704 }
9705 }
9706
9707 return result;
9708 }
9709
9710 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009711 * Prints information about this view in the log output, with the tag
9712 * {@link #VIEW_LOG_TAG}.
9713 *
9714 * @hide
9715 */
9716 public void debug() {
9717 debug(0);
9718 }
9719
9720 /**
9721 * Prints information about this view in the log output, with the tag
9722 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
9723 * indentation defined by the <code>depth</code>.
9724 *
9725 * @param depth the indentation level
9726 *
9727 * @hide
9728 */
9729 protected void debug(int depth) {
9730 String output = debugIndent(depth - 1);
9731
9732 output += "+ " + this;
9733 int id = getId();
9734 if (id != -1) {
9735 output += " (id=" + id + ")";
9736 }
9737 Object tag = getTag();
9738 if (tag != null) {
9739 output += " (tag=" + tag + ")";
9740 }
9741 Log.d(VIEW_LOG_TAG, output);
9742
9743 if ((mPrivateFlags & FOCUSED) != 0) {
9744 output = debugIndent(depth) + " FOCUSED";
9745 Log.d(VIEW_LOG_TAG, output);
9746 }
9747
9748 output = debugIndent(depth);
9749 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
9750 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
9751 + "} ";
9752 Log.d(VIEW_LOG_TAG, output);
9753
9754 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
9755 || mPaddingBottom != 0) {
9756 output = debugIndent(depth);
9757 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
9758 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
9759 Log.d(VIEW_LOG_TAG, output);
9760 }
9761
9762 output = debugIndent(depth);
9763 output += "mMeasureWidth=" + mMeasuredWidth +
9764 " mMeasureHeight=" + mMeasuredHeight;
9765 Log.d(VIEW_LOG_TAG, output);
9766
9767 output = debugIndent(depth);
9768 if (mLayoutParams == null) {
9769 output += "BAD! no layout params";
9770 } else {
9771 output = mLayoutParams.debug(output);
9772 }
9773 Log.d(VIEW_LOG_TAG, output);
9774
9775 output = debugIndent(depth);
9776 output += "flags={";
9777 output += View.printFlags(mViewFlags);
9778 output += "}";
9779 Log.d(VIEW_LOG_TAG, output);
9780
9781 output = debugIndent(depth);
9782 output += "privateFlags={";
9783 output += View.printPrivateFlags(mPrivateFlags);
9784 output += "}";
9785 Log.d(VIEW_LOG_TAG, output);
9786 }
9787
9788 /**
9789 * Creates an string of whitespaces used for indentation.
9790 *
9791 * @param depth the indentation level
9792 * @return a String containing (depth * 2 + 3) * 2 white spaces
9793 *
9794 * @hide
9795 */
9796 protected static String debugIndent(int depth) {
9797 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
9798 for (int i = 0; i < (depth * 2) + 3; i++) {
9799 spaces.append(' ').append(' ');
9800 }
9801 return spaces.toString();
9802 }
9803
9804 /**
9805 * <p>Return the offset of the widget's text baseline from the widget's top
9806 * boundary. If this widget does not support baseline alignment, this
9807 * method returns -1. </p>
9808 *
9809 * @return the offset of the baseline within the widget's bounds or -1
9810 * if baseline alignment is not supported
9811 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07009812 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009813 public int getBaseline() {
9814 return -1;
9815 }
9816
9817 /**
9818 * Call this when something has changed which has invalidated the
9819 * layout of this view. This will schedule a layout pass of the view
9820 * tree.
9821 */
9822 public void requestLayout() {
9823 if (ViewDebug.TRACE_HIERARCHY) {
9824 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
9825 }
9826
9827 mPrivateFlags |= FORCE_LAYOUT;
9828
9829 if (mParent != null && !mParent.isLayoutRequested()) {
9830 mParent.requestLayout();
9831 }
9832 }
9833
9834 /**
9835 * Forces this view to be laid out during the next layout pass.
9836 * This method does not call requestLayout() or forceLayout()
9837 * on the parent.
9838 */
9839 public void forceLayout() {
9840 mPrivateFlags |= FORCE_LAYOUT;
9841 }
9842
9843 /**
9844 * <p>
9845 * This is called to find out how big a view should be. The parent
9846 * supplies constraint information in the width and height parameters.
9847 * </p>
9848 *
9849 * <p>
9850 * The actual mesurement work of a view is performed in
9851 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
9852 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
9853 * </p>
9854 *
9855 *
9856 * @param widthMeasureSpec Horizontal space requirements as imposed by the
9857 * parent
9858 * @param heightMeasureSpec Vertical space requirements as imposed by the
9859 * parent
9860 *
9861 * @see #onMeasure(int, int)
9862 */
9863 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
9864 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
9865 widthMeasureSpec != mOldWidthMeasureSpec ||
9866 heightMeasureSpec != mOldHeightMeasureSpec) {
9867
9868 // first clears the measured dimension flag
9869 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9870
9871 if (ViewDebug.TRACE_HIERARCHY) {
9872 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
9873 }
9874
9875 // measure ourselves, this should set the measured dimension flag back
9876 onMeasure(widthMeasureSpec, heightMeasureSpec);
9877
9878 // flag not set, setMeasuredDimension() was not invoked, we raise
9879 // an exception to warn the developer
9880 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9881 throw new IllegalStateException("onMeasure() did not set the"
9882 + " measured dimension by calling"
9883 + " setMeasuredDimension()");
9884 }
9885
9886 mPrivateFlags |= LAYOUT_REQUIRED;
9887 }
9888
9889 mOldWidthMeasureSpec = widthMeasureSpec;
9890 mOldHeightMeasureSpec = heightMeasureSpec;
9891 }
9892
9893 /**
9894 * <p>
9895 * Measure the view and its content to determine the measured width and the
9896 * measured height. This method is invoked by {@link #measure(int, int)} and
9897 * should be overriden by subclasses to provide accurate and efficient
9898 * measurement of their contents.
9899 * </p>
9900 *
9901 * <p>
9902 * <strong>CONTRACT:</strong> When overriding this method, you
9903 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
9904 * measured width and height of this view. Failure to do so will trigger an
9905 * <code>IllegalStateException</code>, thrown by
9906 * {@link #measure(int, int)}. Calling the superclass'
9907 * {@link #onMeasure(int, int)} is a valid use.
9908 * </p>
9909 *
9910 * <p>
9911 * The base class implementation of measure defaults to the background size,
9912 * unless a larger size is allowed by the MeasureSpec. Subclasses should
9913 * override {@link #onMeasure(int, int)} to provide better measurements of
9914 * their content.
9915 * </p>
9916 *
9917 * <p>
9918 * If this method is overridden, it is the subclass's responsibility to make
9919 * sure the measured height and width are at least the view's minimum height
9920 * and width ({@link #getSuggestedMinimumHeight()} and
9921 * {@link #getSuggestedMinimumWidth()}).
9922 * </p>
9923 *
9924 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
9925 * The requirements are encoded with
9926 * {@link android.view.View.MeasureSpec}.
9927 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
9928 * The requirements are encoded with
9929 * {@link android.view.View.MeasureSpec}.
9930 *
9931 * @see #getMeasuredWidth()
9932 * @see #getMeasuredHeight()
9933 * @see #setMeasuredDimension(int, int)
9934 * @see #getSuggestedMinimumHeight()
9935 * @see #getSuggestedMinimumWidth()
9936 * @see android.view.View.MeasureSpec#getMode(int)
9937 * @see android.view.View.MeasureSpec#getSize(int)
9938 */
9939 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9940 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
9941 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
9942 }
9943
9944 /**
9945 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
9946 * measured width and measured height. Failing to do so will trigger an
9947 * exception at measurement time.</p>
9948 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08009949 * @param measuredWidth The measured width of this view. May be a complex
9950 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
9951 * {@link #MEASURED_STATE_TOO_SMALL}.
9952 * @param measuredHeight The measured height of this view. May be a complex
9953 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
9954 * {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009955 */
9956 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
9957 mMeasuredWidth = measuredWidth;
9958 mMeasuredHeight = measuredHeight;
9959
9960 mPrivateFlags |= MEASURED_DIMENSION_SET;
9961 }
9962
9963 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08009964 * Merge two states as returned by {@link #getMeasuredState()}.
9965 * @param curState The current state as returned from a view or the result
9966 * of combining multiple views.
9967 * @param newState The new view state to combine.
9968 * @return Returns a new integer reflecting the combination of the two
9969 * states.
9970 */
9971 public static int combineMeasuredStates(int curState, int newState) {
9972 return curState | newState;
9973 }
9974
9975 /**
9976 * Version of {@link #resolveSizeAndState(int, int, int)}
9977 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
9978 */
9979 public static int resolveSize(int size, int measureSpec) {
9980 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
9981 }
9982
9983 /**
9984 * Utility to reconcile a desired size and state, with constraints imposed
9985 * by a MeasureSpec. Will take the desired size, unless a different size
9986 * is imposed by the constraints. The returned value is a compound integer,
9987 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
9988 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
9989 * size is smaller than the size the view wants to be.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009990 *
9991 * @param size How big the view wants to be
9992 * @param measureSpec Constraints imposed by the parent
Dianne Hackborn189ee182010-12-02 21:48:53 -08009993 * @return Size information bit mask as defined by
9994 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009995 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08009996 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009997 int result = size;
9998 int specMode = MeasureSpec.getMode(measureSpec);
9999 int specSize = MeasureSpec.getSize(measureSpec);
10000 switch (specMode) {
10001 case MeasureSpec.UNSPECIFIED:
10002 result = size;
10003 break;
10004 case MeasureSpec.AT_MOST:
Dianne Hackborn189ee182010-12-02 21:48:53 -080010005 if (specSize < size) {
10006 result = specSize | MEASURED_STATE_TOO_SMALL;
10007 } else {
10008 result = size;
10009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010010 break;
10011 case MeasureSpec.EXACTLY:
10012 result = specSize;
10013 break;
10014 }
Dianne Hackborn189ee182010-12-02 21:48:53 -080010015 return result | (childMeasuredState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010016 }
10017
10018 /**
10019 * Utility to return a default size. Uses the supplied size if the
10020 * MeasureSpec imposed no contraints. Will get larger if allowed
10021 * by the MeasureSpec.
10022 *
10023 * @param size Default size for this view
10024 * @param measureSpec Constraints imposed by the parent
10025 * @return The size this view should be.
10026 */
10027 public static int getDefaultSize(int size, int measureSpec) {
10028 int result = size;
10029 int specMode = MeasureSpec.getMode(measureSpec);
10030 int specSize = MeasureSpec.getSize(measureSpec);
10031
10032 switch (specMode) {
10033 case MeasureSpec.UNSPECIFIED:
10034 result = size;
10035 break;
10036 case MeasureSpec.AT_MOST:
10037 case MeasureSpec.EXACTLY:
10038 result = specSize;
10039 break;
10040 }
10041 return result;
10042 }
10043
10044 /**
10045 * Returns the suggested minimum height that the view should use. This
10046 * returns the maximum of the view's minimum height
10047 * and the background's minimum height
10048 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10049 * <p>
10050 * When being used in {@link #onMeasure(int, int)}, the caller should still
10051 * ensure the returned height is within the requirements of the parent.
10052 *
10053 * @return The suggested minimum height of the view.
10054 */
10055 protected int getSuggestedMinimumHeight() {
10056 int suggestedMinHeight = mMinHeight;
10057
10058 if (mBGDrawable != null) {
10059 final int bgMinHeight = mBGDrawable.getMinimumHeight();
10060 if (suggestedMinHeight < bgMinHeight) {
10061 suggestedMinHeight = bgMinHeight;
10062 }
10063 }
10064
10065 return suggestedMinHeight;
10066 }
10067
10068 /**
10069 * Returns the suggested minimum width that the view should use. This
10070 * returns the maximum of the view's minimum width)
10071 * and the background's minimum width
10072 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10073 * <p>
10074 * When being used in {@link #onMeasure(int, int)}, the caller should still
10075 * ensure the returned width is within the requirements of the parent.
10076 *
10077 * @return The suggested minimum width of the view.
10078 */
10079 protected int getSuggestedMinimumWidth() {
10080 int suggestedMinWidth = mMinWidth;
10081
10082 if (mBGDrawable != null) {
10083 final int bgMinWidth = mBGDrawable.getMinimumWidth();
10084 if (suggestedMinWidth < bgMinWidth) {
10085 suggestedMinWidth = bgMinWidth;
10086 }
10087 }
10088
10089 return suggestedMinWidth;
10090 }
10091
10092 /**
10093 * Sets the minimum height of the view. It is not guaranteed the view will
10094 * be able to achieve this minimum height (for example, if its parent layout
10095 * constrains it with less available height).
10096 *
10097 * @param minHeight The minimum height the view will try to be.
10098 */
10099 public void setMinimumHeight(int minHeight) {
10100 mMinHeight = minHeight;
10101 }
10102
10103 /**
10104 * Sets the minimum width of the view. It is not guaranteed the view will
10105 * be able to achieve this minimum width (for example, if its parent layout
10106 * constrains it with less available width).
10107 *
10108 * @param minWidth The minimum width the view will try to be.
10109 */
10110 public void setMinimumWidth(int minWidth) {
10111 mMinWidth = minWidth;
10112 }
10113
10114 /**
10115 * Get the animation currently associated with this view.
10116 *
10117 * @return The animation that is currently playing or
10118 * scheduled to play for this view.
10119 */
10120 public Animation getAnimation() {
10121 return mCurrentAnimation;
10122 }
10123
10124 /**
10125 * Start the specified animation now.
10126 *
10127 * @param animation the animation to start now
10128 */
10129 public void startAnimation(Animation animation) {
10130 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10131 setAnimation(animation);
10132 invalidate();
10133 }
10134
10135 /**
10136 * Cancels any animations for this view.
10137 */
10138 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -080010139 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -080010140 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -080010141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010142 mCurrentAnimation = null;
10143 }
10144
10145 /**
10146 * Sets the next animation to play for this view.
10147 * If you want the animation to play immediately, use
10148 * startAnimation. This method provides allows fine-grained
10149 * control over the start time and invalidation, but you
10150 * must make sure that 1) the animation has a start time set, and
10151 * 2) the view will be invalidated when the animation is supposed to
10152 * start.
10153 *
10154 * @param animation The next animation, or null.
10155 */
10156 public void setAnimation(Animation animation) {
10157 mCurrentAnimation = animation;
10158 if (animation != null) {
10159 animation.reset();
10160 }
10161 }
10162
10163 /**
10164 * Invoked by a parent ViewGroup to notify the start of the animation
10165 * currently associated with this view. If you override this method,
10166 * always call super.onAnimationStart();
10167 *
10168 * @see #setAnimation(android.view.animation.Animation)
10169 * @see #getAnimation()
10170 */
10171 protected void onAnimationStart() {
10172 mPrivateFlags |= ANIMATION_STARTED;
10173 }
10174
10175 /**
10176 * Invoked by a parent ViewGroup to notify the end of the animation
10177 * currently associated with this view. If you override this method,
10178 * always call super.onAnimationEnd();
10179 *
10180 * @see #setAnimation(android.view.animation.Animation)
10181 * @see #getAnimation()
10182 */
10183 protected void onAnimationEnd() {
10184 mPrivateFlags &= ~ANIMATION_STARTED;
10185 }
10186
10187 /**
10188 * Invoked if there is a Transform that involves alpha. Subclass that can
10189 * draw themselves with the specified alpha should return true, and then
10190 * respect that alpha when their onDraw() is called. If this returns false
10191 * then the view may be redirected to draw into an offscreen buffer to
10192 * fulfill the request, which will look fine, but may be slower than if the
10193 * subclass handles it internally. The default implementation returns false.
10194 *
10195 * @param alpha The alpha (0..255) to apply to the view's drawing
10196 * @return true if the view can draw with the specified alpha.
10197 */
10198 protected boolean onSetAlpha(int alpha) {
10199 return false;
10200 }
10201
10202 /**
10203 * This is used by the RootView to perform an optimization when
10204 * the view hierarchy contains one or several SurfaceView.
10205 * SurfaceView is always considered transparent, but its children are not,
10206 * therefore all View objects remove themselves from the global transparent
10207 * region (passed as a parameter to this function).
10208 *
10209 * @param region The transparent region for this ViewRoot (window).
10210 *
10211 * @return Returns true if the effective visibility of the view at this
10212 * point is opaque, regardless of the transparent region; returns false
10213 * if it is possible for underlying windows to be seen behind the view.
10214 *
10215 * {@hide}
10216 */
10217 public boolean gatherTransparentRegion(Region region) {
10218 final AttachInfo attachInfo = mAttachInfo;
10219 if (region != null && attachInfo != null) {
10220 final int pflags = mPrivateFlags;
10221 if ((pflags & SKIP_DRAW) == 0) {
10222 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10223 // remove it from the transparent region.
10224 final int[] location = attachInfo.mTransparentLocation;
10225 getLocationInWindow(location);
10226 region.op(location[0], location[1], location[0] + mRight - mLeft,
10227 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10228 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10229 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10230 // exists, so we remove the background drawable's non-transparent
10231 // parts from this transparent region.
10232 applyDrawableToTransparentRegion(mBGDrawable, region);
10233 }
10234 }
10235 return true;
10236 }
10237
10238 /**
10239 * Play a sound effect for this view.
10240 *
10241 * <p>The framework will play sound effects for some built in actions, such as
10242 * clicking, but you may wish to play these effects in your widget,
10243 * for instance, for internal navigation.
10244 *
10245 * <p>The sound effect will only be played if sound effects are enabled by the user, and
10246 * {@link #isSoundEffectsEnabled()} is true.
10247 *
10248 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10249 */
10250 public void playSoundEffect(int soundConstant) {
10251 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10252 return;
10253 }
10254 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10255 }
10256
10257 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010258 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010259 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010260 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010261 *
10262 * <p>The framework will provide haptic feedback for some built in actions,
10263 * such as long presses, but you may wish to provide feedback for your
10264 * own widget.
10265 *
10266 * <p>The feedback will only be performed if
10267 * {@link #isHapticFeedbackEnabled()} is true.
10268 *
10269 * @param feedbackConstant One of the constants defined in
10270 * {@link HapticFeedbackConstants}
10271 */
10272 public boolean performHapticFeedback(int feedbackConstant) {
10273 return performHapticFeedback(feedbackConstant, 0);
10274 }
10275
10276 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010277 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010278 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010279 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010280 *
10281 * @param feedbackConstant One of the constants defined in
10282 * {@link HapticFeedbackConstants}
10283 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10284 */
10285 public boolean performHapticFeedback(int feedbackConstant, int flags) {
10286 if (mAttachInfo == null) {
10287 return false;
10288 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010289 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010290 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010291 && !isHapticFeedbackEnabled()) {
10292 return false;
10293 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010294 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10295 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010296 }
10297
10298 /**
Christopher Tate2c095f32010-10-04 14:13:40 -070010299 * !!! TODO: real docs
10300 *
10301 * The base class implementation makes the thumbnail the same size and appearance
10302 * as the view itself, and positions it with its center at the touch point.
10303 */
Christopher Tatea0374192010-10-05 13:06:41 -070010304 public static class DragThumbnailBuilder {
10305 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010306
10307 /**
10308 * Construct a thumbnail builder object for use with the given view.
10309 * @param view
10310 */
10311 public DragThumbnailBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010312 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010313 }
10314
Chris Tate6b391282010-10-14 15:48:59 -070010315 final public View getView() {
10316 return mView.get();
10317 }
10318
Christopher Tate2c095f32010-10-04 14:13:40 -070010319 /**
10320 * Provide the draggable-thumbnail metrics for the operation: the dimensions of
10321 * the thumbnail image itself, and the point within that thumbnail that should
10322 * be centered under the touch location while dragging.
10323 * <p>
10324 * The default implementation sets the dimensions of the thumbnail to be the
10325 * same as the dimensions of the View itself and centers the thumbnail under
10326 * the touch point.
10327 *
10328 * @param thumbnailSize The application should set the {@code x} member of this
10329 * parameter to the desired thumbnail width, and the {@code y} member to
10330 * the desired height.
10331 * @param thumbnailTouchPoint The application should set this point to be the
10332 * location within the thumbnail that should track directly underneath
10333 * the touch point on the screen during a drag.
10334 */
10335 public void onProvideThumbnailMetrics(Point thumbnailSize, Point thumbnailTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070010336 final View view = mView.get();
10337 if (view != null) {
10338 thumbnailSize.set(view.getWidth(), view.getHeight());
10339 thumbnailTouchPoint.set(thumbnailSize.x / 2, thumbnailSize.y / 2);
10340 } else {
10341 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10342 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010343 }
10344
10345 /**
10346 * Draw the thumbnail image for the upcoming drag. The thumbnail canvas was
10347 * created with the dimensions supplied by the onProvideThumbnailMetrics()
10348 * callback.
10349 *
10350 * @param canvas
10351 */
10352 public void onDrawThumbnail(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070010353 final View view = mView.get();
10354 if (view != null) {
10355 view.draw(canvas);
10356 } else {
10357 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag thumb but no view");
10358 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010359 }
10360 }
10361
10362 /**
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010363 * Drag and drop. App calls startDrag(), then callbacks to the thumbnail builder's
10364 * onProvideThumbnailMetrics() and onDrawThumbnail() methods happen, then the drag
10365 * operation is handed over to the OS.
Christopher Tatea53146c2010-09-07 11:57:52 -070010366 * !!! TODO: real docs
Christopher Tate407b4e92010-11-30 17:14:08 -080010367 *
10368 * @param data !!! TODO
10369 * @param thumbBuilder !!! TODO
10370 * @param myWindowOnly When {@code true}, indicates that the drag operation should be
10371 * restricted to the calling application. In this case only the calling application
10372 * will see any DragEvents related to this drag operation.
10373 * @param myLocalState An arbitrary object that will be passed as part of every DragEvent
10374 * delivered to the calling application during the course of the current drag operation.
10375 * This object is private to the application that called startDrag(), and is not
10376 * visible to other applications. It provides a lightweight way for the application to
10377 * propagate information from the initiator to the recipient of a drag within its own
10378 * application; for example, to help disambiguate between 'copy' and 'move' semantics.
10379 * @return {@code true} if the drag operation was initiated successfully; {@code false} if
10380 * an error prevented the drag from taking place.
Christopher Tatea53146c2010-09-07 11:57:52 -070010381 */
Christopher Tate2c095f32010-10-04 14:13:40 -070010382 public final boolean startDrag(ClipData data, DragThumbnailBuilder thumbBuilder,
Christopher Tate407b4e92010-11-30 17:14:08 -080010383 boolean myWindowOnly, Object myLocalState) {
Christopher Tate2c095f32010-10-04 14:13:40 -070010384 if (ViewDebug.DEBUG_DRAG) {
10385 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " local=" + myWindowOnly);
Christopher Tatea53146c2010-09-07 11:57:52 -070010386 }
10387 boolean okay = false;
10388
Christopher Tate2c095f32010-10-04 14:13:40 -070010389 Point thumbSize = new Point();
10390 Point thumbTouchPoint = new Point();
10391 thumbBuilder.onProvideThumbnailMetrics(thumbSize, thumbTouchPoint);
10392
10393 if ((thumbSize.x < 0) || (thumbSize.y < 0) ||
10394 (thumbTouchPoint.x < 0) || (thumbTouchPoint.y < 0)) {
10395 throw new IllegalStateException("Drag thumb dimensions must not be negative");
10396 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010397
Chris Tatea32dcf72010-10-14 12:13:50 -070010398 if (ViewDebug.DEBUG_DRAG) {
10399 Log.d(VIEW_LOG_TAG, "drag thumb: width=" + thumbSize.x + " height=" + thumbSize.y
10400 + " thumbX=" + thumbTouchPoint.x + " thumbY=" + thumbTouchPoint.y);
10401 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010402 Surface surface = new Surface();
10403 try {
10404 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Chris Tatea32dcf72010-10-14 12:13:50 -070010405 myWindowOnly, thumbSize.x, thumbSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070010406 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070010407 + " surface=" + surface);
10408 if (token != null) {
10409 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070010410 try {
Chris Tate6b391282010-10-14 15:48:59 -070010411 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate2c095f32010-10-04 14:13:40 -070010412 thumbBuilder.onDrawThumbnail(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070010413 } finally {
10414 surface.unlockCanvasAndPost(canvas);
10415 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010416
Christopher Tate407b4e92010-11-30 17:14:08 -080010417 final ViewRoot root = getViewRoot();
10418
10419 // Cache the local state object for delivery with DragEvents
10420 root.setLocalDragState(myLocalState);
10421
Christopher Tate2c095f32010-10-04 14:13:40 -070010422 // repurpose 'thumbSize' for the last touch point
Christopher Tate407b4e92010-11-30 17:14:08 -080010423 root.getLastTouchPoint(thumbSize);
Christopher Tate2c095f32010-10-04 14:13:40 -070010424
Christopher Tatea53146c2010-09-07 11:57:52 -070010425 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate2c095f32010-10-04 14:13:40 -070010426 (float) thumbSize.x, (float) thumbSize.y,
10427 (float) thumbTouchPoint.x, (float) thumbTouchPoint.y, data);
10428 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070010429 }
10430 } catch (Exception e) {
10431 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
10432 surface.destroy();
10433 }
10434
10435 return okay;
10436 }
10437
Christopher Tatea53146c2010-09-07 11:57:52 -070010438 /**
10439 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
10440 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
10441 *
10442 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
10443 * being dragged. onDragEvent() should return 'true' if the view can handle
10444 * a drop of that content. A view that returns 'false' here will receive no
10445 * further calls to onDragEvent() about the drag/drop operation.
10446 *
10447 * For DRAG_ENTERED, event.getClipDescription() describes the content being
10448 * dragged. This will be the same content description passed in the
10449 * DRAG_STARTED_EVENT invocation.
10450 *
10451 * For DRAG_EXITED, event.getClipDescription() describes the content being
10452 * dragged. This will be the same content description passed in the
10453 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
10454 * drag-acceptance visual state.
10455 *
10456 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10457 * coordinates of the current drag point. The view must return 'true' if it
10458 * can accept a drop of the current drag content, false otherwise.
10459 *
10460 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10461 * within the view; also, event.getClipData() returns the full data payload
10462 * being dropped. The view should return 'true' if it consumed the dropped
10463 * content, 'false' if it did not.
10464 *
10465 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
10466 * to its normal visual state.
10467 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010468 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070010469 return false;
10470 }
10471
10472 /**
10473 * Views typically don't need to override dispatchDragEvent(); it just calls
Chris Tate32affef2010-10-18 15:29:21 -070010474 * onDragEvent(event) and passes the result up appropriately.
Christopher Tatea53146c2010-09-07 11:57:52 -070010475 */
10476 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070010477 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10478 && mOnDragListener.onDrag(this, event)) {
10479 return true;
10480 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010481 return onDragEvent(event);
10482 }
10483
10484 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070010485 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
10486 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070010487 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070010488 */
10489 public void onCloseSystemDialogs(String reason) {
10490 }
10491
10492 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010493 * Given a Drawable whose bounds have been set to draw into this view,
10494 * update a Region being computed for {@link #gatherTransparentRegion} so
10495 * that any non-transparent parts of the Drawable are removed from the
10496 * given transparent region.
10497 *
10498 * @param dr The Drawable whose transparency is to be applied to the region.
10499 * @param region A Region holding the current transparency information,
10500 * where any parts of the region that are set are considered to be
10501 * transparent. On return, this region will be modified to have the
10502 * transparency information reduced by the corresponding parts of the
10503 * Drawable that are not transparent.
10504 * {@hide}
10505 */
10506 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
10507 if (DBG) {
10508 Log.i("View", "Getting transparent region for: " + this);
10509 }
10510 final Region r = dr.getTransparentRegion();
10511 final Rect db = dr.getBounds();
10512 final AttachInfo attachInfo = mAttachInfo;
10513 if (r != null && attachInfo != null) {
10514 final int w = getRight()-getLeft();
10515 final int h = getBottom()-getTop();
10516 if (db.left > 0) {
10517 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
10518 r.op(0, 0, db.left, h, Region.Op.UNION);
10519 }
10520 if (db.right < w) {
10521 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
10522 r.op(db.right, 0, w, h, Region.Op.UNION);
10523 }
10524 if (db.top > 0) {
10525 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
10526 r.op(0, 0, w, db.top, Region.Op.UNION);
10527 }
10528 if (db.bottom < h) {
10529 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
10530 r.op(0, db.bottom, w, h, Region.Op.UNION);
10531 }
10532 final int[] location = attachInfo.mTransparentLocation;
10533 getLocationInWindow(location);
10534 r.translate(location[0], location[1]);
10535 region.op(r, Region.Op.INTERSECT);
10536 } else {
10537 region.op(db, Region.Op.DIFFERENCE);
10538 }
10539 }
10540
Adam Powelle14579b2009-12-16 18:39:52 -080010541 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 mHasPerformedLongPress = false;
10543
10544 if (mPendingCheckForLongPress == null) {
10545 mPendingCheckForLongPress = new CheckForLongPress();
10546 }
10547 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080010548 postDelayed(mPendingCheckForLongPress,
10549 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010550 }
10551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010552 /**
10553 * Inflate a view from an XML resource. This convenience method wraps the {@link
10554 * LayoutInflater} class, which provides a full range of options for view inflation.
10555 *
10556 * @param context The Context object for your activity or application.
10557 * @param resource The resource ID to inflate
10558 * @param root A view group that will be the parent. Used to properly inflate the
10559 * layout_* parameters.
10560 * @see LayoutInflater
10561 */
10562 public static View inflate(Context context, int resource, ViewGroup root) {
10563 LayoutInflater factory = LayoutInflater.from(context);
10564 return factory.inflate(resource, root);
10565 }
Romain Guy33e72ae2010-07-17 12:40:29 -070010566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010567 /**
Adam Powell637d3372010-08-25 14:37:03 -070010568 * Scroll the view with standard behavior for scrolling beyond the normal
10569 * content boundaries. Views that call this method should override
10570 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
10571 * results of an over-scroll operation.
10572 *
10573 * Views can use this method to handle any touch or fling-based scrolling.
10574 *
10575 * @param deltaX Change in X in pixels
10576 * @param deltaY Change in Y in pixels
10577 * @param scrollX Current X scroll value in pixels before applying deltaX
10578 * @param scrollY Current Y scroll value in pixels before applying deltaY
10579 * @param scrollRangeX Maximum content scroll range along the X axis
10580 * @param scrollRangeY Maximum content scroll range along the Y axis
10581 * @param maxOverScrollX Number of pixels to overscroll by in either direction
10582 * along the X axis.
10583 * @param maxOverScrollY Number of pixels to overscroll by in either direction
10584 * along the Y axis.
10585 * @param isTouchEvent true if this scroll operation is the result of a touch event.
10586 * @return true if scrolling was clamped to an over-scroll boundary along either
10587 * axis, false otherwise.
10588 */
10589 protected boolean overScrollBy(int deltaX, int deltaY,
10590 int scrollX, int scrollY,
10591 int scrollRangeX, int scrollRangeY,
10592 int maxOverScrollX, int maxOverScrollY,
10593 boolean isTouchEvent) {
10594 final int overScrollMode = mOverScrollMode;
10595 final boolean canScrollHorizontal =
10596 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
10597 final boolean canScrollVertical =
10598 computeVerticalScrollRange() > computeVerticalScrollExtent();
10599 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
10600 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
10601 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
10602 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
10603
10604 int newScrollX = scrollX + deltaX;
10605 if (!overScrollHorizontal) {
10606 maxOverScrollX = 0;
10607 }
10608
10609 int newScrollY = scrollY + deltaY;
10610 if (!overScrollVertical) {
10611 maxOverScrollY = 0;
10612 }
10613
10614 // Clamp values if at the limits and record
10615 final int left = -maxOverScrollX;
10616 final int right = maxOverScrollX + scrollRangeX;
10617 final int top = -maxOverScrollY;
10618 final int bottom = maxOverScrollY + scrollRangeY;
10619
10620 boolean clampedX = false;
10621 if (newScrollX > right) {
10622 newScrollX = right;
10623 clampedX = true;
10624 } else if (newScrollX < left) {
10625 newScrollX = left;
10626 clampedX = true;
10627 }
10628
10629 boolean clampedY = false;
10630 if (newScrollY > bottom) {
10631 newScrollY = bottom;
10632 clampedY = true;
10633 } else if (newScrollY < top) {
10634 newScrollY = top;
10635 clampedY = true;
10636 }
10637
10638 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
10639
10640 return clampedX || clampedY;
10641 }
10642
10643 /**
10644 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
10645 * respond to the results of an over-scroll operation.
10646 *
10647 * @param scrollX New X scroll value in pixels
10648 * @param scrollY New Y scroll value in pixels
10649 * @param clampedX True if scrollX was clamped to an over-scroll boundary
10650 * @param clampedY True if scrollY was clamped to an over-scroll boundary
10651 */
10652 protected void onOverScrolled(int scrollX, int scrollY,
10653 boolean clampedX, boolean clampedY) {
10654 // Intentionally empty.
10655 }
10656
10657 /**
10658 * Returns the over-scroll mode for this view. The result will be
10659 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10660 * (allow over-scrolling only if the view content is larger than the container),
10661 * or {@link #OVER_SCROLL_NEVER}.
10662 *
10663 * @return This view's over-scroll mode.
10664 */
10665 public int getOverScrollMode() {
10666 return mOverScrollMode;
10667 }
10668
10669 /**
10670 * Set the over-scroll mode for this view. Valid over-scroll modes are
10671 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10672 * (allow over-scrolling only if the view content is larger than the container),
10673 * or {@link #OVER_SCROLL_NEVER}.
10674 *
10675 * Setting the over-scroll mode of a view will have an effect only if the
10676 * view is capable of scrolling.
10677 *
10678 * @param overScrollMode The new over-scroll mode for this view.
10679 */
10680 public void setOverScrollMode(int overScrollMode) {
10681 if (overScrollMode != OVER_SCROLL_ALWAYS &&
10682 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
10683 overScrollMode != OVER_SCROLL_NEVER) {
10684 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
10685 }
10686 mOverScrollMode = overScrollMode;
10687 }
10688
10689 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010690 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
10691 * Each MeasureSpec represents a requirement for either the width or the height.
10692 * A MeasureSpec is comprised of a size and a mode. There are three possible
10693 * modes:
10694 * <dl>
10695 * <dt>UNSPECIFIED</dt>
10696 * <dd>
10697 * The parent has not imposed any constraint on the child. It can be whatever size
10698 * it wants.
10699 * </dd>
10700 *
10701 * <dt>EXACTLY</dt>
10702 * <dd>
10703 * The parent has determined an exact size for the child. The child is going to be
10704 * given those bounds regardless of how big it wants to be.
10705 * </dd>
10706 *
10707 * <dt>AT_MOST</dt>
10708 * <dd>
10709 * The child can be as large as it wants up to the specified size.
10710 * </dd>
10711 * </dl>
10712 *
10713 * MeasureSpecs are implemented as ints to reduce object allocation. This class
10714 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
10715 */
10716 public static class MeasureSpec {
10717 private static final int MODE_SHIFT = 30;
10718 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
10719
10720 /**
10721 * Measure specification mode: The parent has not imposed any constraint
10722 * on the child. It can be whatever size it wants.
10723 */
10724 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
10725
10726 /**
10727 * Measure specification mode: The parent has determined an exact size
10728 * for the child. The child is going to be given those bounds regardless
10729 * of how big it wants to be.
10730 */
10731 public static final int EXACTLY = 1 << MODE_SHIFT;
10732
10733 /**
10734 * Measure specification mode: The child can be as large as it wants up
10735 * to the specified size.
10736 */
10737 public static final int AT_MOST = 2 << MODE_SHIFT;
10738
10739 /**
10740 * Creates a measure specification based on the supplied size and mode.
10741 *
10742 * The mode must always be one of the following:
10743 * <ul>
10744 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
10745 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
10746 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
10747 * </ul>
10748 *
10749 * @param size the size of the measure specification
10750 * @param mode the mode of the measure specification
10751 * @return the measure specification based on size and mode
10752 */
10753 public static int makeMeasureSpec(int size, int mode) {
10754 return size + mode;
10755 }
10756
10757 /**
10758 * Extracts the mode from the supplied measure specification.
10759 *
10760 * @param measureSpec the measure specification to extract the mode from
10761 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
10762 * {@link android.view.View.MeasureSpec#AT_MOST} or
10763 * {@link android.view.View.MeasureSpec#EXACTLY}
10764 */
10765 public static int getMode(int measureSpec) {
10766 return (measureSpec & MODE_MASK);
10767 }
10768
10769 /**
10770 * Extracts the size from the supplied measure specification.
10771 *
10772 * @param measureSpec the measure specification to extract the size from
10773 * @return the size in pixels defined in the supplied measure specification
10774 */
10775 public static int getSize(int measureSpec) {
10776 return (measureSpec & ~MODE_MASK);
10777 }
10778
10779 /**
10780 * Returns a String representation of the specified measure
10781 * specification.
10782 *
10783 * @param measureSpec the measure specification to convert to a String
10784 * @return a String with the following format: "MeasureSpec: MODE SIZE"
10785 */
10786 public static String toString(int measureSpec) {
10787 int mode = getMode(measureSpec);
10788 int size = getSize(measureSpec);
10789
10790 StringBuilder sb = new StringBuilder("MeasureSpec: ");
10791
10792 if (mode == UNSPECIFIED)
10793 sb.append("UNSPECIFIED ");
10794 else if (mode == EXACTLY)
10795 sb.append("EXACTLY ");
10796 else if (mode == AT_MOST)
10797 sb.append("AT_MOST ");
10798 else
10799 sb.append(mode).append(" ");
10800
10801 sb.append(size);
10802 return sb.toString();
10803 }
10804 }
10805
10806 class CheckForLongPress implements Runnable {
10807
10808 private int mOriginalWindowAttachCount;
10809
10810 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070010811 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010812 && mOriginalWindowAttachCount == mWindowAttachCount) {
10813 if (performLongClick()) {
10814 mHasPerformedLongPress = true;
10815 }
10816 }
10817 }
10818
10819 public void rememberWindowAttachCount() {
10820 mOriginalWindowAttachCount = mWindowAttachCount;
10821 }
10822 }
Adam Powelle14579b2009-12-16 18:39:52 -080010823
10824 private final class CheckForTap implements Runnable {
10825 public void run() {
10826 mPrivateFlags &= ~PREPRESSED;
10827 mPrivateFlags |= PRESSED;
10828 refreshDrawableState();
10829 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
10830 postCheckForLongClick(ViewConfiguration.getTapTimeout());
10831 }
10832 }
10833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010834
Adam Powella35d7682010-03-12 14:48:13 -080010835 private final class PerformClick implements Runnable {
10836 public void run() {
10837 performClick();
10838 }
10839 }
10840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010841 /**
10842 * Interface definition for a callback to be invoked when a key event is
10843 * dispatched to this view. The callback will be invoked before the key
10844 * event is given to the view.
10845 */
10846 public interface OnKeyListener {
10847 /**
10848 * Called when a key is dispatched to a view. This allows listeners to
10849 * get a chance to respond before the target view.
10850 *
10851 * @param v The view the key has been dispatched to.
10852 * @param keyCode The code for the physical key that was pressed
10853 * @param event The KeyEvent object containing full information about
10854 * the event.
10855 * @return True if the listener has consumed the event, false otherwise.
10856 */
10857 boolean onKey(View v, int keyCode, KeyEvent event);
10858 }
10859
10860 /**
10861 * Interface definition for a callback to be invoked when a touch event is
10862 * dispatched to this view. The callback will be invoked before the touch
10863 * event is given to the view.
10864 */
10865 public interface OnTouchListener {
10866 /**
10867 * Called when a touch event is dispatched to a view. This allows listeners to
10868 * get a chance to respond before the target view.
10869 *
10870 * @param v The view the touch event has been dispatched to.
10871 * @param event The MotionEvent object containing full information about
10872 * the event.
10873 * @return True if the listener has consumed the event, false otherwise.
10874 */
10875 boolean onTouch(View v, MotionEvent event);
10876 }
10877
10878 /**
10879 * Interface definition for a callback to be invoked when a view has been clicked and held.
10880 */
10881 public interface OnLongClickListener {
10882 /**
10883 * Called when a view has been clicked and held.
10884 *
10885 * @param v The view that was clicked and held.
10886 *
10887 * return True if the callback consumed the long click, false otherwise
10888 */
10889 boolean onLongClick(View v);
10890 }
10891
10892 /**
Chris Tate32affef2010-10-18 15:29:21 -070010893 * Interface definition for a callback to be invoked when a drag is being dispatched
10894 * to this view. The callback will be invoked before the hosting view's own
10895 * onDrag(event) method. If the listener wants to fall back to the hosting view's
10896 * onDrag(event) behavior, it should return 'false' from this callback.
10897 */
10898 public interface OnDragListener {
10899 /**
10900 * Called when a drag event is dispatched to a view. This allows listeners
10901 * to get a chance to override base View behavior.
10902 *
10903 * @param v The view the drag has been dispatched to.
10904 * @param event The DragEvent object containing full information
10905 * about the event.
10906 * @return true if the listener consumed the DragEvent, false in order to fall
10907 * back to the view's default handling.
10908 */
10909 boolean onDrag(View v, DragEvent event);
10910 }
10911
10912 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010913 * Interface definition for a callback to be invoked when the focus state of
10914 * a view changed.
10915 */
10916 public interface OnFocusChangeListener {
10917 /**
10918 * Called when the focus state of a view has changed.
10919 *
10920 * @param v The view whose state has changed.
10921 * @param hasFocus The new focus state of v.
10922 */
10923 void onFocusChange(View v, boolean hasFocus);
10924 }
10925
10926 /**
10927 * Interface definition for a callback to be invoked when a view is clicked.
10928 */
10929 public interface OnClickListener {
10930 /**
10931 * Called when a view has been clicked.
10932 *
10933 * @param v The view that was clicked.
10934 */
10935 void onClick(View v);
10936 }
10937
10938 /**
10939 * Interface definition for a callback to be invoked when the context menu
10940 * for this view is being built.
10941 */
10942 public interface OnCreateContextMenuListener {
10943 /**
10944 * Called when the context menu for this view is being built. It is not
10945 * safe to hold onto the menu after this method returns.
10946 *
10947 * @param menu The context menu that is being built
10948 * @param v The view for which the context menu is being built
10949 * @param menuInfo Extra information about the item for which the
10950 * context menu should be shown. This information will vary
10951 * depending on the class of v.
10952 */
10953 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
10954 }
10955
10956 private final class UnsetPressedState implements Runnable {
10957 public void run() {
10958 setPressed(false);
10959 }
10960 }
10961
10962 /**
10963 * Base class for derived classes that want to save and restore their own
10964 * state in {@link android.view.View#onSaveInstanceState()}.
10965 */
10966 public static class BaseSavedState extends AbsSavedState {
10967 /**
10968 * Constructor used when reading from a parcel. Reads the state of the superclass.
10969 *
10970 * @param source
10971 */
10972 public BaseSavedState(Parcel source) {
10973 super(source);
10974 }
10975
10976 /**
10977 * Constructor called by derived classes when creating their SavedState objects
10978 *
10979 * @param superState The state of the superclass of this view
10980 */
10981 public BaseSavedState(Parcelable superState) {
10982 super(superState);
10983 }
10984
10985 public static final Parcelable.Creator<BaseSavedState> CREATOR =
10986 new Parcelable.Creator<BaseSavedState>() {
10987 public BaseSavedState createFromParcel(Parcel in) {
10988 return new BaseSavedState(in);
10989 }
10990
10991 public BaseSavedState[] newArray(int size) {
10992 return new BaseSavedState[size];
10993 }
10994 };
10995 }
10996
10997 /**
10998 * A set of information given to a view when it is attached to its parent
10999 * window.
11000 */
11001 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011002 interface Callbacks {
11003 void playSoundEffect(int effectId);
11004 boolean performHapticFeedback(int effectId, boolean always);
11005 }
11006
11007 /**
11008 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11009 * to a Handler. This class contains the target (View) to invalidate and
11010 * the coordinates of the dirty rectangle.
11011 *
11012 * For performance purposes, this class also implements a pool of up to
11013 * POOL_LIMIT objects that get reused. This reduces memory allocations
11014 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011015 */
Romain Guyd928d682009-03-31 17:52:16 -070011016 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011017 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070011018 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11019 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070011020 public InvalidateInfo newInstance() {
11021 return new InvalidateInfo();
11022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023
Romain Guyd928d682009-03-31 17:52:16 -070011024 public void onAcquired(InvalidateInfo element) {
11025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011026
Romain Guyd928d682009-03-31 17:52:16 -070011027 public void onReleased(InvalidateInfo element) {
11028 }
11029 }, POOL_LIMIT)
11030 );
11031
11032 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011033
11034 View target;
11035
11036 int left;
11037 int top;
11038 int right;
11039 int bottom;
11040
Romain Guyd928d682009-03-31 17:52:16 -070011041 public void setNextPoolable(InvalidateInfo element) {
11042 mNext = element;
11043 }
11044
11045 public InvalidateInfo getNextPoolable() {
11046 return mNext;
11047 }
11048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011049 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070011050 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011051 }
11052
11053 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070011054 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011055 }
11056 }
11057
11058 final IWindowSession mSession;
11059
11060 final IWindow mWindow;
11061
11062 final IBinder mWindowToken;
11063
11064 final Callbacks mRootCallbacks;
11065
11066 /**
11067 * The top view of the hierarchy.
11068 */
11069 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070011070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011071 IBinder mPanelParentWindowToken;
11072 Surface mSurface;
11073
Romain Guyb051e892010-09-28 19:09:36 -070011074 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080011075 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070011076 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070011077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011078 /**
Romain Guy8506ab42009-06-11 17:35:47 -070011079 * Scale factor used by the compatibility mode
11080 */
11081 float mApplicationScale;
11082
11083 /**
11084 * Indicates whether the application is in compatibility mode
11085 */
11086 boolean mScalingRequired;
11087
11088 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011089 * Left position of this view's window
11090 */
11091 int mWindowLeft;
11092
11093 /**
11094 * Top position of this view's window
11095 */
11096 int mWindowTop;
11097
11098 /**
Adam Powell26153a32010-11-08 15:22:27 -080011099 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070011100 */
Adam Powell26153a32010-11-08 15:22:27 -080011101 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070011102
11103 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011104 * For windows that are full-screen but using insets to layout inside
11105 * of the screen decorations, these are the current insets for the
11106 * content of the window.
11107 */
11108 final Rect mContentInsets = new Rect();
11109
11110 /**
11111 * For windows that are full-screen but using insets to layout inside
11112 * of the screen decorations, these are the current insets for the
11113 * actual visible parts of the window.
11114 */
11115 final Rect mVisibleInsets = new Rect();
11116
11117 /**
11118 * The internal insets given by this window. This value is
11119 * supplied by the client (through
11120 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11121 * be given to the window manager when changed to be used in laying
11122 * out windows behind it.
11123 */
11124 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11125 = new ViewTreeObserver.InternalInsetsInfo();
11126
11127 /**
11128 * All views in the window's hierarchy that serve as scroll containers,
11129 * used to determine if the window can be resized or must be panned
11130 * to adjust for a soft input area.
11131 */
11132 final ArrayList<View> mScrollContainers = new ArrayList<View>();
11133
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070011134 final KeyEvent.DispatcherState mKeyDispatchState
11135 = new KeyEvent.DispatcherState();
11136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011137 /**
11138 * Indicates whether the view's window currently has the focus.
11139 */
11140 boolean mHasWindowFocus;
11141
11142 /**
11143 * The current visibility of the window.
11144 */
11145 int mWindowVisibility;
11146
11147 /**
11148 * Indicates the time at which drawing started to occur.
11149 */
11150 long mDrawingTime;
11151
11152 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070011153 * Indicates whether or not ignoring the DIRTY_MASK flags.
11154 */
11155 boolean mIgnoreDirtyState;
11156
11157 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011158 * Indicates whether the view's window is currently in touch mode.
11159 */
11160 boolean mInTouchMode;
11161
11162 /**
11163 * Indicates that ViewRoot should trigger a global layout change
11164 * the next time it performs a traversal
11165 */
11166 boolean mRecomputeGlobalAttributes;
11167
11168 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011169 * Set during a traveral if any views want to keep the screen on.
11170 */
11171 boolean mKeepScreenOn;
11172
11173 /**
11174 * Set if the visibility of any views has changed.
11175 */
11176 boolean mViewVisibilityChanged;
11177
11178 /**
11179 * Set to true if a view has been scrolled.
11180 */
11181 boolean mViewScrollChanged;
11182
11183 /**
11184 * Global to the view hierarchy used as a temporary for dealing with
11185 * x/y points in the transparent region computations.
11186 */
11187 final int[] mTransparentLocation = new int[2];
11188
11189 /**
11190 * Global to the view hierarchy used as a temporary for dealing with
11191 * x/y points in the ViewGroup.invalidateChild implementation.
11192 */
11193 final int[] mInvalidateChildLocation = new int[2];
11194
Chet Haasec3aa3612010-06-17 08:50:37 -070011195
11196 /**
11197 * Global to the view hierarchy used as a temporary for dealing with
11198 * x/y location when view is transformed.
11199 */
11200 final float[] mTmpTransformLocation = new float[2];
11201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011202 /**
11203 * The view tree observer used to dispatch global events like
11204 * layout, pre-draw, touch mode change, etc.
11205 */
11206 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11207
11208 /**
11209 * A Canvas used by the view hierarchy to perform bitmap caching.
11210 */
11211 Canvas mCanvas;
11212
11213 /**
11214 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11215 * handler can be used to pump events in the UI events queue.
11216 */
11217 final Handler mHandler;
11218
11219 /**
11220 * Identifier for messages requesting the view to be invalidated.
11221 * Such messages should be sent to {@link #mHandler}.
11222 */
11223 static final int INVALIDATE_MSG = 0x1;
11224
11225 /**
11226 * Identifier for messages requesting the view to invalidate a region.
11227 * Such messages should be sent to {@link #mHandler}.
11228 */
11229 static final int INVALIDATE_RECT_MSG = 0x2;
11230
11231 /**
11232 * Temporary for use in computing invalidate rectangles while
11233 * calling up the hierarchy.
11234 */
11235 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070011236
11237 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070011238 * Temporary for use in computing hit areas with transformed views
11239 */
11240 final RectF mTmpTransformRect = new RectF();
11241
11242 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070011243 * Temporary list for use in collecting focusable descendents of a view.
11244 */
11245 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011247 /**
11248 * Creates a new set of attachment information with the specified
11249 * events handler and thread.
11250 *
11251 * @param handler the events handler the view must use
11252 */
11253 AttachInfo(IWindowSession session, IWindow window,
11254 Handler handler, Callbacks effectPlayer) {
11255 mSession = session;
11256 mWindow = window;
11257 mWindowToken = window.asBinder();
11258 mHandler = handler;
11259 mRootCallbacks = effectPlayer;
11260 }
11261 }
11262
11263 /**
11264 * <p>ScrollabilityCache holds various fields used by a View when scrolling
11265 * is supported. This avoids keeping too many unused fields in most
11266 * instances of View.</p>
11267 */
Mike Cleronf116bf82009-09-27 19:14:12 -070011268 private static class ScrollabilityCache implements Runnable {
11269
11270 /**
11271 * Scrollbars are not visible
11272 */
11273 public static final int OFF = 0;
11274
11275 /**
11276 * Scrollbars are visible
11277 */
11278 public static final int ON = 1;
11279
11280 /**
11281 * Scrollbars are fading away
11282 */
11283 public static final int FADING = 2;
11284
11285 public boolean fadeScrollBars;
11286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070011288 public int scrollBarDefaultDelayBeforeFade;
11289 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011290
11291 public int scrollBarSize;
11292 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070011293 public float[] interpolatorValues;
11294 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011295
11296 public final Paint paint;
11297 public final Matrix matrix;
11298 public Shader shader;
11299
Mike Cleronf116bf82009-09-27 19:14:12 -070011300 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11301
Romain Guy8fb95422010-08-17 18:38:51 -070011302 private final float[] mOpaque = { 255.0f };
11303 private final float[] mTransparent = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070011304
11305 /**
11306 * When fading should start. This time moves into the future every time
11307 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11308 */
11309 public long fadeStartTime;
11310
11311
11312 /**
11313 * The current state of the scrollbars: ON, OFF, or FADING
11314 */
11315 public int state = OFF;
11316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011317 private int mLastColor;
11318
Mike Cleronf116bf82009-09-27 19:14:12 -070011319 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011320 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11321 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070011322 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11323 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011324
11325 paint = new Paint();
11326 matrix = new Matrix();
11327 // use use a height of 1, and then wack the matrix each time we
11328 // actually use it.
11329 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 paint.setShader(shader);
11332 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070011333 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011334 }
Romain Guy8506ab42009-06-11 17:35:47 -070011335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011336 public void setFadeColor(int color) {
11337 if (color != 0 && color != mLastColor) {
11338 mLastColor = color;
11339 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070011340
Romain Guye55e1a72009-08-27 10:42:26 -070011341 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11342 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011344 paint.setShader(shader);
11345 // Restore the default transfer mode (src_over)
11346 paint.setXfermode(null);
11347 }
11348 }
Mike Cleronf116bf82009-09-27 19:14:12 -070011349
11350 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070011351 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070011352 if (now >= fadeStartTime) {
11353
11354 // the animation fades the scrollbars out by changing
11355 // the opacity (alpha) from fully opaque to fully
11356 // transparent
11357 int nextFrame = (int) now;
11358 int framesCount = 0;
11359
11360 Interpolator interpolator = scrollBarInterpolator;
11361
11362 // Start opaque
11363 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
11364
11365 // End transparent
11366 nextFrame += scrollBarFadeDuration;
11367 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
11368
11369 state = FADING;
11370
11371 // Kick off the fade animation
11372 host.invalidate();
11373 }
11374 }
11375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011376 }
11377}