blob: be49255ee1862cea00865a78dd7c1943b6fc5857 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Christopher Tatea53146c2010-09-07 11:57:52 -070019import android.content.ClipData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080021import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070025import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070027import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.graphics.LinearGradient;
29import android.graphics.Matrix;
30import android.graphics.Paint;
31import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070032import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
35import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070036import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.graphics.Region;
38import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Message;
44import android.os.Parcel;
45import android.os.Parcelable;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.os.SystemProperties;
49import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070051import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070052import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070053import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070054import android.util.Pools;
55import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.view.ContextMenu.ContextMenuInfo;
svetoslavganov75986cf2009-05-14 22:28:01 -070057import android.view.accessibility.AccessibilityEvent;
58import android.view.accessibility.AccessibilityEventSource;
59import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070061import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070062import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.view.inputmethod.InputConnection;
64import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.widget.ScrollBarDrawable;
Romain Guyf607bdc2010-09-10 19:20:06 -070066import com.android.internal.R;
67import com.android.internal.view.menu.MenuBuilder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
Christopher Tatea0374192010-10-05 13:06:41 -070069import java.lang.ref.WeakReference;
svetoslavganov75986cf2009-05-14 22:28:01 -070070import java.lang.reflect.InvocationTargetException;
71import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.util.ArrayList;
73import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070074import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070075import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
77/**
78 * <p>
79 * This class represents the basic building block for user interface components. A View
80 * occupies a rectangular area on the screen and is responsible for drawing and
81 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070082 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
84 * are invisible containers that hold other Views (or other ViewGroups) and define
85 * their layout properties.
86 * </p>
87 *
88 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070089 * <p>For an introduction to using this class to develop your
90 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070092 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
94 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
95 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
101 * </p>
102 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700103 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 * <a name="Using"></a>
105 * <h3>Using Views</h3>
106 * <p>
107 * All of the views in a window are arranged in a single tree. You can add views
108 * either from code or by specifying a tree of views in one or more XML layout
109 * files. There are many specialized subclasses of views that act as controls or
110 * are capable of displaying text, images, or other content.
111 * </p>
112 * <p>
113 * Once you have created a tree of views, there are typically a few types of
114 * common operations you may wish to perform:
115 * <ul>
116 * <li><strong>Set properties:</strong> for example setting the text of a
117 * {@link android.widget.TextView}. The available properties and the methods
118 * that set them will vary among the different subclasses of views. Note that
119 * properties that are known at build time can be set in the XML layout
120 * files.</li>
121 * <li><strong>Set focus:</strong> The framework will handled moving focus in
122 * response to user input. To force focus to a specific view, call
123 * {@link #requestFocus}.</li>
124 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
125 * that will be notified when something interesting happens to the view. For
126 * example, all views will let you set a listener to be notified when the view
127 * gains or loses focus. You can register such a listener using
128 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
129 * specialized listeners. For example, a Button exposes a listener to notify
130 * clients when the button is clicked.</li>
131 * <li><strong>Set visibility:</strong> You can hide or show views using
132 * {@link #setVisibility}.</li>
133 * </ul>
134 * </p>
135 * <p><em>
136 * Note: The Android framework is responsible for measuring, laying out and
137 * drawing views. You should not call methods that perform these actions on
138 * views yourself unless you are actually implementing a
139 * {@link android.view.ViewGroup}.
140 * </em></p>
141 *
142 * <a name="Lifecycle"></a>
143 * <h3>Implementing a Custom View</h3>
144 *
145 * <p>
146 * To implement a custom view, you will usually begin by providing overrides for
147 * some of the standard methods that the framework calls on all views. You do
148 * not need to override all of these methods. In fact, you can start by just
149 * overriding {@link #onDraw(android.graphics.Canvas)}.
150 * <table border="2" width="85%" align="center" cellpadding="5">
151 * <thead>
152 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
153 * </thead>
154 *
155 * <tbody>
156 * <tr>
157 * <td rowspan="2">Creation</td>
158 * <td>Constructors</td>
159 * <td>There is a form of the constructor that are called when the view
160 * is created from code and a form that is called when the view is
161 * inflated from a layout file. The second form should parse and apply
162 * any attributes defined in the layout file.
163 * </td>
164 * </tr>
165 * <tr>
166 * <td><code>{@link #onFinishInflate()}</code></td>
167 * <td>Called after a view and all of its children has been inflated
168 * from XML.</td>
169 * </tr>
170 *
171 * <tr>
172 * <td rowspan="3">Layout</td>
173 * <td><code>{@link #onMeasure}</code></td>
174 * <td>Called to determine the size requirements for this view and all
175 * of its children.
176 * </td>
177 * </tr>
178 * <tr>
179 * <td><code>{@link #onLayout}</code></td>
180 * <td>Called when this view should assign a size and position to all
181 * of its children.
182 * </td>
183 * </tr>
184 * <tr>
185 * <td><code>{@link #onSizeChanged}</code></td>
186 * <td>Called when the size of this view has changed.
187 * </td>
188 * </tr>
189 *
190 * <tr>
191 * <td>Drawing</td>
192 * <td><code>{@link #onDraw}</code></td>
193 * <td>Called when the view should render its content.
194 * </td>
195 * </tr>
196 *
197 * <tr>
198 * <td rowspan="4">Event processing</td>
199 * <td><code>{@link #onKeyDown}</code></td>
200 * <td>Called when a new key event occurs.
201 * </td>
202 * </tr>
203 * <tr>
204 * <td><code>{@link #onKeyUp}</code></td>
205 * <td>Called when a key up event occurs.
206 * </td>
207 * </tr>
208 * <tr>
209 * <td><code>{@link #onTrackballEvent}</code></td>
210 * <td>Called when a trackball motion event occurs.
211 * </td>
212 * </tr>
213 * <tr>
214 * <td><code>{@link #onTouchEvent}</code></td>
215 * <td>Called when a touch screen motion event occurs.
216 * </td>
217 * </tr>
218 *
219 * <tr>
220 * <td rowspan="2">Focus</td>
221 * <td><code>{@link #onFocusChanged}</code></td>
222 * <td>Called when the view gains or loses focus.
223 * </td>
224 * </tr>
225 *
226 * <tr>
227 * <td><code>{@link #onWindowFocusChanged}</code></td>
228 * <td>Called when the window containing the view gains or loses focus.
229 * </td>
230 * </tr>
231 *
232 * <tr>
233 * <td rowspan="3">Attaching</td>
234 * <td><code>{@link #onAttachedToWindow()}</code></td>
235 * <td>Called when the view is attached to a window.
236 * </td>
237 * </tr>
238 *
239 * <tr>
240 * <td><code>{@link #onDetachedFromWindow}</code></td>
241 * <td>Called when the view is detached from its window.
242 * </td>
243 * </tr>
244 *
245 * <tr>
246 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
247 * <td>Called when the visibility of the window containing the view
248 * has changed.
249 * </td>
250 * </tr>
251 * </tbody>
252 *
253 * </table>
254 * </p>
255 *
256 * <a name="IDs"></a>
257 * <h3>IDs</h3>
258 * Views may have an integer id associated with them. These ids are typically
259 * assigned in the layout XML files, and are used to find specific views within
260 * the view tree. A common pattern is to:
261 * <ul>
262 * <li>Define a Button in the layout file and assign it a unique ID.
263 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700264 * &lt;Button
265 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 * android:layout_width="wrap_content"
267 * android:layout_height="wrap_content"
268 * android:text="@string/my_button_text"/&gt;
269 * </pre></li>
270 * <li>From the onCreate method of an Activity, find the Button
271 * <pre class="prettyprint">
272 * Button myButton = (Button) findViewById(R.id.my_button);
273 * </pre></li>
274 * </ul>
275 * <p>
276 * View IDs need not be unique throughout the tree, but it is good practice to
277 * ensure that they are at least unique within the part of the tree you are
278 * searching.
279 * </p>
280 *
281 * <a name="Position"></a>
282 * <h3>Position</h3>
283 * <p>
284 * The geometry of a view is that of a rectangle. A view has a location,
285 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
286 * two dimensions, expressed as a width and a height. The unit for location
287 * and dimensions is the pixel.
288 * </p>
289 *
290 * <p>
291 * It is possible to retrieve the location of a view by invoking the methods
292 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
293 * coordinate of the rectangle representing the view. The latter returns the
294 * top, or Y, coordinate of the rectangle representing the view. These methods
295 * both return the location of the view relative to its parent. For instance,
296 * when getLeft() returns 20, that means the view is located 20 pixels to the
297 * right of the left edge of its direct parent.
298 * </p>
299 *
300 * <p>
301 * In addition, several convenience methods are offered to avoid unnecessary
302 * computations, namely {@link #getRight()} and {@link #getBottom()}.
303 * These methods return the coordinates of the right and bottom edges of the
304 * rectangle representing the view. For instance, calling {@link #getRight()}
305 * is similar to the following computation: <code>getLeft() + getWidth()</code>
306 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
307 * </p>
308 *
309 * <a name="SizePaddingMargins"></a>
310 * <h3>Size, padding and margins</h3>
311 * <p>
312 * The size of a view is expressed with a width and a height. A view actually
313 * possess two pairs of width and height values.
314 * </p>
315 *
316 * <p>
317 * The first pair is known as <em>measured width</em> and
318 * <em>measured height</em>. These dimensions define how big a view wants to be
319 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
320 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
321 * and {@link #getMeasuredHeight()}.
322 * </p>
323 *
324 * <p>
325 * The second pair is simply known as <em>width</em> and <em>height</em>, or
326 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
327 * dimensions define the actual size of the view on screen, at drawing time and
328 * after layout. These values may, but do not have to, be different from the
329 * measured width and height. The width and height can be obtained by calling
330 * {@link #getWidth()} and {@link #getHeight()}.
331 * </p>
332 *
333 * <p>
334 * To measure its dimensions, a view takes into account its padding. The padding
335 * is expressed in pixels for the left, top, right and bottom parts of the view.
336 * Padding can be used to offset the content of the view by a specific amount of
337 * pixels. For instance, a left padding of 2 will push the view's content by
338 * 2 pixels to the right of the left edge. Padding can be set using the
339 * {@link #setPadding(int, int, int, int)} method and queried by calling
340 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
341 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
342 * </p>
343 *
344 * <p>
345 * Even though a view can define a padding, it does not provide any support for
346 * margins. However, view groups provide such a support. Refer to
347 * {@link android.view.ViewGroup} and
348 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
349 * </p>
350 *
351 * <a name="Layout"></a>
352 * <h3>Layout</h3>
353 * <p>
354 * Layout is a two pass process: a measure pass and a layout pass. The measuring
355 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
356 * of the view tree. Each view pushes dimension specifications down the tree
357 * during the recursion. At the end of the measure pass, every view has stored
358 * its measurements. The second pass happens in
359 * {@link #layout(int,int,int,int)} and is also top-down. During
360 * this pass each parent is responsible for positioning all of its children
361 * using the sizes computed in the measure pass.
362 * </p>
363 *
364 * <p>
365 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
366 * {@link #getMeasuredHeight()} values must be set, along with those for all of
367 * that view's descendants. A view's measured width and measured height values
368 * must respect the constraints imposed by the view's parents. This guarantees
369 * that at the end of the measure pass, all parents accept all of their
370 * children's measurements. A parent view may call measure() more than once on
371 * its children. For example, the parent may measure each child once with
372 * unspecified dimensions to find out how big they want to be, then call
373 * measure() on them again with actual numbers if the sum of all the children's
374 * unconstrained sizes is too big or too small.
375 * </p>
376 *
377 * <p>
378 * The measure pass uses two classes to communicate dimensions. The
379 * {@link MeasureSpec} class is used by views to tell their parents how they
380 * want to be measured and positioned. The base LayoutParams class just
381 * describes how big the view wants to be for both width and height. For each
382 * dimension, it can specify one of:
383 * <ul>
384 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800385 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 * (minus padding)
387 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
388 * enclose its content (plus padding).
389 * </ul>
390 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
391 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
392 * an X and Y value.
393 * </p>
394 *
395 * <p>
396 * MeasureSpecs are used to push requirements down the tree from parent to
397 * child. A MeasureSpec can be in one of three modes:
398 * <ul>
399 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
400 * of a child view. For example, a LinearLayout may call measure() on its child
401 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
402 * tall the child view wants to be given a width of 240 pixels.
403 * <li>EXACTLY: This is used by the parent to impose an exact size on the
404 * child. The child must use this size, and guarantee that all of its
405 * descendants will fit within this size.
406 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
407 * child. The child must gurantee that it and all of its descendants will fit
408 * within this size.
409 * </ul>
410 * </p>
411 *
412 * <p>
413 * To intiate a layout, call {@link #requestLayout}. This method is typically
414 * called by a view on itself when it believes that is can no longer fit within
415 * its current bounds.
416 * </p>
417 *
418 * <a name="Drawing"></a>
419 * <h3>Drawing</h3>
420 * <p>
421 * Drawing is handled by walking the tree and rendering each view that
422 * intersects the the invalid region. Because the tree is traversed in-order,
423 * this means that parents will draw before (i.e., behind) their children, with
424 * siblings drawn in the order they appear in the tree.
425 * If you set a background drawable for a View, then the View will draw it for you
426 * before calling back to its <code>onDraw()</code> method.
427 * </p>
428 *
429 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700430 * Note that the framework will not draw views that are not in the invalid region.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 * </p>
432 *
433 * <p>
434 * To force a view to draw, call {@link #invalidate()}.
435 * </p>
436 *
437 * <a name="EventHandlingThreading"></a>
438 * <h3>Event Handling and Threading</h3>
439 * <p>
440 * The basic cycle of a view is as follows:
441 * <ol>
442 * <li>An event comes in and is dispatched to the appropriate view. The view
443 * handles the event and notifies any listeners.</li>
444 * <li>If in the course of processing the event, the view's bounds may need
445 * to be changed, the view will call {@link #requestLayout()}.</li>
446 * <li>Similarly, if in the course of processing the event the view's appearance
447 * may need to be changed, the view will call {@link #invalidate()}.</li>
448 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
449 * the framework will take care of measuring, laying out, and drawing the tree
450 * as appropriate.</li>
451 * </ol>
452 * </p>
453 *
454 * <p><em>Note: The entire view tree is single threaded. You must always be on
455 * the UI thread when calling any method on any view.</em>
456 * If you are doing work on other threads and want to update the state of a view
457 * from that thread, you should use a {@link Handler}.
458 * </p>
459 *
460 * <a name="FocusHandling"></a>
461 * <h3>Focus Handling</h3>
462 * <p>
463 * The framework will handle routine focus movement in response to user input.
464 * This includes changing the focus as views are removed or hidden, or as new
465 * views become available. Views indicate their willingness to take focus
466 * through the {@link #isFocusable} method. To change whether a view can take
467 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
468 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
469 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
470 * </p>
471 * <p>
472 * Focus movement is based on an algorithm which finds the nearest neighbor in a
473 * given direction. In rare cases, the default algorithm may not match the
474 * intended behavior of the developer. In these situations, you can provide
475 * explicit overrides by using these XML attributes in the layout file:
476 * <pre>
477 * nextFocusDown
478 * nextFocusLeft
479 * nextFocusRight
480 * nextFocusUp
481 * </pre>
482 * </p>
483 *
484 *
485 * <p>
486 * To get a particular view to take focus, call {@link #requestFocus()}.
487 * </p>
488 *
489 * <a name="TouchMode"></a>
490 * <h3>Touch Mode</h3>
491 * <p>
492 * When a user is navigating a user interface via directional keys such as a D-pad, it is
493 * necessary to give focus to actionable items such as buttons so the user can see
494 * what will take input. If the device has touch capabilities, however, and the user
495 * begins interacting with the interface by touching it, it is no longer necessary to
496 * always highlight, or give focus to, a particular view. This motivates a mode
497 * for interaction named 'touch mode'.
498 * </p>
499 * <p>
500 * For a touch capable device, once the user touches the screen, the device
501 * will enter touch mode. From this point onward, only views for which
502 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
503 * Other views that are touchable, like buttons, will not take focus when touched; they will
504 * only fire the on click listeners.
505 * </p>
506 * <p>
507 * Any time a user hits a directional key, such as a D-pad direction, the view device will
508 * exit touch mode, and find a view to take focus, so that the user may resume interacting
509 * with the user interface without touching the screen again.
510 * </p>
511 * <p>
512 * The touch mode state is maintained across {@link android.app.Activity}s. Call
513 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
514 * </p>
515 *
516 * <a name="Scrolling"></a>
517 * <h3>Scrolling</h3>
518 * <p>
519 * The framework provides basic support for views that wish to internally
520 * scroll their content. This includes keeping track of the X and Y scroll
521 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700522 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
523 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 * </p>
525 *
526 * <a name="Tags"></a>
527 * <h3>Tags</h3>
528 * <p>
529 * Unlike IDs, tags are not used to identify views. Tags are essentially an
530 * extra piece of information that can be associated with a view. They are most
531 * often used as a convenience to store data related to views in the views
532 * themselves rather than by putting them in a separate structure.
533 * </p>
534 *
535 * <a name="Animation"></a>
536 * <h3>Animation</h3>
537 * <p>
538 * You can attach an {@link Animation} object to a view using
539 * {@link #setAnimation(Animation)} or
540 * {@link #startAnimation(Animation)}. The animation can alter the scale,
541 * rotation, translation and alpha of a view over time. If the animation is
542 * attached to a view that has children, the animation will affect the entire
543 * subtree rooted by that node. When an animation is started, the framework will
544 * take care of redrawing the appropriate views until the animation completes.
545 * </p>
546 *
Jeff Brown85a31762010-09-01 17:01:00 -0700547 * <a name="Security"></a>
548 * <h3>Security</h3>
549 * <p>
550 * Sometimes it is essential that an application be able to verify that an action
551 * is being performed with the full knowledge and consent of the user, such as
552 * granting a permission request, making a purchase or clicking on an advertisement.
553 * Unfortunately, a malicious application could try to spoof the user into
554 * performing these actions, unaware, by concealing the intended purpose of the view.
555 * As a remedy, the framework offers a touch filtering mechanism that can be used to
556 * improve the security of views that provide access to sensitive functionality.
557 * </p><p>
558 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
559 * andoird:filterTouchesWhenObscured attribute to true. When enabled, the framework
560 * will discard touches that are received whenever the view's window is obscured by
561 * another visible window. As a result, the view will not receive touches whenever a
562 * toast, dialog or other window appears above the view's window.
563 * </p><p>
564 * For more fine-grained control over security, consider overriding the
565 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
566 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
567 * </p>
568 *
Romain Guyd6a463a2009-05-21 23:10:10 -0700569 * @attr ref android.R.styleable#View_background
570 * @attr ref android.R.styleable#View_clickable
571 * @attr ref android.R.styleable#View_contentDescription
572 * @attr ref android.R.styleable#View_drawingCacheQuality
573 * @attr ref android.R.styleable#View_duplicateParentState
574 * @attr ref android.R.styleable#View_id
575 * @attr ref android.R.styleable#View_fadingEdge
576 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700577 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700579 * @attr ref android.R.styleable#View_isScrollContainer
580 * @attr ref android.R.styleable#View_focusable
581 * @attr ref android.R.styleable#View_focusableInTouchMode
582 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
583 * @attr ref android.R.styleable#View_keepScreenOn
584 * @attr ref android.R.styleable#View_longClickable
585 * @attr ref android.R.styleable#View_minHeight
586 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 * @attr ref android.R.styleable#View_nextFocusDown
588 * @attr ref android.R.styleable#View_nextFocusLeft
589 * @attr ref android.R.styleable#View_nextFocusRight
590 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700591 * @attr ref android.R.styleable#View_onClick
592 * @attr ref android.R.styleable#View_padding
593 * @attr ref android.R.styleable#View_paddingBottom
594 * @attr ref android.R.styleable#View_paddingLeft
595 * @attr ref android.R.styleable#View_paddingRight
596 * @attr ref android.R.styleable#View_paddingTop
597 * @attr ref android.R.styleable#View_saveEnabled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 * @attr ref android.R.styleable#View_scrollX
599 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700600 * @attr ref android.R.styleable#View_scrollbarSize
601 * @attr ref android.R.styleable#View_scrollbarStyle
602 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700603 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
604 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
606 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 * @attr ref android.R.styleable#View_scrollbarThumbVertical
608 * @attr ref android.R.styleable#View_scrollbarTrackVertical
609 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
610 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700611 * @attr ref android.R.styleable#View_soundEffectsEnabled
612 * @attr ref android.R.styleable#View_tag
613 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 *
615 * @see android.view.ViewGroup
616 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700617public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 private static final boolean DBG = false;
619
620 /**
621 * The logging tag used by this class with android.util.Log.
622 */
623 protected static final String VIEW_LOG_TAG = "View";
624
625 /**
626 * Used to mark a View that has no ID.
627 */
628 public static final int NO_ID = -1;
629
630 /**
631 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
632 * calling setFlags.
633 */
634 private static final int NOT_FOCUSABLE = 0x00000000;
635
636 /**
637 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
638 * setFlags.
639 */
640 private static final int FOCUSABLE = 0x00000001;
641
642 /**
643 * Mask for use with setFlags indicating bits used for focus.
644 */
645 private static final int FOCUSABLE_MASK = 0x00000001;
646
647 /**
648 * This view will adjust its padding to fit sytem windows (e.g. status bar)
649 */
650 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
651
652 /**
653 * This view is visible. Use with {@link #setVisibility}.
654 */
655 public static final int VISIBLE = 0x00000000;
656
657 /**
658 * This view is invisible, but it still takes up space for layout purposes.
659 * Use with {@link #setVisibility}.
660 */
661 public static final int INVISIBLE = 0x00000004;
662
663 /**
664 * This view is invisible, and it doesn't take any space for layout
665 * purposes. Use with {@link #setVisibility}.
666 */
667 public static final int GONE = 0x00000008;
668
669 /**
670 * Mask for use with setFlags indicating bits used for visibility.
671 * {@hide}
672 */
673 static final int VISIBILITY_MASK = 0x0000000C;
674
675 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
676
677 /**
678 * This view is enabled. Intrepretation varies by subclass.
679 * Use with ENABLED_MASK when calling setFlags.
680 * {@hide}
681 */
682 static final int ENABLED = 0x00000000;
683
684 /**
685 * This view is disabled. Intrepretation varies by subclass.
686 * Use with ENABLED_MASK when calling setFlags.
687 * {@hide}
688 */
689 static final int DISABLED = 0x00000020;
690
691 /**
692 * Mask for use with setFlags indicating bits used for indicating whether
693 * this view is enabled
694 * {@hide}
695 */
696 static final int ENABLED_MASK = 0x00000020;
697
698 /**
699 * This view won't draw. {@link #onDraw} won't be called and further
700 * optimizations
701 * will be performed. It is okay to have this flag set and a background.
702 * Use with DRAW_MASK when calling setFlags.
703 * {@hide}
704 */
705 static final int WILL_NOT_DRAW = 0x00000080;
706
707 /**
708 * Mask for use with setFlags indicating bits used for indicating whether
709 * this view is will draw
710 * {@hide}
711 */
712 static final int DRAW_MASK = 0x00000080;
713
714 /**
715 * <p>This view doesn't show scrollbars.</p>
716 * {@hide}
717 */
718 static final int SCROLLBARS_NONE = 0x00000000;
719
720 /**
721 * <p>This view shows horizontal scrollbars.</p>
722 * {@hide}
723 */
724 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
725
726 /**
727 * <p>This view shows vertical scrollbars.</p>
728 * {@hide}
729 */
730 static final int SCROLLBARS_VERTICAL = 0x00000200;
731
732 /**
733 * <p>Mask for use with setFlags indicating bits used for indicating which
734 * scrollbars are enabled.</p>
735 * {@hide}
736 */
737 static final int SCROLLBARS_MASK = 0x00000300;
738
Jeff Brown85a31762010-09-01 17:01:00 -0700739 /**
740 * Indicates that the view should filter touches when its window is obscured.
741 * Refer to the class comments for more information about this security feature.
742 * {@hide}
743 */
744 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
745
746 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747
748 /**
749 * <p>This view doesn't show fading edges.</p>
750 * {@hide}
751 */
752 static final int FADING_EDGE_NONE = 0x00000000;
753
754 /**
755 * <p>This view shows horizontal fading edges.</p>
756 * {@hide}
757 */
758 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
759
760 /**
761 * <p>This view shows vertical fading edges.</p>
762 * {@hide}
763 */
764 static final int FADING_EDGE_VERTICAL = 0x00002000;
765
766 /**
767 * <p>Mask for use with setFlags indicating bits used for indicating which
768 * fading edges are enabled.</p>
769 * {@hide}
770 */
771 static final int FADING_EDGE_MASK = 0x00003000;
772
773 /**
774 * <p>Indicates this view can be clicked. When clickable, a View reacts
775 * to clicks by notifying the OnClickListener.<p>
776 * {@hide}
777 */
778 static final int CLICKABLE = 0x00004000;
779
780 /**
781 * <p>Indicates this view is caching its drawing into a bitmap.</p>
782 * {@hide}
783 */
784 static final int DRAWING_CACHE_ENABLED = 0x00008000;
785
786 /**
787 * <p>Indicates that no icicle should be saved for this view.<p>
788 * {@hide}
789 */
790 static final int SAVE_DISABLED = 0x000010000;
791
792 /**
793 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
794 * property.</p>
795 * {@hide}
796 */
797 static final int SAVE_DISABLED_MASK = 0x000010000;
798
799 /**
800 * <p>Indicates that no drawing cache should ever be created for this view.<p>
801 * {@hide}
802 */
803 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
804
805 /**
806 * <p>Indicates this view can take / keep focus when int touch mode.</p>
807 * {@hide}
808 */
809 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
810
811 /**
812 * <p>Enables low quality mode for the drawing cache.</p>
813 */
814 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
815
816 /**
817 * <p>Enables high quality mode for the drawing cache.</p>
818 */
819 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
820
821 /**
822 * <p>Enables automatic quality mode for the drawing cache.</p>
823 */
824 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
825
826 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
827 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
828 };
829
830 /**
831 * <p>Mask for use with setFlags indicating bits used for the cache
832 * quality property.</p>
833 * {@hide}
834 */
835 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
836
837 /**
838 * <p>
839 * Indicates this view can be long clicked. When long clickable, a View
840 * reacts to long clicks by notifying the OnLongClickListener or showing a
841 * context menu.
842 * </p>
843 * {@hide}
844 */
845 static final int LONG_CLICKABLE = 0x00200000;
846
847 /**
848 * <p>Indicates that this view gets its drawable states from its direct parent
849 * and ignores its original internal states.</p>
850 *
851 * @hide
852 */
853 static final int DUPLICATE_PARENT_STATE = 0x00400000;
854
855 /**
856 * The scrollbar style to display the scrollbars inside the content area,
857 * without increasing the padding. The scrollbars will be overlaid with
858 * translucency on the view's content.
859 */
860 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
861
862 /**
863 * The scrollbar style to display the scrollbars inside the padded area,
864 * increasing the padding of the view. The scrollbars will not overlap the
865 * content area of the view.
866 */
867 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
868
869 /**
870 * The scrollbar style to display the scrollbars at the edge of the view,
871 * without increasing the padding. The scrollbars will be overlaid with
872 * translucency.
873 */
874 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
875
876 /**
877 * The scrollbar style to display the scrollbars at the edge of the view,
878 * increasing the padding of the view. The scrollbars will only overlap the
879 * background, if any.
880 */
881 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
882
883 /**
884 * Mask to check if the scrollbar style is overlay or inset.
885 * {@hide}
886 */
887 static final int SCROLLBARS_INSET_MASK = 0x01000000;
888
889 /**
890 * Mask to check if the scrollbar style is inside or outside.
891 * {@hide}
892 */
893 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
894
895 /**
896 * Mask for scrollbar style.
897 * {@hide}
898 */
899 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
900
901 /**
902 * View flag indicating that the screen should remain on while the
903 * window containing this view is visible to the user. This effectively
904 * takes care of automatically setting the WindowManager's
905 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
906 */
907 public static final int KEEP_SCREEN_ON = 0x04000000;
908
909 /**
910 * View flag indicating whether this view should have sound effects enabled
911 * for events such as clicking and touching.
912 */
913 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
914
915 /**
916 * View flag indicating whether this view should have haptic feedback
917 * enabled for events such as long presses.
918 */
919 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
920
921 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700922 * <p>Indicates that the view hierarchy should stop saving state when
923 * it reaches this view. If state saving is initiated immediately at
924 * the view, it will be allowed.
925 * {@hide}
926 */
927 static final int PARENT_SAVE_DISABLED = 0x20000000;
928
929 /**
930 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
931 * {@hide}
932 */
933 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
934
935 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700936 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
937 * should add all focusable Views regardless if they are focusable in touch mode.
938 */
939 public static final int FOCUSABLES_ALL = 0x00000000;
940
941 /**
942 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
943 * should add only Views focusable in touch mode.
944 */
945 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
946
947 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 * Use with {@link #focusSearch}. Move focus to the previous selectable
949 * item.
950 */
951 public static final int FOCUS_BACKWARD = 0x00000001;
952
953 /**
954 * Use with {@link #focusSearch}. Move focus to the next selectable
955 * item.
956 */
957 public static final int FOCUS_FORWARD = 0x00000002;
958
959 /**
960 * Use with {@link #focusSearch}. Move focus to the left.
961 */
962 public static final int FOCUS_LEFT = 0x00000011;
963
964 /**
965 * Use with {@link #focusSearch}. Move focus up.
966 */
967 public static final int FOCUS_UP = 0x00000021;
968
969 /**
970 * Use with {@link #focusSearch}. Move focus to the right.
971 */
972 public static final int FOCUS_RIGHT = 0x00000042;
973
974 /**
975 * Use with {@link #focusSearch}. Move focus down.
976 */
977 public static final int FOCUS_DOWN = 0x00000082;
978
979 /**
980 * Base View state sets
981 */
982 // Singles
983 /**
984 * Indicates the view has no states set. States are used with
985 * {@link android.graphics.drawable.Drawable} to change the drawing of the
986 * view depending on its state.
987 *
988 * @see android.graphics.drawable.Drawable
989 * @see #getDrawableState()
990 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -0700991 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 /**
993 * Indicates the view is enabled. States are used with
994 * {@link android.graphics.drawable.Drawable} to change the drawing of the
995 * view depending on its state.
996 *
997 * @see android.graphics.drawable.Drawable
998 * @see #getDrawableState()
999 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001000 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 /**
1002 * Indicates the view is focused. States are used with
1003 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1004 * view depending on its state.
1005 *
1006 * @see android.graphics.drawable.Drawable
1007 * @see #getDrawableState()
1008 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001009 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 /**
1011 * Indicates the view is selected. States are used with
1012 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1013 * view depending on its state.
1014 *
1015 * @see android.graphics.drawable.Drawable
1016 * @see #getDrawableState()
1017 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001018 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 /**
1020 * Indicates the view is pressed. States are used with
1021 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1022 * view depending on its state.
1023 *
1024 * @see android.graphics.drawable.Drawable
1025 * @see #getDrawableState()
1026 * @hide
1027 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001028 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 /**
1030 * Indicates the view's window has focus. States are used with
1031 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1032 * view depending on its state.
1033 *
1034 * @see android.graphics.drawable.Drawable
1035 * @see #getDrawableState()
1036 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001037 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 // Doubles
1039 /**
1040 * Indicates the view is enabled and has the focus.
1041 *
1042 * @see #ENABLED_STATE_SET
1043 * @see #FOCUSED_STATE_SET
1044 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001045 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 /**
1047 * Indicates the view is enabled and selected.
1048 *
1049 * @see #ENABLED_STATE_SET
1050 * @see #SELECTED_STATE_SET
1051 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001052 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 /**
1054 * Indicates the view is enabled and that its window has focus.
1055 *
1056 * @see #ENABLED_STATE_SET
1057 * @see #WINDOW_FOCUSED_STATE_SET
1058 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001059 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 /**
1061 * Indicates the view is focused and selected.
1062 *
1063 * @see #FOCUSED_STATE_SET
1064 * @see #SELECTED_STATE_SET
1065 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001066 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 /**
1068 * Indicates the view has the focus and that its window has the focus.
1069 *
1070 * @see #FOCUSED_STATE_SET
1071 * @see #WINDOW_FOCUSED_STATE_SET
1072 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001073 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 /**
1075 * Indicates the view is selected and that its window has the focus.
1076 *
1077 * @see #SELECTED_STATE_SET
1078 * @see #WINDOW_FOCUSED_STATE_SET
1079 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001080 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 // Triples
1082 /**
1083 * Indicates the view is enabled, focused and selected.
1084 *
1085 * @see #ENABLED_STATE_SET
1086 * @see #FOCUSED_STATE_SET
1087 * @see #SELECTED_STATE_SET
1088 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001089 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 /**
1091 * Indicates the view is enabled, focused and its window has the focus.
1092 *
1093 * @see #ENABLED_STATE_SET
1094 * @see #FOCUSED_STATE_SET
1095 * @see #WINDOW_FOCUSED_STATE_SET
1096 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001097 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 /**
1099 * Indicates the view is enabled, selected and its window has the focus.
1100 *
1101 * @see #ENABLED_STATE_SET
1102 * @see #SELECTED_STATE_SET
1103 * @see #WINDOW_FOCUSED_STATE_SET
1104 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001105 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 /**
1107 * Indicates the view is focused, selected and its window has the focus.
1108 *
1109 * @see #FOCUSED_STATE_SET
1110 * @see #SELECTED_STATE_SET
1111 * @see #WINDOW_FOCUSED_STATE_SET
1112 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001113 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 /**
1115 * Indicates the view is enabled, focused, selected and its window
1116 * has the focus.
1117 *
1118 * @see #ENABLED_STATE_SET
1119 * @see #FOCUSED_STATE_SET
1120 * @see #SELECTED_STATE_SET
1121 * @see #WINDOW_FOCUSED_STATE_SET
1122 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001123 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 /**
1125 * Indicates the view is pressed and its window has the focus.
1126 *
1127 * @see #PRESSED_STATE_SET
1128 * @see #WINDOW_FOCUSED_STATE_SET
1129 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001130 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 /**
1132 * Indicates the view is pressed and selected.
1133 *
1134 * @see #PRESSED_STATE_SET
1135 * @see #SELECTED_STATE_SET
1136 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001137 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 /**
1139 * Indicates the view is pressed, selected and its window has the focus.
1140 *
1141 * @see #PRESSED_STATE_SET
1142 * @see #SELECTED_STATE_SET
1143 * @see #WINDOW_FOCUSED_STATE_SET
1144 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001145 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 /**
1147 * Indicates the view is pressed and focused.
1148 *
1149 * @see #PRESSED_STATE_SET
1150 * @see #FOCUSED_STATE_SET
1151 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001152 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 /**
1154 * Indicates the view is pressed, focused and its window has the focus.
1155 *
1156 * @see #PRESSED_STATE_SET
1157 * @see #FOCUSED_STATE_SET
1158 * @see #WINDOW_FOCUSED_STATE_SET
1159 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001160 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 /**
1162 * Indicates the view is pressed, focused and selected.
1163 *
1164 * @see #PRESSED_STATE_SET
1165 * @see #SELECTED_STATE_SET
1166 * @see #FOCUSED_STATE_SET
1167 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001168 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 /**
1170 * Indicates the view is pressed, focused, selected and its window has the focus.
1171 *
1172 * @see #PRESSED_STATE_SET
1173 * @see #FOCUSED_STATE_SET
1174 * @see #SELECTED_STATE_SET
1175 * @see #WINDOW_FOCUSED_STATE_SET
1176 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001177 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 /**
1179 * Indicates the view is pressed and enabled.
1180 *
1181 * @see #PRESSED_STATE_SET
1182 * @see #ENABLED_STATE_SET
1183 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001184 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 /**
1186 * Indicates the view is pressed, enabled and its window has the focus.
1187 *
1188 * @see #PRESSED_STATE_SET
1189 * @see #ENABLED_STATE_SET
1190 * @see #WINDOW_FOCUSED_STATE_SET
1191 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001192 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 /**
1194 * Indicates the view is pressed, enabled and selected.
1195 *
1196 * @see #PRESSED_STATE_SET
1197 * @see #ENABLED_STATE_SET
1198 * @see #SELECTED_STATE_SET
1199 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001200 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 /**
1202 * Indicates the view is pressed, enabled, selected and its window has the
1203 * focus.
1204 *
1205 * @see #PRESSED_STATE_SET
1206 * @see #ENABLED_STATE_SET
1207 * @see #SELECTED_STATE_SET
1208 * @see #WINDOW_FOCUSED_STATE_SET
1209 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001210 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 /**
1212 * Indicates the view is pressed, enabled and focused.
1213 *
1214 * @see #PRESSED_STATE_SET
1215 * @see #ENABLED_STATE_SET
1216 * @see #FOCUSED_STATE_SET
1217 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001218 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 /**
1220 * Indicates the view is pressed, enabled, focused and its window has the
1221 * focus.
1222 *
1223 * @see #PRESSED_STATE_SET
1224 * @see #ENABLED_STATE_SET
1225 * @see #FOCUSED_STATE_SET
1226 * @see #WINDOW_FOCUSED_STATE_SET
1227 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001228 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 /**
1230 * Indicates the view is pressed, enabled, focused and selected.
1231 *
1232 * @see #PRESSED_STATE_SET
1233 * @see #ENABLED_STATE_SET
1234 * @see #SELECTED_STATE_SET
1235 * @see #FOCUSED_STATE_SET
1236 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001237 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 /**
1239 * Indicates the view is pressed, enabled, focused, selected and its window
1240 * has the focus.
1241 *
1242 * @see #PRESSED_STATE_SET
1243 * @see #ENABLED_STATE_SET
1244 * @see #SELECTED_STATE_SET
1245 * @see #FOCUSED_STATE_SET
1246 * @see #WINDOW_FOCUSED_STATE_SET
1247 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001248 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249
1250 /**
1251 * The order here is very important to {@link #getDrawableState()}
1252 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001253 private static final int[][] VIEW_STATE_SETS;
1254
Romain Guyb051e892010-09-28 19:09:36 -07001255 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1256 static final int VIEW_STATE_SELECTED = 1 << 1;
1257 static final int VIEW_STATE_FOCUSED = 1 << 2;
1258 static final int VIEW_STATE_ENABLED = 1 << 3;
1259 static final int VIEW_STATE_PRESSED = 1 << 4;
1260 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001261 static final int VIEW_STATE_ACCELERATED = 1 << 6;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001262
1263 static final int[] VIEW_STATE_IDS = new int[] {
1264 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1265 R.attr.state_selected, VIEW_STATE_SELECTED,
1266 R.attr.state_focused, VIEW_STATE_FOCUSED,
1267 R.attr.state_enabled, VIEW_STATE_ENABLED,
1268 R.attr.state_pressed, VIEW_STATE_PRESSED,
1269 R.attr.state_activated, VIEW_STATE_ACTIVATED,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001270 R.attr.state_accelerated, VIEW_STATE_ACCELERATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 };
1272
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001273 static {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001274 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1275 throw new IllegalStateException(
1276 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1277 }
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001278 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001279 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001280 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001281 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001282 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001283 orderedIds[i * 2] = viewState;
1284 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001285 }
1286 }
1287 }
Romain Guyb051e892010-09-28 19:09:36 -07001288 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1289 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1290 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001291 int numBits = Integer.bitCount(i);
1292 int[] set = new int[numBits];
1293 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001294 for (int j = 0; j < orderedIds.length; j += 2) {
1295 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001296 set[pos++] = orderedIds[j];
1297 }
1298 }
1299 VIEW_STATE_SETS[i] = set;
1300 }
1301
1302 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1303 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1304 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1305 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1306 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1307 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1308 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1309 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1310 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1311 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1312 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1313 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1314 | VIEW_STATE_FOCUSED];
1315 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1316 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1317 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1318 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1319 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1320 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1321 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1322 | VIEW_STATE_ENABLED];
1323 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1324 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1325 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1326 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1327 | VIEW_STATE_ENABLED];
1328 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1329 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1330 | VIEW_STATE_ENABLED];
1331 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1332 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1333 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1334
1335 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1336 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1337 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1338 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1339 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1340 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1341 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1342 | VIEW_STATE_PRESSED];
1343 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1344 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1345 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1346 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1347 | VIEW_STATE_PRESSED];
1348 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1349 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1350 | VIEW_STATE_PRESSED];
1351 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1352 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1353 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1354 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1355 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1356 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1357 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1358 | VIEW_STATE_PRESSED];
1359 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1360 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1361 | VIEW_STATE_PRESSED];
1362 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1363 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1364 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1365 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1366 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1367 | VIEW_STATE_PRESSED];
1368 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1369 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1370 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1371 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1372 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1373 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1374 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1375 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1376 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1377 | VIEW_STATE_PRESSED];
1378 }
1379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 /**
1381 * Used by views that contain lists of items. This state indicates that
1382 * the view is showing the last item.
1383 * @hide
1384 */
1385 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1386 /**
1387 * Used by views that contain lists of items. This state indicates that
1388 * the view is showing the first item.
1389 * @hide
1390 */
1391 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1392 /**
1393 * Used by views that contain lists of items. This state indicates that
1394 * the view is showing the middle item.
1395 * @hide
1396 */
1397 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1398 /**
1399 * Used by views that contain lists of items. This state indicates that
1400 * the view is showing only one item.
1401 * @hide
1402 */
1403 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1404 /**
1405 * Used by views that contain lists of items. This state indicates that
1406 * the view is pressed and showing the last item.
1407 * @hide
1408 */
1409 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1410 /**
1411 * Used by views that contain lists of items. This state indicates that
1412 * the view is pressed and showing the first item.
1413 * @hide
1414 */
1415 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1416 /**
1417 * Used by views that contain lists of items. This state indicates that
1418 * the view is pressed and showing the middle item.
1419 * @hide
1420 */
1421 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1422 /**
1423 * Used by views that contain lists of items. This state indicates that
1424 * the view is pressed and showing only one item.
1425 * @hide
1426 */
1427 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1428
1429 /**
1430 * Temporary Rect currently for use in setBackground(). This will probably
1431 * be extended in the future to hold our own class with more than just
1432 * a Rect. :)
1433 */
1434 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001435
1436 /**
1437 * Map used to store views' tags.
1438 */
1439 private static WeakHashMap<View, SparseArray<Object>> sTags;
1440
1441 /**
1442 * Lock used to access sTags.
1443 */
1444 private static final Object sTagsLock = new Object();
1445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 /**
1447 * The animation currently associated with this view.
1448 * @hide
1449 */
1450 protected Animation mCurrentAnimation = null;
1451
1452 /**
1453 * Width as measured during measure pass.
1454 * {@hide}
1455 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001456 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 protected int mMeasuredWidth;
1458
1459 /**
1460 * Height as measured during measure pass.
1461 * {@hide}
1462 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001463 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 protected int mMeasuredHeight;
1465
1466 /**
1467 * The view's identifier.
1468 * {@hide}
1469 *
1470 * @see #setId(int)
1471 * @see #getId()
1472 */
1473 @ViewDebug.ExportedProperty(resolveId = true)
1474 int mID = NO_ID;
1475
1476 /**
1477 * The view's tag.
1478 * {@hide}
1479 *
1480 * @see #setTag(Object)
1481 * @see #getTag()
1482 */
1483 protected Object mTag;
1484
1485 // for mPrivateFlags:
1486 /** {@hide} */
1487 static final int WANTS_FOCUS = 0x00000001;
1488 /** {@hide} */
1489 static final int FOCUSED = 0x00000002;
1490 /** {@hide} */
1491 static final int SELECTED = 0x00000004;
1492 /** {@hide} */
1493 static final int IS_ROOT_NAMESPACE = 0x00000008;
1494 /** {@hide} */
1495 static final int HAS_BOUNDS = 0x00000010;
1496 /** {@hide} */
1497 static final int DRAWN = 0x00000020;
1498 /**
1499 * When this flag is set, this view is running an animation on behalf of its
1500 * children and should therefore not cancel invalidate requests, even if they
1501 * lie outside of this view's bounds.
1502 *
1503 * {@hide}
1504 */
1505 static final int DRAW_ANIMATION = 0x00000040;
1506 /** {@hide} */
1507 static final int SKIP_DRAW = 0x00000080;
1508 /** {@hide} */
1509 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1510 /** {@hide} */
1511 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1512 /** {@hide} */
1513 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1514 /** {@hide} */
1515 static final int MEASURED_DIMENSION_SET = 0x00000800;
1516 /** {@hide} */
1517 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001518 /** {@hide} */
1519 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520
1521 private static final int PRESSED = 0x00004000;
1522
1523 /** {@hide} */
1524 static final int DRAWING_CACHE_VALID = 0x00008000;
1525 /**
1526 * Flag used to indicate that this view should be drawn once more (and only once
1527 * more) after its animation has completed.
1528 * {@hide}
1529 */
1530 static final int ANIMATION_STARTED = 0x00010000;
1531
1532 private static final int SAVE_STATE_CALLED = 0x00020000;
1533
1534 /**
1535 * Indicates that the View returned true when onSetAlpha() was called and that
1536 * the alpha must be restored.
1537 * {@hide}
1538 */
1539 static final int ALPHA_SET = 0x00040000;
1540
1541 /**
1542 * Set by {@link #setScrollContainer(boolean)}.
1543 */
1544 static final int SCROLL_CONTAINER = 0x00080000;
1545
1546 /**
1547 * Set by {@link #setScrollContainer(boolean)}.
1548 */
1549 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1550
1551 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001552 * View flag indicating whether this view was invalidated (fully or partially.)
1553 *
1554 * @hide
1555 */
1556 static final int DIRTY = 0x00200000;
1557
1558 /**
1559 * View flag indicating whether this view was invalidated by an opaque
1560 * invalidate request.
1561 *
1562 * @hide
1563 */
1564 static final int DIRTY_OPAQUE = 0x00400000;
1565
1566 /**
1567 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1568 *
1569 * @hide
1570 */
1571 static final int DIRTY_MASK = 0x00600000;
1572
1573 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001574 * Indicates whether the background is opaque.
1575 *
1576 * @hide
1577 */
1578 static final int OPAQUE_BACKGROUND = 0x00800000;
1579
1580 /**
1581 * Indicates whether the scrollbars are opaque.
1582 *
1583 * @hide
1584 */
1585 static final int OPAQUE_SCROLLBARS = 0x01000000;
1586
1587 /**
1588 * Indicates whether the view is opaque.
1589 *
1590 * @hide
1591 */
1592 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001593
1594 /**
1595 * Indicates a prepressed state;
1596 * the short time between ACTION_DOWN and recognizing
1597 * a 'real' press. Prepressed is used to recognize quick taps
1598 * even when they are shorter than ViewConfiguration.getTapTimeout().
1599 *
1600 * @hide
1601 */
1602 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001603
1604 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001605 * Indicates whether the view is temporarily detached.
1606 *
1607 * @hide
1608 */
1609 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001610
1611 /**
1612 * Indicates that we should awaken scroll bars once attached
1613 *
1614 * @hide
1615 */
1616 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001617
1618 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001619 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1620 * for transform operations
1621 *
1622 * @hide
1623 */
Adam Powellf37df072010-09-17 16:22:49 -07001624 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001625
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001626 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001627 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001628
Chet Haasefd2b0022010-08-06 13:08:56 -07001629 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 * The parent this view is attached to.
1631 * {@hide}
1632 *
1633 * @see #getParent()
1634 */
1635 protected ViewParent mParent;
1636
1637 /**
1638 * {@hide}
1639 */
1640 AttachInfo mAttachInfo;
1641
1642 /**
1643 * {@hide}
1644 */
Romain Guy809a7f62009-05-14 15:44:42 -07001645 @ViewDebug.ExportedProperty(flagMapping = {
1646 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1647 name = "FORCE_LAYOUT"),
1648 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1649 name = "LAYOUT_REQUIRED"),
1650 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001651 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001652 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1653 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1654 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1655 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1656 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 int mPrivateFlags;
1658
1659 /**
1660 * Count of how many windows this view has been attached to.
1661 */
1662 int mWindowAttachCount;
1663
1664 /**
1665 * The layout parameters associated with this view and used by the parent
1666 * {@link android.view.ViewGroup} to determine how this view should be
1667 * laid out.
1668 * {@hide}
1669 */
1670 protected ViewGroup.LayoutParams mLayoutParams;
1671
1672 /**
1673 * The view flags hold various views states.
1674 * {@hide}
1675 */
1676 @ViewDebug.ExportedProperty
1677 int mViewFlags;
1678
1679 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001680 * The transform matrix for the View. This transform is calculated internally
1681 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1682 * is used by default. Do *not* use this variable directly; instead call
1683 * getMatrix(), which will automatically recalculate the matrix if necessary
1684 * to get the correct matrix based on the latest rotation and scale properties.
1685 */
1686 private final Matrix mMatrix = new Matrix();
1687
1688 /**
1689 * The transform matrix for the View. This transform is calculated internally
1690 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1691 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001692 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001693 * to get the correct matrix based on the latest rotation and scale properties.
1694 */
1695 private Matrix mInverseMatrix;
1696
1697 /**
1698 * An internal variable that tracks whether we need to recalculate the
1699 * transform matrix, based on whether the rotation or scaleX/Y properties
1700 * have changed since the matrix was last calculated.
1701 */
1702 private boolean mMatrixDirty = false;
1703
1704 /**
1705 * An internal variable that tracks whether we need to recalculate the
1706 * transform matrix, based on whether the rotation or scaleX/Y properties
1707 * have changed since the matrix was last calculated.
1708 */
1709 private boolean mInverseMatrixDirty = true;
1710
1711 /**
1712 * A variable that tracks whether we need to recalculate the
1713 * transform matrix, based on whether the rotation or scaleX/Y properties
1714 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001715 * is only valid after a call to updateMatrix() or to a function that
1716 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001717 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001718 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001719
1720 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001721 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1722 */
1723 private Camera mCamera = null;
1724
1725 /**
1726 * This matrix is used when computing the matrix for 3D rotations.
1727 */
1728 private Matrix matrix3D = null;
1729
1730 /**
1731 * These prev values are used to recalculate a centered pivot point when necessary. The
1732 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1733 * set), so thes values are only used then as well.
1734 */
1735 private int mPrevWidth = -1;
1736 private int mPrevHeight = -1;
1737
1738 /**
1739 * Convenience value to check for float values that are close enough to zero to be considered
1740 * zero.
1741 */
Romain Guy2542d192010-08-18 11:47:12 -07001742 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001743
1744 /**
1745 * The degrees rotation around the vertical axis through the pivot point.
1746 */
1747 @ViewDebug.ExportedProperty
1748 private float mRotationY = 0f;
1749
1750 /**
1751 * The degrees rotation around the horizontal axis through the pivot point.
1752 */
1753 @ViewDebug.ExportedProperty
1754 private float mRotationX = 0f;
1755
1756 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001757 * The degrees rotation around the pivot point.
1758 */
1759 @ViewDebug.ExportedProperty
1760 private float mRotation = 0f;
1761
1762 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001763 * The amount of translation of the object away from its left property (post-layout).
1764 */
1765 @ViewDebug.ExportedProperty
1766 private float mTranslationX = 0f;
1767
1768 /**
1769 * The amount of translation of the object away from its top property (post-layout).
1770 */
1771 @ViewDebug.ExportedProperty
1772 private float mTranslationY = 0f;
1773
1774 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001775 * The amount of scale in the x direction around the pivot point. A
1776 * value of 1 means no scaling is applied.
1777 */
1778 @ViewDebug.ExportedProperty
1779 private float mScaleX = 1f;
1780
1781 /**
1782 * The amount of scale in the y direction around the pivot point. A
1783 * value of 1 means no scaling is applied.
1784 */
1785 @ViewDebug.ExportedProperty
1786 private float mScaleY = 1f;
1787
1788 /**
1789 * The amount of scale in the x direction around the pivot point. A
1790 * value of 1 means no scaling is applied.
1791 */
1792 @ViewDebug.ExportedProperty
1793 private float mPivotX = 0f;
1794
1795 /**
1796 * The amount of scale in the y direction around the pivot point. A
1797 * value of 1 means no scaling is applied.
1798 */
1799 @ViewDebug.ExportedProperty
1800 private float mPivotY = 0f;
1801
1802 /**
1803 * The opacity of the View. This is a value from 0 to 1, where 0 means
1804 * completely transparent and 1 means completely opaque.
1805 */
1806 @ViewDebug.ExportedProperty
1807 private float mAlpha = 1f;
1808
1809 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 * The distance in pixels from the left edge of this view's parent
1811 * to the left edge of this view.
1812 * {@hide}
1813 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001814 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 protected int mLeft;
1816 /**
1817 * The distance in pixels from the left edge of this view's parent
1818 * to the right edge of this view.
1819 * {@hide}
1820 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001821 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 protected int mRight;
1823 /**
1824 * The distance in pixels from the top edge of this view's parent
1825 * to the top edge of this view.
1826 * {@hide}
1827 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001828 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 protected int mTop;
1830 /**
1831 * The distance in pixels from the top edge of this view's parent
1832 * to the bottom edge of this view.
1833 * {@hide}
1834 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001835 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 protected int mBottom;
1837
1838 /**
1839 * The offset, in pixels, by which the content of this view is scrolled
1840 * horizontally.
1841 * {@hide}
1842 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001843 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 protected int mScrollX;
1845 /**
1846 * The offset, in pixels, by which the content of this view is scrolled
1847 * vertically.
1848 * {@hide}
1849 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001850 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 protected int mScrollY;
1852
1853 /**
1854 * The left padding in pixels, that is the distance in pixels between the
1855 * left edge of this view and the left edge of its content.
1856 * {@hide}
1857 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001858 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 protected int mPaddingLeft;
1860 /**
1861 * The right padding in pixels, that is the distance in pixels between the
1862 * right edge of this view and the right edge of its content.
1863 * {@hide}
1864 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001865 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 protected int mPaddingRight;
1867 /**
1868 * The top padding in pixels, that is the distance in pixels between the
1869 * top edge of this view and the top edge of its content.
1870 * {@hide}
1871 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001872 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 protected int mPaddingTop;
1874 /**
1875 * The bottom padding in pixels, that is the distance in pixels between the
1876 * bottom edge of this view and the bottom edge of its content.
1877 * {@hide}
1878 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001879 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 protected int mPaddingBottom;
1881
1882 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001883 * Briefly describes the view and is primarily used for accessibility support.
1884 */
1885 private CharSequence mContentDescription;
1886
1887 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 * Cache the paddingRight set by the user to append to the scrollbar's size.
1889 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001890 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 int mUserPaddingRight;
1892
1893 /**
1894 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1895 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001896 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 int mUserPaddingBottom;
1898
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001899 /**
1900 * @hide
1901 */
1902 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1903 /**
1904 * @hide
1905 */
1906 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907
1908 private Resources mResources = null;
1909
1910 private Drawable mBGDrawable;
1911
1912 private int mBackgroundResource;
1913 private boolean mBackgroundSizeChanged;
1914
1915 /**
1916 * Listener used to dispatch focus change events.
1917 * This field should be made private, so it is hidden from the SDK.
1918 * {@hide}
1919 */
1920 protected OnFocusChangeListener mOnFocusChangeListener;
1921
1922 /**
Chet Haase21cd1382010-09-01 17:42:29 -07001923 * Listeners for layout change events.
1924 */
1925 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
1926
1927 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 * Listener used to dispatch click events.
1929 * This field should be made private, so it is hidden from the SDK.
1930 * {@hide}
1931 */
1932 protected OnClickListener mOnClickListener;
1933
1934 /**
1935 * Listener used to dispatch long click events.
1936 * This field should be made private, so it is hidden from the SDK.
1937 * {@hide}
1938 */
1939 protected OnLongClickListener mOnLongClickListener;
1940
1941 /**
1942 * Listener used to build the context menu.
1943 * This field should be made private, so it is hidden from the SDK.
1944 * {@hide}
1945 */
1946 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
1947
1948 private OnKeyListener mOnKeyListener;
1949
1950 private OnTouchListener mOnTouchListener;
1951
Chris Tate32affef2010-10-18 15:29:21 -07001952 private OnDragListener mOnDragListener;
1953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 /**
1955 * The application environment this view lives in.
1956 * This field should be made private, so it is hidden from the SDK.
1957 * {@hide}
1958 */
1959 protected Context mContext;
1960
1961 private ScrollabilityCache mScrollCache;
1962
1963 private int[] mDrawableState = null;
1964
Romain Guy02890fd2010-08-06 17:58:44 -07001965 private Bitmap mDrawingCache;
1966 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07001967 private DisplayList mDisplayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968
1969 /**
1970 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
1971 * the user may specify which view to go to next.
1972 */
1973 private int mNextFocusLeftId = View.NO_ID;
1974
1975 /**
1976 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
1977 * the user may specify which view to go to next.
1978 */
1979 private int mNextFocusRightId = View.NO_ID;
1980
1981 /**
1982 * When this view has focus and the next focus is {@link #FOCUS_UP},
1983 * the user may specify which view to go to next.
1984 */
1985 private int mNextFocusUpId = View.NO_ID;
1986
1987 /**
1988 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
1989 * the user may specify which view to go to next.
1990 */
1991 private int mNextFocusDownId = View.NO_ID;
1992
1993 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08001994 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08001995 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08001996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 private UnsetPressedState mUnsetPressedState;
1998
1999 /**
2000 * Whether the long press's action has been invoked. The tap's action is invoked on the
2001 * up event while a long press is invoked as soon as the long press duration is reached, so
2002 * a long press could be performed before the tap is checked, in which case the tap's action
2003 * should not be invoked.
2004 */
2005 private boolean mHasPerformedLongPress;
2006
2007 /**
2008 * The minimum height of the view. We'll try our best to have the height
2009 * of this view to at least this amount.
2010 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002011 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 private int mMinHeight;
2013
2014 /**
2015 * The minimum width of the view. We'll try our best to have the width
2016 * of this view to at least this amount.
2017 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002018 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 private int mMinWidth;
2020
2021 /**
2022 * The delegate to handle touch events that are physically in this view
2023 * but should be handled by another view.
2024 */
2025 private TouchDelegate mTouchDelegate = null;
2026
2027 /**
2028 * Solid color to use as a background when creating the drawing cache. Enables
2029 * the cache to use 16 bit bitmaps instead of 32 bit.
2030 */
2031 private int mDrawingCacheBackgroundColor = 0;
2032
2033 /**
2034 * Special tree observer used when mAttachInfo is null.
2035 */
2036 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002037
2038 /**
2039 * Cache the touch slop from the context that created the view.
2040 */
2041 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002044 * Cache drag/drop state
2045 *
2046 */
2047 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002048
2049 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 * Simple constructor to use when creating a view from code.
2051 *
2052 * @param context The Context the view is running in, through which it can
2053 * access the current theme, resources, etc.
2054 */
2055 public View(Context context) {
2056 mContext = context;
2057 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002058 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002059 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
2061
2062 /**
2063 * Constructor that is called when inflating a view from XML. This is called
2064 * when a view is being constructed from an XML file, supplying attributes
2065 * that were specified in the XML file. This version uses a default style of
2066 * 0, so the only attribute values applied are those in the Context's Theme
2067 * and the given AttributeSet.
2068 *
2069 * <p>
2070 * The method onFinishInflate() will be called after all children have been
2071 * added.
2072 *
2073 * @param context The Context the view is running in, through which it can
2074 * access the current theme, resources, etc.
2075 * @param attrs The attributes of the XML tag that is inflating the view.
2076 * @see #View(Context, AttributeSet, int)
2077 */
2078 public View(Context context, AttributeSet attrs) {
2079 this(context, attrs, 0);
2080 }
2081
2082 /**
2083 * Perform inflation from XML and apply a class-specific base style. This
2084 * constructor of View allows subclasses to use their own base style when
2085 * they are inflating. For example, a Button class's constructor would call
2086 * this version of the super class constructor and supply
2087 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2088 * the theme's button style to modify all of the base view attributes (in
2089 * particular its background) as well as the Button class's attributes.
2090 *
2091 * @param context The Context the view is running in, through which it can
2092 * access the current theme, resources, etc.
2093 * @param attrs The attributes of the XML tag that is inflating the view.
2094 * @param defStyle The default style to apply to this view. If 0, no style
2095 * will be applied (beyond what is included in the theme). This may
2096 * either be an attribute resource, whose value will be retrieved
2097 * from the current theme, or an explicit style resource.
2098 * @see #View(Context, AttributeSet)
2099 */
2100 public View(Context context, AttributeSet attrs, int defStyle) {
2101 this(context);
2102
2103 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2104 defStyle, 0);
2105
2106 Drawable background = null;
2107
2108 int leftPadding = -1;
2109 int topPadding = -1;
2110 int rightPadding = -1;
2111 int bottomPadding = -1;
2112
2113 int padding = -1;
2114
2115 int viewFlagValues = 0;
2116 int viewFlagMasks = 0;
2117
2118 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 int x = 0;
2121 int y = 0;
2122
2123 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2124
2125 final int N = a.getIndexCount();
2126 for (int i = 0; i < N; i++) {
2127 int attr = a.getIndex(i);
2128 switch (attr) {
2129 case com.android.internal.R.styleable.View_background:
2130 background = a.getDrawable(attr);
2131 break;
2132 case com.android.internal.R.styleable.View_padding:
2133 padding = a.getDimensionPixelSize(attr, -1);
2134 break;
2135 case com.android.internal.R.styleable.View_paddingLeft:
2136 leftPadding = a.getDimensionPixelSize(attr, -1);
2137 break;
2138 case com.android.internal.R.styleable.View_paddingTop:
2139 topPadding = a.getDimensionPixelSize(attr, -1);
2140 break;
2141 case com.android.internal.R.styleable.View_paddingRight:
2142 rightPadding = a.getDimensionPixelSize(attr, -1);
2143 break;
2144 case com.android.internal.R.styleable.View_paddingBottom:
2145 bottomPadding = a.getDimensionPixelSize(attr, -1);
2146 break;
2147 case com.android.internal.R.styleable.View_scrollX:
2148 x = a.getDimensionPixelOffset(attr, 0);
2149 break;
2150 case com.android.internal.R.styleable.View_scrollY:
2151 y = a.getDimensionPixelOffset(attr, 0);
2152 break;
2153 case com.android.internal.R.styleable.View_id:
2154 mID = a.getResourceId(attr, NO_ID);
2155 break;
2156 case com.android.internal.R.styleable.View_tag:
2157 mTag = a.getText(attr);
2158 break;
2159 case com.android.internal.R.styleable.View_fitsSystemWindows:
2160 if (a.getBoolean(attr, false)) {
2161 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2162 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2163 }
2164 break;
2165 case com.android.internal.R.styleable.View_focusable:
2166 if (a.getBoolean(attr, false)) {
2167 viewFlagValues |= FOCUSABLE;
2168 viewFlagMasks |= FOCUSABLE_MASK;
2169 }
2170 break;
2171 case com.android.internal.R.styleable.View_focusableInTouchMode:
2172 if (a.getBoolean(attr, false)) {
2173 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2174 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2175 }
2176 break;
2177 case com.android.internal.R.styleable.View_clickable:
2178 if (a.getBoolean(attr, false)) {
2179 viewFlagValues |= CLICKABLE;
2180 viewFlagMasks |= CLICKABLE;
2181 }
2182 break;
2183 case com.android.internal.R.styleable.View_longClickable:
2184 if (a.getBoolean(attr, false)) {
2185 viewFlagValues |= LONG_CLICKABLE;
2186 viewFlagMasks |= LONG_CLICKABLE;
2187 }
2188 break;
2189 case com.android.internal.R.styleable.View_saveEnabled:
2190 if (!a.getBoolean(attr, true)) {
2191 viewFlagValues |= SAVE_DISABLED;
2192 viewFlagMasks |= SAVE_DISABLED_MASK;
2193 }
2194 break;
2195 case com.android.internal.R.styleable.View_duplicateParentState:
2196 if (a.getBoolean(attr, false)) {
2197 viewFlagValues |= DUPLICATE_PARENT_STATE;
2198 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2199 }
2200 break;
2201 case com.android.internal.R.styleable.View_visibility:
2202 final int visibility = a.getInt(attr, 0);
2203 if (visibility != 0) {
2204 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2205 viewFlagMasks |= VISIBILITY_MASK;
2206 }
2207 break;
2208 case com.android.internal.R.styleable.View_drawingCacheQuality:
2209 final int cacheQuality = a.getInt(attr, 0);
2210 if (cacheQuality != 0) {
2211 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2212 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2213 }
2214 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002215 case com.android.internal.R.styleable.View_contentDescription:
2216 mContentDescription = a.getString(attr);
2217 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2219 if (!a.getBoolean(attr, true)) {
2220 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2221 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2222 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002223 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2225 if (!a.getBoolean(attr, true)) {
2226 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2227 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2228 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002229 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 case R.styleable.View_scrollbars:
2231 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2232 if (scrollbars != SCROLLBARS_NONE) {
2233 viewFlagValues |= scrollbars;
2234 viewFlagMasks |= SCROLLBARS_MASK;
2235 initializeScrollbars(a);
2236 }
2237 break;
2238 case R.styleable.View_fadingEdge:
2239 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2240 if (fadingEdge != FADING_EDGE_NONE) {
2241 viewFlagValues |= fadingEdge;
2242 viewFlagMasks |= FADING_EDGE_MASK;
2243 initializeFadingEdge(a);
2244 }
2245 break;
2246 case R.styleable.View_scrollbarStyle:
2247 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2248 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2249 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2250 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2251 }
2252 break;
2253 case R.styleable.View_isScrollContainer:
2254 setScrollContainer = true;
2255 if (a.getBoolean(attr, false)) {
2256 setScrollContainer(true);
2257 }
2258 break;
2259 case com.android.internal.R.styleable.View_keepScreenOn:
2260 if (a.getBoolean(attr, false)) {
2261 viewFlagValues |= KEEP_SCREEN_ON;
2262 viewFlagMasks |= KEEP_SCREEN_ON;
2263 }
2264 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002265 case R.styleable.View_filterTouchesWhenObscured:
2266 if (a.getBoolean(attr, false)) {
2267 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2268 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2269 }
2270 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 case R.styleable.View_nextFocusLeft:
2272 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2273 break;
2274 case R.styleable.View_nextFocusRight:
2275 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2276 break;
2277 case R.styleable.View_nextFocusUp:
2278 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2279 break;
2280 case R.styleable.View_nextFocusDown:
2281 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2282 break;
2283 case R.styleable.View_minWidth:
2284 mMinWidth = a.getDimensionPixelSize(attr, 0);
2285 break;
2286 case R.styleable.View_minHeight:
2287 mMinHeight = a.getDimensionPixelSize(attr, 0);
2288 break;
Romain Guy9a817362009-05-01 10:57:14 -07002289 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002290 if (context.isRestricted()) {
2291 throw new IllegalStateException("The android:onClick attribute cannot "
2292 + "be used within a restricted context");
2293 }
2294
Romain Guy9a817362009-05-01 10:57:14 -07002295 final String handlerName = a.getString(attr);
2296 if (handlerName != null) {
2297 setOnClickListener(new OnClickListener() {
2298 private Method mHandler;
2299
2300 public void onClick(View v) {
2301 if (mHandler == null) {
2302 try {
2303 mHandler = getContext().getClass().getMethod(handlerName,
2304 View.class);
2305 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002306 int id = getId();
2307 String idText = id == NO_ID ? "" : " with id '"
2308 + getContext().getResources().getResourceEntryName(
2309 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002310 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002311 handlerName + "(View) in the activity "
2312 + getContext().getClass() + " for onClick handler"
2313 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002314 }
2315 }
2316
2317 try {
2318 mHandler.invoke(getContext(), View.this);
2319 } catch (IllegalAccessException e) {
2320 throw new IllegalStateException("Could not execute non "
2321 + "public method of the activity", e);
2322 } catch (InvocationTargetException e) {
2323 throw new IllegalStateException("Could not execute "
2324 + "method of the activity", e);
2325 }
2326 }
2327 });
2328 }
2329 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 }
2331 }
2332
2333 if (background != null) {
2334 setBackgroundDrawable(background);
2335 }
2336
2337 if (padding >= 0) {
2338 leftPadding = padding;
2339 topPadding = padding;
2340 rightPadding = padding;
2341 bottomPadding = padding;
2342 }
2343
2344 // If the user specified the padding (either with android:padding or
2345 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2346 // use the default padding or the padding from the background drawable
2347 // (stored at this point in mPadding*)
2348 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2349 topPadding >= 0 ? topPadding : mPaddingTop,
2350 rightPadding >= 0 ? rightPadding : mPaddingRight,
2351 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2352
2353 if (viewFlagMasks != 0) {
2354 setFlags(viewFlagValues, viewFlagMasks);
2355 }
2356
2357 // Needs to be called after mViewFlags is set
2358 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2359 recomputePadding();
2360 }
2361
2362 if (x != 0 || y != 0) {
2363 scrollTo(x, y);
2364 }
2365
2366 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2367 setScrollContainer(true);
2368 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002369
2370 computeOpaqueFlags();
2371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 a.recycle();
2373 }
2374
2375 /**
2376 * Non-public constructor for use in testing
2377 */
2378 View() {
2379 }
2380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 /**
2382 * <p>
2383 * Initializes the fading edges from a given set of styled attributes. This
2384 * method should be called by subclasses that need fading edges and when an
2385 * instance of these subclasses is created programmatically rather than
2386 * being inflated from XML. This method is automatically called when the XML
2387 * is inflated.
2388 * </p>
2389 *
2390 * @param a the styled attributes set to initialize the fading edges from
2391 */
2392 protected void initializeFadingEdge(TypedArray a) {
2393 initScrollCache();
2394
2395 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2396 R.styleable.View_fadingEdgeLength,
2397 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2398 }
2399
2400 /**
2401 * Returns the size of the vertical faded edges used to indicate that more
2402 * content in this view is visible.
2403 *
2404 * @return The size in pixels of the vertical faded edge or 0 if vertical
2405 * faded edges are not enabled for this view.
2406 * @attr ref android.R.styleable#View_fadingEdgeLength
2407 */
2408 public int getVerticalFadingEdgeLength() {
2409 if (isVerticalFadingEdgeEnabled()) {
2410 ScrollabilityCache cache = mScrollCache;
2411 if (cache != null) {
2412 return cache.fadingEdgeLength;
2413 }
2414 }
2415 return 0;
2416 }
2417
2418 /**
2419 * Set the size of the faded edge used to indicate that more content in this
2420 * view is available. Will not change whether the fading edge is enabled; use
2421 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2422 * to enable the fading edge for the vertical or horizontal fading edges.
2423 *
2424 * @param length The size in pixels of the faded edge used to indicate that more
2425 * content in this view is visible.
2426 */
2427 public void setFadingEdgeLength(int length) {
2428 initScrollCache();
2429 mScrollCache.fadingEdgeLength = length;
2430 }
2431
2432 /**
2433 * Returns the size of the horizontal faded edges used to indicate that more
2434 * content in this view is visible.
2435 *
2436 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2437 * faded edges are not enabled for this view.
2438 * @attr ref android.R.styleable#View_fadingEdgeLength
2439 */
2440 public int getHorizontalFadingEdgeLength() {
2441 if (isHorizontalFadingEdgeEnabled()) {
2442 ScrollabilityCache cache = mScrollCache;
2443 if (cache != null) {
2444 return cache.fadingEdgeLength;
2445 }
2446 }
2447 return 0;
2448 }
2449
2450 /**
2451 * Returns the width of the vertical scrollbar.
2452 *
2453 * @return The width in pixels of the vertical scrollbar or 0 if there
2454 * is no vertical scrollbar.
2455 */
2456 public int getVerticalScrollbarWidth() {
2457 ScrollabilityCache cache = mScrollCache;
2458 if (cache != null) {
2459 ScrollBarDrawable scrollBar = cache.scrollBar;
2460 if (scrollBar != null) {
2461 int size = scrollBar.getSize(true);
2462 if (size <= 0) {
2463 size = cache.scrollBarSize;
2464 }
2465 return size;
2466 }
2467 return 0;
2468 }
2469 return 0;
2470 }
2471
2472 /**
2473 * Returns the height of the horizontal scrollbar.
2474 *
2475 * @return The height in pixels of the horizontal scrollbar or 0 if
2476 * there is no horizontal scrollbar.
2477 */
2478 protected int getHorizontalScrollbarHeight() {
2479 ScrollabilityCache cache = mScrollCache;
2480 if (cache != null) {
2481 ScrollBarDrawable scrollBar = cache.scrollBar;
2482 if (scrollBar != null) {
2483 int size = scrollBar.getSize(false);
2484 if (size <= 0) {
2485 size = cache.scrollBarSize;
2486 }
2487 return size;
2488 }
2489 return 0;
2490 }
2491 return 0;
2492 }
2493
2494 /**
2495 * <p>
2496 * Initializes the scrollbars from a given set of styled attributes. This
2497 * method should be called by subclasses that need scrollbars and when an
2498 * instance of these subclasses is created programmatically rather than
2499 * being inflated from XML. This method is automatically called when the XML
2500 * is inflated.
2501 * </p>
2502 *
2503 * @param a the styled attributes set to initialize the scrollbars from
2504 */
2505 protected void initializeScrollbars(TypedArray a) {
2506 initScrollCache();
2507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002509
2510 if (scrollabilityCache.scrollBar == null) {
2511 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2512 }
2513
Romain Guy8bda2482010-03-02 11:42:11 -08002514 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515
Mike Cleronf116bf82009-09-27 19:14:12 -07002516 if (!fadeScrollbars) {
2517 scrollabilityCache.state = ScrollabilityCache.ON;
2518 }
2519 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2520
2521
2522 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2523 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2524 .getScrollBarFadeDuration());
2525 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2526 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2527 ViewConfiguration.getScrollDefaultDelay());
2528
2529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2531 com.android.internal.R.styleable.View_scrollbarSize,
2532 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2533
2534 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2535 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2536
2537 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2538 if (thumb != null) {
2539 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2540 }
2541
2542 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2543 false);
2544 if (alwaysDraw) {
2545 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2546 }
2547
2548 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2549 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2550
2551 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2552 if (thumb != null) {
2553 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2554 }
2555
2556 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2557 false);
2558 if (alwaysDraw) {
2559 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2560 }
2561
2562 // Re-apply user/background padding so that scrollbar(s) get added
2563 recomputePadding();
2564 }
2565
2566 /**
2567 * <p>
2568 * Initalizes the scrollability cache if necessary.
2569 * </p>
2570 */
2571 private void initScrollCache() {
2572 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002573 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575 }
2576
2577 /**
2578 * Register a callback to be invoked when focus of this view changed.
2579 *
2580 * @param l The callback that will run.
2581 */
2582 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2583 mOnFocusChangeListener = l;
2584 }
2585
2586 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002587 * Add a listener that will be called when the bounds of the view change due to
2588 * layout processing.
2589 *
2590 * @param listener The listener that will be called when layout bounds change.
2591 */
2592 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2593 if (mOnLayoutChangeListeners == null) {
2594 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2595 }
2596 mOnLayoutChangeListeners.add(listener);
2597 }
2598
2599 /**
2600 * Remove a listener for layout changes.
2601 *
2602 * @param listener The listener for layout bounds change.
2603 */
2604 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2605 if (mOnLayoutChangeListeners == null) {
2606 return;
2607 }
2608 mOnLayoutChangeListeners.remove(listener);
2609 }
2610
2611 /**
2612 * Gets the current list of listeners for layout changes.
2613 * @return
2614 */
2615 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2616 return mOnLayoutChangeListeners;
2617 }
2618
2619 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 * Returns the focus-change callback registered for this view.
2621 *
2622 * @return The callback, or null if one is not registered.
2623 */
2624 public OnFocusChangeListener getOnFocusChangeListener() {
2625 return mOnFocusChangeListener;
2626 }
2627
2628 /**
2629 * Register a callback to be invoked when this view is clicked. If this view is not
2630 * clickable, it becomes clickable.
2631 *
2632 * @param l The callback that will run
2633 *
2634 * @see #setClickable(boolean)
2635 */
2636 public void setOnClickListener(OnClickListener l) {
2637 if (!isClickable()) {
2638 setClickable(true);
2639 }
2640 mOnClickListener = l;
2641 }
2642
2643 /**
2644 * Register a callback to be invoked when this view is clicked and held. If this view is not
2645 * long clickable, it becomes long clickable.
2646 *
2647 * @param l The callback that will run
2648 *
2649 * @see #setLongClickable(boolean)
2650 */
2651 public void setOnLongClickListener(OnLongClickListener l) {
2652 if (!isLongClickable()) {
2653 setLongClickable(true);
2654 }
2655 mOnLongClickListener = l;
2656 }
2657
2658 /**
2659 * Register a callback to be invoked when the context menu for this view is
2660 * being built. If this view is not long clickable, it becomes long clickable.
2661 *
2662 * @param l The callback that will run
2663 *
2664 */
2665 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2666 if (!isLongClickable()) {
2667 setLongClickable(true);
2668 }
2669 mOnCreateContextMenuListener = l;
2670 }
2671
2672 /**
2673 * Call this view's OnClickListener, if it is defined.
2674 *
2675 * @return True there was an assigned OnClickListener that was called, false
2676 * otherwise is returned.
2677 */
2678 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002679 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 if (mOnClickListener != null) {
2682 playSoundEffect(SoundEffectConstants.CLICK);
2683 mOnClickListener.onClick(this);
2684 return true;
2685 }
2686
2687 return false;
2688 }
2689
2690 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002691 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2692 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002694 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 */
2696 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002697 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 boolean handled = false;
2700 if (mOnLongClickListener != null) {
2701 handled = mOnLongClickListener.onLongClick(View.this);
2702 }
2703 if (!handled) {
2704 handled = showContextMenu();
2705 }
2706 if (handled) {
2707 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2708 }
2709 return handled;
2710 }
2711
2712 /**
2713 * Bring up the context menu for this view.
2714 *
2715 * @return Whether a context menu was displayed.
2716 */
2717 public boolean showContextMenu() {
2718 return getParent().showContextMenuForChild(this);
2719 }
2720
2721 /**
Adam Powell6e346362010-07-23 10:18:23 -07002722 * Start an action mode.
2723 *
2724 * @param callback Callback that will control the lifecycle of the action mode
2725 * @return The new action mode if it is started, null otherwise
2726 *
2727 * @see ActionMode
2728 */
2729 public ActionMode startActionMode(ActionMode.Callback callback) {
2730 return getParent().startActionModeForChild(this, callback);
2731 }
2732
2733 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 * Register a callback to be invoked when a key is pressed in this view.
2735 * @param l the key listener to attach to this view
2736 */
2737 public void setOnKeyListener(OnKeyListener l) {
2738 mOnKeyListener = l;
2739 }
2740
2741 /**
2742 * Register a callback to be invoked when a touch event is sent to this view.
2743 * @param l the touch listener to attach to this view
2744 */
2745 public void setOnTouchListener(OnTouchListener l) {
2746 mOnTouchListener = l;
2747 }
2748
2749 /**
Chris Tate32affef2010-10-18 15:29:21 -07002750 * Register a callback to be invoked when a drag event is sent to this view.
2751 * @param l The drag listener to attach to this view
2752 */
2753 public void setOnDragListener(OnDragListener l) {
2754 mOnDragListener = l;
2755 }
2756
2757 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2759 *
2760 * Note: this does not check whether this {@link View} should get focus, it just
2761 * gives it focus no matter what. It should only be called internally by framework
2762 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2763 *
2764 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2765 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2766 * focus moved when requestFocus() is called. It may not always
2767 * apply, in which case use the default View.FOCUS_DOWN.
2768 * @param previouslyFocusedRect The rectangle of the view that had focus
2769 * prior in this View's coordinate system.
2770 */
2771 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2772 if (DBG) {
2773 System.out.println(this + " requestFocus()");
2774 }
2775
2776 if ((mPrivateFlags & FOCUSED) == 0) {
2777 mPrivateFlags |= FOCUSED;
2778
2779 if (mParent != null) {
2780 mParent.requestChildFocus(this, this);
2781 }
2782
2783 onFocusChanged(true, direction, previouslyFocusedRect);
2784 refreshDrawableState();
2785 }
2786 }
2787
2788 /**
2789 * Request that a rectangle of this view be visible on the screen,
2790 * scrolling if necessary just enough.
2791 *
2792 * <p>A View should call this if it maintains some notion of which part
2793 * of its content is interesting. For example, a text editing view
2794 * should call this when its cursor moves.
2795 *
2796 * @param rectangle The rectangle.
2797 * @return Whether any parent scrolled.
2798 */
2799 public boolean requestRectangleOnScreen(Rect rectangle) {
2800 return requestRectangleOnScreen(rectangle, false);
2801 }
2802
2803 /**
2804 * Request that a rectangle of this view be visible on the screen,
2805 * scrolling if necessary just enough.
2806 *
2807 * <p>A View should call this if it maintains some notion of which part
2808 * of its content is interesting. For example, a text editing view
2809 * should call this when its cursor moves.
2810 *
2811 * <p>When <code>immediate</code> is set to true, scrolling will not be
2812 * animated.
2813 *
2814 * @param rectangle The rectangle.
2815 * @param immediate True to forbid animated scrolling, false otherwise
2816 * @return Whether any parent scrolled.
2817 */
2818 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
2819 View child = this;
2820 ViewParent parent = mParent;
2821 boolean scrolled = false;
2822 while (parent != null) {
2823 scrolled |= parent.requestChildRectangleOnScreen(child,
2824 rectangle, immediate);
2825
2826 // offset rect so next call has the rectangle in the
2827 // coordinate system of its direct child.
2828 rectangle.offset(child.getLeft(), child.getTop());
2829 rectangle.offset(-child.getScrollX(), -child.getScrollY());
2830
2831 if (!(parent instanceof View)) {
2832 break;
2833 }
Romain Guy8506ab42009-06-11 17:35:47 -07002834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 child = (View) parent;
2836 parent = child.getParent();
2837 }
2838 return scrolled;
2839 }
2840
2841 /**
2842 * Called when this view wants to give up focus. This will cause
2843 * {@link #onFocusChanged} to be called.
2844 */
2845 public void clearFocus() {
2846 if (DBG) {
2847 System.out.println(this + " clearFocus()");
2848 }
2849
2850 if ((mPrivateFlags & FOCUSED) != 0) {
2851 mPrivateFlags &= ~FOCUSED;
2852
2853 if (mParent != null) {
2854 mParent.clearChildFocus(this);
2855 }
2856
2857 onFocusChanged(false, 0, null);
2858 refreshDrawableState();
2859 }
2860 }
2861
2862 /**
2863 * Called to clear the focus of a view that is about to be removed.
2864 * Doesn't call clearChildFocus, which prevents this view from taking
2865 * focus again before it has been removed from the parent
2866 */
2867 void clearFocusForRemoval() {
2868 if ((mPrivateFlags & FOCUSED) != 0) {
2869 mPrivateFlags &= ~FOCUSED;
2870
2871 onFocusChanged(false, 0, null);
2872 refreshDrawableState();
2873 }
2874 }
2875
2876 /**
2877 * Called internally by the view system when a new view is getting focus.
2878 * This is what clears the old focus.
2879 */
2880 void unFocus() {
2881 if (DBG) {
2882 System.out.println(this + " unFocus()");
2883 }
2884
2885 if ((mPrivateFlags & FOCUSED) != 0) {
2886 mPrivateFlags &= ~FOCUSED;
2887
2888 onFocusChanged(false, 0, null);
2889 refreshDrawableState();
2890 }
2891 }
2892
2893 /**
2894 * Returns true if this view has focus iteself, or is the ancestor of the
2895 * view that has focus.
2896 *
2897 * @return True if this view has or contains focus, false otherwise.
2898 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002899 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 public boolean hasFocus() {
2901 return (mPrivateFlags & FOCUSED) != 0;
2902 }
2903
2904 /**
2905 * Returns true if this view is focusable or if it contains a reachable View
2906 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
2907 * is a View whose parents do not block descendants focus.
2908 *
2909 * Only {@link #VISIBLE} views are considered focusable.
2910 *
2911 * @return True if the view is focusable or if the view contains a focusable
2912 * View, false otherwise.
2913 *
2914 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
2915 */
2916 public boolean hasFocusable() {
2917 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
2918 }
2919
2920 /**
2921 * Called by the view system when the focus state of this view changes.
2922 * When the focus change event is caused by directional navigation, direction
2923 * and previouslyFocusedRect provide insight into where the focus is coming from.
2924 * When overriding, be sure to call up through to the super class so that
2925 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07002926 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 * @param gainFocus True if the View has focus; false otherwise.
2928 * @param direction The direction focus has moved when requestFocus()
2929 * is called to give this view focus. Values are
Romain Guyea4823c2009-12-08 15:03:39 -08002930 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT} or
2931 * {@link #FOCUS_RIGHT}. It may not always apply, in which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 * case use the default.
2933 * @param previouslyFocusedRect The rectangle, in this view's coordinate
2934 * system, of the previously focused view. If applicable, this will be
2935 * passed in as finer grained information about where the focus is coming
2936 * from (in addition to direction). Will be <code>null</code> otherwise.
2937 */
2938 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07002939 if (gainFocus) {
2940 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2941 }
2942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 InputMethodManager imm = InputMethodManager.peekInstance();
2944 if (!gainFocus) {
2945 if (isPressed()) {
2946 setPressed(false);
2947 }
2948 if (imm != null && mAttachInfo != null
2949 && mAttachInfo.mHasWindowFocus) {
2950 imm.focusOut(this);
2951 }
Romain Guya2431d02009-04-30 16:30:00 -07002952 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 } else if (imm != null && mAttachInfo != null
2954 && mAttachInfo.mHasWindowFocus) {
2955 imm.focusIn(this);
2956 }
Romain Guy8506ab42009-06-11 17:35:47 -07002957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 invalidate();
2959 if (mOnFocusChangeListener != null) {
2960 mOnFocusChangeListener.onFocusChange(this, gainFocus);
2961 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002962
2963 if (mAttachInfo != null) {
2964 mAttachInfo.mKeyDispatchState.reset(this);
2965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 }
2967
2968 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002969 * {@inheritDoc}
2970 */
2971 public void sendAccessibilityEvent(int eventType) {
2972 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2973 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
2974 }
2975 }
2976
2977 /**
2978 * {@inheritDoc}
2979 */
2980 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
2981 event.setClassName(getClass().getName());
2982 event.setPackageName(getContext().getPackageName());
2983 event.setEnabled(isEnabled());
2984 event.setContentDescription(mContentDescription);
2985
2986 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
2987 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
2988 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
2989 event.setItemCount(focusablesTempList.size());
2990 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
2991 focusablesTempList.clear();
2992 }
2993
2994 dispatchPopulateAccessibilityEvent(event);
2995
2996 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
2997 }
2998
2999 /**
3000 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3001 * to be populated.
3002 *
3003 * @param event The event.
3004 *
3005 * @return True if the event population was completed.
3006 */
3007 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3008 return false;
3009 }
3010
3011 /**
3012 * Gets the {@link View} description. It briefly describes the view and is
3013 * primarily used for accessibility support. Set this property to enable
3014 * better accessibility support for your application. This is especially
3015 * true for views that do not have textual representation (For example,
3016 * ImageButton).
3017 *
3018 * @return The content descriptiopn.
3019 *
3020 * @attr ref android.R.styleable#View_contentDescription
3021 */
3022 public CharSequence getContentDescription() {
3023 return mContentDescription;
3024 }
3025
3026 /**
3027 * Sets the {@link View} description. It briefly describes the view and is
3028 * primarily used for accessibility support. Set this property to enable
3029 * better accessibility support for your application. This is especially
3030 * true for views that do not have textual representation (For example,
3031 * ImageButton).
3032 *
3033 * @param contentDescription The content description.
3034 *
3035 * @attr ref android.R.styleable#View_contentDescription
3036 */
3037 public void setContentDescription(CharSequence contentDescription) {
3038 mContentDescription = contentDescription;
3039 }
3040
3041 /**
Romain Guya2431d02009-04-30 16:30:00 -07003042 * Invoked whenever this view loses focus, either by losing window focus or by losing
3043 * focus within its window. This method can be used to clear any state tied to the
3044 * focus. For instance, if a button is held pressed with the trackball and the window
3045 * loses focus, this method can be used to cancel the press.
3046 *
3047 * Subclasses of View overriding this method should always call super.onFocusLost().
3048 *
3049 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003050 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003051 *
3052 * @hide pending API council approval
3053 */
3054 protected void onFocusLost() {
3055 resetPressedState();
3056 }
3057
3058 private void resetPressedState() {
3059 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3060 return;
3061 }
3062
3063 if (isPressed()) {
3064 setPressed(false);
3065
3066 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003067 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003068 }
3069 }
3070 }
3071
3072 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 * Returns true if this view has focus
3074 *
3075 * @return True if this view has focus, false otherwise.
3076 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003077 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 public boolean isFocused() {
3079 return (mPrivateFlags & FOCUSED) != 0;
3080 }
3081
3082 /**
3083 * Find the view in the hierarchy rooted at this view that currently has
3084 * focus.
3085 *
3086 * @return The view that currently has focus, or null if no focused view can
3087 * be found.
3088 */
3089 public View findFocus() {
3090 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3091 }
3092
3093 /**
3094 * Change whether this view is one of the set of scrollable containers in
3095 * its window. This will be used to determine whether the window can
3096 * resize or must pan when a soft input area is open -- scrollable
3097 * containers allow the window to use resize mode since the container
3098 * will appropriately shrink.
3099 */
3100 public void setScrollContainer(boolean isScrollContainer) {
3101 if (isScrollContainer) {
3102 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3103 mAttachInfo.mScrollContainers.add(this);
3104 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3105 }
3106 mPrivateFlags |= SCROLL_CONTAINER;
3107 } else {
3108 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3109 mAttachInfo.mScrollContainers.remove(this);
3110 }
3111 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3112 }
3113 }
3114
3115 /**
3116 * Returns the quality of the drawing cache.
3117 *
3118 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3119 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3120 *
3121 * @see #setDrawingCacheQuality(int)
3122 * @see #setDrawingCacheEnabled(boolean)
3123 * @see #isDrawingCacheEnabled()
3124 *
3125 * @attr ref android.R.styleable#View_drawingCacheQuality
3126 */
3127 public int getDrawingCacheQuality() {
3128 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3129 }
3130
3131 /**
3132 * Set the drawing cache quality of this view. This value is used only when the
3133 * drawing cache is enabled
3134 *
3135 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3136 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3137 *
3138 * @see #getDrawingCacheQuality()
3139 * @see #setDrawingCacheEnabled(boolean)
3140 * @see #isDrawingCacheEnabled()
3141 *
3142 * @attr ref android.R.styleable#View_drawingCacheQuality
3143 */
3144 public void setDrawingCacheQuality(int quality) {
3145 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3146 }
3147
3148 /**
3149 * Returns whether the screen should remain on, corresponding to the current
3150 * value of {@link #KEEP_SCREEN_ON}.
3151 *
3152 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3153 *
3154 * @see #setKeepScreenOn(boolean)
3155 *
3156 * @attr ref android.R.styleable#View_keepScreenOn
3157 */
3158 public boolean getKeepScreenOn() {
3159 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3160 }
3161
3162 /**
3163 * Controls whether the screen should remain on, modifying the
3164 * value of {@link #KEEP_SCREEN_ON}.
3165 *
3166 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3167 *
3168 * @see #getKeepScreenOn()
3169 *
3170 * @attr ref android.R.styleable#View_keepScreenOn
3171 */
3172 public void setKeepScreenOn(boolean keepScreenOn) {
3173 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3174 }
3175
3176 /**
3177 * @return The user specified next focus ID.
3178 *
3179 * @attr ref android.R.styleable#View_nextFocusLeft
3180 */
3181 public int getNextFocusLeftId() {
3182 return mNextFocusLeftId;
3183 }
3184
3185 /**
3186 * Set the id of the view to use for the next focus
3187 *
3188 * @param nextFocusLeftId
3189 *
3190 * @attr ref android.R.styleable#View_nextFocusLeft
3191 */
3192 public void setNextFocusLeftId(int nextFocusLeftId) {
3193 mNextFocusLeftId = nextFocusLeftId;
3194 }
3195
3196 /**
3197 * @return The user specified next focus ID.
3198 *
3199 * @attr ref android.R.styleable#View_nextFocusRight
3200 */
3201 public int getNextFocusRightId() {
3202 return mNextFocusRightId;
3203 }
3204
3205 /**
3206 * Set the id of the view to use for the next focus
3207 *
3208 * @param nextFocusRightId
3209 *
3210 * @attr ref android.R.styleable#View_nextFocusRight
3211 */
3212 public void setNextFocusRightId(int nextFocusRightId) {
3213 mNextFocusRightId = nextFocusRightId;
3214 }
3215
3216 /**
3217 * @return The user specified next focus ID.
3218 *
3219 * @attr ref android.R.styleable#View_nextFocusUp
3220 */
3221 public int getNextFocusUpId() {
3222 return mNextFocusUpId;
3223 }
3224
3225 /**
3226 * Set the id of the view to use for the next focus
3227 *
3228 * @param nextFocusUpId
3229 *
3230 * @attr ref android.R.styleable#View_nextFocusUp
3231 */
3232 public void setNextFocusUpId(int nextFocusUpId) {
3233 mNextFocusUpId = nextFocusUpId;
3234 }
3235
3236 /**
3237 * @return The user specified next focus ID.
3238 *
3239 * @attr ref android.R.styleable#View_nextFocusDown
3240 */
3241 public int getNextFocusDownId() {
3242 return mNextFocusDownId;
3243 }
3244
3245 /**
3246 * Set the id of the view to use for the next focus
3247 *
3248 * @param nextFocusDownId
3249 *
3250 * @attr ref android.R.styleable#View_nextFocusDown
3251 */
3252 public void setNextFocusDownId(int nextFocusDownId) {
3253 mNextFocusDownId = nextFocusDownId;
3254 }
3255
3256 /**
3257 * Returns the visibility of this view and all of its ancestors
3258 *
3259 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3260 */
3261 public boolean isShown() {
3262 View current = this;
3263 //noinspection ConstantConditions
3264 do {
3265 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3266 return false;
3267 }
3268 ViewParent parent = current.mParent;
3269 if (parent == null) {
3270 return false; // We are not attached to the view root
3271 }
3272 if (!(parent instanceof View)) {
3273 return true;
3274 }
3275 current = (View) parent;
3276 } while (current != null);
3277
3278 return false;
3279 }
3280
3281 /**
3282 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3283 * is set
3284 *
3285 * @param insets Insets for system windows
3286 *
3287 * @return True if this view applied the insets, false otherwise
3288 */
3289 protected boolean fitSystemWindows(Rect insets) {
3290 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3291 mPaddingLeft = insets.left;
3292 mPaddingTop = insets.top;
3293 mPaddingRight = insets.right;
3294 mPaddingBottom = insets.bottom;
3295 requestLayout();
3296 return true;
3297 }
3298 return false;
3299 }
3300
3301 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003302 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3303 * @return True if window has FITS_SYSTEM_WINDOWS set
3304 *
3305 * @hide
3306 */
3307 public boolean isFitsSystemWindowsFlagSet() {
3308 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3309 }
3310
3311 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 * Returns the visibility status for this view.
3313 *
3314 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3315 * @attr ref android.R.styleable#View_visibility
3316 */
3317 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003318 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3319 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3320 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 })
3322 public int getVisibility() {
3323 return mViewFlags & VISIBILITY_MASK;
3324 }
3325
3326 /**
3327 * Set the enabled state of this view.
3328 *
3329 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3330 * @attr ref android.R.styleable#View_visibility
3331 */
3332 @RemotableViewMethod
3333 public void setVisibility(int visibility) {
3334 setFlags(visibility, VISIBILITY_MASK);
3335 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3336 }
3337
3338 /**
3339 * Returns the enabled status for this view. The interpretation of the
3340 * enabled state varies by subclass.
3341 *
3342 * @return True if this view is enabled, false otherwise.
3343 */
3344 @ViewDebug.ExportedProperty
3345 public boolean isEnabled() {
3346 return (mViewFlags & ENABLED_MASK) == ENABLED;
3347 }
3348
3349 /**
3350 * Set the enabled state of this view. The interpretation of the enabled
3351 * state varies by subclass.
3352 *
3353 * @param enabled True if this view is enabled, false otherwise.
3354 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003355 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003357 if (enabled == isEnabled()) return;
3358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3360
3361 /*
3362 * The View most likely has to change its appearance, so refresh
3363 * the drawable state.
3364 */
3365 refreshDrawableState();
3366
3367 // Invalidate too, since the default behavior for views is to be
3368 // be drawn at 50% alpha rather than to change the drawable.
3369 invalidate();
3370 }
3371
3372 /**
3373 * Set whether this view can receive the focus.
3374 *
3375 * Setting this to false will also ensure that this view is not focusable
3376 * in touch mode.
3377 *
3378 * @param focusable If true, this view can receive the focus.
3379 *
3380 * @see #setFocusableInTouchMode(boolean)
3381 * @attr ref android.R.styleable#View_focusable
3382 */
3383 public void setFocusable(boolean focusable) {
3384 if (!focusable) {
3385 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3386 }
3387 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3388 }
3389
3390 /**
3391 * Set whether this view can receive focus while in touch mode.
3392 *
3393 * Setting this to true will also ensure that this view is focusable.
3394 *
3395 * @param focusableInTouchMode If true, this view can receive the focus while
3396 * in touch mode.
3397 *
3398 * @see #setFocusable(boolean)
3399 * @attr ref android.R.styleable#View_focusableInTouchMode
3400 */
3401 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3402 // Focusable in touch mode should always be set before the focusable flag
3403 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3404 // which, in touch mode, will not successfully request focus on this view
3405 // because the focusable in touch mode flag is not set
3406 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3407 if (focusableInTouchMode) {
3408 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3409 }
3410 }
3411
3412 /**
3413 * Set whether this view should have sound effects enabled for events such as
3414 * clicking and touching.
3415 *
3416 * <p>You may wish to disable sound effects for a view if you already play sounds,
3417 * for instance, a dial key that plays dtmf tones.
3418 *
3419 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3420 * @see #isSoundEffectsEnabled()
3421 * @see #playSoundEffect(int)
3422 * @attr ref android.R.styleable#View_soundEffectsEnabled
3423 */
3424 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3425 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3426 }
3427
3428 /**
3429 * @return whether this view should have sound effects enabled for events such as
3430 * clicking and touching.
3431 *
3432 * @see #setSoundEffectsEnabled(boolean)
3433 * @see #playSoundEffect(int)
3434 * @attr ref android.R.styleable#View_soundEffectsEnabled
3435 */
3436 @ViewDebug.ExportedProperty
3437 public boolean isSoundEffectsEnabled() {
3438 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3439 }
3440
3441 /**
3442 * Set whether this view should have haptic feedback for events such as
3443 * long presses.
3444 *
3445 * <p>You may wish to disable haptic feedback if your view already controls
3446 * its own haptic feedback.
3447 *
3448 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3449 * @see #isHapticFeedbackEnabled()
3450 * @see #performHapticFeedback(int)
3451 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3452 */
3453 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3454 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3455 }
3456
3457 /**
3458 * @return whether this view should have haptic feedback enabled for events
3459 * long presses.
3460 *
3461 * @see #setHapticFeedbackEnabled(boolean)
3462 * @see #performHapticFeedback(int)
3463 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3464 */
3465 @ViewDebug.ExportedProperty
3466 public boolean isHapticFeedbackEnabled() {
3467 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3468 }
3469
3470 /**
3471 * If this view doesn't do any drawing on its own, set this flag to
3472 * allow further optimizations. By default, this flag is not set on
3473 * View, but could be set on some View subclasses such as ViewGroup.
3474 *
3475 * Typically, if you override {@link #onDraw} you should clear this flag.
3476 *
3477 * @param willNotDraw whether or not this View draw on its own
3478 */
3479 public void setWillNotDraw(boolean willNotDraw) {
3480 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3481 }
3482
3483 /**
3484 * Returns whether or not this View draws on its own.
3485 *
3486 * @return true if this view has nothing to draw, false otherwise
3487 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003488 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 public boolean willNotDraw() {
3490 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3491 }
3492
3493 /**
3494 * When a View's drawing cache is enabled, drawing is redirected to an
3495 * offscreen bitmap. Some views, like an ImageView, must be able to
3496 * bypass this mechanism if they already draw a single bitmap, to avoid
3497 * unnecessary usage of the memory.
3498 *
3499 * @param willNotCacheDrawing true if this view does not cache its
3500 * drawing, false otherwise
3501 */
3502 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3503 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3504 }
3505
3506 /**
3507 * Returns whether or not this View can cache its drawing or not.
3508 *
3509 * @return true if this view does not cache its drawing, false otherwise
3510 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003511 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 public boolean willNotCacheDrawing() {
3513 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3514 }
3515
3516 /**
3517 * Indicates whether this view reacts to click events or not.
3518 *
3519 * @return true if the view is clickable, false otherwise
3520 *
3521 * @see #setClickable(boolean)
3522 * @attr ref android.R.styleable#View_clickable
3523 */
3524 @ViewDebug.ExportedProperty
3525 public boolean isClickable() {
3526 return (mViewFlags & CLICKABLE) == CLICKABLE;
3527 }
3528
3529 /**
3530 * Enables or disables click events for this view. When a view
3531 * is clickable it will change its state to "pressed" on every click.
3532 * Subclasses should set the view clickable to visually react to
3533 * user's clicks.
3534 *
3535 * @param clickable true to make the view clickable, false otherwise
3536 *
3537 * @see #isClickable()
3538 * @attr ref android.R.styleable#View_clickable
3539 */
3540 public void setClickable(boolean clickable) {
3541 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3542 }
3543
3544 /**
3545 * Indicates whether this view reacts to long click events or not.
3546 *
3547 * @return true if the view is long clickable, false otherwise
3548 *
3549 * @see #setLongClickable(boolean)
3550 * @attr ref android.R.styleable#View_longClickable
3551 */
3552 public boolean isLongClickable() {
3553 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3554 }
3555
3556 /**
3557 * Enables or disables long click events for this view. When a view is long
3558 * clickable it reacts to the user holding down the button for a longer
3559 * duration than a tap. This event can either launch the listener or a
3560 * context menu.
3561 *
3562 * @param longClickable true to make the view long clickable, false otherwise
3563 * @see #isLongClickable()
3564 * @attr ref android.R.styleable#View_longClickable
3565 */
3566 public void setLongClickable(boolean longClickable) {
3567 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3568 }
3569
3570 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003571 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003572 *
3573 * @see #isClickable()
3574 * @see #setClickable(boolean)
3575 *
3576 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3577 * the View's internal state from a previously set "pressed" state.
3578 */
3579 public void setPressed(boolean pressed) {
3580 if (pressed) {
3581 mPrivateFlags |= PRESSED;
3582 } else {
3583 mPrivateFlags &= ~PRESSED;
3584 }
3585 refreshDrawableState();
3586 dispatchSetPressed(pressed);
3587 }
3588
3589 /**
3590 * Dispatch setPressed to all of this View's children.
3591 *
3592 * @see #setPressed(boolean)
3593 *
3594 * @param pressed The new pressed state
3595 */
3596 protected void dispatchSetPressed(boolean pressed) {
3597 }
3598
3599 /**
3600 * Indicates whether the view is currently in pressed state. Unless
3601 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3602 * the pressed state.
3603 *
3604 * @see #setPressed
3605 * @see #isClickable()
3606 * @see #setClickable(boolean)
3607 *
3608 * @return true if the view is currently pressed, false otherwise
3609 */
3610 public boolean isPressed() {
3611 return (mPrivateFlags & PRESSED) == PRESSED;
3612 }
3613
3614 /**
3615 * Indicates whether this view will save its state (that is,
3616 * whether its {@link #onSaveInstanceState} method will be called).
3617 *
3618 * @return Returns true if the view state saving is enabled, else false.
3619 *
3620 * @see #setSaveEnabled(boolean)
3621 * @attr ref android.R.styleable#View_saveEnabled
3622 */
3623 public boolean isSaveEnabled() {
3624 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3625 }
3626
3627 /**
3628 * Controls whether the saving of this view's state is
3629 * enabled (that is, whether its {@link #onSaveInstanceState} method
3630 * will be called). Note that even if freezing is enabled, the
3631 * view still must have an id assigned to it (via {@link #setId setId()})
3632 * for its state to be saved. This flag can only disable the
3633 * saving of this view; any child views may still have their state saved.
3634 *
3635 * @param enabled Set to false to <em>disable</em> state saving, or true
3636 * (the default) to allow it.
3637 *
3638 * @see #isSaveEnabled()
3639 * @see #setId(int)
3640 * @see #onSaveInstanceState()
3641 * @attr ref android.R.styleable#View_saveEnabled
3642 */
3643 public void setSaveEnabled(boolean enabled) {
3644 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3645 }
3646
Jeff Brown85a31762010-09-01 17:01:00 -07003647 /**
3648 * Gets whether the framework should discard touches when the view's
3649 * window is obscured by another visible window.
3650 * Refer to the {@link View} security documentation for more details.
3651 *
3652 * @return True if touch filtering is enabled.
3653 *
3654 * @see #setFilterTouchesWhenObscured(boolean)
3655 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3656 */
3657 @ViewDebug.ExportedProperty
3658 public boolean getFilterTouchesWhenObscured() {
3659 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3660 }
3661
3662 /**
3663 * Sets whether the framework should discard touches when the view's
3664 * window is obscured by another visible window.
3665 * Refer to the {@link View} security documentation for more details.
3666 *
3667 * @param enabled True if touch filtering should be enabled.
3668 *
3669 * @see #getFilterTouchesWhenObscured
3670 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3671 */
3672 public void setFilterTouchesWhenObscured(boolean enabled) {
3673 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3674 FILTER_TOUCHES_WHEN_OBSCURED);
3675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676
3677 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003678 * Indicates whether the entire hierarchy under this view will save its
3679 * state when a state saving traversal occurs from its parent. The default
3680 * is true; if false, these views will not be saved unless
3681 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3682 *
3683 * @return Returns true if the view state saving from parent is enabled, else false.
3684 *
3685 * @see #setSaveFromParentEnabled(boolean)
3686 */
3687 public boolean isSaveFromParentEnabled() {
3688 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3689 }
3690
3691 /**
3692 * Controls whether the entire hierarchy under this view will save its
3693 * state when a state saving traversal occurs from its parent. The default
3694 * is true; if false, these views will not be saved unless
3695 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3696 *
3697 * @param enabled Set to false to <em>disable</em> state saving, or true
3698 * (the default) to allow it.
3699 *
3700 * @see #isSaveFromParentEnabled()
3701 * @see #setId(int)
3702 * @see #onSaveInstanceState()
3703 */
3704 public void setSaveFromParentEnabled(boolean enabled) {
3705 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
3706 }
3707
3708
3709 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 * Returns whether this View is able to take focus.
3711 *
3712 * @return True if this view can take focus, or false otherwise.
3713 * @attr ref android.R.styleable#View_focusable
3714 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003715 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 public final boolean isFocusable() {
3717 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3718 }
3719
3720 /**
3721 * When a view is focusable, it may not want to take focus when in touch mode.
3722 * For example, a button would like focus when the user is navigating via a D-pad
3723 * so that the user can click on it, but once the user starts touching the screen,
3724 * the button shouldn't take focus
3725 * @return Whether the view is focusable in touch mode.
3726 * @attr ref android.R.styleable#View_focusableInTouchMode
3727 */
3728 @ViewDebug.ExportedProperty
3729 public final boolean isFocusableInTouchMode() {
3730 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3731 }
3732
3733 /**
3734 * Find the nearest view in the specified direction that can take focus.
3735 * This does not actually give focus to that view.
3736 *
3737 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3738 *
3739 * @return The nearest focusable in the specified direction, or null if none
3740 * can be found.
3741 */
3742 public View focusSearch(int direction) {
3743 if (mParent != null) {
3744 return mParent.focusSearch(this, direction);
3745 } else {
3746 return null;
3747 }
3748 }
3749
3750 /**
3751 * This method is the last chance for the focused view and its ancestors to
3752 * respond to an arrow key. This is called when the focused view did not
3753 * consume the key internally, nor could the view system find a new view in
3754 * the requested direction to give focus to.
3755 *
3756 * @param focused The currently focused view.
3757 * @param direction The direction focus wants to move. One of FOCUS_UP,
3758 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3759 * @return True if the this view consumed this unhandled move.
3760 */
3761 public boolean dispatchUnhandledMove(View focused, int direction) {
3762 return false;
3763 }
3764
3765 /**
3766 * If a user manually specified the next view id for a particular direction,
3767 * use the root to look up the view. Once a view is found, it is cached
3768 * for future lookups.
3769 * @param root The root view of the hierarchy containing this view.
3770 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3771 * @return The user specified next view, or null if there is none.
3772 */
3773 View findUserSetNextFocus(View root, int direction) {
3774 switch (direction) {
3775 case FOCUS_LEFT:
3776 if (mNextFocusLeftId == View.NO_ID) return null;
3777 return findViewShouldExist(root, mNextFocusLeftId);
3778 case FOCUS_RIGHT:
3779 if (mNextFocusRightId == View.NO_ID) return null;
3780 return findViewShouldExist(root, mNextFocusRightId);
3781 case FOCUS_UP:
3782 if (mNextFocusUpId == View.NO_ID) return null;
3783 return findViewShouldExist(root, mNextFocusUpId);
3784 case FOCUS_DOWN:
3785 if (mNextFocusDownId == View.NO_ID) return null;
3786 return findViewShouldExist(root, mNextFocusDownId);
3787 }
3788 return null;
3789 }
3790
3791 private static View findViewShouldExist(View root, int childViewId) {
3792 View result = root.findViewById(childViewId);
3793 if (result == null) {
3794 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3795 + "by user for id " + childViewId);
3796 }
3797 return result;
3798 }
3799
3800 /**
3801 * Find and return all focusable views that are descendants of this view,
3802 * possibly including this view if it is focusable itself.
3803 *
3804 * @param direction The direction of the focus
3805 * @return A list of focusable views
3806 */
3807 public ArrayList<View> getFocusables(int direction) {
3808 ArrayList<View> result = new ArrayList<View>(24);
3809 addFocusables(result, direction);
3810 return result;
3811 }
3812
3813 /**
3814 * Add any focusable views that are descendants of this view (possibly
3815 * including this view if it is focusable itself) to views. If we are in touch mode,
3816 * only add views that are also focusable in touch mode.
3817 *
3818 * @param views Focusable views found so far
3819 * @param direction The direction of the focus
3820 */
3821 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003822 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003824
svetoslavganov75986cf2009-05-14 22:28:01 -07003825 /**
3826 * Adds any focusable views that are descendants of this view (possibly
3827 * including this view if it is focusable itself) to views. This method
3828 * adds all focusable views regardless if we are in touch mode or
3829 * only views focusable in touch mode if we are in touch mode depending on
3830 * the focusable mode paramater.
3831 *
3832 * @param views Focusable views found so far or null if all we are interested is
3833 * the number of focusables.
3834 * @param direction The direction of the focus.
3835 * @param focusableMode The type of focusables to be added.
3836 *
3837 * @see #FOCUSABLES_ALL
3838 * @see #FOCUSABLES_TOUCH_MODE
3839 */
3840 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3841 if (!isFocusable()) {
3842 return;
3843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844
svetoslavganov75986cf2009-05-14 22:28:01 -07003845 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3846 isInTouchMode() && !isFocusableInTouchMode()) {
3847 return;
3848 }
3849
3850 if (views != null) {
3851 views.add(this);
3852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 }
3854
3855 /**
3856 * Find and return all touchable views that are descendants of this view,
3857 * possibly including this view if it is touchable itself.
3858 *
3859 * @return A list of touchable views
3860 */
3861 public ArrayList<View> getTouchables() {
3862 ArrayList<View> result = new ArrayList<View>();
3863 addTouchables(result);
3864 return result;
3865 }
3866
3867 /**
3868 * Add any touchable views that are descendants of this view (possibly
3869 * including this view if it is touchable itself) to views.
3870 *
3871 * @param views Touchable views found so far
3872 */
3873 public void addTouchables(ArrayList<View> views) {
3874 final int viewFlags = mViewFlags;
3875
3876 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
3877 && (viewFlags & ENABLED_MASK) == ENABLED) {
3878 views.add(this);
3879 }
3880 }
3881
3882 /**
3883 * Call this to try to give focus to a specific view or to one of its
3884 * descendants.
3885 *
3886 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3887 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3888 * while the device is in touch mode.
3889 *
3890 * See also {@link #focusSearch}, which is what you call to say that you
3891 * have focus, and you want your parent to look for the next one.
3892 *
3893 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
3894 * {@link #FOCUS_DOWN} and <code>null</code>.
3895 *
3896 * @return Whether this view or one of its descendants actually took focus.
3897 */
3898 public final boolean requestFocus() {
3899 return requestFocus(View.FOCUS_DOWN);
3900 }
3901
3902
3903 /**
3904 * Call this to try to give focus to a specific view or to one of its
3905 * descendants and give it a hint about what direction focus is heading.
3906 *
3907 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3908 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3909 * while the device is in touch mode.
3910 *
3911 * See also {@link #focusSearch}, which is what you call to say that you
3912 * have focus, and you want your parent to look for the next one.
3913 *
3914 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
3915 * <code>null</code> set for the previously focused rectangle.
3916 *
3917 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3918 * @return Whether this view or one of its descendants actually took focus.
3919 */
3920 public final boolean requestFocus(int direction) {
3921 return requestFocus(direction, null);
3922 }
3923
3924 /**
3925 * Call this to try to give focus to a specific view or to one of its descendants
3926 * and give it hints about the direction and a specific rectangle that the focus
3927 * is coming from. The rectangle can help give larger views a finer grained hint
3928 * about where focus is coming from, and therefore, where to show selection, or
3929 * forward focus change internally.
3930 *
3931 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3932 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3933 * while the device is in touch mode.
3934 *
3935 * A View will not take focus if it is not visible.
3936 *
3937 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
3938 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
3939 *
3940 * See also {@link #focusSearch}, which is what you call to say that you
3941 * have focus, and you want your parent to look for the next one.
3942 *
3943 * You may wish to override this method if your custom {@link View} has an internal
3944 * {@link View} that it wishes to forward the request to.
3945 *
3946 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3947 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
3948 * to give a finer grained hint about where focus is coming from. May be null
3949 * if there is no hint.
3950 * @return Whether this view or one of its descendants actually took focus.
3951 */
3952 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
3953 // need to be focusable
3954 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
3955 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3956 return false;
3957 }
3958
3959 // need to be focusable in touch mode if in touch mode
3960 if (isInTouchMode() &&
3961 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
3962 return false;
3963 }
3964
3965 // need to not have any parents blocking us
3966 if (hasAncestorThatBlocksDescendantFocus()) {
3967 return false;
3968 }
3969
3970 handleFocusGainInternal(direction, previouslyFocusedRect);
3971 return true;
3972 }
3973
Christopher Tate2c095f32010-10-04 14:13:40 -07003974 /** Gets the ViewRoot, or null if not attached. */
3975 /*package*/ ViewRoot getViewRoot() {
3976 View root = getRootView();
3977 return root != null ? (ViewRoot)root.getParent() : null;
3978 }
3979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 /**
3981 * Call this to try to give focus to a specific view or to one of its descendants. This is a
3982 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
3983 * touch mode to request focus when they are touched.
3984 *
3985 * @return Whether this view or one of its descendants actually took focus.
3986 *
3987 * @see #isInTouchMode()
3988 *
3989 */
3990 public final boolean requestFocusFromTouch() {
3991 // Leave touch mode if we need to
3992 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07003993 ViewRoot viewRoot = getViewRoot();
3994 if (viewRoot != null) {
3995 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 }
3997 }
3998 return requestFocus(View.FOCUS_DOWN);
3999 }
4000
4001 /**
4002 * @return Whether any ancestor of this view blocks descendant focus.
4003 */
4004 private boolean hasAncestorThatBlocksDescendantFocus() {
4005 ViewParent ancestor = mParent;
4006 while (ancestor instanceof ViewGroup) {
4007 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4008 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4009 return true;
4010 } else {
4011 ancestor = vgAncestor.getParent();
4012 }
4013 }
4014 return false;
4015 }
4016
4017 /**
Romain Guya440b002010-02-24 15:57:54 -08004018 * @hide
4019 */
4020 public void dispatchStartTemporaryDetach() {
4021 onStartTemporaryDetach();
4022 }
4023
4024 /**
4025 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4027 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004028 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 */
4030 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004031 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004032 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004033 }
4034
4035 /**
4036 * @hide
4037 */
4038 public void dispatchFinishTemporaryDetach() {
4039 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 }
Romain Guy8506ab42009-06-11 17:35:47 -07004041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004042 /**
4043 * Called after {@link #onStartTemporaryDetach} when the container is done
4044 * changing the view.
4045 */
4046 public void onFinishTemporaryDetach() {
4047 }
Romain Guy8506ab42009-06-11 17:35:47 -07004048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 /**
4050 * capture information of this view for later analysis: developement only
4051 * check dynamic switch to make sure we only dump view
4052 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4053 */
4054 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004055 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 return;
4057 }
4058 ViewDebug.dumpCapturedView(subTag, v);
4059 }
4060
4061 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004062 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4063 * for this view's window. Returns null if the view is not currently attached
4064 * to the window. Normally you will not need to use this directly, but
4065 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4066 */
4067 public KeyEvent.DispatcherState getKeyDispatcherState() {
4068 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4069 }
4070
4071 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 * Dispatch a key event before it is processed by any input method
4073 * associated with the view hierarchy. This can be used to intercept
4074 * key events in special situations before the IME consumes them; a
4075 * typical example would be handling the BACK key to update the application's
4076 * UI instead of allowing the IME to see it and close itself.
4077 *
4078 * @param event The key event to be dispatched.
4079 * @return True if the event was handled, false otherwise.
4080 */
4081 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4082 return onKeyPreIme(event.getKeyCode(), event);
4083 }
4084
4085 /**
4086 * Dispatch a key event to the next view on the focus path. This path runs
4087 * from the top of the view tree down to the currently focused view. If this
4088 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4089 * the next node down the focus path. This method also fires any key
4090 * listeners.
4091 *
4092 * @param event The key event to be dispatched.
4093 * @return True if the event was handled, false otherwise.
4094 */
4095 public boolean dispatchKeyEvent(KeyEvent event) {
4096 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097
Romain Guyf607bdc2010-09-10 19:20:06 -07004098 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 if (android.util.Config.LOGV) {
4100 captureViewInfo("captureViewKeyEvent", this);
4101 }
4102
Romain Guyf607bdc2010-09-10 19:20:06 -07004103 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4105 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4106 return true;
4107 }
4108
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004109 return event.dispatch(this, mAttachInfo != null
4110 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 }
4112
4113 /**
4114 * Dispatches a key shortcut event.
4115 *
4116 * @param event The key event to be dispatched.
4117 * @return True if the event was handled by the view, false otherwise.
4118 */
4119 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4120 return onKeyShortcut(event.getKeyCode(), event);
4121 }
4122
4123 /**
4124 * Pass the touch screen motion event down to the target view, or this
4125 * view if it is the target.
4126 *
4127 * @param event The motion event to be dispatched.
4128 * @return True if the event was handled by the view, false otherwise.
4129 */
4130 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004131 if (!onFilterTouchEventForSecurity(event)) {
4132 return false;
4133 }
4134
Romain Guyf607bdc2010-09-10 19:20:06 -07004135 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4137 mOnTouchListener.onTouch(this, event)) {
4138 return true;
4139 }
4140 return onTouchEvent(event);
4141 }
4142
4143 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004144 * Filter the touch event to apply security policies.
4145 *
4146 * @param event The motion event to be filtered.
4147 * @return True if the event should be dispatched, false if the event should be dropped.
4148 *
4149 * @see #getFilterTouchesWhenObscured
4150 */
4151 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004152 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004153 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4154 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4155 // Window is obscured, drop this touch.
4156 return false;
4157 }
4158 return true;
4159 }
4160
4161 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 * Pass a trackball motion event down to the focused view.
4163 *
4164 * @param event The motion event to be dispatched.
4165 * @return True if the event was handled by the view, false otherwise.
4166 */
4167 public boolean dispatchTrackballEvent(MotionEvent event) {
4168 //Log.i("view", "view=" + this + ", " + event.toString());
4169 return onTrackballEvent(event);
4170 }
4171
4172 /**
4173 * Called when the window containing this view gains or loses window focus.
4174 * ViewGroups should override to route to their children.
4175 *
4176 * @param hasFocus True if the window containing this view now has focus,
4177 * false otherwise.
4178 */
4179 public void dispatchWindowFocusChanged(boolean hasFocus) {
4180 onWindowFocusChanged(hasFocus);
4181 }
4182
4183 /**
4184 * Called when the window containing this view gains or loses focus. Note
4185 * that this is separate from view focus: to receive key events, both
4186 * your view and its window must have focus. If a window is displayed
4187 * on top of yours that takes input focus, then your own window will lose
4188 * focus but the view focus will remain unchanged.
4189 *
4190 * @param hasWindowFocus True if the window containing this view now has
4191 * focus, false otherwise.
4192 */
4193 public void onWindowFocusChanged(boolean hasWindowFocus) {
4194 InputMethodManager imm = InputMethodManager.peekInstance();
4195 if (!hasWindowFocus) {
4196 if (isPressed()) {
4197 setPressed(false);
4198 }
4199 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4200 imm.focusOut(this);
4201 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004202 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004203 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004204 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4206 imm.focusIn(this);
4207 }
4208 refreshDrawableState();
4209 }
4210
4211 /**
4212 * Returns true if this view is in a window that currently has window focus.
4213 * Note that this is not the same as the view itself having focus.
4214 *
4215 * @return True if this view is in a window that currently has window focus.
4216 */
4217 public boolean hasWindowFocus() {
4218 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4219 }
4220
4221 /**
Adam Powell326d8082009-12-09 15:10:07 -08004222 * Dispatch a view visibility change down the view hierarchy.
4223 * ViewGroups should override to route to their children.
4224 * @param changedView The view whose visibility changed. Could be 'this' or
4225 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004226 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4227 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004228 */
4229 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4230 onVisibilityChanged(changedView, visibility);
4231 }
4232
4233 /**
4234 * Called when the visibility of the view or an ancestor of the view is changed.
4235 * @param changedView The view whose visibility changed. Could be 'this' or
4236 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004237 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4238 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004239 */
4240 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004241 if (visibility == VISIBLE) {
4242 if (mAttachInfo != null) {
4243 initialAwakenScrollBars();
4244 } else {
4245 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4246 }
4247 }
Adam Powell326d8082009-12-09 15:10:07 -08004248 }
4249
4250 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004251 * Dispatch a hint about whether this view is displayed. For instance, when
4252 * a View moves out of the screen, it might receives a display hint indicating
4253 * the view is not displayed. Applications should not <em>rely</em> on this hint
4254 * as there is no guarantee that they will receive one.
4255 *
4256 * @param hint A hint about whether or not this view is displayed:
4257 * {@link #VISIBLE} or {@link #INVISIBLE}.
4258 */
4259 public void dispatchDisplayHint(int hint) {
4260 onDisplayHint(hint);
4261 }
4262
4263 /**
4264 * Gives this view a hint about whether is displayed or not. For instance, when
4265 * a View moves out of the screen, it might receives a display hint indicating
4266 * the view is not displayed. Applications should not <em>rely</em> on this hint
4267 * as there is no guarantee that they will receive one.
4268 *
4269 * @param hint A hint about whether or not this view is displayed:
4270 * {@link #VISIBLE} or {@link #INVISIBLE}.
4271 */
4272 protected void onDisplayHint(int hint) {
4273 }
4274
4275 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 * Dispatch a window visibility change down the view hierarchy.
4277 * ViewGroups should override to route to their children.
4278 *
4279 * @param visibility The new visibility of the window.
4280 *
4281 * @see #onWindowVisibilityChanged
4282 */
4283 public void dispatchWindowVisibilityChanged(int visibility) {
4284 onWindowVisibilityChanged(visibility);
4285 }
4286
4287 /**
4288 * Called when the window containing has change its visibility
4289 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4290 * that this tells you whether or not your window is being made visible
4291 * to the window manager; this does <em>not</em> tell you whether or not
4292 * your window is obscured by other windows on the screen, even if it
4293 * is itself visible.
4294 *
4295 * @param visibility The new visibility of the window.
4296 */
4297 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004298 if (visibility == VISIBLE) {
4299 initialAwakenScrollBars();
4300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 }
4302
4303 /**
4304 * Returns the current visibility of the window this view is attached to
4305 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4306 *
4307 * @return Returns the current visibility of the view's window.
4308 */
4309 public int getWindowVisibility() {
4310 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4311 }
4312
4313 /**
4314 * Retrieve the overall visible display size in which the window this view is
4315 * attached to has been positioned in. This takes into account screen
4316 * decorations above the window, for both cases where the window itself
4317 * is being position inside of them or the window is being placed under
4318 * then and covered insets are used for the window to position its content
4319 * inside. In effect, this tells you the available area where content can
4320 * be placed and remain visible to users.
4321 *
4322 * <p>This function requires an IPC back to the window manager to retrieve
4323 * the requested information, so should not be used in performance critical
4324 * code like drawing.
4325 *
4326 * @param outRect Filled in with the visible display frame. If the view
4327 * is not attached to a window, this is simply the raw display size.
4328 */
4329 public void getWindowVisibleDisplayFrame(Rect outRect) {
4330 if (mAttachInfo != null) {
4331 try {
4332 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4333 } catch (RemoteException e) {
4334 return;
4335 }
4336 // XXX This is really broken, and probably all needs to be done
4337 // in the window manager, and we need to know more about whether
4338 // we want the area behind or in front of the IME.
4339 final Rect insets = mAttachInfo.mVisibleInsets;
4340 outRect.left += insets.left;
4341 outRect.top += insets.top;
4342 outRect.right -= insets.right;
4343 outRect.bottom -= insets.bottom;
4344 return;
4345 }
4346 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4347 outRect.set(0, 0, d.getWidth(), d.getHeight());
4348 }
4349
4350 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004351 * Dispatch a notification about a resource configuration change down
4352 * the view hierarchy.
4353 * ViewGroups should override to route to their children.
4354 *
4355 * @param newConfig The new resource configuration.
4356 *
4357 * @see #onConfigurationChanged
4358 */
4359 public void dispatchConfigurationChanged(Configuration newConfig) {
4360 onConfigurationChanged(newConfig);
4361 }
4362
4363 /**
4364 * Called when the current configuration of the resources being used
4365 * by the application have changed. You can use this to decide when
4366 * to reload resources that can changed based on orientation and other
4367 * configuration characterstics. You only need to use this if you are
4368 * not relying on the normal {@link android.app.Activity} mechanism of
4369 * recreating the activity instance upon a configuration change.
4370 *
4371 * @param newConfig The new resource configuration.
4372 */
4373 protected void onConfigurationChanged(Configuration newConfig) {
4374 }
4375
4376 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004377 * Private function to aggregate all per-view attributes in to the view
4378 * root.
4379 */
4380 void dispatchCollectViewAttributes(int visibility) {
4381 performCollectViewAttributes(visibility);
4382 }
4383
4384 void performCollectViewAttributes(int visibility) {
4385 //noinspection PointlessBitwiseExpression
4386 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4387 == (VISIBLE | KEEP_SCREEN_ON)) {
4388 mAttachInfo.mKeepScreenOn = true;
4389 }
4390 }
4391
4392 void needGlobalAttributesUpdate(boolean force) {
4393 AttachInfo ai = mAttachInfo;
4394 if (ai != null) {
4395 if (ai.mKeepScreenOn || force) {
4396 ai.mRecomputeGlobalAttributes = true;
4397 }
4398 }
4399 }
4400
4401 /**
4402 * Returns whether the device is currently in touch mode. Touch mode is entered
4403 * once the user begins interacting with the device by touch, and affects various
4404 * things like whether focus is always visible to the user.
4405 *
4406 * @return Whether the device is in touch mode.
4407 */
4408 @ViewDebug.ExportedProperty
4409 public boolean isInTouchMode() {
4410 if (mAttachInfo != null) {
4411 return mAttachInfo.mInTouchMode;
4412 } else {
4413 return ViewRoot.isInTouchMode();
4414 }
4415 }
4416
4417 /**
4418 * Returns the context the view is running in, through which it can
4419 * access the current theme, resources, etc.
4420 *
4421 * @return The view's Context.
4422 */
4423 @ViewDebug.CapturedViewProperty
4424 public final Context getContext() {
4425 return mContext;
4426 }
4427
4428 /**
4429 * Handle a key event before it is processed by any input method
4430 * associated with the view hierarchy. This can be used to intercept
4431 * key events in special situations before the IME consumes them; a
4432 * typical example would be handling the BACK key to update the application's
4433 * UI instead of allowing the IME to see it and close itself.
4434 *
4435 * @param keyCode The value in event.getKeyCode().
4436 * @param event Description of the key event.
4437 * @return If you handled the event, return true. If you want to allow the
4438 * event to be handled by the next receiver, return false.
4439 */
4440 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4441 return false;
4442 }
4443
4444 /**
4445 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4446 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4447 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4448 * is released, if the view is enabled and clickable.
4449 *
4450 * @param keyCode A key code that represents the button pressed, from
4451 * {@link android.view.KeyEvent}.
4452 * @param event The KeyEvent object that defines the button action.
4453 */
4454 public boolean onKeyDown(int keyCode, KeyEvent event) {
4455 boolean result = false;
4456
4457 switch (keyCode) {
4458 case KeyEvent.KEYCODE_DPAD_CENTER:
4459 case KeyEvent.KEYCODE_ENTER: {
4460 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4461 return true;
4462 }
4463 // Long clickable items don't necessarily have to be clickable
4464 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4465 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4466 (event.getRepeatCount() == 0)) {
4467 setPressed(true);
4468 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004469 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004470 }
4471 return true;
4472 }
4473 break;
4474 }
4475 }
4476 return result;
4477 }
4478
4479 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004480 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4481 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4482 * the event).
4483 */
4484 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4485 return false;
4486 }
4487
4488 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4490 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4491 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4492 * {@link KeyEvent#KEYCODE_ENTER} is released.
4493 *
4494 * @param keyCode A key code that represents the button pressed, from
4495 * {@link android.view.KeyEvent}.
4496 * @param event The KeyEvent object that defines the button action.
4497 */
4498 public boolean onKeyUp(int keyCode, KeyEvent event) {
4499 boolean result = false;
4500
4501 switch (keyCode) {
4502 case KeyEvent.KEYCODE_DPAD_CENTER:
4503 case KeyEvent.KEYCODE_ENTER: {
4504 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4505 return true;
4506 }
4507 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4508 setPressed(false);
4509
4510 if (!mHasPerformedLongPress) {
4511 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004512 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513
4514 result = performClick();
4515 }
4516 }
4517 break;
4518 }
4519 }
4520 return result;
4521 }
4522
4523 /**
4524 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4525 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4526 * the event).
4527 *
4528 * @param keyCode A key code that represents the button pressed, from
4529 * {@link android.view.KeyEvent}.
4530 * @param repeatCount The number of times the action was made.
4531 * @param event The KeyEvent object that defines the button action.
4532 */
4533 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4534 return false;
4535 }
4536
4537 /**
4538 * Called when an unhandled key shortcut event occurs.
4539 *
4540 * @param keyCode The value in event.getKeyCode().
4541 * @param event Description of the key event.
4542 * @return If you handled the event, return true. If you want to allow the
4543 * event to be handled by the next receiver, return false.
4544 */
4545 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4546 return false;
4547 }
4548
4549 /**
4550 * Check whether the called view is a text editor, in which case it
4551 * would make sense to automatically display a soft input window for
4552 * it. Subclasses should override this if they implement
4553 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004554 * a call on that method would return a non-null InputConnection, and
4555 * they are really a first-class editor that the user would normally
4556 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004557 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004558 * <p>The default implementation always returns false. This does
4559 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4560 * will not be called or the user can not otherwise perform edits on your
4561 * view; it is just a hint to the system that this is not the primary
4562 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004563 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004564 * @return Returns true if this view is a text editor, else false.
4565 */
4566 public boolean onCheckIsTextEditor() {
4567 return false;
4568 }
Romain Guy8506ab42009-06-11 17:35:47 -07004569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570 /**
4571 * Create a new InputConnection for an InputMethod to interact
4572 * with the view. The default implementation returns null, since it doesn't
4573 * support input methods. You can override this to implement such support.
4574 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004575 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 * <p>When implementing this, you probably also want to implement
4577 * {@link #onCheckIsTextEditor()} to indicate you will return a
4578 * non-null InputConnection.
4579 *
4580 * @param outAttrs Fill in with attribute information about the connection.
4581 */
4582 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4583 return null;
4584 }
4585
4586 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004587 * Called by the {@link android.view.inputmethod.InputMethodManager}
4588 * when a view who is not the current
4589 * input connection target is trying to make a call on the manager. The
4590 * default implementation returns false; you can override this to return
4591 * true for certain views if you are performing InputConnection proxying
4592 * to them.
4593 * @param view The View that is making the InputMethodManager call.
4594 * @return Return true to allow the call, false to reject.
4595 */
4596 public boolean checkInputConnectionProxy(View view) {
4597 return false;
4598 }
Romain Guy8506ab42009-06-11 17:35:47 -07004599
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004600 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004601 * Show the context menu for this view. It is not safe to hold on to the
4602 * menu after returning from this method.
4603 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004604 * You should normally not overload this method. Overload
4605 * {@link #onCreateContextMenu(ContextMenu)} or define an
4606 * {@link OnCreateContextMenuListener} to add items to the context menu.
4607 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 * @param menu The context menu to populate
4609 */
4610 public void createContextMenu(ContextMenu menu) {
4611 ContextMenuInfo menuInfo = getContextMenuInfo();
4612
4613 // Sets the current menu info so all items added to menu will have
4614 // my extra info set.
4615 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4616
4617 onCreateContextMenu(menu);
4618 if (mOnCreateContextMenuListener != null) {
4619 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4620 }
4621
4622 // Clear the extra information so subsequent items that aren't mine don't
4623 // have my extra info.
4624 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4625
4626 if (mParent != null) {
4627 mParent.createContextMenu(menu);
4628 }
4629 }
4630
4631 /**
4632 * Views should implement this if they have extra information to associate
4633 * with the context menu. The return result is supplied as a parameter to
4634 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4635 * callback.
4636 *
4637 * @return Extra information about the item for which the context menu
4638 * should be shown. This information will vary across different
4639 * subclasses of View.
4640 */
4641 protected ContextMenuInfo getContextMenuInfo() {
4642 return null;
4643 }
4644
4645 /**
4646 * Views should implement this if the view itself is going to add items to
4647 * the context menu.
4648 *
4649 * @param menu the context menu to populate
4650 */
4651 protected void onCreateContextMenu(ContextMenu menu) {
4652 }
4653
4654 /**
4655 * Implement this method to handle trackball motion events. The
4656 * <em>relative</em> movement of the trackball since the last event
4657 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4658 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4659 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4660 * they will often be fractional values, representing the more fine-grained
4661 * movement information available from a trackball).
4662 *
4663 * @param event The motion event.
4664 * @return True if the event was handled, false otherwise.
4665 */
4666 public boolean onTrackballEvent(MotionEvent event) {
4667 return false;
4668 }
4669
4670 /**
4671 * Implement this method to handle touch screen motion events.
4672 *
4673 * @param event The motion event.
4674 * @return True if the event was handled, false otherwise.
4675 */
4676 public boolean onTouchEvent(MotionEvent event) {
4677 final int viewFlags = mViewFlags;
4678
4679 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4680 // A disabled view that is clickable still consumes the touch
4681 // events, it just doesn't respond to them.
4682 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4683 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4684 }
4685
4686 if (mTouchDelegate != null) {
4687 if (mTouchDelegate.onTouchEvent(event)) {
4688 return true;
4689 }
4690 }
4691
4692 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4693 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4694 switch (event.getAction()) {
4695 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004696 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4697 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 // take focus if we don't have it already and we should in
4699 // touch mode.
4700 boolean focusTaken = false;
4701 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4702 focusTaken = requestFocus();
4703 }
4704
4705 if (!mHasPerformedLongPress) {
4706 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004707 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004708
4709 // Only perform take click actions if we were in the pressed state
4710 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004711 // Use a Runnable and post this rather than calling
4712 // performClick directly. This lets other visual state
4713 // of the view update before click actions start.
4714 if (mPerformClick == null) {
4715 mPerformClick = new PerformClick();
4716 }
4717 if (!post(mPerformClick)) {
4718 performClick();
4719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004720 }
4721 }
4722
4723 if (mUnsetPressedState == null) {
4724 mUnsetPressedState = new UnsetPressedState();
4725 }
4726
Adam Powelle14579b2009-12-16 18:39:52 -08004727 if (prepressed) {
4728 mPrivateFlags |= PRESSED;
4729 refreshDrawableState();
4730 postDelayed(mUnsetPressedState,
4731 ViewConfiguration.getPressedStateDuration());
4732 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004733 // If the post failed, unpress right now
4734 mUnsetPressedState.run();
4735 }
Adam Powelle14579b2009-12-16 18:39:52 -08004736 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004737 }
4738 break;
4739
4740 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004741 if (mPendingCheckForTap == null) {
4742 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004743 }
Adam Powelle14579b2009-12-16 18:39:52 -08004744 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004745 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004746 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004747 break;
4748
4749 case MotionEvent.ACTION_CANCEL:
4750 mPrivateFlags &= ~PRESSED;
4751 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004752 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753 break;
4754
4755 case MotionEvent.ACTION_MOVE:
4756 final int x = (int) event.getX();
4757 final int y = (int) event.getY();
4758
4759 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004760 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004761 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004762 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004763 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004764 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004765 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766
4767 // Need to switch from pressed to not pressed
4768 mPrivateFlags &= ~PRESSED;
4769 refreshDrawableState();
4770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004771 }
4772 break;
4773 }
4774 return true;
4775 }
4776
4777 return false;
4778 }
4779
4780 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004781 * Remove the longpress detection timer.
4782 */
4783 private void removeLongPressCallback() {
4784 if (mPendingCheckForLongPress != null) {
4785 removeCallbacks(mPendingCheckForLongPress);
4786 }
4787 }
Adam Powelle14579b2009-12-16 18:39:52 -08004788
4789 /**
Romain Guya440b002010-02-24 15:57:54 -08004790 * Remove the prepress detection timer.
4791 */
4792 private void removeUnsetPressCallback() {
4793 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4794 setPressed(false);
4795 removeCallbacks(mUnsetPressedState);
4796 }
4797 }
4798
4799 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004800 * Remove the tap detection timer.
4801 */
4802 private void removeTapCallback() {
4803 if (mPendingCheckForTap != null) {
4804 mPrivateFlags &= ~PREPRESSED;
4805 removeCallbacks(mPendingCheckForTap);
4806 }
4807 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004808
4809 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004810 * Cancels a pending long press. Your subclass can use this if you
4811 * want the context menu to come up if the user presses and holds
4812 * at the same place, but you don't want it to come up if they press
4813 * and then move around enough to cause scrolling.
4814 */
4815 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004816 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004817
4818 /*
4819 * The prepressed state handled by the tap callback is a display
4820 * construct, but the tap callback will post a long press callback
4821 * less its own timeout. Remove it here.
4822 */
4823 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004824 }
4825
4826 /**
4827 * Sets the TouchDelegate for this View.
4828 */
4829 public void setTouchDelegate(TouchDelegate delegate) {
4830 mTouchDelegate = delegate;
4831 }
4832
4833 /**
4834 * Gets the TouchDelegate for this View.
4835 */
4836 public TouchDelegate getTouchDelegate() {
4837 return mTouchDelegate;
4838 }
4839
4840 /**
4841 * Set flags controlling behavior of this view.
4842 *
4843 * @param flags Constant indicating the value which should be set
4844 * @param mask Constant indicating the bit range that should be changed
4845 */
4846 void setFlags(int flags, int mask) {
4847 int old = mViewFlags;
4848 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4849
4850 int changed = mViewFlags ^ old;
4851 if (changed == 0) {
4852 return;
4853 }
4854 int privateFlags = mPrivateFlags;
4855
4856 /* Check if the FOCUSABLE bit has changed */
4857 if (((changed & FOCUSABLE_MASK) != 0) &&
4858 ((privateFlags & HAS_BOUNDS) !=0)) {
4859 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4860 && ((privateFlags & FOCUSED) != 0)) {
4861 /* Give up focus if we are no longer focusable */
4862 clearFocus();
4863 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4864 && ((privateFlags & FOCUSED) == 0)) {
4865 /*
4866 * Tell the view system that we are now available to take focus
4867 * if no one else already has it.
4868 */
4869 if (mParent != null) mParent.focusableViewAvailable(this);
4870 }
4871 }
4872
4873 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4874 if ((changed & VISIBILITY_MASK) != 0) {
4875 /*
4876 * If this view is becoming visible, set the DRAWN flag so that
4877 * the next invalidate() will not be skipped.
4878 */
4879 mPrivateFlags |= DRAWN;
4880
4881 needGlobalAttributesUpdate(true);
4882
4883 // a view becoming visible is worth notifying the parent
4884 // about in case nothing has focus. even if this specific view
4885 // isn't focusable, it may contain something that is, so let
4886 // the root view try to give this focus if nothing else does.
4887 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4888 mParent.focusableViewAvailable(this);
4889 }
4890 }
4891 }
4892
4893 /* Check if the GONE bit has changed */
4894 if ((changed & GONE) != 0) {
4895 needGlobalAttributesUpdate(false);
4896 requestLayout();
4897 invalidate();
4898
Romain Guyecd80ee2009-12-03 17:13:02 -08004899 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
4900 if (hasFocus()) clearFocus();
4901 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 }
4903 if (mAttachInfo != null) {
4904 mAttachInfo.mViewVisibilityChanged = true;
4905 }
4906 }
4907
4908 /* Check if the VISIBLE bit has changed */
4909 if ((changed & INVISIBLE) != 0) {
4910 needGlobalAttributesUpdate(false);
4911 invalidate();
4912
4913 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4914 // root view becoming invisible shouldn't clear focus
4915 if (getRootView() != this) {
4916 clearFocus();
4917 }
4918 }
4919 if (mAttachInfo != null) {
4920 mAttachInfo.mViewVisibilityChanged = true;
4921 }
4922 }
4923
Adam Powell326d8082009-12-09 15:10:07 -08004924 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07004925 if (mParent instanceof ViewGroup) {
4926 ((ViewGroup)mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
4927 }
Adam Powell326d8082009-12-09 15:10:07 -08004928 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
4929 }
4930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4932 destroyDrawingCache();
4933 }
4934
4935 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4936 destroyDrawingCache();
4937 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4938 }
4939
4940 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4941 destroyDrawingCache();
4942 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4943 }
4944
4945 if ((changed & DRAW_MASK) != 0) {
4946 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4947 if (mBGDrawable != null) {
4948 mPrivateFlags &= ~SKIP_DRAW;
4949 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4950 } else {
4951 mPrivateFlags |= SKIP_DRAW;
4952 }
4953 } else {
4954 mPrivateFlags &= ~SKIP_DRAW;
4955 }
4956 requestLayout();
4957 invalidate();
4958 }
4959
4960 if ((changed & KEEP_SCREEN_ON) != 0) {
4961 if (mParent != null) {
4962 mParent.recomputeViewAttributes(this);
4963 }
4964 }
4965 }
4966
4967 /**
4968 * Change the view's z order in the tree, so it's on top of other sibling
4969 * views
4970 */
4971 public void bringToFront() {
4972 if (mParent != null) {
4973 mParent.bringChildToFront(this);
4974 }
4975 }
4976
4977 /**
4978 * This is called in response to an internal scroll in this view (i.e., the
4979 * view scrolled its own contents). This is typically as a result of
4980 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4981 * called.
4982 *
4983 * @param l Current horizontal scroll origin.
4984 * @param t Current vertical scroll origin.
4985 * @param oldl Previous horizontal scroll origin.
4986 * @param oldt Previous vertical scroll origin.
4987 */
4988 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4989 mBackgroundSizeChanged = true;
4990
4991 final AttachInfo ai = mAttachInfo;
4992 if (ai != null) {
4993 ai.mViewScrollChanged = true;
4994 }
4995 }
4996
4997 /**
Chet Haase21cd1382010-09-01 17:42:29 -07004998 * Interface definition for a callback to be invoked when the layout bounds of a view
4999 * changes due to layout processing.
5000 */
5001 public interface OnLayoutChangeListener {
5002 /**
5003 * Called when the focus state of a view has changed.
5004 *
5005 * @param v The view whose state has changed.
5006 * @param left The new value of the view's left property.
5007 * @param top The new value of the view's top property.
5008 * @param right The new value of the view's right property.
5009 * @param bottom The new value of the view's bottom property.
5010 * @param oldLeft The previous value of the view's left property.
5011 * @param oldTop The previous value of the view's top property.
5012 * @param oldRight The previous value of the view's right property.
5013 * @param oldBottom The previous value of the view's bottom property.
5014 */
5015 void onLayoutChange(View v, int left, int top, int right, int bottom,
5016 int oldLeft, int oldTop, int oldRight, int oldBottom);
5017 }
5018
5019 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005020 * This is called during layout when the size of this view has changed. If
5021 * you were just added to the view hierarchy, you're called with the old
5022 * values of 0.
5023 *
5024 * @param w Current width of this view.
5025 * @param h Current height of this view.
5026 * @param oldw Old width of this view.
5027 * @param oldh Old height of this view.
5028 */
5029 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5030 }
5031
5032 /**
5033 * Called by draw to draw the child views. This may be overridden
5034 * by derived classes to gain control just before its children are drawn
5035 * (but after its own view has been drawn).
5036 * @param canvas the canvas on which to draw the view
5037 */
5038 protected void dispatchDraw(Canvas canvas) {
5039 }
5040
5041 /**
5042 * Gets the parent of this view. Note that the parent is a
5043 * ViewParent and not necessarily a View.
5044 *
5045 * @return Parent of this view.
5046 */
5047 public final ViewParent getParent() {
5048 return mParent;
5049 }
5050
5051 /**
5052 * Return the scrolled left position of this view. This is the left edge of
5053 * the displayed part of your view. You do not need to draw any pixels
5054 * farther left, since those are outside of the frame of your view on
5055 * screen.
5056 *
5057 * @return The left edge of the displayed part of your view, in pixels.
5058 */
5059 public final int getScrollX() {
5060 return mScrollX;
5061 }
5062
5063 /**
5064 * Return the scrolled top position of this view. This is the top edge of
5065 * the displayed part of your view. You do not need to draw any pixels above
5066 * it, since those are outside of the frame of your view on screen.
5067 *
5068 * @return The top edge of the displayed part of your view, in pixels.
5069 */
5070 public final int getScrollY() {
5071 return mScrollY;
5072 }
5073
5074 /**
5075 * Return the width of the your view.
5076 *
5077 * @return The width of your view, in pixels.
5078 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005079 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 public final int getWidth() {
5081 return mRight - mLeft;
5082 }
5083
5084 /**
5085 * Return the height of your view.
5086 *
5087 * @return The height of your view, in pixels.
5088 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005089 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005090 public final int getHeight() {
5091 return mBottom - mTop;
5092 }
5093
5094 /**
5095 * Return the visible drawing bounds of your view. Fills in the output
5096 * rectangle with the values from getScrollX(), getScrollY(),
5097 * getWidth(), and getHeight().
5098 *
5099 * @param outRect The (scrolled) drawing bounds of the view.
5100 */
5101 public void getDrawingRect(Rect outRect) {
5102 outRect.left = mScrollX;
5103 outRect.top = mScrollY;
5104 outRect.right = mScrollX + (mRight - mLeft);
5105 outRect.bottom = mScrollY + (mBottom - mTop);
5106 }
5107
5108 /**
5109 * The width of this view as measured in the most recent call to measure().
5110 * This should be used during measurement and layout calculations only. Use
5111 * {@link #getWidth()} to see how wide a view is after layout.
5112 *
5113 * @return The measured width of this view.
5114 */
5115 public final int getMeasuredWidth() {
5116 return mMeasuredWidth;
5117 }
5118
5119 /**
5120 * The height of this view as measured in the most recent call to measure().
5121 * This should be used during measurement and layout calculations only. Use
5122 * {@link #getHeight()} to see how tall a view is after layout.
5123 *
5124 * @return The measured height of this view.
5125 */
5126 public final int getMeasuredHeight() {
5127 return mMeasuredHeight;
5128 }
5129
5130 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005131 * The transform matrix of this view, which is calculated based on the current
5132 * roation, scale, and pivot properties.
5133 *
5134 * @see #getRotation()
5135 * @see #getScaleX()
5136 * @see #getScaleY()
5137 * @see #getPivotX()
5138 * @see #getPivotY()
5139 * @return The current transform matrix for the view
5140 */
5141 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005142 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005143 return mMatrix;
5144 }
5145
5146 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005147 * Utility function to determine if the value is far enough away from zero to be
5148 * considered non-zero.
5149 * @param value A floating point value to check for zero-ness
5150 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5151 */
5152 private static boolean nonzero(float value) {
5153 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5154 }
5155
5156 /**
Jeff Brown86671742010-09-30 20:00:15 -07005157 * Returns true if the transform matrix is the identity matrix.
5158 * Recomputes the matrix if necessary.
Romain Guy33e72ae2010-07-17 12:40:29 -07005159 *
5160 * @return True if the transform matrix is the identity matrix, false otherwise.
5161 */
Jeff Brown86671742010-09-30 20:00:15 -07005162 final boolean hasIdentityMatrix() {
5163 updateMatrix();
5164 return mMatrixIsIdentity;
5165 }
5166
5167 /**
5168 * Recomputes the transform matrix if necessary.
5169 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005170 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005171 if (mMatrixDirty) {
5172 // transform-related properties have changed since the last time someone
5173 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005174
5175 // Figure out if we need to update the pivot point
5176 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5177 if ((mRight - mLeft) != mPrevWidth && (mBottom - mTop) != mPrevHeight) {
5178 mPrevWidth = mRight - mLeft;
5179 mPrevHeight = mBottom - mTop;
5180 mPivotX = (float) mPrevWidth / 2f;
5181 mPivotY = (float) mPrevHeight / 2f;
5182 }
5183 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005184 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005185 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5186 mMatrix.setTranslate(mTranslationX, mTranslationY);
5187 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5188 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5189 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005190 if (mCamera == null) {
5191 mCamera = new Camera();
5192 matrix3D = new Matrix();
5193 }
5194 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005195 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005196 mCamera.rotateX(mRotationX);
5197 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005198 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005199 mCamera.getMatrix(matrix3D);
5200 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005201 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005202 mMatrix.postConcat(matrix3D);
5203 mCamera.restore();
5204 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005205 mMatrixDirty = false;
5206 mMatrixIsIdentity = mMatrix.isIdentity();
5207 mInverseMatrixDirty = true;
5208 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005209 }
5210
5211 /**
5212 * Utility method to retrieve the inverse of the current mMatrix property.
5213 * We cache the matrix to avoid recalculating it when transform properties
5214 * have not changed.
5215 *
5216 * @return The inverse of the current matrix of this view.
5217 */
Jeff Brown86671742010-09-30 20:00:15 -07005218 final Matrix getInverseMatrix() {
5219 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005220 if (mInverseMatrixDirty) {
5221 if (mInverseMatrix == null) {
5222 mInverseMatrix = new Matrix();
5223 }
5224 mMatrix.invert(mInverseMatrix);
5225 mInverseMatrixDirty = false;
5226 }
5227 return mInverseMatrix;
5228 }
5229
5230 /**
5231 * The degrees that the view is rotated around the pivot point.
5232 *
5233 * @see #getPivotX()
5234 * @see #getPivotY()
5235 * @return The degrees of rotation.
5236 */
5237 public float getRotation() {
5238 return mRotation;
5239 }
5240
5241 /**
Chet Haase897247b2010-09-09 14:54:47 -07005242 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5243 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005244 *
5245 * @param rotation The degrees of rotation.
5246 * @see #getPivotX()
5247 * @see #getPivotY()
5248 */
5249 public void setRotation(float rotation) {
5250 if (mRotation != rotation) {
5251 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005252 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005253 mRotation = rotation;
5254 mMatrixDirty = true;
5255 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005256 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005257 }
5258 }
5259
5260 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005261 * The degrees that the view is rotated around the vertical axis through the pivot point.
5262 *
5263 * @see #getPivotX()
5264 * @see #getPivotY()
5265 * @return The degrees of Y rotation.
5266 */
5267 public float getRotationY() {
5268 return mRotationY;
5269 }
5270
5271 /**
Chet Haase897247b2010-09-09 14:54:47 -07005272 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5273 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5274 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005275 *
5276 * @param rotationY The degrees of Y rotation.
5277 * @see #getPivotX()
5278 * @see #getPivotY()
5279 */
5280 public void setRotationY(float rotationY) {
5281 if (mRotationY != rotationY) {
5282 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005283 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005284 mRotationY = rotationY;
5285 mMatrixDirty = true;
5286 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005287 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005288 }
5289 }
5290
5291 /**
5292 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5293 *
5294 * @see #getPivotX()
5295 * @see #getPivotY()
5296 * @return The degrees of X rotation.
5297 */
5298 public float getRotationX() {
5299 return mRotationX;
5300 }
5301
5302 /**
Chet Haase897247b2010-09-09 14:54:47 -07005303 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5304 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5305 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005306 *
5307 * @param rotationX The degrees of X rotation.
5308 * @see #getPivotX()
5309 * @see #getPivotY()
5310 */
5311 public void setRotationX(float rotationX) {
5312 if (mRotationX != rotationX) {
5313 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005314 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005315 mRotationX = rotationX;
5316 mMatrixDirty = true;
5317 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005318 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005319 }
5320 }
5321
5322 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005323 * The amount that the view is scaled in x around the pivot point, as a proportion of
5324 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5325 *
Joe Onorato93162322010-09-16 15:42:01 -04005326 * <p>By default, this is 1.0f.
5327 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005328 * @see #getPivotX()
5329 * @see #getPivotY()
5330 * @return The scaling factor.
5331 */
5332 public float getScaleX() {
5333 return mScaleX;
5334 }
5335
5336 /**
5337 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5338 * the view's unscaled width. A value of 1 means that no scaling is applied.
5339 *
5340 * @param scaleX The scaling factor.
5341 * @see #getPivotX()
5342 * @see #getPivotY()
5343 */
5344 public void setScaleX(float scaleX) {
5345 if (mScaleX != scaleX) {
5346 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005347 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005348 mScaleX = scaleX;
5349 mMatrixDirty = true;
5350 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005351 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005352 }
5353 }
5354
5355 /**
5356 * The amount that the view is scaled in y around the pivot point, as a proportion of
5357 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5358 *
Joe Onorato93162322010-09-16 15:42:01 -04005359 * <p>By default, this is 1.0f.
5360 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005361 * @see #getPivotX()
5362 * @see #getPivotY()
5363 * @return The scaling factor.
5364 */
5365 public float getScaleY() {
5366 return mScaleY;
5367 }
5368
5369 /**
5370 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5371 * the view's unscaled width. A value of 1 means that no scaling is applied.
5372 *
5373 * @param scaleY The scaling factor.
5374 * @see #getPivotX()
5375 * @see #getPivotY()
5376 */
5377 public void setScaleY(float scaleY) {
5378 if (mScaleY != scaleY) {
5379 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005380 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005381 mScaleY = scaleY;
5382 mMatrixDirty = true;
5383 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005384 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005385 }
5386 }
5387
5388 /**
5389 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5390 * and {@link #setScaleX(float) scaled}.
5391 *
5392 * @see #getRotation()
5393 * @see #getScaleX()
5394 * @see #getScaleY()
5395 * @see #getPivotY()
5396 * @return The x location of the pivot point.
5397 */
5398 public float getPivotX() {
5399 return mPivotX;
5400 }
5401
5402 /**
5403 * Sets the x location of the point around which the view is
5404 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005405 * By default, the pivot point is centered on the object.
5406 * Setting this property disables this behavior and causes the view to use only the
5407 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005408 *
5409 * @param pivotX The x location of the pivot point.
5410 * @see #getRotation()
5411 * @see #getScaleX()
5412 * @see #getScaleY()
5413 * @see #getPivotY()
5414 */
5415 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005416 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005417 if (mPivotX != pivotX) {
5418 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005419 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005420 mPivotX = pivotX;
5421 mMatrixDirty = true;
5422 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005423 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005424 }
5425 }
5426
5427 /**
5428 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5429 * and {@link #setScaleY(float) scaled}.
5430 *
5431 * @see #getRotation()
5432 * @see #getScaleX()
5433 * @see #getScaleY()
5434 * @see #getPivotY()
5435 * @return The y location of the pivot point.
5436 */
5437 public float getPivotY() {
5438 return mPivotY;
5439 }
5440
5441 /**
5442 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005443 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5444 * Setting this property disables this behavior and causes the view to use only the
5445 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005446 *
5447 * @param pivotY The y location of the pivot point.
5448 * @see #getRotation()
5449 * @see #getScaleX()
5450 * @see #getScaleY()
5451 * @see #getPivotY()
5452 */
5453 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005454 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005455 if (mPivotY != pivotY) {
5456 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005457 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005458 mPivotY = pivotY;
5459 mMatrixDirty = true;
5460 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005461 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005462 }
5463 }
5464
5465 /**
5466 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5467 * completely transparent and 1 means the view is completely opaque.
5468 *
Joe Onorato93162322010-09-16 15:42:01 -04005469 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005470 * @return The opacity of the view.
5471 */
5472 public float getAlpha() {
5473 return mAlpha;
5474 }
5475
5476 /**
5477 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5478 * completely transparent and 1 means the view is completely opaque.
5479 *
5480 * @param alpha The opacity of the view.
5481 */
5482 public void setAlpha(float alpha) {
5483 mAlpha = alpha;
Chet Haaseed032702010-10-01 14:05:54 -07005484 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07005485 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005486 // subclass is handling alpha - don't optimize rendering cache invalidation
5487 invalidate();
5488 } else {
Romain Guya3496a92010-10-12 11:53:24 -07005489 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005490 invalidate(false);
5491 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005492 }
5493
5494 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 * Top position of this view relative to its parent.
5496 *
5497 * @return The top of this view, in pixels.
5498 */
5499 @ViewDebug.CapturedViewProperty
5500 public final int getTop() {
5501 return mTop;
5502 }
5503
5504 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005505 * Sets the top position of this view relative to its parent. This method is meant to be called
5506 * by the layout system and should not generally be called otherwise, because the property
5507 * may be changed at any time by the layout.
5508 *
5509 * @param top The top of this view, in pixels.
5510 */
5511 public final void setTop(int top) {
5512 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07005513 updateMatrix();
5514 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005515 final ViewParent p = mParent;
5516 if (p != null && mAttachInfo != null) {
5517 final Rect r = mAttachInfo.mTmpInvalRect;
5518 int minTop;
5519 int yLoc;
5520 if (top < mTop) {
5521 minTop = top;
5522 yLoc = top - mTop;
5523 } else {
5524 minTop = mTop;
5525 yLoc = 0;
5526 }
5527 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5528 p.invalidateChild(this, r);
5529 }
5530 } else {
5531 // Double-invalidation is necessary to capture view's old and new areas
5532 invalidate();
5533 }
5534
Chet Haaseed032702010-10-01 14:05:54 -07005535 int width = mRight - mLeft;
5536 int oldHeight = mBottom - mTop;
5537
Chet Haase21cd1382010-09-01 17:42:29 -07005538 mTop = top;
5539
Chet Haaseed032702010-10-01 14:05:54 -07005540 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5541
Chet Haase21cd1382010-09-01 17:42:29 -07005542 if (!mMatrixIsIdentity) {
5543 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5544 invalidate();
5545 }
5546 }
5547 }
5548
5549 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 * Bottom position of this view relative to its parent.
5551 *
5552 * @return The bottom of this view, in pixels.
5553 */
5554 @ViewDebug.CapturedViewProperty
5555 public final int getBottom() {
5556 return mBottom;
5557 }
5558
5559 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005560 * Sets the bottom position of this view relative to its parent. This method is meant to be
5561 * called by the layout system and should not generally be called otherwise, because the
5562 * property may be changed at any time by the layout.
5563 *
5564 * @param bottom The bottom of this view, in pixels.
5565 */
5566 public final void setBottom(int bottom) {
5567 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07005568 updateMatrix();
5569 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005570 final ViewParent p = mParent;
5571 if (p != null && mAttachInfo != null) {
5572 final Rect r = mAttachInfo.mTmpInvalRect;
5573 int maxBottom;
5574 if (bottom < mBottom) {
5575 maxBottom = mBottom;
5576 } else {
5577 maxBottom = bottom;
5578 }
5579 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5580 p.invalidateChild(this, r);
5581 }
5582 } else {
5583 // Double-invalidation is necessary to capture view's old and new areas
5584 invalidate();
5585 }
5586
Chet Haaseed032702010-10-01 14:05:54 -07005587 int width = mRight - mLeft;
5588 int oldHeight = mBottom - mTop;
5589
Chet Haase21cd1382010-09-01 17:42:29 -07005590 mBottom = bottom;
5591
Chet Haaseed032702010-10-01 14:05:54 -07005592 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5593
Chet Haase21cd1382010-09-01 17:42:29 -07005594 if (!mMatrixIsIdentity) {
5595 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5596 invalidate();
5597 }
5598 }
5599 }
5600
5601 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 * Left position of this view relative to its parent.
5603 *
5604 * @return The left edge of this view, in pixels.
5605 */
5606 @ViewDebug.CapturedViewProperty
5607 public final int getLeft() {
5608 return mLeft;
5609 }
5610
5611 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005612 * Sets the left position of this view relative to its parent. This method is meant to be called
5613 * by the layout system and should not generally be called otherwise, because the property
5614 * may be changed at any time by the layout.
5615 *
5616 * @param left The bottom of this view, in pixels.
5617 */
5618 public final void setLeft(int left) {
5619 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07005620 updateMatrix();
5621 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005622 final ViewParent p = mParent;
5623 if (p != null && mAttachInfo != null) {
5624 final Rect r = mAttachInfo.mTmpInvalRect;
5625 int minLeft;
5626 int xLoc;
5627 if (left < mLeft) {
5628 minLeft = left;
5629 xLoc = left - mLeft;
5630 } else {
5631 minLeft = mLeft;
5632 xLoc = 0;
5633 }
5634 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
5635 p.invalidateChild(this, r);
5636 }
5637 } else {
5638 // Double-invalidation is necessary to capture view's old and new areas
5639 invalidate();
5640 }
5641
Chet Haaseed032702010-10-01 14:05:54 -07005642 int oldWidth = mRight - mLeft;
5643 int height = mBottom - mTop;
5644
Chet Haase21cd1382010-09-01 17:42:29 -07005645 mLeft = left;
5646
Chet Haaseed032702010-10-01 14:05:54 -07005647 onSizeChanged(mRight - mLeft, height, oldWidth, height);
5648
Chet Haase21cd1382010-09-01 17:42:29 -07005649 if (!mMatrixIsIdentity) {
5650 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5651 invalidate();
5652 }
Chet Haaseed032702010-10-01 14:05:54 -07005653
Chet Haase21cd1382010-09-01 17:42:29 -07005654 }
5655 }
5656
5657 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 * Right position of this view relative to its parent.
5659 *
5660 * @return The right edge of this view, in pixels.
5661 */
5662 @ViewDebug.CapturedViewProperty
5663 public final int getRight() {
5664 return mRight;
5665 }
5666
5667 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005668 * Sets the right position of this view relative to its parent. This method is meant to be called
5669 * by the layout system and should not generally be called otherwise, because the property
5670 * may be changed at any time by the layout.
5671 *
5672 * @param right The bottom of this view, in pixels.
5673 */
5674 public final void setRight(int right) {
5675 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07005676 updateMatrix();
5677 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005678 final ViewParent p = mParent;
5679 if (p != null && mAttachInfo != null) {
5680 final Rect r = mAttachInfo.mTmpInvalRect;
5681 int maxRight;
5682 if (right < mRight) {
5683 maxRight = mRight;
5684 } else {
5685 maxRight = right;
5686 }
5687 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
5688 p.invalidateChild(this, r);
5689 }
5690 } else {
5691 // Double-invalidation is necessary to capture view's old and new areas
5692 invalidate();
5693 }
5694
Chet Haaseed032702010-10-01 14:05:54 -07005695 int oldWidth = mRight - mLeft;
5696 int height = mBottom - mTop;
5697
Chet Haase21cd1382010-09-01 17:42:29 -07005698 mRight = right;
5699
Chet Haaseed032702010-10-01 14:05:54 -07005700 onSizeChanged(mRight - mLeft, height, oldWidth, height);
5701
Chet Haase21cd1382010-09-01 17:42:29 -07005702 if (!mMatrixIsIdentity) {
5703 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5704 invalidate();
5705 }
5706 }
5707 }
5708
5709 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005710 * The visual x position of this view, in pixels. This is equivalent to the
5711 * {@link #setTranslationX(float) translationX} property plus the current
5712 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07005713 *
Chet Haasedf030d22010-07-30 17:22:38 -07005714 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005715 */
Chet Haasedf030d22010-07-30 17:22:38 -07005716 public float getX() {
5717 return mLeft + mTranslationX;
5718 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005719
Chet Haasedf030d22010-07-30 17:22:38 -07005720 /**
5721 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
5722 * {@link #setTranslationX(float) translationX} property to be the difference between
5723 * the x value passed in and the current {@link #getLeft() left} property.
5724 *
5725 * @param x The visual x position of this view, in pixels.
5726 */
5727 public void setX(float x) {
5728 setTranslationX(x - mLeft);
5729 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005730
Chet Haasedf030d22010-07-30 17:22:38 -07005731 /**
5732 * The visual y position of this view, in pixels. This is equivalent to the
5733 * {@link #setTranslationY(float) translationY} property plus the current
5734 * {@link #getTop() top} property.
5735 *
5736 * @return The visual y position of this view, in pixels.
5737 */
5738 public float getY() {
5739 return mTop + mTranslationY;
5740 }
5741
5742 /**
5743 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
5744 * {@link #setTranslationY(float) translationY} property to be the difference between
5745 * the y value passed in and the current {@link #getTop() top} property.
5746 *
5747 * @param y The visual y position of this view, in pixels.
5748 */
5749 public void setY(float y) {
5750 setTranslationY(y - mTop);
5751 }
5752
5753
5754 /**
5755 * The horizontal location of this view relative to its {@link #getLeft() left} position.
5756 * This position is post-layout, in addition to wherever the object's
5757 * layout placed it.
5758 *
5759 * @return The horizontal position of this view relative to its left position, in pixels.
5760 */
5761 public float getTranslationX() {
5762 return mTranslationX;
5763 }
5764
5765 /**
5766 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
5767 * This effectively positions the object post-layout, in addition to wherever the object's
5768 * layout placed it.
5769 *
5770 * @param translationX The horizontal position of this view relative to its left position,
5771 * in pixels.
5772 */
5773 public void setTranslationX(float translationX) {
5774 if (mTranslationX != translationX) {
5775 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005776 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07005777 mTranslationX = translationX;
5778 mMatrixDirty = true;
5779 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005780 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005781 }
5782 }
5783
5784 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005785 * The horizontal location of this view relative to its {@link #getTop() top} position.
5786 * This position is post-layout, in addition to wherever the object's
5787 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005788 *
Chet Haasedf030d22010-07-30 17:22:38 -07005789 * @return The vertical position of this view relative to its top position,
5790 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005791 */
Chet Haasedf030d22010-07-30 17:22:38 -07005792 public float getTranslationY() {
5793 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07005794 }
5795
5796 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005797 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
5798 * This effectively positions the object post-layout, in addition to wherever the object's
5799 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005800 *
Chet Haasedf030d22010-07-30 17:22:38 -07005801 * @param translationY The vertical position of this view relative to its top position,
5802 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005803 */
Chet Haasedf030d22010-07-30 17:22:38 -07005804 public void setTranslationY(float translationY) {
5805 if (mTranslationY != translationY) {
5806 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005807 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07005808 mTranslationY = translationY;
5809 mMatrixDirty = true;
5810 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005811 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07005812 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005813 }
5814
5815 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 * Hit rectangle in parent's coordinates
5817 *
5818 * @param outRect The hit rectangle of the view.
5819 */
5820 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07005821 updateMatrix();
5822 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005823 outRect.set(mLeft, mTop, mRight, mBottom);
5824 } else {
5825 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07005826 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07005827 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07005828 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
5829 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07005830 }
5831 }
5832
5833 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07005834 * Determines whether the given point, in local coordinates is inside the view.
5835 */
5836 /*package*/ final boolean pointInView(float localX, float localY) {
5837 return localX >= 0 && localX < (mRight - mLeft)
5838 && localY >= 0 && localY < (mBottom - mTop);
5839 }
5840
5841 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005842 * Utility method to determine whether the given point, in local coordinates,
5843 * is inside the view, where the area of the view is expanded by the slop factor.
5844 * This method is called while processing touch-move events to determine if the event
5845 * is still within the view.
5846 */
5847 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07005848 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07005849 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005850 }
5851
5852 /**
5853 * When a view has focus and the user navigates away from it, the next view is searched for
5854 * starting from the rectangle filled in by this method.
5855 *
5856 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
5857 * view maintains some idea of internal selection, such as a cursor, or a selected row
5858 * or column, you should override this method and fill in a more specific rectangle.
5859 *
5860 * @param r The rectangle to fill in, in this view's coordinates.
5861 */
5862 public void getFocusedRect(Rect r) {
5863 getDrawingRect(r);
5864 }
5865
5866 /**
5867 * If some part of this view is not clipped by any of its parents, then
5868 * return that area in r in global (root) coordinates. To convert r to local
5869 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
5870 * -globalOffset.y)) If the view is completely clipped or translated out,
5871 * return false.
5872 *
5873 * @param r If true is returned, r holds the global coordinates of the
5874 * visible portion of this view.
5875 * @param globalOffset If true is returned, globalOffset holds the dx,dy
5876 * between this view and its root. globalOffet may be null.
5877 * @return true if r is non-empty (i.e. part of the view is visible at the
5878 * root level.
5879 */
5880 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
5881 int width = mRight - mLeft;
5882 int height = mBottom - mTop;
5883 if (width > 0 && height > 0) {
5884 r.set(0, 0, width, height);
5885 if (globalOffset != null) {
5886 globalOffset.set(-mScrollX, -mScrollY);
5887 }
5888 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
5889 }
5890 return false;
5891 }
5892
5893 public final boolean getGlobalVisibleRect(Rect r) {
5894 return getGlobalVisibleRect(r, null);
5895 }
5896
5897 public final boolean getLocalVisibleRect(Rect r) {
5898 Point offset = new Point();
5899 if (getGlobalVisibleRect(r, offset)) {
5900 r.offset(-offset.x, -offset.y); // make r local
5901 return true;
5902 }
5903 return false;
5904 }
5905
5906 /**
5907 * Offset this view's vertical location by the specified number of pixels.
5908 *
5909 * @param offset the number of pixels to offset the view by
5910 */
5911 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005912 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07005913 updateMatrix();
5914 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005915 final ViewParent p = mParent;
5916 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005917 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005918 int minTop;
5919 int maxBottom;
5920 int yLoc;
5921 if (offset < 0) {
5922 minTop = mTop + offset;
5923 maxBottom = mBottom;
5924 yLoc = offset;
5925 } else {
5926 minTop = mTop;
5927 maxBottom = mBottom + offset;
5928 yLoc = 0;
5929 }
5930 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
5931 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005932 }
5933 } else {
Chet Haaseed032702010-10-01 14:05:54 -07005934 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005935 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005936
Chet Haasec3aa3612010-06-17 08:50:37 -07005937 mTop += offset;
5938 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005939
Chet Haasec3aa3612010-06-17 08:50:37 -07005940 if (!mMatrixIsIdentity) {
5941 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005942 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005943 }
5944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 }
5946
5947 /**
5948 * Offset this view's horizontal location by the specified amount of pixels.
5949 *
5950 * @param offset the numer of pixels to offset the view by
5951 */
5952 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005953 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07005954 updateMatrix();
5955 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005956 final ViewParent p = mParent;
5957 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005958 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005959 int minLeft;
5960 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005961 if (offset < 0) {
5962 minLeft = mLeft + offset;
5963 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005964 } else {
5965 minLeft = mLeft;
5966 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005967 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005968 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07005969 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005970 }
5971 } else {
Chet Haaseed032702010-10-01 14:05:54 -07005972 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005973 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005974
Chet Haasec3aa3612010-06-17 08:50:37 -07005975 mLeft += offset;
5976 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005977
Chet Haasec3aa3612010-06-17 08:50:37 -07005978 if (!mMatrixIsIdentity) {
5979 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005980 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005981 }
5982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 }
5984
5985 /**
5986 * Get the LayoutParams associated with this view. All views should have
5987 * layout parameters. These supply parameters to the <i>parent</i> of this
5988 * view specifying how it should be arranged. There are many subclasses of
5989 * ViewGroup.LayoutParams, and these correspond to the different subclasses
5990 * of ViewGroup that are responsible for arranging their children.
5991 * @return The LayoutParams associated with this view
5992 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07005993 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 public ViewGroup.LayoutParams getLayoutParams() {
5995 return mLayoutParams;
5996 }
5997
5998 /**
5999 * Set the layout parameters associated with this view. These supply
6000 * parameters to the <i>parent</i> of this view specifying how it should be
6001 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6002 * correspond to the different subclasses of ViewGroup that are responsible
6003 * for arranging their children.
6004 *
6005 * @param params the layout parameters for this view
6006 */
6007 public void setLayoutParams(ViewGroup.LayoutParams params) {
6008 if (params == null) {
6009 throw new NullPointerException("params == null");
6010 }
6011 mLayoutParams = params;
6012 requestLayout();
6013 }
6014
6015 /**
6016 * Set the scrolled position of your view. This will cause a call to
6017 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6018 * invalidated.
6019 * @param x the x position to scroll to
6020 * @param y the y position to scroll to
6021 */
6022 public void scrollTo(int x, int y) {
6023 if (mScrollX != x || mScrollY != y) {
6024 int oldX = mScrollX;
6025 int oldY = mScrollY;
6026 mScrollX = x;
6027 mScrollY = y;
6028 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006029 if (!awakenScrollBars()) {
6030 invalidate();
6031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 }
6033 }
6034
6035 /**
6036 * Move the scrolled position of your view. This will cause a call to
6037 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6038 * invalidated.
6039 * @param x the amount of pixels to scroll by horizontally
6040 * @param y the amount of pixels to scroll by vertically
6041 */
6042 public void scrollBy(int x, int y) {
6043 scrollTo(mScrollX + x, mScrollY + y);
6044 }
6045
6046 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006047 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6048 * animation to fade the scrollbars out after a default delay. If a subclass
6049 * provides animated scrolling, the start delay should equal the duration
6050 * of the scrolling animation.</p>
6051 *
6052 * <p>The animation starts only if at least one of the scrollbars is
6053 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6054 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6055 * this method returns true, and false otherwise. If the animation is
6056 * started, this method calls {@link #invalidate()}; in that case the
6057 * caller should not call {@link #invalidate()}.</p>
6058 *
6059 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006060 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006061 *
6062 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6063 * and {@link #scrollTo(int, int)}.</p>
6064 *
6065 * @return true if the animation is played, false otherwise
6066 *
6067 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006068 * @see #scrollBy(int, int)
6069 * @see #scrollTo(int, int)
6070 * @see #isHorizontalScrollBarEnabled()
6071 * @see #isVerticalScrollBarEnabled()
6072 * @see #setHorizontalScrollBarEnabled(boolean)
6073 * @see #setVerticalScrollBarEnabled(boolean)
6074 */
6075 protected boolean awakenScrollBars() {
6076 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006077 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006078 }
6079
6080 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006081 * Trigger the scrollbars to draw.
6082 * This method differs from awakenScrollBars() only in its default duration.
6083 * initialAwakenScrollBars() will show the scroll bars for longer than
6084 * usual to give the user more of a chance to notice them.
6085 *
6086 * @return true if the animation is played, false otherwise.
6087 */
6088 private boolean initialAwakenScrollBars() {
6089 return mScrollCache != null &&
6090 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6091 }
6092
6093 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006094 * <p>
6095 * Trigger the scrollbars to draw. When invoked this method starts an
6096 * animation to fade the scrollbars out after a fixed delay. If a subclass
6097 * provides animated scrolling, the start delay should equal the duration of
6098 * the scrolling animation.
6099 * </p>
6100 *
6101 * <p>
6102 * The animation starts only if at least one of the scrollbars is enabled,
6103 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6104 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6105 * this method returns true, and false otherwise. If the animation is
6106 * started, this method calls {@link #invalidate()}; in that case the caller
6107 * should not call {@link #invalidate()}.
6108 * </p>
6109 *
6110 * <p>
6111 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006112 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006113 * </p>
6114 *
6115 * @param startDelay the delay, in milliseconds, after which the animation
6116 * should start; when the delay is 0, the animation starts
6117 * immediately
6118 * @return true if the animation is played, false otherwise
6119 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006120 * @see #scrollBy(int, int)
6121 * @see #scrollTo(int, int)
6122 * @see #isHorizontalScrollBarEnabled()
6123 * @see #isVerticalScrollBarEnabled()
6124 * @see #setHorizontalScrollBarEnabled(boolean)
6125 * @see #setVerticalScrollBarEnabled(boolean)
6126 */
6127 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006128 return awakenScrollBars(startDelay, true);
6129 }
6130
6131 /**
6132 * <p>
6133 * Trigger the scrollbars to draw. When invoked this method starts an
6134 * animation to fade the scrollbars out after a fixed delay. If a subclass
6135 * provides animated scrolling, the start delay should equal the duration of
6136 * the scrolling animation.
6137 * </p>
6138 *
6139 * <p>
6140 * The animation starts only if at least one of the scrollbars is enabled,
6141 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6142 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6143 * this method returns true, and false otherwise. If the animation is
6144 * started, this method calls {@link #invalidate()} if the invalidate parameter
6145 * is set to true; in that case the caller
6146 * should not call {@link #invalidate()}.
6147 * </p>
6148 *
6149 * <p>
6150 * This method should be invoked everytime a subclass directly updates the
6151 * scroll parameters.
6152 * </p>
6153 *
6154 * @param startDelay the delay, in milliseconds, after which the animation
6155 * should start; when the delay is 0, the animation starts
6156 * immediately
6157 *
6158 * @param invalidate Wheter this method should call invalidate
6159 *
6160 * @return true if the animation is played, false otherwise
6161 *
6162 * @see #scrollBy(int, int)
6163 * @see #scrollTo(int, int)
6164 * @see #isHorizontalScrollBarEnabled()
6165 * @see #isVerticalScrollBarEnabled()
6166 * @see #setHorizontalScrollBarEnabled(boolean)
6167 * @see #setVerticalScrollBarEnabled(boolean)
6168 */
6169 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006170 final ScrollabilityCache scrollCache = mScrollCache;
6171
6172 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6173 return false;
6174 }
6175
6176 if (scrollCache.scrollBar == null) {
6177 scrollCache.scrollBar = new ScrollBarDrawable();
6178 }
6179
6180 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6181
Mike Cleron290947b2009-09-29 18:34:32 -07006182 if (invalidate) {
6183 // Invalidate to show the scrollbars
6184 invalidate();
6185 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006186
6187 if (scrollCache.state == ScrollabilityCache.OFF) {
6188 // FIXME: this is copied from WindowManagerService.
6189 // We should get this value from the system when it
6190 // is possible to do so.
6191 final int KEY_REPEAT_FIRST_DELAY = 750;
6192 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6193 }
6194
6195 // Tell mScrollCache when we should start fading. This may
6196 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006197 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006198 scrollCache.fadeStartTime = fadeStartTime;
6199 scrollCache.state = ScrollabilityCache.ON;
6200
6201 // Schedule our fader to run, unscheduling any old ones first
6202 if (mAttachInfo != null) {
6203 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6204 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6205 }
6206
6207 return true;
6208 }
6209
6210 return false;
6211 }
6212
6213 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 * Mark the the area defined by dirty as needing to be drawn. If the view is
6215 * visible, {@link #onDraw} will be called at some point in the future.
6216 * This must be called from a UI thread. To call from a non-UI thread, call
6217 * {@link #postInvalidate()}.
6218 *
6219 * WARNING: This method is destructive to dirty.
6220 * @param dirty the rectangle representing the bounds of the dirty region
6221 */
6222 public void invalidate(Rect dirty) {
6223 if (ViewDebug.TRACE_HIERARCHY) {
6224 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6225 }
6226
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006227 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6228 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6230 final ViewParent p = mParent;
6231 final AttachInfo ai = mAttachInfo;
6232 if (p != null && ai != null) {
6233 final int scrollX = mScrollX;
6234 final int scrollY = mScrollY;
6235 final Rect r = ai.mTmpInvalRect;
6236 r.set(dirty.left - scrollX, dirty.top - scrollY,
6237 dirty.right - scrollX, dirty.bottom - scrollY);
6238 mParent.invalidateChild(this, r);
6239 }
6240 }
6241 }
6242
6243 /**
6244 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6245 * The coordinates of the dirty rect are relative to the view.
6246 * If the view is visible, {@link #onDraw} will be called at some point
6247 * in the future. This must be called from a UI thread. To call
6248 * from a non-UI thread, call {@link #postInvalidate()}.
6249 * @param l the left position of the dirty region
6250 * @param t the top position of the dirty region
6251 * @param r the right position of the dirty region
6252 * @param b the bottom position of the dirty region
6253 */
6254 public void invalidate(int l, int t, int r, int b) {
6255 if (ViewDebug.TRACE_HIERARCHY) {
6256 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6257 }
6258
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006259 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6260 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6262 final ViewParent p = mParent;
6263 final AttachInfo ai = mAttachInfo;
6264 if (p != null && ai != null && l < r && t < b) {
6265 final int scrollX = mScrollX;
6266 final int scrollY = mScrollY;
6267 final Rect tmpr = ai.mTmpInvalRect;
6268 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6269 p.invalidateChild(this, tmpr);
6270 }
6271 }
6272 }
6273
6274 /**
6275 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6276 * be called at some point in the future. This must be called from a
6277 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6278 */
6279 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006280 invalidate(true);
6281 }
6282
6283 /**
6284 * This is where the invalidate() work actually happens. A full invalidate()
6285 * causes the drawing cache to be invalidated, but this function can be called with
6286 * invalidateCache set to false to skip that invalidation step for cases that do not
6287 * need it (for example, a component that remains at the same dimensions with the same
6288 * content).
6289 *
6290 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6291 * well. This is usually true for a full invalidate, but may be set to false if the
6292 * View's contents or dimensions have not changed.
6293 */
6294 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 if (ViewDebug.TRACE_HIERARCHY) {
6296 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6297 }
6298
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006299 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6300 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID)) {
Chet Haaseed032702010-10-01 14:05:54 -07006301 mPrivateFlags &= ~DRAWN;
6302 if (invalidateCache) {
6303 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006306 final ViewParent p = mParent;
Chet Haaseea40e9a2010-11-01 16:54:22 -07006307 if (p != null && ai != null && ai.mHardwareAccelerated) {
Chet Haase70d4ba12010-10-06 09:46:45 -07006308 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6309 // with a null dirty rect, which tells the ViewRoot to redraw everything
6310 p.invalidateChild(this, null);
6311 return;
6312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 if (p != null && ai != null) {
6314 final Rect r = ai.mTmpInvalRect;
6315 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6316 // Don't call invalidate -- we don't want to internally scroll
6317 // our own bounds
6318 p.invalidateChild(this, r);
6319 }
6320 }
6321 }
6322
6323 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006324 * Indicates whether this View is opaque. An opaque View guarantees that it will
6325 * draw all the pixels overlapping its bounds using a fully opaque color.
6326 *
6327 * Subclasses of View should override this method whenever possible to indicate
6328 * whether an instance is opaque. Opaque Views are treated in a special way by
6329 * the View hierarchy, possibly allowing it to perform optimizations during
6330 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006331 *
Romain Guy24443ea2009-05-11 11:56:30 -07006332 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006333 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006334 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006335 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006336 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6337 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006338 }
6339
6340 private void computeOpaqueFlags() {
6341 // Opaque if:
6342 // - Has a background
6343 // - Background is opaque
6344 // - Doesn't have scrollbars or scrollbars are inside overlay
6345
6346 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6347 mPrivateFlags |= OPAQUE_BACKGROUND;
6348 } else {
6349 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6350 }
6351
6352 final int flags = mViewFlags;
6353 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6354 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6355 mPrivateFlags |= OPAQUE_SCROLLBARS;
6356 } else {
6357 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6358 }
6359 }
6360
6361 /**
6362 * @hide
6363 */
6364 protected boolean hasOpaqueScrollbars() {
6365 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006366 }
6367
6368 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 * @return A handler associated with the thread running the View. This
6370 * handler can be used to pump events in the UI events queue.
6371 */
6372 public Handler getHandler() {
6373 if (mAttachInfo != null) {
6374 return mAttachInfo.mHandler;
6375 }
6376 return null;
6377 }
6378
6379 /**
6380 * Causes the Runnable to be added to the message queue.
6381 * The runnable will be run on the user interface thread.
6382 *
6383 * @param action The Runnable that will be executed.
6384 *
6385 * @return Returns true if the Runnable was successfully placed in to the
6386 * message queue. Returns false on failure, usually because the
6387 * looper processing the message queue is exiting.
6388 */
6389 public boolean post(Runnable action) {
6390 Handler handler;
6391 if (mAttachInfo != null) {
6392 handler = mAttachInfo.mHandler;
6393 } else {
6394 // Assume that post will succeed later
6395 ViewRoot.getRunQueue().post(action);
6396 return true;
6397 }
6398
6399 return handler.post(action);
6400 }
6401
6402 /**
6403 * Causes the Runnable to be added to the message queue, to be run
6404 * after the specified amount of time elapses.
6405 * The runnable will be run on the user interface thread.
6406 *
6407 * @param action The Runnable that will be executed.
6408 * @param delayMillis The delay (in milliseconds) until the Runnable
6409 * will be executed.
6410 *
6411 * @return true if the Runnable was successfully placed in to the
6412 * message queue. Returns false on failure, usually because the
6413 * looper processing the message queue is exiting. Note that a
6414 * result of true does not mean the Runnable will be processed --
6415 * if the looper is quit before the delivery time of the message
6416 * occurs then the message will be dropped.
6417 */
6418 public boolean postDelayed(Runnable action, long delayMillis) {
6419 Handler handler;
6420 if (mAttachInfo != null) {
6421 handler = mAttachInfo.mHandler;
6422 } else {
6423 // Assume that post will succeed later
6424 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6425 return true;
6426 }
6427
6428 return handler.postDelayed(action, delayMillis);
6429 }
6430
6431 /**
6432 * Removes the specified Runnable from the message queue.
6433 *
6434 * @param action The Runnable to remove from the message handling queue
6435 *
6436 * @return true if this view could ask the Handler to remove the Runnable,
6437 * false otherwise. When the returned value is true, the Runnable
6438 * may or may not have been actually removed from the message queue
6439 * (for instance, if the Runnable was not in the queue already.)
6440 */
6441 public boolean removeCallbacks(Runnable action) {
6442 Handler handler;
6443 if (mAttachInfo != null) {
6444 handler = mAttachInfo.mHandler;
6445 } else {
6446 // Assume that post will succeed later
6447 ViewRoot.getRunQueue().removeCallbacks(action);
6448 return true;
6449 }
6450
6451 handler.removeCallbacks(action);
6452 return true;
6453 }
6454
6455 /**
6456 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6457 * Use this to invalidate the View from a non-UI thread.
6458 *
6459 * @see #invalidate()
6460 */
6461 public void postInvalidate() {
6462 postInvalidateDelayed(0);
6463 }
6464
6465 /**
6466 * Cause an invalidate of the specified area to happen on a subsequent cycle
6467 * through the event loop. Use this to invalidate the View from a non-UI thread.
6468 *
6469 * @param left The left coordinate of the rectangle to invalidate.
6470 * @param top The top coordinate of the rectangle to invalidate.
6471 * @param right The right coordinate of the rectangle to invalidate.
6472 * @param bottom The bottom coordinate of the rectangle to invalidate.
6473 *
6474 * @see #invalidate(int, int, int, int)
6475 * @see #invalidate(Rect)
6476 */
6477 public void postInvalidate(int left, int top, int right, int bottom) {
6478 postInvalidateDelayed(0, left, top, right, bottom);
6479 }
6480
6481 /**
6482 * Cause an invalidate to happen on a subsequent cycle through the event
6483 * loop. Waits for the specified amount of time.
6484 *
6485 * @param delayMilliseconds the duration in milliseconds to delay the
6486 * invalidation by
6487 */
6488 public void postInvalidateDelayed(long delayMilliseconds) {
6489 // We try only with the AttachInfo because there's no point in invalidating
6490 // if we are not attached to our window
6491 if (mAttachInfo != null) {
6492 Message msg = Message.obtain();
6493 msg.what = AttachInfo.INVALIDATE_MSG;
6494 msg.obj = this;
6495 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6496 }
6497 }
6498
6499 /**
6500 * Cause an invalidate of the specified area to happen on a subsequent cycle
6501 * through the event loop. Waits for the specified amount of time.
6502 *
6503 * @param delayMilliseconds the duration in milliseconds to delay the
6504 * invalidation by
6505 * @param left The left coordinate of the rectangle to invalidate.
6506 * @param top The top coordinate of the rectangle to invalidate.
6507 * @param right The right coordinate of the rectangle to invalidate.
6508 * @param bottom The bottom coordinate of the rectangle to invalidate.
6509 */
6510 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6511 int right, int bottom) {
6512
6513 // We try only with the AttachInfo because there's no point in invalidating
6514 // if we are not attached to our window
6515 if (mAttachInfo != null) {
6516 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6517 info.target = this;
6518 info.left = left;
6519 info.top = top;
6520 info.right = right;
6521 info.bottom = bottom;
6522
6523 final Message msg = Message.obtain();
6524 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6525 msg.obj = info;
6526 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6527 }
6528 }
6529
6530 /**
6531 * Called by a parent to request that a child update its values for mScrollX
6532 * and mScrollY if necessary. This will typically be done if the child is
6533 * animating a scroll using a {@link android.widget.Scroller Scroller}
6534 * object.
6535 */
6536 public void computeScroll() {
6537 }
6538
6539 /**
6540 * <p>Indicate whether the horizontal edges are faded when the view is
6541 * scrolled horizontally.</p>
6542 *
6543 * @return true if the horizontal edges should are faded on scroll, false
6544 * otherwise
6545 *
6546 * @see #setHorizontalFadingEdgeEnabled(boolean)
6547 * @attr ref android.R.styleable#View_fadingEdge
6548 */
6549 public boolean isHorizontalFadingEdgeEnabled() {
6550 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6551 }
6552
6553 /**
6554 * <p>Define whether the horizontal edges should be faded when this view
6555 * is scrolled horizontally.</p>
6556 *
6557 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6558 * be faded when the view is scrolled
6559 * horizontally
6560 *
6561 * @see #isHorizontalFadingEdgeEnabled()
6562 * @attr ref android.R.styleable#View_fadingEdge
6563 */
6564 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6565 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6566 if (horizontalFadingEdgeEnabled) {
6567 initScrollCache();
6568 }
6569
6570 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6571 }
6572 }
6573
6574 /**
6575 * <p>Indicate whether the vertical edges are faded when the view is
6576 * scrolled horizontally.</p>
6577 *
6578 * @return true if the vertical edges should are faded on scroll, false
6579 * otherwise
6580 *
6581 * @see #setVerticalFadingEdgeEnabled(boolean)
6582 * @attr ref android.R.styleable#View_fadingEdge
6583 */
6584 public boolean isVerticalFadingEdgeEnabled() {
6585 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6586 }
6587
6588 /**
6589 * <p>Define whether the vertical edges should be faded when this view
6590 * is scrolled vertically.</p>
6591 *
6592 * @param verticalFadingEdgeEnabled true if the vertical edges should
6593 * be faded when the view is scrolled
6594 * vertically
6595 *
6596 * @see #isVerticalFadingEdgeEnabled()
6597 * @attr ref android.R.styleable#View_fadingEdge
6598 */
6599 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6600 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6601 if (verticalFadingEdgeEnabled) {
6602 initScrollCache();
6603 }
6604
6605 mViewFlags ^= FADING_EDGE_VERTICAL;
6606 }
6607 }
6608
6609 /**
6610 * Returns the strength, or intensity, of the top faded edge. The strength is
6611 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6612 * returns 0.0 or 1.0 but no value in between.
6613 *
6614 * Subclasses should override this method to provide a smoother fade transition
6615 * when scrolling occurs.
6616 *
6617 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6618 */
6619 protected float getTopFadingEdgeStrength() {
6620 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6621 }
6622
6623 /**
6624 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6625 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6626 * returns 0.0 or 1.0 but no value in between.
6627 *
6628 * Subclasses should override this method to provide a smoother fade transition
6629 * when scrolling occurs.
6630 *
6631 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6632 */
6633 protected float getBottomFadingEdgeStrength() {
6634 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6635 computeVerticalScrollRange() ? 1.0f : 0.0f;
6636 }
6637
6638 /**
6639 * Returns the strength, or intensity, of the left faded edge. The strength is
6640 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6641 * returns 0.0 or 1.0 but no value in between.
6642 *
6643 * Subclasses should override this method to provide a smoother fade transition
6644 * when scrolling occurs.
6645 *
6646 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6647 */
6648 protected float getLeftFadingEdgeStrength() {
6649 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6650 }
6651
6652 /**
6653 * Returns the strength, or intensity, of the right faded edge. The strength is
6654 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6655 * returns 0.0 or 1.0 but no value in between.
6656 *
6657 * Subclasses should override this method to provide a smoother fade transition
6658 * when scrolling occurs.
6659 *
6660 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6661 */
6662 protected float getRightFadingEdgeStrength() {
6663 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6664 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6665 }
6666
6667 /**
6668 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6669 * scrollbar is not drawn by default.</p>
6670 *
6671 * @return true if the horizontal scrollbar should be painted, false
6672 * otherwise
6673 *
6674 * @see #setHorizontalScrollBarEnabled(boolean)
6675 */
6676 public boolean isHorizontalScrollBarEnabled() {
6677 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6678 }
6679
6680 /**
6681 * <p>Define whether the horizontal scrollbar should be drawn or not. The
6682 * scrollbar is not drawn by default.</p>
6683 *
6684 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
6685 * be painted
6686 *
6687 * @see #isHorizontalScrollBarEnabled()
6688 */
6689 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
6690 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
6691 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006692 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 recomputePadding();
6694 }
6695 }
6696
6697 /**
6698 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
6699 * scrollbar is not drawn by default.</p>
6700 *
6701 * @return true if the vertical scrollbar should be painted, false
6702 * otherwise
6703 *
6704 * @see #setVerticalScrollBarEnabled(boolean)
6705 */
6706 public boolean isVerticalScrollBarEnabled() {
6707 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
6708 }
6709
6710 /**
6711 * <p>Define whether the vertical scrollbar should be drawn or not. The
6712 * scrollbar is not drawn by default.</p>
6713 *
6714 * @param verticalScrollBarEnabled true if the vertical scrollbar should
6715 * be painted
6716 *
6717 * @see #isVerticalScrollBarEnabled()
6718 */
6719 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
6720 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
6721 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006722 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006723 recomputePadding();
6724 }
6725 }
6726
6727 private void recomputePadding() {
6728 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
6729 }
Mike Cleronfe81d382009-09-28 14:22:16 -07006730
6731 /**
6732 * Define whether scrollbars will fade when the view is not scrolling.
6733 *
6734 * @param fadeScrollbars wheter to enable fading
6735 *
6736 */
6737 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
6738 initScrollCache();
6739 final ScrollabilityCache scrollabilityCache = mScrollCache;
6740 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07006741 if (fadeScrollbars) {
6742 scrollabilityCache.state = ScrollabilityCache.OFF;
6743 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07006744 scrollabilityCache.state = ScrollabilityCache.ON;
6745 }
6746 }
6747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006748 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07006749 *
6750 * Returns true if scrollbars will fade when this view is not scrolling
6751 *
6752 * @return true if scrollbar fading is enabled
6753 */
6754 public boolean isScrollbarFadingEnabled() {
6755 return mScrollCache != null && mScrollCache.fadeScrollBars;
6756 }
6757
6758 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
6760 * inset. When inset, they add to the padding of the view. And the scrollbars
6761 * can be drawn inside the padding area or on the edge of the view. For example,
6762 * if a view has a background drawable and you want to draw the scrollbars
6763 * inside the padding specified by the drawable, you can use
6764 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
6765 * appear at the edge of the view, ignoring the padding, then you can use
6766 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
6767 * @param style the style of the scrollbars. Should be one of
6768 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
6769 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
6770 * @see #SCROLLBARS_INSIDE_OVERLAY
6771 * @see #SCROLLBARS_INSIDE_INSET
6772 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6773 * @see #SCROLLBARS_OUTSIDE_INSET
6774 */
6775 public void setScrollBarStyle(int style) {
6776 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
6777 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07006778 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 recomputePadding();
6780 }
6781 }
6782
6783 /**
6784 * <p>Returns the current scrollbar style.</p>
6785 * @return the current scrollbar style
6786 * @see #SCROLLBARS_INSIDE_OVERLAY
6787 * @see #SCROLLBARS_INSIDE_INSET
6788 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6789 * @see #SCROLLBARS_OUTSIDE_INSET
6790 */
6791 public int getScrollBarStyle() {
6792 return mViewFlags & SCROLLBARS_STYLE_MASK;
6793 }
6794
6795 /**
6796 * <p>Compute the horizontal range that the horizontal scrollbar
6797 * represents.</p>
6798 *
6799 * <p>The range is expressed in arbitrary units that must be the same as the
6800 * units used by {@link #computeHorizontalScrollExtent()} and
6801 * {@link #computeHorizontalScrollOffset()}.</p>
6802 *
6803 * <p>The default range is the drawing width of this view.</p>
6804 *
6805 * @return the total horizontal range represented by the horizontal
6806 * scrollbar
6807 *
6808 * @see #computeHorizontalScrollExtent()
6809 * @see #computeHorizontalScrollOffset()
6810 * @see android.widget.ScrollBarDrawable
6811 */
6812 protected int computeHorizontalScrollRange() {
6813 return getWidth();
6814 }
6815
6816 /**
6817 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
6818 * within the horizontal range. This value is used to compute the position
6819 * of the thumb within the scrollbar's track.</p>
6820 *
6821 * <p>The range is expressed in arbitrary units that must be the same as the
6822 * units used by {@link #computeHorizontalScrollRange()} and
6823 * {@link #computeHorizontalScrollExtent()}.</p>
6824 *
6825 * <p>The default offset is the scroll offset of this view.</p>
6826 *
6827 * @return the horizontal offset of the scrollbar's thumb
6828 *
6829 * @see #computeHorizontalScrollRange()
6830 * @see #computeHorizontalScrollExtent()
6831 * @see android.widget.ScrollBarDrawable
6832 */
6833 protected int computeHorizontalScrollOffset() {
6834 return mScrollX;
6835 }
6836
6837 /**
6838 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
6839 * within the horizontal range. This value is used to compute the length
6840 * of the thumb within the scrollbar's track.</p>
6841 *
6842 * <p>The range is expressed in arbitrary units that must be the same as the
6843 * units used by {@link #computeHorizontalScrollRange()} and
6844 * {@link #computeHorizontalScrollOffset()}.</p>
6845 *
6846 * <p>The default extent is the drawing width of this view.</p>
6847 *
6848 * @return the horizontal extent of the scrollbar's thumb
6849 *
6850 * @see #computeHorizontalScrollRange()
6851 * @see #computeHorizontalScrollOffset()
6852 * @see android.widget.ScrollBarDrawable
6853 */
6854 protected int computeHorizontalScrollExtent() {
6855 return getWidth();
6856 }
6857
6858 /**
6859 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
6860 *
6861 * <p>The range is expressed in arbitrary units that must be the same as the
6862 * units used by {@link #computeVerticalScrollExtent()} and
6863 * {@link #computeVerticalScrollOffset()}.</p>
6864 *
6865 * @return the total vertical range represented by the vertical scrollbar
6866 *
6867 * <p>The default range is the drawing height of this view.</p>
6868 *
6869 * @see #computeVerticalScrollExtent()
6870 * @see #computeVerticalScrollOffset()
6871 * @see android.widget.ScrollBarDrawable
6872 */
6873 protected int computeVerticalScrollRange() {
6874 return getHeight();
6875 }
6876
6877 /**
6878 * <p>Compute the vertical offset of the vertical scrollbar's thumb
6879 * within the horizontal range. This value is used to compute the position
6880 * of the thumb within the scrollbar's track.</p>
6881 *
6882 * <p>The range is expressed in arbitrary units that must be the same as the
6883 * units used by {@link #computeVerticalScrollRange()} and
6884 * {@link #computeVerticalScrollExtent()}.</p>
6885 *
6886 * <p>The default offset is the scroll offset of this view.</p>
6887 *
6888 * @return the vertical offset of the scrollbar's thumb
6889 *
6890 * @see #computeVerticalScrollRange()
6891 * @see #computeVerticalScrollExtent()
6892 * @see android.widget.ScrollBarDrawable
6893 */
6894 protected int computeVerticalScrollOffset() {
6895 return mScrollY;
6896 }
6897
6898 /**
6899 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
6900 * within the vertical range. This value is used to compute the length
6901 * of the thumb within the scrollbar's track.</p>
6902 *
6903 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08006904 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006905 * {@link #computeVerticalScrollOffset()}.</p>
6906 *
6907 * <p>The default extent is the drawing height of this view.</p>
6908 *
6909 * @return the vertical extent of the scrollbar's thumb
6910 *
6911 * @see #computeVerticalScrollRange()
6912 * @see #computeVerticalScrollOffset()
6913 * @see android.widget.ScrollBarDrawable
6914 */
6915 protected int computeVerticalScrollExtent() {
6916 return getHeight();
6917 }
6918
6919 /**
6920 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
6921 * scrollbars are painted only if they have been awakened first.</p>
6922 *
6923 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07006924 *
6925 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08006927 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006928 // scrollbars are drawn only when the animation is running
6929 final ScrollabilityCache cache = mScrollCache;
6930 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006931
6932 int state = cache.state;
6933
6934 if (state == ScrollabilityCache.OFF) {
6935 return;
6936 }
6937
6938 boolean invalidate = false;
6939
6940 if (state == ScrollabilityCache.FADING) {
6941 // We're fading -- get our fade interpolation
6942 if (cache.interpolatorValues == null) {
6943 cache.interpolatorValues = new float[1];
6944 }
6945
6946 float[] values = cache.interpolatorValues;
6947
6948 // Stops the animation if we're done
6949 if (cache.scrollBarInterpolator.timeToValues(values) ==
6950 Interpolator.Result.FREEZE_END) {
6951 cache.state = ScrollabilityCache.OFF;
6952 } else {
6953 cache.scrollBar.setAlpha(Math.round(values[0]));
6954 }
6955
6956 // This will make the scroll bars inval themselves after
6957 // drawing. We only want this when we're fading so that
6958 // we prevent excessive redraws
6959 invalidate = true;
6960 } else {
6961 // We're just on -- but we may have been fading before so
6962 // reset alpha
6963 cache.scrollBar.setAlpha(255);
6964 }
6965
6966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 final int viewFlags = mViewFlags;
6968
6969 final boolean drawHorizontalScrollBar =
6970 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6971 final boolean drawVerticalScrollBar =
6972 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
6973 && !isVerticalScrollBarHidden();
6974
6975 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
6976 final int width = mRight - mLeft;
6977 final int height = mBottom - mTop;
6978
6979 final ScrollBarDrawable scrollBar = cache.scrollBar;
6980 int size = scrollBar.getSize(false);
6981 if (size <= 0) {
6982 size = cache.scrollBarSize;
6983 }
6984
Mike Reede8853fc2009-09-04 14:01:48 -04006985 final int scrollX = mScrollX;
6986 final int scrollY = mScrollY;
6987 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
6988
Mike Cleronf116bf82009-09-27 19:14:12 -07006989 int left, top, right, bottom;
6990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006991 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006992 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04006993 computeHorizontalScrollOffset(),
6994 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04006995 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07006996 getVerticalScrollbarWidth() : 0;
6997 top = scrollY + height - size - (mUserPaddingBottom & inside);
6998 left = scrollX + (mPaddingLeft & inside);
6999 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7000 bottom = top + size;
7001 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7002 if (invalidate) {
7003 invalidate(left, top, right, bottom);
7004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007005 }
7006
7007 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04007008 scrollBar.setParameters(computeVerticalScrollRange(),
7009 computeVerticalScrollOffset(),
7010 computeVerticalScrollExtent(), true);
7011 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07007012 left = scrollX + width - size - (mUserPaddingRight & inside);
7013 top = scrollY + (mPaddingTop & inside);
7014 right = left + size;
7015 bottom = scrollY + height - (mUserPaddingBottom & inside);
7016 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7017 if (invalidate) {
7018 invalidate(left, top, right, bottom);
7019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007020 }
7021 }
7022 }
7023 }
Romain Guy8506ab42009-06-11 17:35:47 -07007024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007025 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007026 * 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 -08007027 * FastScroller is visible.
7028 * @return whether to temporarily hide the vertical scrollbar
7029 * @hide
7030 */
7031 protected boolean isVerticalScrollBarHidden() {
7032 return false;
7033 }
7034
7035 /**
7036 * <p>Draw the horizontal scrollbar if
7037 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7038 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007039 * @param canvas the canvas on which to draw the scrollbar
7040 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 *
7042 * @see #isHorizontalScrollBarEnabled()
7043 * @see #computeHorizontalScrollRange()
7044 * @see #computeHorizontalScrollExtent()
7045 * @see #computeHorizontalScrollOffset()
7046 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007047 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007048 */
Romain Guy8fb95422010-08-17 18:38:51 -07007049 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7050 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007051 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007052 scrollBar.draw(canvas);
7053 }
Mike Reede8853fc2009-09-04 14:01:48 -04007054
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007055 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7057 * returns true.</p>
7058 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007059 * @param canvas the canvas on which to draw the scrollbar
7060 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 *
7062 * @see #isVerticalScrollBarEnabled()
7063 * @see #computeVerticalScrollRange()
7064 * @see #computeVerticalScrollExtent()
7065 * @see #computeVerticalScrollOffset()
7066 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007067 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007068 */
Romain Guy8fb95422010-08-17 18:38:51 -07007069 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7070 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007071 scrollBar.setBounds(l, t, r, b);
7072 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 }
7074
7075 /**
7076 * Implement this to do your drawing.
7077 *
7078 * @param canvas the canvas on which the background will be drawn
7079 */
7080 protected void onDraw(Canvas canvas) {
7081 }
7082
7083 /*
7084 * Caller is responsible for calling requestLayout if necessary.
7085 * (This allows addViewInLayout to not request a new layout.)
7086 */
7087 void assignParent(ViewParent parent) {
7088 if (mParent == null) {
7089 mParent = parent;
7090 } else if (parent == null) {
7091 mParent = null;
7092 } else {
7093 throw new RuntimeException("view " + this + " being added, but"
7094 + " it already has a parent");
7095 }
7096 }
7097
7098 /**
7099 * This is called when the view is attached to a window. At this point it
7100 * has a Surface and will start drawing. Note that this function is
7101 * guaranteed to be called before {@link #onDraw}, however it may be called
7102 * any time before the first onDraw -- including before or after
7103 * {@link #onMeasure}.
7104 *
7105 * @see #onDetachedFromWindow()
7106 */
7107 protected void onAttachedToWindow() {
7108 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7109 mParent.requestTransparentRegion(this);
7110 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007111 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7112 initialAwakenScrollBars();
7113 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007115 }
7116
7117 /**
7118 * This is called when the view is detached from a window. At this point it
7119 * no longer has a surface for drawing.
7120 *
7121 * @see #onAttachedToWindow()
7122 */
7123 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007124 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08007125 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007126 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007127 destroyDrawingCache();
7128 }
7129
7130 /**
7131 * @return The number of times this view has been attached to a window
7132 */
7133 protected int getWindowAttachCount() {
7134 return mWindowAttachCount;
7135 }
7136
7137 /**
7138 * Retrieve a unique token identifying the window this view is attached to.
7139 * @return Return the window's token for use in
7140 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7141 */
7142 public IBinder getWindowToken() {
7143 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7144 }
7145
7146 /**
7147 * Retrieve a unique token identifying the top-level "real" window of
7148 * the window that this view is attached to. That is, this is like
7149 * {@link #getWindowToken}, except if the window this view in is a panel
7150 * window (attached to another containing window), then the token of
7151 * the containing window is returned instead.
7152 *
7153 * @return Returns the associated window token, either
7154 * {@link #getWindowToken()} or the containing window's token.
7155 */
7156 public IBinder getApplicationWindowToken() {
7157 AttachInfo ai = mAttachInfo;
7158 if (ai != null) {
7159 IBinder appWindowToken = ai.mPanelParentWindowToken;
7160 if (appWindowToken == null) {
7161 appWindowToken = ai.mWindowToken;
7162 }
7163 return appWindowToken;
7164 }
7165 return null;
7166 }
7167
7168 /**
7169 * Retrieve private session object this view hierarchy is using to
7170 * communicate with the window manager.
7171 * @return the session object to communicate with the window manager
7172 */
7173 /*package*/ IWindowSession getWindowSession() {
7174 return mAttachInfo != null ? mAttachInfo.mSession : null;
7175 }
7176
7177 /**
7178 * @param info the {@link android.view.View.AttachInfo} to associated with
7179 * this view
7180 */
7181 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7182 //System.out.println("Attached! " + this);
7183 mAttachInfo = info;
7184 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007185 // We will need to evaluate the drawable state at least once.
7186 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 if (mFloatingTreeObserver != null) {
7188 info.mTreeObserver.merge(mFloatingTreeObserver);
7189 mFloatingTreeObserver = null;
7190 }
7191 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7192 mAttachInfo.mScrollContainers.add(this);
7193 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7194 }
7195 performCollectViewAttributes(visibility);
7196 onAttachedToWindow();
7197 int vis = info.mWindowVisibility;
7198 if (vis != GONE) {
7199 onWindowVisibilityChanged(vis);
7200 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007201 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7202 // If nobody has evaluated the drawable state yet, then do it now.
7203 refreshDrawableState();
7204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 }
7206
7207 void dispatchDetachedFromWindow() {
7208 //System.out.println("Detached! " + this);
7209 AttachInfo info = mAttachInfo;
7210 if (info != null) {
7211 int vis = info.mWindowVisibility;
7212 if (vis != GONE) {
7213 onWindowVisibilityChanged(GONE);
7214 }
7215 }
7216
7217 onDetachedFromWindow();
7218 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7219 mAttachInfo.mScrollContainers.remove(this);
7220 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7221 }
7222 mAttachInfo = null;
7223 }
7224
7225 /**
7226 * Store this view hierarchy's frozen state into the given container.
7227 *
7228 * @param container The SparseArray in which to save the view's state.
7229 *
7230 * @see #restoreHierarchyState
7231 * @see #dispatchSaveInstanceState
7232 * @see #onSaveInstanceState
7233 */
7234 public void saveHierarchyState(SparseArray<Parcelable> container) {
7235 dispatchSaveInstanceState(container);
7236 }
7237
7238 /**
7239 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7240 * May be overridden to modify how freezing happens to a view's children; for example, some
7241 * views may want to not store state for their children.
7242 *
7243 * @param container The SparseArray in which to save the view's state.
7244 *
7245 * @see #dispatchRestoreInstanceState
7246 * @see #saveHierarchyState
7247 * @see #onSaveInstanceState
7248 */
7249 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7250 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7251 mPrivateFlags &= ~SAVE_STATE_CALLED;
7252 Parcelable state = onSaveInstanceState();
7253 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7254 throw new IllegalStateException(
7255 "Derived class did not call super.onSaveInstanceState()");
7256 }
7257 if (state != null) {
7258 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7259 // + ": " + state);
7260 container.put(mID, state);
7261 }
7262 }
7263 }
7264
7265 /**
7266 * Hook allowing a view to generate a representation of its internal state
7267 * that can later be used to create a new instance with that same state.
7268 * This state should only contain information that is not persistent or can
7269 * not be reconstructed later. For example, you will never store your
7270 * current position on screen because that will be computed again when a
7271 * new instance of the view is placed in its view hierarchy.
7272 * <p>
7273 * Some examples of things you may store here: the current cursor position
7274 * in a text view (but usually not the text itself since that is stored in a
7275 * content provider or other persistent storage), the currently selected
7276 * item in a list view.
7277 *
7278 * @return Returns a Parcelable object containing the view's current dynamic
7279 * state, or null if there is nothing interesting to save. The
7280 * default implementation returns null.
7281 * @see #onRestoreInstanceState
7282 * @see #saveHierarchyState
7283 * @see #dispatchSaveInstanceState
7284 * @see #setSaveEnabled(boolean)
7285 */
7286 protected Parcelable onSaveInstanceState() {
7287 mPrivateFlags |= SAVE_STATE_CALLED;
7288 return BaseSavedState.EMPTY_STATE;
7289 }
7290
7291 /**
7292 * Restore this view hierarchy's frozen state from the given container.
7293 *
7294 * @param container The SparseArray which holds previously frozen states.
7295 *
7296 * @see #saveHierarchyState
7297 * @see #dispatchRestoreInstanceState
7298 * @see #onRestoreInstanceState
7299 */
7300 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7301 dispatchRestoreInstanceState(container);
7302 }
7303
7304 /**
7305 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7306 * children. May be overridden to modify how restoreing happens to a view's children; for
7307 * example, some views may want to not store state for their children.
7308 *
7309 * @param container The SparseArray which holds previously saved state.
7310 *
7311 * @see #dispatchSaveInstanceState
7312 * @see #restoreHierarchyState
7313 * @see #onRestoreInstanceState
7314 */
7315 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7316 if (mID != NO_ID) {
7317 Parcelable state = container.get(mID);
7318 if (state != null) {
7319 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7320 // + ": " + state);
7321 mPrivateFlags &= ~SAVE_STATE_CALLED;
7322 onRestoreInstanceState(state);
7323 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7324 throw new IllegalStateException(
7325 "Derived class did not call super.onRestoreInstanceState()");
7326 }
7327 }
7328 }
7329 }
7330
7331 /**
7332 * Hook allowing a view to re-apply a representation of its internal state that had previously
7333 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7334 * null state.
7335 *
7336 * @param state The frozen state that had previously been returned by
7337 * {@link #onSaveInstanceState}.
7338 *
7339 * @see #onSaveInstanceState
7340 * @see #restoreHierarchyState
7341 * @see #dispatchRestoreInstanceState
7342 */
7343 protected void onRestoreInstanceState(Parcelable state) {
7344 mPrivateFlags |= SAVE_STATE_CALLED;
7345 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007346 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7347 + "received " + state.getClass().toString() + " instead. This usually happens "
7348 + "when two views of different type have the same id in the same hierarchy. "
7349 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7350 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 }
7352 }
7353
7354 /**
7355 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7356 *
7357 * @return the drawing start time in milliseconds
7358 */
7359 public long getDrawingTime() {
7360 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7361 }
7362
7363 /**
7364 * <p>Enables or disables the duplication of the parent's state into this view. When
7365 * duplication is enabled, this view gets its drawable state from its parent rather
7366 * than from its own internal properties.</p>
7367 *
7368 * <p>Note: in the current implementation, setting this property to true after the
7369 * view was added to a ViewGroup might have no effect at all. This property should
7370 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7371 *
7372 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7373 * property is enabled, an exception will be thrown.</p>
7374 *
7375 * @param enabled True to enable duplication of the parent's drawable state, false
7376 * to disable it.
7377 *
7378 * @see #getDrawableState()
7379 * @see #isDuplicateParentStateEnabled()
7380 */
7381 public void setDuplicateParentStateEnabled(boolean enabled) {
7382 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7383 }
7384
7385 /**
7386 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7387 *
7388 * @return True if this view's drawable state is duplicated from the parent,
7389 * false otherwise
7390 *
7391 * @see #getDrawableState()
7392 * @see #setDuplicateParentStateEnabled(boolean)
7393 */
7394 public boolean isDuplicateParentStateEnabled() {
7395 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7396 }
7397
7398 /**
7399 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
7400 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
7401 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
7402 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
7403 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
7404 * null.</p>
7405 *
7406 * @param enabled true to enable the drawing cache, false otherwise
7407 *
7408 * @see #isDrawingCacheEnabled()
7409 * @see #getDrawingCache()
7410 * @see #buildDrawingCache()
7411 */
7412 public void setDrawingCacheEnabled(boolean enabled) {
7413 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
7414 }
7415
7416 /**
7417 * <p>Indicates whether the drawing cache is enabled for this view.</p>
7418 *
7419 * @return true if the drawing cache is enabled
7420 *
7421 * @see #setDrawingCacheEnabled(boolean)
7422 * @see #getDrawingCache()
7423 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07007424 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007425 public boolean isDrawingCacheEnabled() {
7426 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
7427 }
7428
7429 /**
Romain Guyb051e892010-09-28 19:09:36 -07007430 * <p>Returns a display list that can be used to draw this view again
7431 * without executing its draw method.</p>
7432 *
7433 * @return A DisplayList ready to replay, or null if caching is not enabled.
7434 */
7435 DisplayList getDisplayList() {
7436 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7437 return null;
7438 }
Romain Guyb051e892010-09-28 19:09:36 -07007439 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
7440 return null;
7441 }
7442
7443 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
7444 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mDisplayList == null)) {
7445
Romain Guyb051e892010-09-28 19:09:36 -07007446 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
7447
7448 final HardwareCanvas canvas = mDisplayList.start();
7449 try {
7450 int width = mRight - mLeft;
7451 int height = mBottom - mTop;
7452
7453 canvas.setViewport(width, height);
7454 canvas.onPreDraw();
7455
7456 final int restoreCount = canvas.save();
7457
Romain Guy2fe9a8f2010-10-04 20:17:01 -07007458 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07007459
7460 // Fast path for layouts with no backgrounds
7461 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7462 mPrivateFlags &= ~DIRTY_MASK;
7463 dispatchDraw(canvas);
7464 } else {
7465 draw(canvas);
7466 }
7467
7468 canvas.restoreToCount(restoreCount);
7469 } finally {
7470 canvas.onPostDraw();
7471
7472 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07007473 }
7474 }
7475
7476 return mDisplayList;
7477 }
7478
7479 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007480 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
7481 *
7482 * @return A non-scaled bitmap representing this view or null if cache is disabled.
7483 *
7484 * @see #getDrawingCache(boolean)
7485 */
7486 public Bitmap getDrawingCache() {
7487 return getDrawingCache(false);
7488 }
7489
7490 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007491 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
7492 * is null when caching is disabled. If caching is enabled and the cache is not ready,
7493 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
7494 * draw from the cache when the cache is enabled. To benefit from the cache, you must
7495 * request the drawing cache by calling this method and draw it on screen if the
7496 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007497 *
7498 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7499 * this method will create a bitmap of the same size as this view. Because this bitmap
7500 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7501 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7502 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7503 * size than the view. This implies that your application must be able to handle this
7504 * size.</p>
7505 *
7506 * @param autoScale Indicates whether the generated bitmap should be scaled based on
7507 * the current density of the screen when the application is in compatibility
7508 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 *
Romain Guyfbd8f692009-06-26 14:51:58 -07007510 * @return A bitmap representing this view or null if cache is disabled.
7511 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007512 * @see #setDrawingCacheEnabled(boolean)
7513 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07007514 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007515 * @see #destroyDrawingCache()
7516 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007517 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007518 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7519 return null;
7520 }
7521 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007522 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 }
Romain Guy02890fd2010-08-06 17:58:44 -07007524 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007525 }
7526
7527 /**
7528 * <p>Frees the resources used by the drawing cache. If you call
7529 * {@link #buildDrawingCache()} manually without calling
7530 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7531 * should cleanup the cache with this method afterwards.</p>
7532 *
7533 * @see #setDrawingCacheEnabled(boolean)
7534 * @see #buildDrawingCache()
7535 * @see #getDrawingCache()
7536 */
7537 public void destroyDrawingCache() {
7538 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007539 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007540 mDrawingCache = null;
7541 }
Romain Guyfbd8f692009-06-26 14:51:58 -07007542 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007543 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07007544 mUnscaledDrawingCache = null;
7545 }
Romain Guyb051e892010-09-28 19:09:36 -07007546 if (mDisplayList != null) {
Romain Guyb051e892010-09-28 19:09:36 -07007547 mDisplayList = null;
7548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007549 }
7550
7551 /**
7552 * Setting a solid background color for the drawing cache's bitmaps will improve
7553 * perfromance and memory usage. Note, though that this should only be used if this
7554 * view will always be drawn on top of a solid color.
7555 *
7556 * @param color The background color to use for the drawing cache's bitmap
7557 *
7558 * @see #setDrawingCacheEnabled(boolean)
7559 * @see #buildDrawingCache()
7560 * @see #getDrawingCache()
7561 */
7562 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08007563 if (color != mDrawingCacheBackgroundColor) {
7564 mDrawingCacheBackgroundColor = color;
7565 mPrivateFlags &= ~DRAWING_CACHE_VALID;
7566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007567 }
7568
7569 /**
7570 * @see #setDrawingCacheBackgroundColor(int)
7571 *
7572 * @return The background color to used for the drawing cache's bitmap
7573 */
7574 public int getDrawingCacheBackgroundColor() {
7575 return mDrawingCacheBackgroundColor;
7576 }
7577
7578 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007579 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
7580 *
7581 * @see #buildDrawingCache(boolean)
7582 */
7583 public void buildDrawingCache() {
7584 buildDrawingCache(false);
7585 }
7586
7587 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
7589 *
7590 * <p>If you call {@link #buildDrawingCache()} manually without calling
7591 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7592 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007593 *
7594 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7595 * this method will create a bitmap of the same size as this view. Because this bitmap
7596 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7597 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7598 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7599 * size than the view. This implies that your application must be able to handle this
7600 * size.</p>
Romain Guy0d9275e2010-10-26 14:22:30 -07007601 *
7602 * <p>You should avoid calling this method when hardware acceleration is enabled. If
7603 * you do not need the drawing cache bitmap, calling this method will increase memory
7604 * usage and cause the view to be rendered in software once, thus negatively impacting
7605 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007606 *
7607 * @see #getDrawingCache()
7608 * @see #destroyDrawingCache()
7609 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007610 public void buildDrawingCache(boolean autoScale) {
7611 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07007612 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613
7614 if (ViewDebug.TRACE_HIERARCHY) {
7615 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007617
Romain Guy8506ab42009-06-11 17:35:47 -07007618 int width = mRight - mLeft;
7619 int height = mBottom - mTop;
7620
7621 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007622 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007623
Romain Guye1123222009-06-29 14:24:56 -07007624 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007625 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7626 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007628
7629 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007630 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08007631 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632
7633 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007634 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08007635 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7637 destroyDrawingCache();
7638 return;
7639 }
7640
7641 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07007642 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007643
7644 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 Bitmap.Config quality;
7646 if (!opaque) {
7647 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7648 case DRAWING_CACHE_QUALITY_AUTO:
7649 quality = Bitmap.Config.ARGB_8888;
7650 break;
7651 case DRAWING_CACHE_QUALITY_LOW:
7652 quality = Bitmap.Config.ARGB_4444;
7653 break;
7654 case DRAWING_CACHE_QUALITY_HIGH:
7655 quality = Bitmap.Config.ARGB_8888;
7656 break;
7657 default:
7658 quality = Bitmap.Config.ARGB_8888;
7659 break;
7660 }
7661 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07007662 // Optimization for translucent windows
7663 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08007664 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007665 }
7666
7667 // Try to cleanup memory
7668 if (bitmap != null) bitmap.recycle();
7669
7670 try {
7671 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07007672 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07007673 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07007674 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007675 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07007676 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007677 }
Adam Powell26153a32010-11-08 15:22:27 -08007678 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 } catch (OutOfMemoryError e) {
7680 // If there is not enough memory to create the bitmap cache, just
7681 // ignore the issue as bitmap caches are not required to draw the
7682 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07007683 if (autoScale) {
7684 mDrawingCache = null;
7685 } else {
7686 mUnscaledDrawingCache = null;
7687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 return;
7689 }
7690
7691 clear = drawingCacheBackgroundColor != 0;
7692 }
7693
7694 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007695 if (attachInfo != null) {
7696 canvas = attachInfo.mCanvas;
7697 if (canvas == null) {
7698 canvas = new Canvas();
7699 }
7700 canvas.setBitmap(bitmap);
7701 // Temporarily clobber the cached Canvas in case one of our children
7702 // is also using a drawing cache. Without this, the children would
7703 // steal the canvas by attaching their own bitmap to it and bad, bad
7704 // thing would happen (invisible views, corrupted drawings, etc.)
7705 attachInfo.mCanvas = null;
7706 } else {
7707 // This case should hopefully never or seldom happen
7708 canvas = new Canvas(bitmap);
7709 }
7710
7711 if (clear) {
7712 bitmap.eraseColor(drawingCacheBackgroundColor);
7713 }
7714
7715 computeScroll();
7716 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07007717
Romain Guye1123222009-06-29 14:24:56 -07007718 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007719 final float scale = attachInfo.mApplicationScale;
7720 canvas.scale(scale, scale);
7721 }
7722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007723 canvas.translate(-mScrollX, -mScrollY);
7724
Romain Guy5bcdff42009-05-14 21:27:18 -07007725 mPrivateFlags |= DRAWN;
Romain Guy0d9275e2010-10-26 14:22:30 -07007726 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated) {
7727 mPrivateFlags |= DRAWING_CACHE_VALID;
7728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729
7730 // Fast path for layouts with no backgrounds
7731 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7732 if (ViewDebug.TRACE_HIERARCHY) {
7733 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7734 }
Romain Guy5bcdff42009-05-14 21:27:18 -07007735 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 dispatchDraw(canvas);
7737 } else {
7738 draw(canvas);
7739 }
7740
7741 canvas.restoreToCount(restoreCount);
7742
7743 if (attachInfo != null) {
7744 // Restore the cached Canvas for our siblings
7745 attachInfo.mCanvas = canvas;
7746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 }
7748 }
7749
7750 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007751 * Create a snapshot of the view into a bitmap. We should probably make
7752 * some form of this public, but should think about the API.
7753 */
Romain Guy223ff5c2010-03-02 17:07:47 -08007754 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007755 int width = mRight - mLeft;
7756 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007757
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007758 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07007759 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007760 width = (int) ((width * scale) + 0.5f);
7761 height = (int) ((height * scale) + 0.5f);
7762
Romain Guy8c11e312009-09-14 15:15:30 -07007763 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007764 if (bitmap == null) {
7765 throw new OutOfMemoryError();
7766 }
7767
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007768 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
7769
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007770 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007771 if (attachInfo != null) {
7772 canvas = attachInfo.mCanvas;
7773 if (canvas == null) {
7774 canvas = new Canvas();
7775 }
7776 canvas.setBitmap(bitmap);
7777 // Temporarily clobber the cached Canvas in case one of our children
7778 // is also using a drawing cache. Without this, the children would
7779 // steal the canvas by attaching their own bitmap to it and bad, bad
7780 // things would happen (invisible views, corrupted drawings, etc.)
7781 attachInfo.mCanvas = null;
7782 } else {
7783 // This case should hopefully never or seldom happen
7784 canvas = new Canvas(bitmap);
7785 }
7786
Romain Guy5bcdff42009-05-14 21:27:18 -07007787 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007788 bitmap.eraseColor(backgroundColor);
7789 }
7790
7791 computeScroll();
7792 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007793 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007794 canvas.translate(-mScrollX, -mScrollY);
7795
Romain Guy5bcdff42009-05-14 21:27:18 -07007796 // Temporarily remove the dirty mask
7797 int flags = mPrivateFlags;
7798 mPrivateFlags &= ~DIRTY_MASK;
7799
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007800 // Fast path for layouts with no backgrounds
7801 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7802 dispatchDraw(canvas);
7803 } else {
7804 draw(canvas);
7805 }
7806
Romain Guy5bcdff42009-05-14 21:27:18 -07007807 mPrivateFlags = flags;
7808
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007809 canvas.restoreToCount(restoreCount);
7810
7811 if (attachInfo != null) {
7812 // Restore the cached Canvas for our siblings
7813 attachInfo.mCanvas = canvas;
7814 }
Romain Guy8506ab42009-06-11 17:35:47 -07007815
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007816 return bitmap;
7817 }
7818
7819 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007820 * Indicates whether this View is currently in edit mode. A View is usually
7821 * in edit mode when displayed within a developer tool. For instance, if
7822 * this View is being drawn by a visual user interface builder, this method
7823 * should return true.
7824 *
7825 * Subclasses should check the return value of this method to provide
7826 * different behaviors if their normal behavior might interfere with the
7827 * host environment. For instance: the class spawns a thread in its
7828 * constructor, the drawing code relies on device-specific features, etc.
7829 *
7830 * This method is usually checked in the drawing code of custom widgets.
7831 *
7832 * @return True if this View is in edit mode, false otherwise.
7833 */
7834 public boolean isInEditMode() {
7835 return false;
7836 }
7837
7838 /**
7839 * If the View draws content inside its padding and enables fading edges,
7840 * it needs to support padding offsets. Padding offsets are added to the
7841 * fading edges to extend the length of the fade so that it covers pixels
7842 * drawn inside the padding.
7843 *
7844 * Subclasses of this class should override this method if they need
7845 * to draw content inside the padding.
7846 *
7847 * @return True if padding offset must be applied, false otherwise.
7848 *
7849 * @see #getLeftPaddingOffset()
7850 * @see #getRightPaddingOffset()
7851 * @see #getTopPaddingOffset()
7852 * @see #getBottomPaddingOffset()
7853 *
7854 * @since CURRENT
7855 */
7856 protected boolean isPaddingOffsetRequired() {
7857 return false;
7858 }
7859
7860 /**
7861 * Amount by which to extend the left fading region. Called only when
7862 * {@link #isPaddingOffsetRequired()} returns true.
7863 *
7864 * @return The left padding offset in pixels.
7865 *
7866 * @see #isPaddingOffsetRequired()
7867 *
7868 * @since CURRENT
7869 */
7870 protected int getLeftPaddingOffset() {
7871 return 0;
7872 }
7873
7874 /**
7875 * Amount by which to extend the right fading region. Called only when
7876 * {@link #isPaddingOffsetRequired()} returns true.
7877 *
7878 * @return The right padding offset in pixels.
7879 *
7880 * @see #isPaddingOffsetRequired()
7881 *
7882 * @since CURRENT
7883 */
7884 protected int getRightPaddingOffset() {
7885 return 0;
7886 }
7887
7888 /**
7889 * Amount by which to extend the top fading region. Called only when
7890 * {@link #isPaddingOffsetRequired()} returns true.
7891 *
7892 * @return The top padding offset in pixels.
7893 *
7894 * @see #isPaddingOffsetRequired()
7895 *
7896 * @since CURRENT
7897 */
7898 protected int getTopPaddingOffset() {
7899 return 0;
7900 }
7901
7902 /**
7903 * Amount by which to extend the bottom fading region. Called only when
7904 * {@link #isPaddingOffsetRequired()} returns true.
7905 *
7906 * @return The bottom padding offset in pixels.
7907 *
7908 * @see #isPaddingOffsetRequired()
7909 *
7910 * @since CURRENT
7911 */
7912 protected int getBottomPaddingOffset() {
7913 return 0;
7914 }
7915
7916 /**
Romain Guy2bffd262010-09-12 17:40:02 -07007917 * <p>Indicates whether this view is attached to an hardware accelerated
7918 * window or not.</p>
7919 *
7920 * <p>Even if this method returns true, it does not mean that every call
7921 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
7922 * accelerated {@link android.graphics.Canvas}. For instance, if this view
7923 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
7924 * window is hardware accelerated,
7925 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
7926 * return false, and this method will return true.</p>
7927 *
7928 * @return True if the view is attached to a window and the window is
7929 * hardware accelerated; false in any other case.
7930 */
7931 public boolean isHardwareAccelerated() {
7932 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
7933 }
7934
7935 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 * Manually render this view (and all of its children) to the given Canvas.
7937 * The view must have already done a full layout before this function is
7938 * called. When implementing a view, do not override this method; instead,
7939 * you should implement {@link #onDraw}.
7940 *
7941 * @param canvas The Canvas to which the View is rendered.
7942 */
7943 public void draw(Canvas canvas) {
7944 if (ViewDebug.TRACE_HIERARCHY) {
7945 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7946 }
7947
Romain Guy5bcdff42009-05-14 21:27:18 -07007948 final int privateFlags = mPrivateFlags;
7949 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
7950 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
7951 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07007952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 /*
7954 * Draw traversal performs several drawing steps which must be executed
7955 * in the appropriate order:
7956 *
7957 * 1. Draw the background
7958 * 2. If necessary, save the canvas' layers to prepare for fading
7959 * 3. Draw view's content
7960 * 4. Draw children
7961 * 5. If necessary, draw the fading edges and restore layers
7962 * 6. Draw decorations (scrollbars for instance)
7963 */
7964
7965 // Step 1, draw the background, if needed
7966 int saveCount;
7967
Romain Guy24443ea2009-05-11 11:56:30 -07007968 if (!dirtyOpaque) {
7969 final Drawable background = mBGDrawable;
7970 if (background != null) {
7971 final int scrollX = mScrollX;
7972 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973
Romain Guy24443ea2009-05-11 11:56:30 -07007974 if (mBackgroundSizeChanged) {
7975 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
7976 mBackgroundSizeChanged = false;
7977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007978
Romain Guy24443ea2009-05-11 11:56:30 -07007979 if ((scrollX | scrollY) == 0) {
7980 background.draw(canvas);
7981 } else {
7982 canvas.translate(scrollX, scrollY);
7983 background.draw(canvas);
7984 canvas.translate(-scrollX, -scrollY);
7985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 }
7987 }
7988
7989 // skip step 2 & 5 if possible (common case)
7990 final int viewFlags = mViewFlags;
7991 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
7992 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
7993 if (!verticalEdges && !horizontalEdges) {
7994 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007995 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996
7997 // Step 4, draw the children
7998 dispatchDraw(canvas);
7999
8000 // Step 6, draw decorations (scrollbars)
8001 onDrawScrollBars(canvas);
8002
8003 // we're done...
8004 return;
8005 }
8006
8007 /*
8008 * Here we do the full fledged routine...
8009 * (this is an uncommon case where speed matters less,
8010 * this is why we repeat some of the tests that have been
8011 * done above)
8012 */
8013
8014 boolean drawTop = false;
8015 boolean drawBottom = false;
8016 boolean drawLeft = false;
8017 boolean drawRight = false;
8018
8019 float topFadeStrength = 0.0f;
8020 float bottomFadeStrength = 0.0f;
8021 float leftFadeStrength = 0.0f;
8022 float rightFadeStrength = 0.0f;
8023
8024 // Step 2, save the canvas' layers
8025 int paddingLeft = mPaddingLeft;
8026 int paddingTop = mPaddingTop;
8027
8028 final boolean offsetRequired = isPaddingOffsetRequired();
8029 if (offsetRequired) {
8030 paddingLeft += getLeftPaddingOffset();
8031 paddingTop += getTopPaddingOffset();
8032 }
8033
8034 int left = mScrollX + paddingLeft;
8035 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8036 int top = mScrollY + paddingTop;
8037 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8038
8039 if (offsetRequired) {
8040 right += getRightPaddingOffset();
8041 bottom += getBottomPaddingOffset();
8042 }
8043
8044 final ScrollabilityCache scrollabilityCache = mScrollCache;
8045 int length = scrollabilityCache.fadingEdgeLength;
8046
8047 // clip the fade length if top and bottom fades overlap
8048 // overlapping fades produce odd-looking artifacts
8049 if (verticalEdges && (top + length > bottom - length)) {
8050 length = (bottom - top) / 2;
8051 }
8052
8053 // also clip horizontal fades if necessary
8054 if (horizontalEdges && (left + length > right - length)) {
8055 length = (right - left) / 2;
8056 }
8057
8058 if (verticalEdges) {
8059 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008060 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008061 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008062 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008063 }
8064
8065 if (horizontalEdges) {
8066 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008067 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008068 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008069 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 }
8071
8072 saveCount = canvas.getSaveCount();
8073
8074 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008075 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008076 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8077
8078 if (drawTop) {
8079 canvas.saveLayer(left, top, right, top + length, null, flags);
8080 }
8081
8082 if (drawBottom) {
8083 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8084 }
8085
8086 if (drawLeft) {
8087 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8088 }
8089
8090 if (drawRight) {
8091 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8092 }
8093 } else {
8094 scrollabilityCache.setFadeColor(solidColor);
8095 }
8096
8097 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008098 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099
8100 // Step 4, draw the children
8101 dispatchDraw(canvas);
8102
8103 // Step 5, draw the fade effect and restore layers
8104 final Paint p = scrollabilityCache.paint;
8105 final Matrix matrix = scrollabilityCache.matrix;
8106 final Shader fade = scrollabilityCache.shader;
8107 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8108
8109 if (drawTop) {
8110 matrix.setScale(1, fadeHeight * topFadeStrength);
8111 matrix.postTranslate(left, top);
8112 fade.setLocalMatrix(matrix);
8113 canvas.drawRect(left, top, right, top + length, p);
8114 }
8115
8116 if (drawBottom) {
8117 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8118 matrix.postRotate(180);
8119 matrix.postTranslate(left, bottom);
8120 fade.setLocalMatrix(matrix);
8121 canvas.drawRect(left, bottom - length, right, bottom, p);
8122 }
8123
8124 if (drawLeft) {
8125 matrix.setScale(1, fadeHeight * leftFadeStrength);
8126 matrix.postRotate(-90);
8127 matrix.postTranslate(left, top);
8128 fade.setLocalMatrix(matrix);
8129 canvas.drawRect(left, top, left + length, bottom, p);
8130 }
8131
8132 if (drawRight) {
8133 matrix.setScale(1, fadeHeight * rightFadeStrength);
8134 matrix.postRotate(90);
8135 matrix.postTranslate(right, top);
8136 fade.setLocalMatrix(matrix);
8137 canvas.drawRect(right - length, top, right, bottom, p);
8138 }
8139
8140 canvas.restoreToCount(saveCount);
8141
8142 // Step 6, draw decorations (scrollbars)
8143 onDrawScrollBars(canvas);
8144 }
8145
8146 /**
8147 * Override this if your view is known to always be drawn on top of a solid color background,
8148 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8149 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8150 * should be set to 0xFF.
8151 *
8152 * @see #setVerticalFadingEdgeEnabled
8153 * @see #setHorizontalFadingEdgeEnabled
8154 *
8155 * @return The known solid color background for this view, or 0 if the color may vary
8156 */
8157 public int getSolidColor() {
8158 return 0;
8159 }
8160
8161 /**
8162 * Build a human readable string representation of the specified view flags.
8163 *
8164 * @param flags the view flags to convert to a string
8165 * @return a String representing the supplied flags
8166 */
8167 private static String printFlags(int flags) {
8168 String output = "";
8169 int numFlags = 0;
8170 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8171 output += "TAKES_FOCUS";
8172 numFlags++;
8173 }
8174
8175 switch (flags & VISIBILITY_MASK) {
8176 case INVISIBLE:
8177 if (numFlags > 0) {
8178 output += " ";
8179 }
8180 output += "INVISIBLE";
8181 // USELESS HERE numFlags++;
8182 break;
8183 case GONE:
8184 if (numFlags > 0) {
8185 output += " ";
8186 }
8187 output += "GONE";
8188 // USELESS HERE numFlags++;
8189 break;
8190 default:
8191 break;
8192 }
8193 return output;
8194 }
8195
8196 /**
8197 * Build a human readable string representation of the specified private
8198 * view flags.
8199 *
8200 * @param privateFlags the private view flags to convert to a string
8201 * @return a String representing the supplied flags
8202 */
8203 private static String printPrivateFlags(int privateFlags) {
8204 String output = "";
8205 int numFlags = 0;
8206
8207 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8208 output += "WANTS_FOCUS";
8209 numFlags++;
8210 }
8211
8212 if ((privateFlags & FOCUSED) == FOCUSED) {
8213 if (numFlags > 0) {
8214 output += " ";
8215 }
8216 output += "FOCUSED";
8217 numFlags++;
8218 }
8219
8220 if ((privateFlags & SELECTED) == SELECTED) {
8221 if (numFlags > 0) {
8222 output += " ";
8223 }
8224 output += "SELECTED";
8225 numFlags++;
8226 }
8227
8228 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8229 if (numFlags > 0) {
8230 output += " ";
8231 }
8232 output += "IS_ROOT_NAMESPACE";
8233 numFlags++;
8234 }
8235
8236 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8237 if (numFlags > 0) {
8238 output += " ";
8239 }
8240 output += "HAS_BOUNDS";
8241 numFlags++;
8242 }
8243
8244 if ((privateFlags & DRAWN) == DRAWN) {
8245 if (numFlags > 0) {
8246 output += " ";
8247 }
8248 output += "DRAWN";
8249 // USELESS HERE numFlags++;
8250 }
8251 return output;
8252 }
8253
8254 /**
8255 * <p>Indicates whether or not this view's layout will be requested during
8256 * the next hierarchy layout pass.</p>
8257 *
8258 * @return true if the layout will be forced during next layout pass
8259 */
8260 public boolean isLayoutRequested() {
8261 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8262 }
8263
8264 /**
8265 * Assign a size and position to a view and all of its
8266 * descendants
8267 *
8268 * <p>This is the second phase of the layout mechanism.
8269 * (The first is measuring). In this phase, each parent calls
8270 * layout on all of its children to position them.
8271 * This is typically done using the child measurements
8272 * that were stored in the measure pass().
8273 *
8274 * Derived classes with children should override
8275 * onLayout. In that method, they should
Chet Haase21cd1382010-09-01 17:42:29 -07008276 * call layout on each of their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008277 *
8278 * @param l Left position, relative to parent
8279 * @param t Top position, relative to parent
8280 * @param r Right position, relative to parent
8281 * @param b Bottom position, relative to parent
8282 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008283 @SuppressWarnings({"unchecked"})
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 public final void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008285 int oldL = mLeft;
8286 int oldT = mTop;
8287 int oldB = mBottom;
8288 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008289 boolean changed = setFrame(l, t, r, b);
8290 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8291 if (ViewDebug.TRACE_HIERARCHY) {
8292 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8293 }
8294
8295 onLayout(changed, l, t, r, b);
8296 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008297
8298 if (mOnLayoutChangeListeners != null) {
8299 ArrayList<OnLayoutChangeListener> listenersCopy =
8300 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8301 int numListeners = listenersCopy.size();
8302 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07008303 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07008304 }
8305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008306 }
8307 mPrivateFlags &= ~FORCE_LAYOUT;
8308 }
8309
8310 /**
8311 * Called from layout when this view should
8312 * assign a size and position to each of its children.
8313 *
8314 * Derived classes with children should override
8315 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008316 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008317 * @param changed This is a new size or position for this view
8318 * @param left Left position, relative to parent
8319 * @param top Top position, relative to parent
8320 * @param right Right position, relative to parent
8321 * @param bottom Bottom position, relative to parent
8322 */
8323 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8324 }
8325
8326 /**
8327 * Assign a size and position to this view.
8328 *
8329 * This is called from layout.
8330 *
8331 * @param left Left position, relative to parent
8332 * @param top Top position, relative to parent
8333 * @param right Right position, relative to parent
8334 * @param bottom Bottom position, relative to parent
8335 * @return true if the new size and position are different than the
8336 * previous ones
8337 * {@hide}
8338 */
8339 protected boolean setFrame(int left, int top, int right, int bottom) {
8340 boolean changed = false;
8341
8342 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008343 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008344 + right + "," + bottom + ")");
8345 }
8346
8347 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8348 changed = true;
8349
8350 // Remember our drawn bit
8351 int drawn = mPrivateFlags & DRAWN;
8352
8353 // Invalidate our old position
8354 invalidate();
8355
8356
8357 int oldWidth = mRight - mLeft;
8358 int oldHeight = mBottom - mTop;
8359
8360 mLeft = left;
8361 mTop = top;
8362 mRight = right;
8363 mBottom = bottom;
8364
8365 mPrivateFlags |= HAS_BOUNDS;
8366
8367 int newWidth = right - left;
8368 int newHeight = bottom - top;
8369
8370 if (newWidth != oldWidth || newHeight != oldHeight) {
8371 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8372 }
8373
8374 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8375 // If we are visible, force the DRAWN bit to on so that
8376 // this invalidate will go through (at least to our parent).
8377 // This is because someone may have invalidated this view
8378 // before this call to setFrame came in, therby clearing
8379 // the DRAWN bit.
8380 mPrivateFlags |= DRAWN;
8381 invalidate();
8382 }
8383
8384 // Reset drawn bit to original value (invalidate turns it off)
8385 mPrivateFlags |= drawn;
8386
8387 mBackgroundSizeChanged = true;
8388 }
8389 return changed;
8390 }
8391
8392 /**
8393 * Finalize inflating a view from XML. This is called as the last phase
8394 * of inflation, after all child views have been added.
8395 *
8396 * <p>Even if the subclass overrides onFinishInflate, they should always be
8397 * sure to call the super method, so that we get called.
8398 */
8399 protected void onFinishInflate() {
8400 }
8401
8402 /**
8403 * Returns the resources associated with this view.
8404 *
8405 * @return Resources object.
8406 */
8407 public Resources getResources() {
8408 return mResources;
8409 }
8410
8411 /**
8412 * Invalidates the specified Drawable.
8413 *
8414 * @param drawable the drawable to invalidate
8415 */
8416 public void invalidateDrawable(Drawable drawable) {
8417 if (verifyDrawable(drawable)) {
8418 final Rect dirty = drawable.getBounds();
8419 final int scrollX = mScrollX;
8420 final int scrollY = mScrollY;
8421
8422 invalidate(dirty.left + scrollX, dirty.top + scrollY,
8423 dirty.right + scrollX, dirty.bottom + scrollY);
8424 }
8425 }
8426
8427 /**
8428 * Schedules an action on a drawable to occur at a specified time.
8429 *
8430 * @param who the recipient of the action
8431 * @param what the action to run on the drawable
8432 * @param when the time at which the action must occur. Uses the
8433 * {@link SystemClock#uptimeMillis} timebase.
8434 */
8435 public void scheduleDrawable(Drawable who, Runnable what, long when) {
8436 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8437 mAttachInfo.mHandler.postAtTime(what, who, when);
8438 }
8439 }
8440
8441 /**
8442 * Cancels a scheduled action on a drawable.
8443 *
8444 * @param who the recipient of the action
8445 * @param what the action to cancel
8446 */
8447 public void unscheduleDrawable(Drawable who, Runnable what) {
8448 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8449 mAttachInfo.mHandler.removeCallbacks(what, who);
8450 }
8451 }
8452
8453 /**
8454 * Unschedule any events associated with the given Drawable. This can be
8455 * used when selecting a new Drawable into a view, so that the previous
8456 * one is completely unscheduled.
8457 *
8458 * @param who The Drawable to unschedule.
8459 *
8460 * @see #drawableStateChanged
8461 */
8462 public void unscheduleDrawable(Drawable who) {
8463 if (mAttachInfo != null) {
8464 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
8465 }
8466 }
8467
8468 /**
8469 * If your view subclass is displaying its own Drawable objects, it should
8470 * override this function and return true for any Drawable it is
8471 * displaying. This allows animations for those drawables to be
8472 * scheduled.
8473 *
8474 * <p>Be sure to call through to the super class when overriding this
8475 * function.
8476 *
8477 * @param who The Drawable to verify. Return true if it is one you are
8478 * displaying, else return the result of calling through to the
8479 * super class.
8480 *
8481 * @return boolean If true than the Drawable is being displayed in the
8482 * view; else false and it is not allowed to animate.
8483 *
8484 * @see #unscheduleDrawable
8485 * @see #drawableStateChanged
8486 */
8487 protected boolean verifyDrawable(Drawable who) {
8488 return who == mBGDrawable;
8489 }
8490
8491 /**
8492 * This function is called whenever the state of the view changes in such
8493 * a way that it impacts the state of drawables being shown.
8494 *
8495 * <p>Be sure to call through to the superclass when overriding this
8496 * function.
8497 *
8498 * @see Drawable#setState
8499 */
8500 protected void drawableStateChanged() {
8501 Drawable d = mBGDrawable;
8502 if (d != null && d.isStateful()) {
8503 d.setState(getDrawableState());
8504 }
8505 }
8506
8507 /**
8508 * Call this to force a view to update its drawable state. This will cause
8509 * drawableStateChanged to be called on this view. Views that are interested
8510 * in the new state should call getDrawableState.
8511 *
8512 * @see #drawableStateChanged
8513 * @see #getDrawableState
8514 */
8515 public void refreshDrawableState() {
8516 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
8517 drawableStateChanged();
8518
8519 ViewParent parent = mParent;
8520 if (parent != null) {
8521 parent.childDrawableStateChanged(this);
8522 }
8523 }
8524
8525 /**
8526 * Return an array of resource IDs of the drawable states representing the
8527 * current state of the view.
8528 *
8529 * @return The current drawable state
8530 *
8531 * @see Drawable#setState
8532 * @see #drawableStateChanged
8533 * @see #onCreateDrawableState
8534 */
8535 public final int[] getDrawableState() {
8536 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
8537 return mDrawableState;
8538 } else {
8539 mDrawableState = onCreateDrawableState(0);
8540 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
8541 return mDrawableState;
8542 }
8543 }
8544
8545 /**
8546 * Generate the new {@link android.graphics.drawable.Drawable} state for
8547 * this view. This is called by the view
8548 * system when the cached Drawable state is determined to be invalid. To
8549 * retrieve the current state, you should use {@link #getDrawableState}.
8550 *
8551 * @param extraSpace if non-zero, this is the number of extra entries you
8552 * would like in the returned array in which you can place your own
8553 * states.
8554 *
8555 * @return Returns an array holding the current {@link Drawable} state of
8556 * the view.
8557 *
8558 * @see #mergeDrawableStates
8559 */
8560 protected int[] onCreateDrawableState(int extraSpace) {
8561 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
8562 mParent instanceof View) {
8563 return ((View) mParent).onCreateDrawableState(extraSpace);
8564 }
8565
8566 int[] drawableState;
8567
8568 int privateFlags = mPrivateFlags;
8569
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008570 int viewStateIndex = 0;
8571 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
8572 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
8573 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07008574 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008575 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
8576 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08008577 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
8578 // This is set if HW acceleration is requested, even if the current
8579 // process doesn't allow it. This is just to allow app preview
8580 // windows to better match their app.
8581 viewStateIndex |= VIEW_STATE_ACCELERATED;
8582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008583
8584 drawableState = VIEW_STATE_SETS[viewStateIndex];
8585
8586 //noinspection ConstantIfStatement
8587 if (false) {
8588 Log.i("View", "drawableStateIndex=" + viewStateIndex);
8589 Log.i("View", toString()
8590 + " pressed=" + ((privateFlags & PRESSED) != 0)
8591 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
8592 + " fo=" + hasFocus()
8593 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008594 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595 + ": " + Arrays.toString(drawableState));
8596 }
8597
8598 if (extraSpace == 0) {
8599 return drawableState;
8600 }
8601
8602 final int[] fullState;
8603 if (drawableState != null) {
8604 fullState = new int[drawableState.length + extraSpace];
8605 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
8606 } else {
8607 fullState = new int[extraSpace];
8608 }
8609
8610 return fullState;
8611 }
8612
8613 /**
8614 * Merge your own state values in <var>additionalState</var> into the base
8615 * state values <var>baseState</var> that were returned by
8616 * {@link #onCreateDrawableState}.
8617 *
8618 * @param baseState The base state values returned by
8619 * {@link #onCreateDrawableState}, which will be modified to also hold your
8620 * own additional state values.
8621 *
8622 * @param additionalState The additional state values you would like
8623 * added to <var>baseState</var>; this array is not modified.
8624 *
8625 * @return As a convenience, the <var>baseState</var> array you originally
8626 * passed into the function is returned.
8627 *
8628 * @see #onCreateDrawableState
8629 */
8630 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
8631 final int N = baseState.length;
8632 int i = N - 1;
8633 while (i >= 0 && baseState[i] == 0) {
8634 i--;
8635 }
8636 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
8637 return baseState;
8638 }
8639
8640 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07008641 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
8642 * on all Drawable objects associated with this view.
8643 */
8644 public void jumpDrawablesToCurrentState() {
8645 if (mBGDrawable != null) {
8646 mBGDrawable.jumpToCurrentState();
8647 }
8648 }
8649
8650 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651 * Sets the background color for this view.
8652 * @param color the color of the background
8653 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008654 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008655 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07008656 if (mBGDrawable instanceof ColorDrawable) {
8657 ((ColorDrawable) mBGDrawable).setColor(color);
8658 } else {
8659 setBackgroundDrawable(new ColorDrawable(color));
8660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 }
8662
8663 /**
8664 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07008665 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008666 * @param resid The identifier of the resource.
8667 * @attr ref android.R.styleable#View_background
8668 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008669 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008670 public void setBackgroundResource(int resid) {
8671 if (resid != 0 && resid == mBackgroundResource) {
8672 return;
8673 }
8674
8675 Drawable d= null;
8676 if (resid != 0) {
8677 d = mResources.getDrawable(resid);
8678 }
8679 setBackgroundDrawable(d);
8680
8681 mBackgroundResource = resid;
8682 }
8683
8684 /**
8685 * Set the background to a given Drawable, or remove the background. If the
8686 * background has padding, this View's padding is set to the background's
8687 * padding. However, when a background is removed, this View's padding isn't
8688 * touched. If setting the padding is desired, please use
8689 * {@link #setPadding(int, int, int, int)}.
8690 *
8691 * @param d The Drawable to use as the background, or null to remove the
8692 * background
8693 */
8694 public void setBackgroundDrawable(Drawable d) {
8695 boolean requestLayout = false;
8696
8697 mBackgroundResource = 0;
8698
8699 /*
8700 * Regardless of whether we're setting a new background or not, we want
8701 * to clear the previous drawable.
8702 */
8703 if (mBGDrawable != null) {
8704 mBGDrawable.setCallback(null);
8705 unscheduleDrawable(mBGDrawable);
8706 }
8707
8708 if (d != null) {
8709 Rect padding = sThreadLocal.get();
8710 if (padding == null) {
8711 padding = new Rect();
8712 sThreadLocal.set(padding);
8713 }
8714 if (d.getPadding(padding)) {
8715 setPadding(padding.left, padding.top, padding.right, padding.bottom);
8716 }
8717
8718 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
8719 // if it has a different minimum size, we should layout again
8720 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
8721 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
8722 requestLayout = true;
8723 }
8724
8725 d.setCallback(this);
8726 if (d.isStateful()) {
8727 d.setState(getDrawableState());
8728 }
8729 d.setVisible(getVisibility() == VISIBLE, false);
8730 mBGDrawable = d;
8731
8732 if ((mPrivateFlags & SKIP_DRAW) != 0) {
8733 mPrivateFlags &= ~SKIP_DRAW;
8734 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8735 requestLayout = true;
8736 }
8737 } else {
8738 /* Remove the background */
8739 mBGDrawable = null;
8740
8741 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
8742 /*
8743 * This view ONLY drew the background before and we're removing
8744 * the background, so now it won't draw anything
8745 * (hence we SKIP_DRAW)
8746 */
8747 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
8748 mPrivateFlags |= SKIP_DRAW;
8749 }
8750
8751 /*
8752 * When the background is set, we try to apply its padding to this
8753 * View. When the background is removed, we don't touch this View's
8754 * padding. This is noted in the Javadocs. Hence, we don't need to
8755 * requestLayout(), the invalidate() below is sufficient.
8756 */
8757
8758 // The old background's minimum size could have affected this
8759 // View's layout, so let's requestLayout
8760 requestLayout = true;
8761 }
8762
Romain Guy8f1344f52009-05-15 16:03:59 -07008763 computeOpaqueFlags();
8764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008765 if (requestLayout) {
8766 requestLayout();
8767 }
8768
8769 mBackgroundSizeChanged = true;
8770 invalidate();
8771 }
8772
8773 /**
8774 * Gets the background drawable
8775 * @return The drawable used as the background for this view, if any.
8776 */
8777 public Drawable getBackground() {
8778 return mBGDrawable;
8779 }
8780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008781 /**
8782 * Sets the padding. The view may add on the space required to display
8783 * the scrollbars, depending on the style and visibility of the scrollbars.
8784 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
8785 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
8786 * from the values set in this call.
8787 *
8788 * @attr ref android.R.styleable#View_padding
8789 * @attr ref android.R.styleable#View_paddingBottom
8790 * @attr ref android.R.styleable#View_paddingLeft
8791 * @attr ref android.R.styleable#View_paddingRight
8792 * @attr ref android.R.styleable#View_paddingTop
8793 * @param left the left padding in pixels
8794 * @param top the top padding in pixels
8795 * @param right the right padding in pixels
8796 * @param bottom the bottom padding in pixels
8797 */
8798 public void setPadding(int left, int top, int right, int bottom) {
8799 boolean changed = false;
8800
8801 mUserPaddingRight = right;
8802 mUserPaddingBottom = bottom;
8803
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008804 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07008805
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008806 // Common case is there are no scroll bars.
8807 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
8808 // TODO: Deal with RTL languages to adjust left padding instead of right.
8809 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
8810 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8811 ? 0 : getVerticalScrollbarWidth();
8812 }
8813 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
8814 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8815 ? 0 : getHorizontalScrollbarHeight();
8816 }
8817 }
Romain Guy8506ab42009-06-11 17:35:47 -07008818
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008819 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008820 changed = true;
8821 mPaddingLeft = left;
8822 }
8823 if (mPaddingTop != top) {
8824 changed = true;
8825 mPaddingTop = top;
8826 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008827 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008828 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008829 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008830 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008831 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008833 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008834 }
8835
8836 if (changed) {
8837 requestLayout();
8838 }
8839 }
8840
8841 /**
8842 * Returns the top padding of this view.
8843 *
8844 * @return the top padding in pixels
8845 */
8846 public int getPaddingTop() {
8847 return mPaddingTop;
8848 }
8849
8850 /**
8851 * Returns the bottom padding of this view. If there are inset and enabled
8852 * scrollbars, this value may include the space required to display the
8853 * scrollbars as well.
8854 *
8855 * @return the bottom padding in pixels
8856 */
8857 public int getPaddingBottom() {
8858 return mPaddingBottom;
8859 }
8860
8861 /**
8862 * Returns the left padding of this view. If there are inset and enabled
8863 * scrollbars, this value may include the space required to display the
8864 * scrollbars as well.
8865 *
8866 * @return the left padding in pixels
8867 */
8868 public int getPaddingLeft() {
8869 return mPaddingLeft;
8870 }
8871
8872 /**
8873 * Returns the right padding of this view. If there are inset and enabled
8874 * scrollbars, this value may include the space required to display the
8875 * scrollbars as well.
8876 *
8877 * @return the right padding in pixels
8878 */
8879 public int getPaddingRight() {
8880 return mPaddingRight;
8881 }
8882
8883 /**
8884 * Changes the selection state of this view. A view can be selected or not.
8885 * Note that selection is not the same as focus. Views are typically
8886 * selected in the context of an AdapterView like ListView or GridView;
8887 * the selected view is the view that is highlighted.
8888 *
8889 * @param selected true if the view must be selected, false otherwise
8890 */
8891 public void setSelected(boolean selected) {
8892 if (((mPrivateFlags & SELECTED) != 0) != selected) {
8893 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07008894 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008895 invalidate();
8896 refreshDrawableState();
8897 dispatchSetSelected(selected);
8898 }
8899 }
8900
8901 /**
8902 * Dispatch setSelected to all of this View's children.
8903 *
8904 * @see #setSelected(boolean)
8905 *
8906 * @param selected The new selected state
8907 */
8908 protected void dispatchSetSelected(boolean selected) {
8909 }
8910
8911 /**
8912 * Indicates the selection state of this view.
8913 *
8914 * @return true if the view is selected, false otherwise
8915 */
8916 @ViewDebug.ExportedProperty
8917 public boolean isSelected() {
8918 return (mPrivateFlags & SELECTED) != 0;
8919 }
8920
8921 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008922 * Changes the activated state of this view. A view can be activated or not.
8923 * Note that activation is not the same as selection. Selection is
8924 * a transient property, representing the view (hierarchy) the user is
8925 * currently interacting with. Activation is a longer-term state that the
8926 * user can move views in and out of. For example, in a list view with
8927 * single or multiple selection enabled, the views in the current selection
8928 * set are activated. (Um, yeah, we are deeply sorry about the terminology
8929 * here.) The activated state is propagated down to children of the view it
8930 * is set on.
8931 *
8932 * @param activated true if the view must be activated, false otherwise
8933 */
8934 public void setActivated(boolean activated) {
8935 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
8936 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
8937 invalidate();
8938 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07008939 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07008940 }
8941 }
8942
8943 /**
8944 * Dispatch setActivated to all of this View's children.
8945 *
8946 * @see #setActivated(boolean)
8947 *
8948 * @param activated The new activated state
8949 */
8950 protected void dispatchSetActivated(boolean activated) {
8951 }
8952
8953 /**
8954 * Indicates the activation state of this view.
8955 *
8956 * @return true if the view is activated, false otherwise
8957 */
8958 @ViewDebug.ExportedProperty
8959 public boolean isActivated() {
8960 return (mPrivateFlags & ACTIVATED) != 0;
8961 }
8962
8963 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
8965 * observer can be used to get notifications when global events, like
8966 * layout, happen.
8967 *
8968 * The returned ViewTreeObserver observer is not guaranteed to remain
8969 * valid for the lifetime of this View. If the caller of this method keeps
8970 * a long-lived reference to ViewTreeObserver, it should always check for
8971 * the return value of {@link ViewTreeObserver#isAlive()}.
8972 *
8973 * @return The ViewTreeObserver for this view's hierarchy.
8974 */
8975 public ViewTreeObserver getViewTreeObserver() {
8976 if (mAttachInfo != null) {
8977 return mAttachInfo.mTreeObserver;
8978 }
8979 if (mFloatingTreeObserver == null) {
8980 mFloatingTreeObserver = new ViewTreeObserver();
8981 }
8982 return mFloatingTreeObserver;
8983 }
8984
8985 /**
8986 * <p>Finds the topmost view in the current view hierarchy.</p>
8987 *
8988 * @return the topmost view containing this view
8989 */
8990 public View getRootView() {
8991 if (mAttachInfo != null) {
8992 final View v = mAttachInfo.mRootView;
8993 if (v != null) {
8994 return v;
8995 }
8996 }
Romain Guy8506ab42009-06-11 17:35:47 -07008997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998 View parent = this;
8999
9000 while (parent.mParent != null && parent.mParent instanceof View) {
9001 parent = (View) parent.mParent;
9002 }
9003
9004 return parent;
9005 }
9006
9007 /**
9008 * <p>Computes the coordinates of this view on the screen. The argument
9009 * must be an array of two integers. After the method returns, the array
9010 * contains the x and y location in that order.</p>
9011 *
9012 * @param location an array of two integers in which to hold the coordinates
9013 */
9014 public void getLocationOnScreen(int[] location) {
9015 getLocationInWindow(location);
9016
9017 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009018 if (info != null) {
9019 location[0] += info.mWindowLeft;
9020 location[1] += info.mWindowTop;
9021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009022 }
9023
9024 /**
9025 * <p>Computes the coordinates of this view in its window. The argument
9026 * must be an array of two integers. After the method returns, the array
9027 * contains the x and y location in that order.</p>
9028 *
9029 * @param location an array of two integers in which to hold the coordinates
9030 */
9031 public void getLocationInWindow(int[] location) {
9032 if (location == null || location.length < 2) {
9033 throw new IllegalArgumentException("location must be an array of "
9034 + "two integers");
9035 }
9036
9037 location[0] = mLeft;
9038 location[1] = mTop;
9039
9040 ViewParent viewParent = mParent;
9041 while (viewParent instanceof View) {
9042 final View view = (View)viewParent;
9043 location[0] += view.mLeft - view.mScrollX;
9044 location[1] += view.mTop - view.mScrollY;
9045 viewParent = view.mParent;
9046 }
Romain Guy8506ab42009-06-11 17:35:47 -07009047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009048 if (viewParent instanceof ViewRoot) {
9049 // *cough*
9050 final ViewRoot vr = (ViewRoot)viewParent;
9051 location[1] -= vr.mCurScrollY;
9052 }
9053 }
9054
9055 /**
9056 * {@hide}
9057 * @param id the id of the view to be found
9058 * @return the view of the specified id, null if cannot be found
9059 */
9060 protected View findViewTraversal(int id) {
9061 if (id == mID) {
9062 return this;
9063 }
9064 return null;
9065 }
9066
9067 /**
9068 * {@hide}
9069 * @param tag the tag of the view to be found
9070 * @return the view of specified tag, null if cannot be found
9071 */
9072 protected View findViewWithTagTraversal(Object tag) {
9073 if (tag != null && tag.equals(mTag)) {
9074 return this;
9075 }
9076 return null;
9077 }
9078
9079 /**
9080 * Look for a child view with the given id. If this view has the given
9081 * id, return this view.
9082 *
9083 * @param id The id to search for.
9084 * @return The view that has the given id in the hierarchy or null
9085 */
9086 public final View findViewById(int id) {
9087 if (id < 0) {
9088 return null;
9089 }
9090 return findViewTraversal(id);
9091 }
9092
9093 /**
9094 * Look for a child view with the given tag. If this view has the given
9095 * tag, return this view.
9096 *
9097 * @param tag The tag to search for, using "tag.equals(getTag())".
9098 * @return The View that has the given tag in the hierarchy or null
9099 */
9100 public final View findViewWithTag(Object tag) {
9101 if (tag == null) {
9102 return null;
9103 }
9104 return findViewWithTagTraversal(tag);
9105 }
9106
9107 /**
9108 * Sets the identifier for this view. The identifier does not have to be
9109 * unique in this view's hierarchy. The identifier should be a positive
9110 * number.
9111 *
9112 * @see #NO_ID
9113 * @see #getId
9114 * @see #findViewById
9115 *
9116 * @param id a number used to identify the view
9117 *
9118 * @attr ref android.R.styleable#View_id
9119 */
9120 public void setId(int id) {
9121 mID = id;
9122 }
9123
9124 /**
9125 * {@hide}
9126 *
9127 * @param isRoot true if the view belongs to the root namespace, false
9128 * otherwise
9129 */
9130 public void setIsRootNamespace(boolean isRoot) {
9131 if (isRoot) {
9132 mPrivateFlags |= IS_ROOT_NAMESPACE;
9133 } else {
9134 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9135 }
9136 }
9137
9138 /**
9139 * {@hide}
9140 *
9141 * @return true if the view belongs to the root namespace, false otherwise
9142 */
9143 public boolean isRootNamespace() {
9144 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9145 }
9146
9147 /**
9148 * Returns this view's identifier.
9149 *
9150 * @return a positive integer used to identify the view or {@link #NO_ID}
9151 * if the view has no ID
9152 *
9153 * @see #setId
9154 * @see #findViewById
9155 * @attr ref android.R.styleable#View_id
9156 */
9157 @ViewDebug.CapturedViewProperty
9158 public int getId() {
9159 return mID;
9160 }
9161
9162 /**
9163 * Returns this view's tag.
9164 *
9165 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07009166 *
9167 * @see #setTag(Object)
9168 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169 */
9170 @ViewDebug.ExportedProperty
9171 public Object getTag() {
9172 return mTag;
9173 }
9174
9175 /**
9176 * Sets the tag associated with this view. A tag can be used to mark
9177 * a view in its hierarchy and does not have to be unique within the
9178 * hierarchy. Tags can also be used to store data within a view without
9179 * resorting to another data structure.
9180 *
9181 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07009182 *
9183 * @see #getTag()
9184 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009185 */
9186 public void setTag(final Object tag) {
9187 mTag = tag;
9188 }
9189
9190 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009191 * Returns the tag associated with this view and the specified key.
9192 *
9193 * @param key The key identifying the tag
9194 *
9195 * @return the Object stored in this view as a tag
9196 *
9197 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009198 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009199 */
9200 public Object getTag(int key) {
9201 SparseArray<Object> tags = null;
9202 synchronized (sTagsLock) {
9203 if (sTags != null) {
9204 tags = sTags.get(this);
9205 }
9206 }
9207
9208 if (tags != null) return tags.get(key);
9209 return null;
9210 }
9211
9212 /**
9213 * Sets a tag associated with this view and a key. A tag can be used
9214 * to mark a view in its hierarchy and does not have to be unique within
9215 * the hierarchy. Tags can also be used to store data within a view
9216 * without resorting to another data structure.
9217 *
9218 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009219 * application to ensure it is unique (see the <a
9220 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9221 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009222 * the Android framework or not associated with any package will cause
9223 * an {@link IllegalArgumentException} to be thrown.
9224 *
9225 * @param key The key identifying the tag
9226 * @param tag An Object to tag the view with
9227 *
9228 * @throws IllegalArgumentException If they specified key is not valid
9229 *
9230 * @see #setTag(Object)
9231 * @see #getTag(int)
9232 */
9233 public void setTag(int key, final Object tag) {
9234 // If the package id is 0x00 or 0x01, it's either an undefined package
9235 // or a framework id
9236 if ((key >>> 24) < 2) {
9237 throw new IllegalArgumentException("The key must be an application-specific "
9238 + "resource id.");
9239 }
9240
9241 setTagInternal(this, key, tag);
9242 }
9243
9244 /**
9245 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9246 * framework id.
9247 *
9248 * @hide
9249 */
9250 public void setTagInternal(int key, Object tag) {
9251 if ((key >>> 24) != 0x1) {
9252 throw new IllegalArgumentException("The key must be a framework-specific "
9253 + "resource id.");
9254 }
9255
Romain Guy8506ab42009-06-11 17:35:47 -07009256 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009257 }
9258
9259 private static void setTagInternal(View view, int key, Object tag) {
9260 SparseArray<Object> tags = null;
9261 synchronized (sTagsLock) {
9262 if (sTags == null) {
9263 sTags = new WeakHashMap<View, SparseArray<Object>>();
9264 } else {
9265 tags = sTags.get(view);
9266 }
9267 }
9268
9269 if (tags == null) {
9270 tags = new SparseArray<Object>(2);
9271 synchronized (sTagsLock) {
9272 sTags.put(view, tags);
9273 }
9274 }
9275
9276 tags.put(key, tag);
9277 }
9278
9279 /**
Romain Guy13922e02009-05-12 17:56:14 -07009280 * @param consistency The type of consistency. See ViewDebug for more information.
9281 *
9282 * @hide
9283 */
9284 protected boolean dispatchConsistencyCheck(int consistency) {
9285 return onConsistencyCheck(consistency);
9286 }
9287
9288 /**
9289 * Method that subclasses should implement to check their consistency. The type of
9290 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009291 *
Romain Guy13922e02009-05-12 17:56:14 -07009292 * @param consistency The type of consistency. See ViewDebug for more information.
9293 *
9294 * @throws IllegalStateException if the view is in an inconsistent state.
9295 *
9296 * @hide
9297 */
9298 protected boolean onConsistencyCheck(int consistency) {
9299 boolean result = true;
9300
9301 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9302 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9303
9304 if (checkLayout) {
9305 if (getParent() == null) {
9306 result = false;
9307 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9308 "View " + this + " does not have a parent.");
9309 }
9310
9311 if (mAttachInfo == null) {
9312 result = false;
9313 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9314 "View " + this + " is not attached to a window.");
9315 }
9316 }
9317
9318 if (checkDrawing) {
9319 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9320 // from their draw() method
9321
9322 if ((mPrivateFlags & DRAWN) != DRAWN &&
9323 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9324 result = false;
9325 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9326 "View " + this + " was invalidated but its drawing cache is valid.");
9327 }
9328 }
9329
9330 return result;
9331 }
9332
9333 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009334 * Prints information about this view in the log output, with the tag
9335 * {@link #VIEW_LOG_TAG}.
9336 *
9337 * @hide
9338 */
9339 public void debug() {
9340 debug(0);
9341 }
9342
9343 /**
9344 * Prints information about this view in the log output, with the tag
9345 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
9346 * indentation defined by the <code>depth</code>.
9347 *
9348 * @param depth the indentation level
9349 *
9350 * @hide
9351 */
9352 protected void debug(int depth) {
9353 String output = debugIndent(depth - 1);
9354
9355 output += "+ " + this;
9356 int id = getId();
9357 if (id != -1) {
9358 output += " (id=" + id + ")";
9359 }
9360 Object tag = getTag();
9361 if (tag != null) {
9362 output += " (tag=" + tag + ")";
9363 }
9364 Log.d(VIEW_LOG_TAG, output);
9365
9366 if ((mPrivateFlags & FOCUSED) != 0) {
9367 output = debugIndent(depth) + " FOCUSED";
9368 Log.d(VIEW_LOG_TAG, output);
9369 }
9370
9371 output = debugIndent(depth);
9372 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
9373 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
9374 + "} ";
9375 Log.d(VIEW_LOG_TAG, output);
9376
9377 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
9378 || mPaddingBottom != 0) {
9379 output = debugIndent(depth);
9380 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
9381 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
9382 Log.d(VIEW_LOG_TAG, output);
9383 }
9384
9385 output = debugIndent(depth);
9386 output += "mMeasureWidth=" + mMeasuredWidth +
9387 " mMeasureHeight=" + mMeasuredHeight;
9388 Log.d(VIEW_LOG_TAG, output);
9389
9390 output = debugIndent(depth);
9391 if (mLayoutParams == null) {
9392 output += "BAD! no layout params";
9393 } else {
9394 output = mLayoutParams.debug(output);
9395 }
9396 Log.d(VIEW_LOG_TAG, output);
9397
9398 output = debugIndent(depth);
9399 output += "flags={";
9400 output += View.printFlags(mViewFlags);
9401 output += "}";
9402 Log.d(VIEW_LOG_TAG, output);
9403
9404 output = debugIndent(depth);
9405 output += "privateFlags={";
9406 output += View.printPrivateFlags(mPrivateFlags);
9407 output += "}";
9408 Log.d(VIEW_LOG_TAG, output);
9409 }
9410
9411 /**
9412 * Creates an string of whitespaces used for indentation.
9413 *
9414 * @param depth the indentation level
9415 * @return a String containing (depth * 2 + 3) * 2 white spaces
9416 *
9417 * @hide
9418 */
9419 protected static String debugIndent(int depth) {
9420 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
9421 for (int i = 0; i < (depth * 2) + 3; i++) {
9422 spaces.append(' ').append(' ');
9423 }
9424 return spaces.toString();
9425 }
9426
9427 /**
9428 * <p>Return the offset of the widget's text baseline from the widget's top
9429 * boundary. If this widget does not support baseline alignment, this
9430 * method returns -1. </p>
9431 *
9432 * @return the offset of the baseline within the widget's bounds or -1
9433 * if baseline alignment is not supported
9434 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07009435 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436 public int getBaseline() {
9437 return -1;
9438 }
9439
9440 /**
9441 * Call this when something has changed which has invalidated the
9442 * layout of this view. This will schedule a layout pass of the view
9443 * tree.
9444 */
9445 public void requestLayout() {
9446 if (ViewDebug.TRACE_HIERARCHY) {
9447 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
9448 }
9449
9450 mPrivateFlags |= FORCE_LAYOUT;
9451
9452 if (mParent != null && !mParent.isLayoutRequested()) {
9453 mParent.requestLayout();
9454 }
9455 }
9456
9457 /**
9458 * Forces this view to be laid out during the next layout pass.
9459 * This method does not call requestLayout() or forceLayout()
9460 * on the parent.
9461 */
9462 public void forceLayout() {
9463 mPrivateFlags |= FORCE_LAYOUT;
9464 }
9465
9466 /**
9467 * <p>
9468 * This is called to find out how big a view should be. The parent
9469 * supplies constraint information in the width and height parameters.
9470 * </p>
9471 *
9472 * <p>
9473 * The actual mesurement work of a view is performed in
9474 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
9475 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
9476 * </p>
9477 *
9478 *
9479 * @param widthMeasureSpec Horizontal space requirements as imposed by the
9480 * parent
9481 * @param heightMeasureSpec Vertical space requirements as imposed by the
9482 * parent
9483 *
9484 * @see #onMeasure(int, int)
9485 */
9486 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
9487 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
9488 widthMeasureSpec != mOldWidthMeasureSpec ||
9489 heightMeasureSpec != mOldHeightMeasureSpec) {
9490
9491 // first clears the measured dimension flag
9492 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9493
9494 if (ViewDebug.TRACE_HIERARCHY) {
9495 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
9496 }
9497
9498 // measure ourselves, this should set the measured dimension flag back
9499 onMeasure(widthMeasureSpec, heightMeasureSpec);
9500
9501 // flag not set, setMeasuredDimension() was not invoked, we raise
9502 // an exception to warn the developer
9503 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9504 throw new IllegalStateException("onMeasure() did not set the"
9505 + " measured dimension by calling"
9506 + " setMeasuredDimension()");
9507 }
9508
9509 mPrivateFlags |= LAYOUT_REQUIRED;
9510 }
9511
9512 mOldWidthMeasureSpec = widthMeasureSpec;
9513 mOldHeightMeasureSpec = heightMeasureSpec;
9514 }
9515
9516 /**
9517 * <p>
9518 * Measure the view and its content to determine the measured width and the
9519 * measured height. This method is invoked by {@link #measure(int, int)} and
9520 * should be overriden by subclasses to provide accurate and efficient
9521 * measurement of their contents.
9522 * </p>
9523 *
9524 * <p>
9525 * <strong>CONTRACT:</strong> When overriding this method, you
9526 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
9527 * measured width and height of this view. Failure to do so will trigger an
9528 * <code>IllegalStateException</code>, thrown by
9529 * {@link #measure(int, int)}. Calling the superclass'
9530 * {@link #onMeasure(int, int)} is a valid use.
9531 * </p>
9532 *
9533 * <p>
9534 * The base class implementation of measure defaults to the background size,
9535 * unless a larger size is allowed by the MeasureSpec. Subclasses should
9536 * override {@link #onMeasure(int, int)} to provide better measurements of
9537 * their content.
9538 * </p>
9539 *
9540 * <p>
9541 * If this method is overridden, it is the subclass's responsibility to make
9542 * sure the measured height and width are at least the view's minimum height
9543 * and width ({@link #getSuggestedMinimumHeight()} and
9544 * {@link #getSuggestedMinimumWidth()}).
9545 * </p>
9546 *
9547 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
9548 * The requirements are encoded with
9549 * {@link android.view.View.MeasureSpec}.
9550 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
9551 * The requirements are encoded with
9552 * {@link android.view.View.MeasureSpec}.
9553 *
9554 * @see #getMeasuredWidth()
9555 * @see #getMeasuredHeight()
9556 * @see #setMeasuredDimension(int, int)
9557 * @see #getSuggestedMinimumHeight()
9558 * @see #getSuggestedMinimumWidth()
9559 * @see android.view.View.MeasureSpec#getMode(int)
9560 * @see android.view.View.MeasureSpec#getSize(int)
9561 */
9562 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9563 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
9564 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
9565 }
9566
9567 /**
9568 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
9569 * measured width and measured height. Failing to do so will trigger an
9570 * exception at measurement time.</p>
9571 *
9572 * @param measuredWidth the measured width of this view
9573 * @param measuredHeight the measured height of this view
9574 */
9575 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
9576 mMeasuredWidth = measuredWidth;
9577 mMeasuredHeight = measuredHeight;
9578
9579 mPrivateFlags |= MEASURED_DIMENSION_SET;
9580 }
9581
9582 /**
9583 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
9584 * Will take the desired size, unless a different size is imposed by the constraints.
9585 *
9586 * @param size How big the view wants to be
9587 * @param measureSpec Constraints imposed by the parent
9588 * @return The size this view should be.
9589 */
9590 public static int resolveSize(int size, int measureSpec) {
9591 int result = size;
9592 int specMode = MeasureSpec.getMode(measureSpec);
9593 int specSize = MeasureSpec.getSize(measureSpec);
9594 switch (specMode) {
9595 case MeasureSpec.UNSPECIFIED:
9596 result = size;
9597 break;
9598 case MeasureSpec.AT_MOST:
9599 result = Math.min(size, specSize);
9600 break;
9601 case MeasureSpec.EXACTLY:
9602 result = specSize;
9603 break;
9604 }
9605 return result;
9606 }
9607
9608 /**
9609 * Utility to return a default size. Uses the supplied size if the
9610 * MeasureSpec imposed no contraints. Will get larger if allowed
9611 * by the MeasureSpec.
9612 *
9613 * @param size Default size for this view
9614 * @param measureSpec Constraints imposed by the parent
9615 * @return The size this view should be.
9616 */
9617 public static int getDefaultSize(int size, int measureSpec) {
9618 int result = size;
9619 int specMode = MeasureSpec.getMode(measureSpec);
9620 int specSize = MeasureSpec.getSize(measureSpec);
9621
9622 switch (specMode) {
9623 case MeasureSpec.UNSPECIFIED:
9624 result = size;
9625 break;
9626 case MeasureSpec.AT_MOST:
9627 case MeasureSpec.EXACTLY:
9628 result = specSize;
9629 break;
9630 }
9631 return result;
9632 }
9633
9634 /**
9635 * Returns the suggested minimum height that the view should use. This
9636 * returns the maximum of the view's minimum height
9637 * and the background's minimum height
9638 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
9639 * <p>
9640 * When being used in {@link #onMeasure(int, int)}, the caller should still
9641 * ensure the returned height is within the requirements of the parent.
9642 *
9643 * @return The suggested minimum height of the view.
9644 */
9645 protected int getSuggestedMinimumHeight() {
9646 int suggestedMinHeight = mMinHeight;
9647
9648 if (mBGDrawable != null) {
9649 final int bgMinHeight = mBGDrawable.getMinimumHeight();
9650 if (suggestedMinHeight < bgMinHeight) {
9651 suggestedMinHeight = bgMinHeight;
9652 }
9653 }
9654
9655 return suggestedMinHeight;
9656 }
9657
9658 /**
9659 * Returns the suggested minimum width that the view should use. This
9660 * returns the maximum of the view's minimum width)
9661 * and the background's minimum width
9662 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
9663 * <p>
9664 * When being used in {@link #onMeasure(int, int)}, the caller should still
9665 * ensure the returned width is within the requirements of the parent.
9666 *
9667 * @return The suggested minimum width of the view.
9668 */
9669 protected int getSuggestedMinimumWidth() {
9670 int suggestedMinWidth = mMinWidth;
9671
9672 if (mBGDrawable != null) {
9673 final int bgMinWidth = mBGDrawable.getMinimumWidth();
9674 if (suggestedMinWidth < bgMinWidth) {
9675 suggestedMinWidth = bgMinWidth;
9676 }
9677 }
9678
9679 return suggestedMinWidth;
9680 }
9681
9682 /**
9683 * Sets the minimum height of the view. It is not guaranteed the view will
9684 * be able to achieve this minimum height (for example, if its parent layout
9685 * constrains it with less available height).
9686 *
9687 * @param minHeight The minimum height the view will try to be.
9688 */
9689 public void setMinimumHeight(int minHeight) {
9690 mMinHeight = minHeight;
9691 }
9692
9693 /**
9694 * Sets the minimum width of the view. It is not guaranteed the view will
9695 * be able to achieve this minimum width (for example, if its parent layout
9696 * constrains it with less available width).
9697 *
9698 * @param minWidth The minimum width the view will try to be.
9699 */
9700 public void setMinimumWidth(int minWidth) {
9701 mMinWidth = minWidth;
9702 }
9703
9704 /**
9705 * Get the animation currently associated with this view.
9706 *
9707 * @return The animation that is currently playing or
9708 * scheduled to play for this view.
9709 */
9710 public Animation getAnimation() {
9711 return mCurrentAnimation;
9712 }
9713
9714 /**
9715 * Start the specified animation now.
9716 *
9717 * @param animation the animation to start now
9718 */
9719 public void startAnimation(Animation animation) {
9720 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
9721 setAnimation(animation);
9722 invalidate();
9723 }
9724
9725 /**
9726 * Cancels any animations for this view.
9727 */
9728 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08009729 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08009730 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08009731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009732 mCurrentAnimation = null;
9733 }
9734
9735 /**
9736 * Sets the next animation to play for this view.
9737 * If you want the animation to play immediately, use
9738 * startAnimation. This method provides allows fine-grained
9739 * control over the start time and invalidation, but you
9740 * must make sure that 1) the animation has a start time set, and
9741 * 2) the view will be invalidated when the animation is supposed to
9742 * start.
9743 *
9744 * @param animation The next animation, or null.
9745 */
9746 public void setAnimation(Animation animation) {
9747 mCurrentAnimation = animation;
9748 if (animation != null) {
9749 animation.reset();
9750 }
9751 }
9752
9753 /**
9754 * Invoked by a parent ViewGroup to notify the start of the animation
9755 * currently associated with this view. If you override this method,
9756 * always call super.onAnimationStart();
9757 *
9758 * @see #setAnimation(android.view.animation.Animation)
9759 * @see #getAnimation()
9760 */
9761 protected void onAnimationStart() {
9762 mPrivateFlags |= ANIMATION_STARTED;
9763 }
9764
9765 /**
9766 * Invoked by a parent ViewGroup to notify the end of the animation
9767 * currently associated with this view. If you override this method,
9768 * always call super.onAnimationEnd();
9769 *
9770 * @see #setAnimation(android.view.animation.Animation)
9771 * @see #getAnimation()
9772 */
9773 protected void onAnimationEnd() {
9774 mPrivateFlags &= ~ANIMATION_STARTED;
9775 }
9776
9777 /**
9778 * Invoked if there is a Transform that involves alpha. Subclass that can
9779 * draw themselves with the specified alpha should return true, and then
9780 * respect that alpha when their onDraw() is called. If this returns false
9781 * then the view may be redirected to draw into an offscreen buffer to
9782 * fulfill the request, which will look fine, but may be slower than if the
9783 * subclass handles it internally. The default implementation returns false.
9784 *
9785 * @param alpha The alpha (0..255) to apply to the view's drawing
9786 * @return true if the view can draw with the specified alpha.
9787 */
9788 protected boolean onSetAlpha(int alpha) {
9789 return false;
9790 }
9791
9792 /**
9793 * This is used by the RootView to perform an optimization when
9794 * the view hierarchy contains one or several SurfaceView.
9795 * SurfaceView is always considered transparent, but its children are not,
9796 * therefore all View objects remove themselves from the global transparent
9797 * region (passed as a parameter to this function).
9798 *
9799 * @param region The transparent region for this ViewRoot (window).
9800 *
9801 * @return Returns true if the effective visibility of the view at this
9802 * point is opaque, regardless of the transparent region; returns false
9803 * if it is possible for underlying windows to be seen behind the view.
9804 *
9805 * {@hide}
9806 */
9807 public boolean gatherTransparentRegion(Region region) {
9808 final AttachInfo attachInfo = mAttachInfo;
9809 if (region != null && attachInfo != null) {
9810 final int pflags = mPrivateFlags;
9811 if ((pflags & SKIP_DRAW) == 0) {
9812 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
9813 // remove it from the transparent region.
9814 final int[] location = attachInfo.mTransparentLocation;
9815 getLocationInWindow(location);
9816 region.op(location[0], location[1], location[0] + mRight - mLeft,
9817 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
9818 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
9819 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
9820 // exists, so we remove the background drawable's non-transparent
9821 // parts from this transparent region.
9822 applyDrawableToTransparentRegion(mBGDrawable, region);
9823 }
9824 }
9825 return true;
9826 }
9827
9828 /**
9829 * Play a sound effect for this view.
9830 *
9831 * <p>The framework will play sound effects for some built in actions, such as
9832 * clicking, but you may wish to play these effects in your widget,
9833 * for instance, for internal navigation.
9834 *
9835 * <p>The sound effect will only be played if sound effects are enabled by the user, and
9836 * {@link #isSoundEffectsEnabled()} is true.
9837 *
9838 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
9839 */
9840 public void playSoundEffect(int soundConstant) {
9841 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
9842 return;
9843 }
9844 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
9845 }
9846
9847 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009848 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009849 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009850 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009851 *
9852 * <p>The framework will provide haptic feedback for some built in actions,
9853 * such as long presses, but you may wish to provide feedback for your
9854 * own widget.
9855 *
9856 * <p>The feedback will only be performed if
9857 * {@link #isHapticFeedbackEnabled()} is true.
9858 *
9859 * @param feedbackConstant One of the constants defined in
9860 * {@link HapticFeedbackConstants}
9861 */
9862 public boolean performHapticFeedback(int feedbackConstant) {
9863 return performHapticFeedback(feedbackConstant, 0);
9864 }
9865
9866 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009867 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009868 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009869 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009870 *
9871 * @param feedbackConstant One of the constants defined in
9872 * {@link HapticFeedbackConstants}
9873 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
9874 */
9875 public boolean performHapticFeedback(int feedbackConstant, int flags) {
9876 if (mAttachInfo == null) {
9877 return false;
9878 }
Romain Guyf607bdc2010-09-10 19:20:06 -07009879 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -07009880 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009881 && !isHapticFeedbackEnabled()) {
9882 return false;
9883 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009884 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
9885 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009886 }
9887
9888 /**
Christopher Tate2c095f32010-10-04 14:13:40 -07009889 * !!! TODO: real docs
9890 *
9891 * The base class implementation makes the thumbnail the same size and appearance
9892 * as the view itself, and positions it with its center at the touch point.
9893 */
Christopher Tatea0374192010-10-05 13:06:41 -07009894 public static class DragThumbnailBuilder {
9895 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -07009896
9897 /**
9898 * Construct a thumbnail builder object for use with the given view.
9899 * @param view
9900 */
9901 public DragThumbnailBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -07009902 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -07009903 }
9904
Chris Tate6b391282010-10-14 15:48:59 -07009905 final public View getView() {
9906 return mView.get();
9907 }
9908
Christopher Tate2c095f32010-10-04 14:13:40 -07009909 /**
9910 * Provide the draggable-thumbnail metrics for the operation: the dimensions of
9911 * the thumbnail image itself, and the point within that thumbnail that should
9912 * be centered under the touch location while dragging.
9913 * <p>
9914 * The default implementation sets the dimensions of the thumbnail to be the
9915 * same as the dimensions of the View itself and centers the thumbnail under
9916 * the touch point.
9917 *
9918 * @param thumbnailSize The application should set the {@code x} member of this
9919 * parameter to the desired thumbnail width, and the {@code y} member to
9920 * the desired height.
9921 * @param thumbnailTouchPoint The application should set this point to be the
9922 * location within the thumbnail that should track directly underneath
9923 * the touch point on the screen during a drag.
9924 */
9925 public void onProvideThumbnailMetrics(Point thumbnailSize, Point thumbnailTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -07009926 final View view = mView.get();
9927 if (view != null) {
9928 thumbnailSize.set(view.getWidth(), view.getHeight());
9929 thumbnailTouchPoint.set(thumbnailSize.x / 2, thumbnailSize.y / 2);
9930 } else {
9931 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
9932 }
Christopher Tate2c095f32010-10-04 14:13:40 -07009933 }
9934
9935 /**
9936 * Draw the thumbnail image for the upcoming drag. The thumbnail canvas was
9937 * created with the dimensions supplied by the onProvideThumbnailMetrics()
9938 * callback.
9939 *
9940 * @param canvas
9941 */
9942 public void onDrawThumbnail(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -07009943 final View view = mView.get();
9944 if (view != null) {
9945 view.draw(canvas);
9946 } else {
9947 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag thumb but no view");
9948 }
Christopher Tate2c095f32010-10-04 14:13:40 -07009949 }
9950 }
9951
9952 /**
Christopher Tate5ada6cb2010-10-05 14:15:29 -07009953 * Drag and drop. App calls startDrag(), then callbacks to the thumbnail builder's
9954 * onProvideThumbnailMetrics() and onDrawThumbnail() methods happen, then the drag
9955 * operation is handed over to the OS.
Christopher Tatea53146c2010-09-07 11:57:52 -07009956 * !!! TODO: real docs
Christopher Tatea53146c2010-09-07 11:57:52 -07009957 */
Christopher Tate2c095f32010-10-04 14:13:40 -07009958 public final boolean startDrag(ClipData data, DragThumbnailBuilder thumbBuilder,
9959 boolean myWindowOnly) {
9960 if (ViewDebug.DEBUG_DRAG) {
9961 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " local=" + myWindowOnly);
Christopher Tatea53146c2010-09-07 11:57:52 -07009962 }
9963 boolean okay = false;
9964
Christopher Tate2c095f32010-10-04 14:13:40 -07009965 Point thumbSize = new Point();
9966 Point thumbTouchPoint = new Point();
9967 thumbBuilder.onProvideThumbnailMetrics(thumbSize, thumbTouchPoint);
9968
9969 if ((thumbSize.x < 0) || (thumbSize.y < 0) ||
9970 (thumbTouchPoint.x < 0) || (thumbTouchPoint.y < 0)) {
9971 throw new IllegalStateException("Drag thumb dimensions must not be negative");
9972 }
Christopher Tatea53146c2010-09-07 11:57:52 -07009973
Chris Tatea32dcf72010-10-14 12:13:50 -07009974 if (ViewDebug.DEBUG_DRAG) {
9975 Log.d(VIEW_LOG_TAG, "drag thumb: width=" + thumbSize.x + " height=" + thumbSize.y
9976 + " thumbX=" + thumbTouchPoint.x + " thumbY=" + thumbTouchPoint.y);
9977 }
Christopher Tatea53146c2010-09-07 11:57:52 -07009978 Surface surface = new Surface();
9979 try {
9980 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Chris Tatea32dcf72010-10-14 12:13:50 -07009981 myWindowOnly, thumbSize.x, thumbSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -07009982 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -07009983 + " surface=" + surface);
9984 if (token != null) {
9985 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -07009986 try {
Chris Tate6b391282010-10-14 15:48:59 -07009987 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate2c095f32010-10-04 14:13:40 -07009988 thumbBuilder.onDrawThumbnail(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -07009989 } finally {
9990 surface.unlockCanvasAndPost(canvas);
9991 }
Christopher Tatea53146c2010-09-07 11:57:52 -07009992
Christopher Tate2c095f32010-10-04 14:13:40 -07009993 // repurpose 'thumbSize' for the last touch point
9994 getViewRoot().getLastTouchPoint(thumbSize);
9995
Christopher Tatea53146c2010-09-07 11:57:52 -07009996 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate2c095f32010-10-04 14:13:40 -07009997 (float) thumbSize.x, (float) thumbSize.y,
9998 (float) thumbTouchPoint.x, (float) thumbTouchPoint.y, data);
9999 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070010000 }
10001 } catch (Exception e) {
10002 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
10003 surface.destroy();
10004 }
10005
10006 return okay;
10007 }
10008
Christopher Tatea53146c2010-09-07 11:57:52 -070010009 /**
10010 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
10011 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
10012 *
10013 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
10014 * being dragged. onDragEvent() should return 'true' if the view can handle
10015 * a drop of that content. A view that returns 'false' here will receive no
10016 * further calls to onDragEvent() about the drag/drop operation.
10017 *
10018 * For DRAG_ENTERED, event.getClipDescription() describes the content being
10019 * dragged. This will be the same content description passed in the
10020 * DRAG_STARTED_EVENT invocation.
10021 *
10022 * For DRAG_EXITED, event.getClipDescription() describes the content being
10023 * dragged. This will be the same content description passed in the
10024 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
10025 * drag-acceptance visual state.
10026 *
10027 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10028 * coordinates of the current drag point. The view must return 'true' if it
10029 * can accept a drop of the current drag content, false otherwise.
10030 *
10031 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10032 * within the view; also, event.getClipData() returns the full data payload
10033 * being dropped. The view should return 'true' if it consumed the dropped
10034 * content, 'false' if it did not.
10035 *
10036 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
10037 * to its normal visual state.
10038 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010039 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070010040 return false;
10041 }
10042
10043 /**
10044 * Views typically don't need to override dispatchDragEvent(); it just calls
Chris Tate32affef2010-10-18 15:29:21 -070010045 * onDragEvent(event) and passes the result up appropriately.
Christopher Tatea53146c2010-09-07 11:57:52 -070010046 */
10047 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070010048 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10049 && mOnDragListener.onDrag(this, event)) {
10050 return true;
10051 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010052 return onDragEvent(event);
10053 }
10054
10055 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070010056 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
10057 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070010058 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070010059 */
10060 public void onCloseSystemDialogs(String reason) {
10061 }
10062
10063 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010064 * Given a Drawable whose bounds have been set to draw into this view,
10065 * update a Region being computed for {@link #gatherTransparentRegion} so
10066 * that any non-transparent parts of the Drawable are removed from the
10067 * given transparent region.
10068 *
10069 * @param dr The Drawable whose transparency is to be applied to the region.
10070 * @param region A Region holding the current transparency information,
10071 * where any parts of the region that are set are considered to be
10072 * transparent. On return, this region will be modified to have the
10073 * transparency information reduced by the corresponding parts of the
10074 * Drawable that are not transparent.
10075 * {@hide}
10076 */
10077 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
10078 if (DBG) {
10079 Log.i("View", "Getting transparent region for: " + this);
10080 }
10081 final Region r = dr.getTransparentRegion();
10082 final Rect db = dr.getBounds();
10083 final AttachInfo attachInfo = mAttachInfo;
10084 if (r != null && attachInfo != null) {
10085 final int w = getRight()-getLeft();
10086 final int h = getBottom()-getTop();
10087 if (db.left > 0) {
10088 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
10089 r.op(0, 0, db.left, h, Region.Op.UNION);
10090 }
10091 if (db.right < w) {
10092 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
10093 r.op(db.right, 0, w, h, Region.Op.UNION);
10094 }
10095 if (db.top > 0) {
10096 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
10097 r.op(0, 0, w, db.top, Region.Op.UNION);
10098 }
10099 if (db.bottom < h) {
10100 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
10101 r.op(0, db.bottom, w, h, Region.Op.UNION);
10102 }
10103 final int[] location = attachInfo.mTransparentLocation;
10104 getLocationInWindow(location);
10105 r.translate(location[0], location[1]);
10106 region.op(r, Region.Op.INTERSECT);
10107 } else {
10108 region.op(db, Region.Op.DIFFERENCE);
10109 }
10110 }
10111
Adam Powelle14579b2009-12-16 18:39:52 -080010112 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010113 mHasPerformedLongPress = false;
10114
10115 if (mPendingCheckForLongPress == null) {
10116 mPendingCheckForLongPress = new CheckForLongPress();
10117 }
10118 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080010119 postDelayed(mPendingCheckForLongPress,
10120 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010121 }
10122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010123 /**
10124 * Inflate a view from an XML resource. This convenience method wraps the {@link
10125 * LayoutInflater} class, which provides a full range of options for view inflation.
10126 *
10127 * @param context The Context object for your activity or application.
10128 * @param resource The resource ID to inflate
10129 * @param root A view group that will be the parent. Used to properly inflate the
10130 * layout_* parameters.
10131 * @see LayoutInflater
10132 */
10133 public static View inflate(Context context, int resource, ViewGroup root) {
10134 LayoutInflater factory = LayoutInflater.from(context);
10135 return factory.inflate(resource, root);
10136 }
Romain Guy33e72ae2010-07-17 12:40:29 -070010137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010138 /**
10139 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
10140 * Each MeasureSpec represents a requirement for either the width or the height.
10141 * A MeasureSpec is comprised of a size and a mode. There are three possible
10142 * modes:
10143 * <dl>
10144 * <dt>UNSPECIFIED</dt>
10145 * <dd>
10146 * The parent has not imposed any constraint on the child. It can be whatever size
10147 * it wants.
10148 * </dd>
10149 *
10150 * <dt>EXACTLY</dt>
10151 * <dd>
10152 * The parent has determined an exact size for the child. The child is going to be
10153 * given those bounds regardless of how big it wants to be.
10154 * </dd>
10155 *
10156 * <dt>AT_MOST</dt>
10157 * <dd>
10158 * The child can be as large as it wants up to the specified size.
10159 * </dd>
10160 * </dl>
10161 *
10162 * MeasureSpecs are implemented as ints to reduce object allocation. This class
10163 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
10164 */
10165 public static class MeasureSpec {
10166 private static final int MODE_SHIFT = 30;
10167 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
10168
10169 /**
10170 * Measure specification mode: The parent has not imposed any constraint
10171 * on the child. It can be whatever size it wants.
10172 */
10173 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
10174
10175 /**
10176 * Measure specification mode: The parent has determined an exact size
10177 * for the child. The child is going to be given those bounds regardless
10178 * of how big it wants to be.
10179 */
10180 public static final int EXACTLY = 1 << MODE_SHIFT;
10181
10182 /**
10183 * Measure specification mode: The child can be as large as it wants up
10184 * to the specified size.
10185 */
10186 public static final int AT_MOST = 2 << MODE_SHIFT;
10187
10188 /**
10189 * Creates a measure specification based on the supplied size and mode.
10190 *
10191 * The mode must always be one of the following:
10192 * <ul>
10193 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
10194 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
10195 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
10196 * </ul>
10197 *
10198 * @param size the size of the measure specification
10199 * @param mode the mode of the measure specification
10200 * @return the measure specification based on size and mode
10201 */
10202 public static int makeMeasureSpec(int size, int mode) {
10203 return size + mode;
10204 }
10205
10206 /**
10207 * Extracts the mode from the supplied measure specification.
10208 *
10209 * @param measureSpec the measure specification to extract the mode from
10210 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
10211 * {@link android.view.View.MeasureSpec#AT_MOST} or
10212 * {@link android.view.View.MeasureSpec#EXACTLY}
10213 */
10214 public static int getMode(int measureSpec) {
10215 return (measureSpec & MODE_MASK);
10216 }
10217
10218 /**
10219 * Extracts the size from the supplied measure specification.
10220 *
10221 * @param measureSpec the measure specification to extract the size from
10222 * @return the size in pixels defined in the supplied measure specification
10223 */
10224 public static int getSize(int measureSpec) {
10225 return (measureSpec & ~MODE_MASK);
10226 }
10227
10228 /**
10229 * Returns a String representation of the specified measure
10230 * specification.
10231 *
10232 * @param measureSpec the measure specification to convert to a String
10233 * @return a String with the following format: "MeasureSpec: MODE SIZE"
10234 */
10235 public static String toString(int measureSpec) {
10236 int mode = getMode(measureSpec);
10237 int size = getSize(measureSpec);
10238
10239 StringBuilder sb = new StringBuilder("MeasureSpec: ");
10240
10241 if (mode == UNSPECIFIED)
10242 sb.append("UNSPECIFIED ");
10243 else if (mode == EXACTLY)
10244 sb.append("EXACTLY ");
10245 else if (mode == AT_MOST)
10246 sb.append("AT_MOST ");
10247 else
10248 sb.append(mode).append(" ");
10249
10250 sb.append(size);
10251 return sb.toString();
10252 }
10253 }
10254
10255 class CheckForLongPress implements Runnable {
10256
10257 private int mOriginalWindowAttachCount;
10258
10259 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070010260 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010261 && mOriginalWindowAttachCount == mWindowAttachCount) {
10262 if (performLongClick()) {
10263 mHasPerformedLongPress = true;
10264 }
10265 }
10266 }
10267
10268 public void rememberWindowAttachCount() {
10269 mOriginalWindowAttachCount = mWindowAttachCount;
10270 }
10271 }
Adam Powelle14579b2009-12-16 18:39:52 -080010272
10273 private final class CheckForTap implements Runnable {
10274 public void run() {
10275 mPrivateFlags &= ~PREPRESSED;
10276 mPrivateFlags |= PRESSED;
10277 refreshDrawableState();
10278 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
10279 postCheckForLongClick(ViewConfiguration.getTapTimeout());
10280 }
10281 }
10282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010283
Adam Powella35d7682010-03-12 14:48:13 -080010284 private final class PerformClick implements Runnable {
10285 public void run() {
10286 performClick();
10287 }
10288 }
10289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010290 /**
10291 * Interface definition for a callback to be invoked when a key event is
10292 * dispatched to this view. The callback will be invoked before the key
10293 * event is given to the view.
10294 */
10295 public interface OnKeyListener {
10296 /**
10297 * Called when a key is dispatched to a view. This allows listeners to
10298 * get a chance to respond before the target view.
10299 *
10300 * @param v The view the key has been dispatched to.
10301 * @param keyCode The code for the physical key that was pressed
10302 * @param event The KeyEvent object containing full information about
10303 * the event.
10304 * @return True if the listener has consumed the event, false otherwise.
10305 */
10306 boolean onKey(View v, int keyCode, KeyEvent event);
10307 }
10308
10309 /**
10310 * Interface definition for a callback to be invoked when a touch event is
10311 * dispatched to this view. The callback will be invoked before the touch
10312 * event is given to the view.
10313 */
10314 public interface OnTouchListener {
10315 /**
10316 * Called when a touch event is dispatched to a view. This allows listeners to
10317 * get a chance to respond before the target view.
10318 *
10319 * @param v The view the touch event has been dispatched to.
10320 * @param event The MotionEvent object containing full information about
10321 * the event.
10322 * @return True if the listener has consumed the event, false otherwise.
10323 */
10324 boolean onTouch(View v, MotionEvent event);
10325 }
10326
10327 /**
10328 * Interface definition for a callback to be invoked when a view has been clicked and held.
10329 */
10330 public interface OnLongClickListener {
10331 /**
10332 * Called when a view has been clicked and held.
10333 *
10334 * @param v The view that was clicked and held.
10335 *
10336 * return True if the callback consumed the long click, false otherwise
10337 */
10338 boolean onLongClick(View v);
10339 }
10340
10341 /**
Chris Tate32affef2010-10-18 15:29:21 -070010342 * Interface definition for a callback to be invoked when a drag is being dispatched
10343 * to this view. The callback will be invoked before the hosting view's own
10344 * onDrag(event) method. If the listener wants to fall back to the hosting view's
10345 * onDrag(event) behavior, it should return 'false' from this callback.
10346 */
10347 public interface OnDragListener {
10348 /**
10349 * Called when a drag event is dispatched to a view. This allows listeners
10350 * to get a chance to override base View behavior.
10351 *
10352 * @param v The view the drag has been dispatched to.
10353 * @param event The DragEvent object containing full information
10354 * about the event.
10355 * @return true if the listener consumed the DragEvent, false in order to fall
10356 * back to the view's default handling.
10357 */
10358 boolean onDrag(View v, DragEvent event);
10359 }
10360
10361 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010362 * Interface definition for a callback to be invoked when the focus state of
10363 * a view changed.
10364 */
10365 public interface OnFocusChangeListener {
10366 /**
10367 * Called when the focus state of a view has changed.
10368 *
10369 * @param v The view whose state has changed.
10370 * @param hasFocus The new focus state of v.
10371 */
10372 void onFocusChange(View v, boolean hasFocus);
10373 }
10374
10375 /**
10376 * Interface definition for a callback to be invoked when a view is clicked.
10377 */
10378 public interface OnClickListener {
10379 /**
10380 * Called when a view has been clicked.
10381 *
10382 * @param v The view that was clicked.
10383 */
10384 void onClick(View v);
10385 }
10386
10387 /**
10388 * Interface definition for a callback to be invoked when the context menu
10389 * for this view is being built.
10390 */
10391 public interface OnCreateContextMenuListener {
10392 /**
10393 * Called when the context menu for this view is being built. It is not
10394 * safe to hold onto the menu after this method returns.
10395 *
10396 * @param menu The context menu that is being built
10397 * @param v The view for which the context menu is being built
10398 * @param menuInfo Extra information about the item for which the
10399 * context menu should be shown. This information will vary
10400 * depending on the class of v.
10401 */
10402 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
10403 }
10404
10405 private final class UnsetPressedState implements Runnable {
10406 public void run() {
10407 setPressed(false);
10408 }
10409 }
10410
10411 /**
10412 * Base class for derived classes that want to save and restore their own
10413 * state in {@link android.view.View#onSaveInstanceState()}.
10414 */
10415 public static class BaseSavedState extends AbsSavedState {
10416 /**
10417 * Constructor used when reading from a parcel. Reads the state of the superclass.
10418 *
10419 * @param source
10420 */
10421 public BaseSavedState(Parcel source) {
10422 super(source);
10423 }
10424
10425 /**
10426 * Constructor called by derived classes when creating their SavedState objects
10427 *
10428 * @param superState The state of the superclass of this view
10429 */
10430 public BaseSavedState(Parcelable superState) {
10431 super(superState);
10432 }
10433
10434 public static final Parcelable.Creator<BaseSavedState> CREATOR =
10435 new Parcelable.Creator<BaseSavedState>() {
10436 public BaseSavedState createFromParcel(Parcel in) {
10437 return new BaseSavedState(in);
10438 }
10439
10440 public BaseSavedState[] newArray(int size) {
10441 return new BaseSavedState[size];
10442 }
10443 };
10444 }
10445
10446 /**
10447 * A set of information given to a view when it is attached to its parent
10448 * window.
10449 */
10450 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010451 interface Callbacks {
10452 void playSoundEffect(int effectId);
10453 boolean performHapticFeedback(int effectId, boolean always);
10454 }
10455
10456 /**
10457 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
10458 * to a Handler. This class contains the target (View) to invalidate and
10459 * the coordinates of the dirty rectangle.
10460 *
10461 * For performance purposes, this class also implements a pool of up to
10462 * POOL_LIMIT objects that get reused. This reduces memory allocations
10463 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010464 */
Romain Guyd928d682009-03-31 17:52:16 -070010465 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010466 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070010467 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
10468 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070010469 public InvalidateInfo newInstance() {
10470 return new InvalidateInfo();
10471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010472
Romain Guyd928d682009-03-31 17:52:16 -070010473 public void onAcquired(InvalidateInfo element) {
10474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010475
Romain Guyd928d682009-03-31 17:52:16 -070010476 public void onReleased(InvalidateInfo element) {
10477 }
10478 }, POOL_LIMIT)
10479 );
10480
10481 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010482
10483 View target;
10484
10485 int left;
10486 int top;
10487 int right;
10488 int bottom;
10489
Romain Guyd928d682009-03-31 17:52:16 -070010490 public void setNextPoolable(InvalidateInfo element) {
10491 mNext = element;
10492 }
10493
10494 public InvalidateInfo getNextPoolable() {
10495 return mNext;
10496 }
10497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010498 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070010499 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010500 }
10501
10502 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070010503 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010504 }
10505 }
10506
10507 final IWindowSession mSession;
10508
10509 final IWindow mWindow;
10510
10511 final IBinder mWindowToken;
10512
10513 final Callbacks mRootCallbacks;
10514
10515 /**
10516 * The top view of the hierarchy.
10517 */
10518 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070010519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010520 IBinder mPanelParentWindowToken;
10521 Surface mSurface;
10522
Romain Guyb051e892010-09-28 19:09:36 -070010523 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080010524 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070010525 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070010526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010527 /**
Romain Guy8506ab42009-06-11 17:35:47 -070010528 * Scale factor used by the compatibility mode
10529 */
10530 float mApplicationScale;
10531
10532 /**
10533 * Indicates whether the application is in compatibility mode
10534 */
10535 boolean mScalingRequired;
10536
10537 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010538 * Left position of this view's window
10539 */
10540 int mWindowLeft;
10541
10542 /**
10543 * Top position of this view's window
10544 */
10545 int mWindowTop;
10546
10547 /**
Adam Powell26153a32010-11-08 15:22:27 -080010548 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070010549 */
Adam Powell26153a32010-11-08 15:22:27 -080010550 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070010551
10552 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010553 * For windows that are full-screen but using insets to layout inside
10554 * of the screen decorations, these are the current insets for the
10555 * content of the window.
10556 */
10557 final Rect mContentInsets = new Rect();
10558
10559 /**
10560 * For windows that are full-screen but using insets to layout inside
10561 * of the screen decorations, these are the current insets for the
10562 * actual visible parts of the window.
10563 */
10564 final Rect mVisibleInsets = new Rect();
10565
10566 /**
10567 * The internal insets given by this window. This value is
10568 * supplied by the client (through
10569 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
10570 * be given to the window manager when changed to be used in laying
10571 * out windows behind it.
10572 */
10573 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
10574 = new ViewTreeObserver.InternalInsetsInfo();
10575
10576 /**
10577 * All views in the window's hierarchy that serve as scroll containers,
10578 * used to determine if the window can be resized or must be panned
10579 * to adjust for a soft input area.
10580 */
10581 final ArrayList<View> mScrollContainers = new ArrayList<View>();
10582
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070010583 final KeyEvent.DispatcherState mKeyDispatchState
10584 = new KeyEvent.DispatcherState();
10585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010586 /**
10587 * Indicates whether the view's window currently has the focus.
10588 */
10589 boolean mHasWindowFocus;
10590
10591 /**
10592 * The current visibility of the window.
10593 */
10594 int mWindowVisibility;
10595
10596 /**
10597 * Indicates the time at which drawing started to occur.
10598 */
10599 long mDrawingTime;
10600
10601 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070010602 * Indicates whether or not ignoring the DIRTY_MASK flags.
10603 */
10604 boolean mIgnoreDirtyState;
10605
10606 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010607 * Indicates whether the view's window is currently in touch mode.
10608 */
10609 boolean mInTouchMode;
10610
10611 /**
10612 * Indicates that ViewRoot should trigger a global layout change
10613 * the next time it performs a traversal
10614 */
10615 boolean mRecomputeGlobalAttributes;
10616
10617 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010618 * Set during a traveral if any views want to keep the screen on.
10619 */
10620 boolean mKeepScreenOn;
10621
10622 /**
10623 * Set if the visibility of any views has changed.
10624 */
10625 boolean mViewVisibilityChanged;
10626
10627 /**
10628 * Set to true if a view has been scrolled.
10629 */
10630 boolean mViewScrollChanged;
10631
10632 /**
10633 * Global to the view hierarchy used as a temporary for dealing with
10634 * x/y points in the transparent region computations.
10635 */
10636 final int[] mTransparentLocation = new int[2];
10637
10638 /**
10639 * Global to the view hierarchy used as a temporary for dealing with
10640 * x/y points in the ViewGroup.invalidateChild implementation.
10641 */
10642 final int[] mInvalidateChildLocation = new int[2];
10643
Chet Haasec3aa3612010-06-17 08:50:37 -070010644
10645 /**
10646 * Global to the view hierarchy used as a temporary for dealing with
10647 * x/y location when view is transformed.
10648 */
10649 final float[] mTmpTransformLocation = new float[2];
10650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010651 /**
10652 * The view tree observer used to dispatch global events like
10653 * layout, pre-draw, touch mode change, etc.
10654 */
10655 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
10656
10657 /**
10658 * A Canvas used by the view hierarchy to perform bitmap caching.
10659 */
10660 Canvas mCanvas;
10661
10662 /**
10663 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
10664 * handler can be used to pump events in the UI events queue.
10665 */
10666 final Handler mHandler;
10667
10668 /**
10669 * Identifier for messages requesting the view to be invalidated.
10670 * Such messages should be sent to {@link #mHandler}.
10671 */
10672 static final int INVALIDATE_MSG = 0x1;
10673
10674 /**
10675 * Identifier for messages requesting the view to invalidate a region.
10676 * Such messages should be sent to {@link #mHandler}.
10677 */
10678 static final int INVALIDATE_RECT_MSG = 0x2;
10679
10680 /**
10681 * Temporary for use in computing invalidate rectangles while
10682 * calling up the hierarchy.
10683 */
10684 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070010685
10686 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070010687 * Temporary for use in computing hit areas with transformed views
10688 */
10689 final RectF mTmpTransformRect = new RectF();
10690
10691 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070010692 * Temporary list for use in collecting focusable descendents of a view.
10693 */
10694 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
10695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010696 /**
10697 * Creates a new set of attachment information with the specified
10698 * events handler and thread.
10699 *
10700 * @param handler the events handler the view must use
10701 */
10702 AttachInfo(IWindowSession session, IWindow window,
10703 Handler handler, Callbacks effectPlayer) {
10704 mSession = session;
10705 mWindow = window;
10706 mWindowToken = window.asBinder();
10707 mHandler = handler;
10708 mRootCallbacks = effectPlayer;
10709 }
10710 }
10711
10712 /**
10713 * <p>ScrollabilityCache holds various fields used by a View when scrolling
10714 * is supported. This avoids keeping too many unused fields in most
10715 * instances of View.</p>
10716 */
Mike Cleronf116bf82009-09-27 19:14:12 -070010717 private static class ScrollabilityCache implements Runnable {
10718
10719 /**
10720 * Scrollbars are not visible
10721 */
10722 public static final int OFF = 0;
10723
10724 /**
10725 * Scrollbars are visible
10726 */
10727 public static final int ON = 1;
10728
10729 /**
10730 * Scrollbars are fading away
10731 */
10732 public static final int FADING = 2;
10733
10734 public boolean fadeScrollBars;
10735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010736 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070010737 public int scrollBarDefaultDelayBeforeFade;
10738 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010739
10740 public int scrollBarSize;
10741 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070010742 public float[] interpolatorValues;
10743 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010744
10745 public final Paint paint;
10746 public final Matrix matrix;
10747 public Shader shader;
10748
Mike Cleronf116bf82009-09-27 19:14:12 -070010749 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
10750
Romain Guy8fb95422010-08-17 18:38:51 -070010751 private final float[] mOpaque = { 255.0f };
10752 private final float[] mTransparent = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070010753
10754 /**
10755 * When fading should start. This time moves into the future every time
10756 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
10757 */
10758 public long fadeStartTime;
10759
10760
10761 /**
10762 * The current state of the scrollbars: ON, OFF, or FADING
10763 */
10764 public int state = OFF;
10765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766 private int mLastColor;
10767
Mike Cleronf116bf82009-09-27 19:14:12 -070010768 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010769 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
10770 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070010771 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
10772 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010773
10774 paint = new Paint();
10775 matrix = new Matrix();
10776 // use use a height of 1, and then wack the matrix each time we
10777 // actually use it.
10778 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010780 paint.setShader(shader);
10781 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070010782 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010783 }
Romain Guy8506ab42009-06-11 17:35:47 -070010784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010785 public void setFadeColor(int color) {
10786 if (color != 0 && color != mLastColor) {
10787 mLastColor = color;
10788 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070010789
Romain Guye55e1a72009-08-27 10:42:26 -070010790 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
10791 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010793 paint.setShader(shader);
10794 // Restore the default transfer mode (src_over)
10795 paint.setXfermode(null);
10796 }
10797 }
Mike Cleronf116bf82009-09-27 19:14:12 -070010798
10799 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070010800 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070010801 if (now >= fadeStartTime) {
10802
10803 // the animation fades the scrollbars out by changing
10804 // the opacity (alpha) from fully opaque to fully
10805 // transparent
10806 int nextFrame = (int) now;
10807 int framesCount = 0;
10808
10809 Interpolator interpolator = scrollBarInterpolator;
10810
10811 // Start opaque
10812 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
10813
10814 // End transparent
10815 nextFrame += scrollBarFadeDuration;
10816 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
10817
10818 state = FADING;
10819
10820 // Kick off the fade animation
10821 host.invalidate();
10822 }
10823 }
10824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 }
10826}